[PATCH] D87587: [clang-format][PR47290] Add ShortNamespaceLines format option

2021-02-27 Thread Krystian Kuzniarek via Phabricator via cfe-commits
kuzkry added a comment.

> Do you need someone to push it?

Yes, I need someone to do that. I don't have write permissions. I'm new here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87587

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


[PATCH] D97620: Fix DecisionForestBenchmark.cpp compile errors

2021-02-27 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc updated this revision to Diff 326937.
poelmanc added a comment.

Shorten comment and add period.


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

https://reviews.llvm.org/D97620

Files:
  
clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp


Index: 
clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
===
--- 
clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
+++ 
clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
@@ -21,7 +21,7 @@
 namespace clangd {
 namespace {
 std::vector generateRandomDataset(int NumExamples) {
-  auto FlipCoin = [&](float Probability) {
+  auto FlipCoin = [&](double Probability) {
 return rand() % 1000 <= Probability * 1000;
   };
   auto RandInt = [&](int Max) { return rand() % Max; };
@@ -38,15 +38,15 @@
 E.setIsImplementationDetail(FlipCoin(0.3)); // Boolean.
 E.setNumReferences(RandInt(1)); // Can be large integer.
 E.setSymbolCategory(RandInt(10));   // 10 Symbol Category.
-
+E.setNumNameInContext(RandInt(20)); // 0 to ContextWords->keys().
+E.setFractionNameInContext(RandFloat(1.0)); // Float in range [0,1].
 E.setIsNameInContext(FlipCoin(0.5)); // Boolean.
-E.setIsForbidden(FlipCoin(0.1)); // Boolean.
 E.setIsInBaseClass(FlipCoin(0.3));   // Boolean.
-E.setFileProximityDistance(
+E.setFileProximityDistanceCost(
 FlipCoin(0.1) ? 99 // Sometimes file distance is not available.
   : RandInt(20));
 E.setSemaFileProximityScore(RandFloat(1)); // Float in range [0,1].
-E.setSymbolScopeDistance(
+E.setSymbolScopeDistanceCost(
 FlipCoin(0.1) ? 99 // Sometimes scope distance is not available.
   : RandInt(20));
 E.setSemaSaysInScope(FlipCoin(0.5));  // Boolean.
@@ -56,7 +56,6 @@
 E.setHadContextType(FlipCoin(0.6));   // Boolean.
 E.setHadSymbolType(FlipCoin(0.6));// Boolean.
 E.setTypeMatchesPreferred(FlipCoin(0.5)); // Boolean.
-E.setFilterLength(RandInt(15));
 Examples.push_back(E);
   }
   return Examples;


Index: clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
===
--- clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
+++ clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
@@ -21,7 +21,7 @@
 namespace clangd {
 namespace {
 std::vector generateRandomDataset(int NumExamples) {
-  auto FlipCoin = [&](float Probability) {
+  auto FlipCoin = [&](double Probability) {
 return rand() % 1000 <= Probability * 1000;
   };
   auto RandInt = [&](int Max) { return rand() % Max; };
@@ -38,15 +38,15 @@
 E.setIsImplementationDetail(FlipCoin(0.3)); // Boolean.
 E.setNumReferences(RandInt(1)); // Can be large integer.
 E.setSymbolCategory(RandInt(10));   // 10 Symbol Category.
-
+E.setNumNameInContext(RandInt(20)); // 0 to ContextWords->keys().
+E.setFractionNameInContext(RandFloat(1.0)); // Float in range [0,1].
 E.setIsNameInContext(FlipCoin(0.5)); // Boolean.
-E.setIsForbidden(FlipCoin(0.1)); // Boolean.
 E.setIsInBaseClass(FlipCoin(0.3));   // Boolean.
-E.setFileProximityDistance(
+E.setFileProximityDistanceCost(
 FlipCoin(0.1) ? 99 // Sometimes file distance is not available.
   : RandInt(20));
 E.setSemaFileProximityScore(RandFloat(1)); // Float in range [0,1].
-E.setSymbolScopeDistance(
+E.setSymbolScopeDistanceCost(
 FlipCoin(0.1) ? 99 // Sometimes scope distance is not available.
   : RandInt(20));
 E.setSemaSaysInScope(FlipCoin(0.5));  // Boolean.
@@ -56,7 +56,6 @@
 E.setHadContextType(FlipCoin(0.6));   // Boolean.
 E.setHadSymbolType(FlipCoin(0.6));// Boolean.
 E.setTypeMatchesPreferred(FlipCoin(0.5)); // Boolean.
-E.setFilterLength(RandInt(15));
 Examples.push_back(E);
   }
   return Examples;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97620: Fix DecisionForestBenchmark.cpp compile errors

2021-02-27 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc created this revision.
poelmanc added a reviewer: usaxena95.
poelmanc added a project: clang-tools-extra.
Herald added subscribers: kadircet, arphaman.
poelmanc requested review of this revision.
Herald added subscribers: cfe-commits, ilya-biryukov.
Herald added a project: clang.

clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp 
fails to compile since `"CompletionModel.h"` is auto-generated from 
clang-tools-extra/clangd/quality/model/features.json, which was changed in 
https://reviews.llvm.org/D94697 to remove `setFilterLength` and 
`setIsForbidden`, rename `setFileProximityDistance` and 
`setSymbolScopeDistance`, and add `setNumNameInContext` and 
`setFractionNameInContext`.  This patch removes calls to the two removed 
functions, updates calls to the two renamed functions, and adds calls to the 
two new functions. (`20` is an arbitrary choice for the `setNumNameInContext` 
argument.) It also changes the `FlipCoin` argument from float to double to 
silence lossy conversion warnings.

Note: I don't use this tool but encountered the build errors and took a shot at 
fixing them. Please holler if there's another recommended solution. Thanks!


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97620

Files:
  
clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp


Index: 
clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
===
--- 
clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
+++ 
clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
@@ -21,7 +21,7 @@
 namespace clangd {
 namespace {
 std::vector generateRandomDataset(int NumExamples) {
-  auto FlipCoin = [&](float Probability) {
+  auto FlipCoin = [&](double Probability) {
 return rand() % 1000 <= Probability * 1000;
   };
   auto RandInt = [&](int Max) { return rand() % Max; };
@@ -38,15 +38,15 @@
 E.setIsImplementationDetail(FlipCoin(0.3)); // Boolean.
 E.setNumReferences(RandInt(1)); // Can be large integer.
 E.setSymbolCategory(RandInt(10));   // 10 Symbol Category.
-
+E.setNumNameInContext(RandInt(20)); // 0 to 
Relevance.ContextWords->keys()
+E.setFractionNameInContext(RandFloat(1.0)); // Float in range [0,1].
 E.setIsNameInContext(FlipCoin(0.5)); // Boolean.
-E.setIsForbidden(FlipCoin(0.1)); // Boolean.
 E.setIsInBaseClass(FlipCoin(0.3));   // Boolean.
-E.setFileProximityDistance(
+E.setFileProximityDistanceCost(
 FlipCoin(0.1) ? 99 // Sometimes file distance is not available.
   : RandInt(20));
 E.setSemaFileProximityScore(RandFloat(1)); // Float in range [0,1].
-E.setSymbolScopeDistance(
+E.setSymbolScopeDistanceCost(
 FlipCoin(0.1) ? 99 // Sometimes scope distance is not available.
   : RandInt(20));
 E.setSemaSaysInScope(FlipCoin(0.5));  // Boolean.
@@ -56,7 +56,6 @@
 E.setHadContextType(FlipCoin(0.6));   // Boolean.
 E.setHadSymbolType(FlipCoin(0.6));// Boolean.
 E.setTypeMatchesPreferred(FlipCoin(0.5)); // Boolean.
-E.setFilterLength(RandInt(15));
 Examples.push_back(E);
   }
   return Examples;


Index: clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
===
--- clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
+++ clang-tools-extra/clangd/benchmarks/CompletionModel/DecisionForestBenchmark.cpp
@@ -21,7 +21,7 @@
 namespace clangd {
 namespace {
 std::vector generateRandomDataset(int NumExamples) {
-  auto FlipCoin = [&](float Probability) {
+  auto FlipCoin = [&](double Probability) {
 return rand() % 1000 <= Probability * 1000;
   };
   auto RandInt = [&](int Max) { return rand() % Max; };
@@ -38,15 +38,15 @@
 E.setIsImplementationDetail(FlipCoin(0.3)); // Boolean.
 E.setNumReferences(RandInt(1)); // Can be large integer.
 E.setSymbolCategory(RandInt(10));   // 10 Symbol Category.
-
+E.setNumNameInContext(RandInt(20)); // 0 to Relevance.ContextWords->keys()
+E.setFractionNameInContext(RandFloat(1.0)); // Float in range [0,1].
 E.setIsNameInContext(FlipCoin(0.5)); // Boolean.
-E.setIsForbidden(FlipCoin(0.1)); // Boolean.
 E.setIsInBaseClass(FlipCoin(0.3));   // Boolean.
-E.setFileProximityDistance(
+E.setFileProximityDistanceCost(
 FlipCoin(0.1) ? 99 // Sometimes file distance is not available.
   : RandInt(20));
 E.setSemaFileProximityScore(RandFloat(1)); // Float in range [0,1].
-E.setSymbolScopeDistance(
+E.setSymbolScopeDistanceCost(
 FlipCoin(0.1) ? 99 // Sometimes scope distance is not available.
   : RandInt(20));
 

[PATCH] D93164: [AST] Add generator for source location introspection

2021-02-27 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Mostly mechanical changes requested here.

In D93164#2456247 , @steveire wrote:

> @thakis FYI - I think the GN build would need to be adapted to this.

FWIW the GN build has a bot that can typically update its gn files.




Comment at: clang/include/clang/Tooling/NodeIntrospection.h:40
+  LocationCall *on() const { return m_on.get(); }
+  std::string name() const { return m_name; }
+  std::vector const () const { return m_args; }

Is there a strong use case to return by value here?



Comment at: clang/include/clang/Tooling/NodeIntrospection.h:54
+public:
+  static std::string format(LocationCall *Call) {
+std::vector vec;

Should this (and potential a few others) be moved to an implementation file.



Comment at: clang/include/clang/Tooling/NodeIntrospection.h:55
+  static std::string format(LocationCall *Call) {
+std::vector vec;
+while (Call) {

It's probably more effective to use a SmallVector to reduce the needs for 
allocations here.



Comment at: clang/include/clang/Tooling/NodeIntrospection.h:60
+}
+std::reverse(vec.begin(), vec.end());
+std::string result;

This is wasteful, just operate on rbegin/rend later and eliminate this call.



Comment at: clang/include/clang/Tooling/NodeIntrospection.h:63
+auto secondLast = std::prev(vec.end());
+for (auto VecIt = vec.begin(); VecIt != secondLast; ++VecIt) {
+  auto VecCall = *VecIt;

Is this more readable, IDK, but it sure as hell is more fun :)



Comment at: clang/include/clang/Tooling/NodeIntrospection.h:65-66
+  auto VecCall = *VecIt;
+  result += VecCall->name() + "()";
+  result += VecCall->returnsPointer() ? "->" : ".";
+}





Comment at: clang/lib/Tooling/DumpTool/APIData.h:21
+
+  bool IsEmpty() const { return Locs.empty() && Rngs.empty(); }
+

steveire wrote:
> aaron.ballman wrote:
> > per the usual naming rules.
> I changed it, but are you referring to this proposal? 
> https://llvm.org/docs/Proposals/VariableNames.html
While there is a proposal in place, right now we should ensure we aren't 
deviating from the current system in patches. Unfortunately 
readability-identifier-naming has been disabled on clang directory due to 
excessive violations. May I suggest re-enabling it locally and then running 
clang-tidy-diff.py over the patch. should square most things up.



Comment at: clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp:22-25
+auto publicAccessor = [](auto... InnerMatcher) {
+  return cxxMethodDecl(isPublic(), parameterCountIs(0), isConst(),
+   InnerMatcher...);
+};

Why is this a variable, a templated function should do the same thing.
I imagine its something like this.



Comment at: clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp:45
+
+  return Finder.release()->newASTConsumer();
+}

This seems dangerous, the `MatchASTConsumer` doesn't own its `MatchFinder`, so 
this is going to leak.



Comment at: clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h:1
+//===- ASTSrcLocProcessor.h 
---===//
+//

Can you add a modeline here, same goes for other headers.



Comment at: clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h:14
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+#include "APIData.h"

Any reason for empty lines between includes?



Comment at: clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp:80
+
+  std::transform(IncludeDirectories.begin(), IncludeDirectories.end(),
+ std::back_inserter(Args),





Comment at: clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp:86-88
+  std::vector Argv;
+  std::transform(Args.begin(), Args.end(), std::back_inserter(Argv),
+ [](const std::string ) { return Arg.c_str(); });




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93164

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


[PATCH] D96896: [clang-format] Respect spaces in line comment section without an active column limit

2021-02-27 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks updated this revision to Diff 326928.
HazardyKnusperkeks added a comment.

- Work with `::max` instead of many checks for `== 0`.
- Additional Testcase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96896

Files:
  clang/lib/Format/ContinuationIndenter.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/FormatTestComments.cpp

Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -3793,6 +3793,189 @@
"int i;//  A Comment to be moved\n"
"  //   with indent\n",
Style));
+
+  Style = getLLVMStyleWithColumns(0);
+  EXPECT_EQ("// Free comment without space\n"
+"\n"
+"//   Free comment with 3 spaces\n"
+"\n"
+"/// Free Doxygen without space\n"
+"\n"
+"///   Free Doxygen with 3 spaces\n"
+"\n"
+"/// A Doxygen Comment with a nested list:\n"
+"/// - Foo\n"
+"/// - Bar\n"
+"///   - Baz\n"
+"///   - End\n"
+"/// of the inner list\n"
+"///   .\n"
+"/// .\n"
+"\n"
+"namespace Foo {\n"
+"bool bar(bool b) {\n"
+"  bool ret1 = true; ///< Doxygenstyle without space\n"
+"  bool ret2 = true; ///<   Doxygenstyle with 3 spaces\n"
+"  if (b) {\n"
+"// Foo\n"
+"\n"
+"//   In function comment\n"
+"ret2 = false;\n"
+"  } // End of if\n"
+"\n"
+"  //  if (ret1) {\n"
+"  //return ret2;\n"
+"  //  }\n"
+"\n"
+"  // if (ret1) {\n"
+"  //   return ret2;\n"
+"  // }\n"
+"\n"
+"  return ret1 && ret2;\n"
+"}\n"
+"} // namespace Foo\n"
+"\n"
+"namespace Bar {\n"
+"int foo();\n"
+"} //  namespace Bar\n"
+"//@Nothing added because of the non ascii char\n"
+"\n"
+"//@  Nothing removed because of the non ascii char\n"
+"\n"
+"//  Comment to move to the left\n"
+"// But not this?\n"
+"//  @but this\n"
+"\n"
+"// Comment to move to the right\n"
+"//@ this stays\n"
+"\n"
+"//} will not move\n"
+"\n"
+"// vv will only move\n"
+"// } if the line above does\n",
+format(Code, Style));
+
+  Style.SpacesInLineCommentPrefix = {0, 0};
+  EXPECT_EQ("//Free comment without space\n"
+"\n"
+"//Free comment with 3 spaces\n"
+"\n"
+"///Free Doxygen without space\n"
+"\n"
+"///Free Doxygen with 3 spaces\n"
+"\n"
+"///A Doxygen Comment with a nested list:\n"
+"///- Foo\n"
+"///- Bar\n"
+"///  - Baz\n" // Here we keep the relative indentation
+"///  - End\n"
+"///of the inner list\n"
+"///  .\n"
+"///.\n"
+"\n"
+"namespace Foo {\n"
+"bool bar(bool b) {\n"
+"  bool ret1 = true; /// SmallString.size();\n"
+  "}";
+  EXPECT_EQ(Code, format(Code, Style));
+}
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/ContinuationIndenter.cpp
===
--- clang/lib/Format/ContinuationIndenter.cpp
+++ clang/lib/Format/ContinuationIndenter.cpp
@@ -1993,6 +1993,11 @@
 // We don't insert backslashes when breaking line comments.
 ColumnLimit = Style.ColumnLimit;
   }
+  if (ColumnLimit == 0) {
+// To make the rest of the function easier set the column limit to the
+// maximum, if there should be no limit.
+ColumnLimit = std::numeric_limits::max();
+  }
   if (Current.UnbreakableTailLength >= ColumnLimit)
 return {0, false};
   // ColumnWidth was already accounted into State.Column before calling
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87587: [clang-format][PR47290] Add ShortNamespaceLines format option

2021-02-27 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Is this acceptable to the others? Do you need someone to push it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87587

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


[PATCH] D94500: [clang-format] Rework Whitesmiths mode to use line-level values in UnwrappedLineParser

2021-02-27 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Do you need someone to push this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94500

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


[PATCH] D97137: [clang-format] Fix AlignConsecutiveDeclarations handling of pointers

2021-02-27 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe0b1df924ae0: [clang-format] Fix 
AlignConsecutiveDeclarations handling of pointers (authored by darwin, 
committed by HazardyKnusperkeks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97137

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -13945,6 +13945,20 @@
   verifyFormat("int  oneTwoThree{0}; // comment\n"
"unsigned oneTwo; // comment",
Alignment);
+  verifyFormat("unsigned int *  a;\n"
+   "int *   b;\n"
+   "unsigned int Const *c;\n"
+   "unsigned int const *d;\n"
+   "unsigned int Const \n"
+   "unsigned int const ",
+   Alignment);
+  verifyFormat("Const unsigned int *c;\n"
+   "const unsigned int *d;\n"
+   "Const unsigned int \n"
+   "const unsigned int \n"
+   "const unsigned  g;\n"
+   "Const unsigned  h;",
+   Alignment);
   EXPECT_EQ("float const a = 5;\n"
 "\n"
 "int oneTwoThree = 123;",
@@ -14249,6 +14263,38 @@
   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
 "foo(int a);",
 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
+
+  Alignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned int*   a;\n"
+   "int*b;\n"
+   "unsigned int Const* c;\n"
+   "unsigned int const* d;\n"
+   "unsigned int Const& e;\n"
+   "unsigned int const& f;",
+   Alignment);
+  verifyFormat("Const unsigned int* c;\n"
+   "const unsigned int* d;\n"
+   "Const unsigned int& e;\n"
+   "const unsigned int& f;\n"
+   "const unsigned  g;\n"
+   "Const unsigned  h;",
+   Alignment);
+
+  Alignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("unsigned int *   a;\n"
+   "int *b;\n"
+   "unsigned int Const * c;\n"
+   "unsigned int const * d;\n"
+   "unsigned int Const & e;\n"
+   "unsigned int const & f;",
+   Alignment);
+  verifyFormat("Const unsigned int * c;\n"
+   "const unsigned int * d;\n"
+   "Const unsigned int & e;\n"
+   "const unsigned int & f;\n"
+   "const unsigned   g;\n"
+   "Const unsigned   h;",
+   Alignment);
 }
 
 TEST_F(FormatTest, LinuxBraceBreaking) {
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -709,6 +709,8 @@
 for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
   if (Next->is(tok::comment))
 continue;
+  if (Next->is(TT_PointerOrReference))
+return false;
   if (!Next->Tok.getIdentifierInfo())
 break;
   if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -13945,6 +13945,20 @@
   verifyFormat("int  oneTwoThree{0}; // comment\n"
"unsigned oneTwo; // comment",
Alignment);
+  verifyFormat("unsigned int *  a;\n"
+   "int *   b;\n"
+   "unsigned int Const *c;\n"
+   "unsigned int const *d;\n"
+   "unsigned int Const \n"
+   "unsigned int const ",
+   Alignment);
+  verifyFormat("Const unsigned int *c;\n"
+   "const unsigned int *d;\n"
+   "Const unsigned int \n"
+   "const unsigned int \n"
+   "const unsigned  g;\n"
+   "Const unsigned  h;",
+   Alignment);
   EXPECT_EQ("float const a = 5;\n"
 "\n"
 "int oneTwoThree = 123;",
@@ -14249,6 +14263,38 @@
   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
 "foo(int a);",
 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
+
+  Alignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned int*   a;\n"
+   "int*b;\n"
+   "unsigned int Const* c;\n"
+   "unsigned int const* d;\n"
+   

[clang] e0b1df9 - [clang-format] Fix AlignConsecutiveDeclarations handling of pointers

2021-02-27 Thread Björn Schäpers via cfe-commits

Author: Darwin Xu
Date: 2021-02-27T22:56:36+01:00
New Revision: e0b1df924ae06d6d88582334087d2eacc6702e8f

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

LOG: [clang-format] Fix AlignConsecutiveDeclarations handling of pointers

This is a bug fix of https://bugs.llvm.org/show_bug.cgi?id=49175

The expected code format:

unsigned int*   a;
int*b;
unsigned int Const* c;

The actual code after formatting (without this patch):

unsigned int* a;
int*  b;
unsigned int Const* c;

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

Added: 


Modified: 
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 7d6964b7c72f..ac68fe0aa01a 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -709,6 +709,8 @@ void WhitespaceManager::alignConsecutiveDeclarations() {
 for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
   if (Next->is(tok::comment))
 continue;
+  if (Next->is(TT_PointerOrReference))
+return false;
   if (!Next->Tok.getIdentifierInfo())
 break;
   if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b4b31fa70c10..8bb90e0d6e61 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -13945,6 +13945,20 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
   verifyFormat("int  oneTwoThree{0}; // comment\n"
"unsigned oneTwo; // comment",
Alignment);
+  verifyFormat("unsigned int *  a;\n"
+   "int *   b;\n"
+   "unsigned int Const *c;\n"
+   "unsigned int const *d;\n"
+   "unsigned int Const \n"
+   "unsigned int const ",
+   Alignment);
+  verifyFormat("Const unsigned int *c;\n"
+   "const unsigned int *d;\n"
+   "Const unsigned int \n"
+   "const unsigned int \n"
+   "const unsigned  g;\n"
+   "Const unsigned  h;",
+   Alignment);
   EXPECT_EQ("float const a = 5;\n"
 "\n"
 "int oneTwoThree = 123;",
@@ -14249,6 +14263,38 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
 "foo(int a);",
 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
+
+  Alignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned int*   a;\n"
+   "int*b;\n"
+   "unsigned int Const* c;\n"
+   "unsigned int const* d;\n"
+   "unsigned int Const& e;\n"
+   "unsigned int const& f;",
+   Alignment);
+  verifyFormat("Const unsigned int* c;\n"
+   "const unsigned int* d;\n"
+   "Const unsigned int& e;\n"
+   "const unsigned int& f;\n"
+   "const unsigned  g;\n"
+   "Const unsigned  h;",
+   Alignment);
+
+  Alignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("unsigned int *   a;\n"
+   "int *b;\n"
+   "unsigned int Const * c;\n"
+   "unsigned int const * d;\n"
+   "unsigned int Const & e;\n"
+   "unsigned int const & f;",
+   Alignment);
+  verifyFormat("Const unsigned int * c;\n"
+   "const unsigned int * d;\n"
+   "Const unsigned int & e;\n"
+   "const unsigned int & f;\n"
+   "const unsigned   g;\n"
+   "Const unsigned   h;",
+   Alignment);
 }
 
 TEST_F(FormatTest, LinuxBraceBreaking) {



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


[PATCH] D96760: [clang-format] Suppress diagnostics on second parse

2021-02-27 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96760

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


[PATCH] D93164: [AST] Add generator for source location introspection

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 326923.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93164

Files:
  clang/include/clang/Tooling/NodeIntrospection.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/DumpTool/APIData.h
  clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
  clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
  clang/lib/Tooling/DumpTool/CMakeLists.txt
  clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
  clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
  clang/lib/Tooling/fallback/NodeIntrospection.cpp
  clang/unittests/CMakeLists.txt
  clang/unittests/Introspection/CMakeLists.txt
  clang/unittests/Introspection/IntrospectionTest.cpp

Index: clang/unittests/Introspection/IntrospectionTest.cpp
===
--- /dev/null
+++ clang/unittests/Introspection/IntrospectionTest.cpp
@@ -0,0 +1,95 @@
+//===- unittest/Introspection/IntrospectionTest.cpp - Introspection test -===//
+//
+// 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
+//
+//===--===//
+//
+// Tests for AST location API introspection.
+//
+//===--===//
+
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/NodeIntrospection.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::tooling;
+
+#if SKIP_INTROSPECTION_GENERATION
+
+TEST(Introspection, NonFatalAPI) {
+  auto AST = buildASTFromCode("void foo() {} void bar() { foo(); }", "foo.cpp",
+  std::make_shared());
+  auto  = AST->getASTContext();
+  auto  = *Ctx.getTranslationUnitDecl();
+
+  auto BoundNodes = ast_matchers::match(
+  decl(hasDescendant(
+  callExpr(callee(functionDecl(hasName("foo".bind("fooCall"))),
+  TU, Ctx);
+
+  EXPECT_EQ(BoundNodes.size(), 1u);
+
+  auto *FooCall = BoundNodes[0].getNodeAs("fooCall");
+
+  auto result = NodeIntrospection::GetLocations(FooCall);
+
+  EXPECT_EQ(result.LocationAccessors.size(), 0);
+  EXPECT_EQ(result.RangeAccessors.size(), 0);
+}
+
+#else
+
+TEST(Introspection, SourceLocations) {
+  auto AST = buildASTFromCode("void foo() {} void bar() { foo(); }", "foo.cpp",
+  std::make_shared());
+  auto  = AST->getASTContext();
+  auto  = *Ctx.getTranslationUnitDecl();
+
+  auto BoundNodes = ast_matchers::match(
+  decl(hasDescendant(
+  callExpr(callee(functionDecl(hasName("foo".bind("fooCall"))),
+  TU, Ctx);
+
+  EXPECT_EQ(BoundNodes.size(), 1u);
+
+  auto *FooCall = BoundNodes[0].getNodeAs("fooCall");
+
+  auto result = NodeIntrospection::GetLocations(FooCall);
+
+  EXPECT_EQ(result.LocationAccessors.size(), 4u);
+
+  EXPECT_EQ(result.LocationAccessors.begin()->first, FooCall->getBeginLoc());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+result.LocationAccessors.begin()->second.get()),
+"getBeginLoc()");
+  EXPECT_EQ(std::next(result.LocationAccessors.begin(), 1)->first,
+FooCall->getExprLoc());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+std::next(result.LocationAccessors.begin(), 1)->second.get()),
+"getExprLoc()");
+  EXPECT_EQ(std::next(result.LocationAccessors.begin(), 2)->first,
+FooCall->getRParenLoc());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+std::next(result.LocationAccessors.begin(), 2)->second.get()),
+"getRParenLoc()");
+  EXPECT_EQ(std::next(result.LocationAccessors.begin(), 3)->first,
+FooCall->getEndLoc());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+std::next(result.LocationAccessors.begin(), 3)->second.get()),
+"getEndLoc()");
+
+  EXPECT_EQ(result.RangeAccessors.size(), 1u);
+  EXPECT_EQ(result.RangeAccessors.begin()->first, FooCall->getSourceRange());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+result.RangeAccessors.begin()->second.get()),
+"getSourceRange()");
+}
+#endif
Index: clang/unittests/Introspection/CMakeLists.txt
===
--- /dev/null
+++ clang/unittests/Introspection/CMakeLists.txt
@@ -0,0 +1,26 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+  FrontendOpenMP
+  Support
+  )
+
+add_clang_unittest(IntrospectionTests
+  IntrospectionTest.cpp
+  )
+
+clang_target_link_libraries(IntrospectionTests
+  PRIVATE
+  clangAST
+  clangASTMatchers
+  clangTooling
+  clangBasic
+  

[PATCH] D96612: [clangd] Improve printing of Objective-C categories and methods

2021-02-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Great, thanks!




Comment at: clang-tools-extra/clangd/FindSymbols.cpp:176
+std::string getSymbolName(ASTContext , const NamedDecl ) {
+  if (const auto *Container = dyn_cast())
+return printObjCContainer(*Container);

can we motivate this with a comment?
// print X rather than Y


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96612

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


[PATCH] D93164: [AST] Add generator for source location introspection

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 326922.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93164

Files:
  clang/include/clang/Tooling/NodeIntrospection.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/DumpTool/APIData.h
  clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
  clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
  clang/lib/Tooling/DumpTool/CMakeLists.txt
  clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
  clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
  clang/lib/Tooling/fallback/NodeIntrospection.cpp
  clang/unittests/CMakeLists.txt
  clang/unittests/Introspection/CMakeLists.txt
  clang/unittests/Introspection/IntrospectionTest.cpp

Index: clang/unittests/Introspection/IntrospectionTest.cpp
===
--- /dev/null
+++ clang/unittests/Introspection/IntrospectionTest.cpp
@@ -0,0 +1,120 @@
+//===- unittest/Introspection/IntrospectionTest.cpp - Introspection test -===//
+//
+// 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
+//
+//===--===//
+//
+// Tests for AST location API introspection.
+//
+//===--===//
+
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/NodeIntrospection.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::tooling;
+
+#if SKIP_INTROSPECTION_GENERATION
+
+TEST(Introspection, NonFatalAPI) {
+  auto AST = buildASTFromCode("void foo() {} void bar() { foo(); }", "foo.cpp",
+  std::make_shared());
+  auto  = AST->getASTContext();
+  auto  = *Ctx.getTranslationUnitDecl();
+
+  auto BoundNodes = ast_matchers::match(
+  decl(hasDescendant(
+  callExpr(callee(functionDecl(hasName("foo".bind("fooCall"))),
+  TU, Ctx);
+
+  EXPECT_EQ(BoundNodes.size(), 1u);
+
+  auto *FooCall = BoundNodes[0].getNodeAs("fooCall");
+
+  auto result = NodeIntrospection::GetLocations(FooCall);
+
+  EXPECT_EQ(result.LocationAccessors.size(), 0);
+  EXPECT_EQ(result.RangeAccessors.size(), 0);
+}
+
+#else
+
+/**
+  A test formatter for a hypothetical language which needs
+  neither casts nor '->'.
+*/
+class LocationCallFormatterSimple {
+public:
+  static std::string format(LocationCall *Call) {
+std::vector vec;
+while (Call) {
+  if (!Call->isCast())
+vec.push_back(Call);
+  Call = Call->on();
+}
+std::reverse(vec.begin(), vec.end());
+std::string result;
+auto secondLast = std::prev(vec.end());
+for (auto VecIt = vec.begin(); VecIt != secondLast; ++VecIt) {
+  auto VecCall = *VecIt;
+  result += VecCall->name() + "().";
+}
+result += vec.back()->name() + "()";
+return result;
+  }
+};
+
+TEST(Introspection, SourceLocations) {
+  auto AST = buildASTFromCode("void foo() {} void bar() { foo(); }", "foo.cpp",
+  std::make_shared());
+  auto  = AST->getASTContext();
+  auto  = *Ctx.getTranslationUnitDecl();
+
+  auto BoundNodes = ast_matchers::match(
+  decl(hasDescendant(
+  callExpr(callee(functionDecl(hasName("foo".bind("fooCall"))),
+  TU, Ctx);
+
+  EXPECT_EQ(BoundNodes.size(), 1u);
+
+  auto *FooCall = BoundNodes[0].getNodeAs("fooCall");
+
+  auto result = NodeIntrospection::GetLocations(FooCall);
+
+  EXPECT_EQ(result.LocationAccessors.size(), 4u);
+
+  EXPECT_EQ(result.LocationAccessors.begin()->first, FooCall->getBeginLoc());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+result.LocationAccessors.begin()->second.get()),
+"getBeginLoc()");
+  EXPECT_EQ(std::next(result.LocationAccessors.begin(), 1)->first,
+FooCall->getExprLoc());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+std::next(result.LocationAccessors.begin(), 1)->second.get()),
+"getExprLoc()");
+  EXPECT_EQ(std::next(result.LocationAccessors.begin(), 2)->first,
+FooCall->getRParenLoc());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+std::next(result.LocationAccessors.begin(), 2)->second.get()),
+"getRParenLoc()");
+  EXPECT_EQ(std::next(result.LocationAccessors.begin(), 3)->first,
+FooCall->getEndLoc());
+  EXPECT_EQ(LocationCallFormatterCpp::format(
+std::next(result.LocationAccessors.begin(), 3)->second.get()),
+"getEndLoc()");
+
+  EXPECT_EQ(result.RangeAccessors.size(), 1u);
+  EXPECT_EQ(result.RangeAccessors.begin()->first, 

[PATCH] D97617: [clangd] ObjC fixes for semantic highlighting and xref highlights

2021-02-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

(not really sure why this suddenly seemed important to me, but if you don't 
have semantic highlighting on, you're missing out!)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97617

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


[PATCH] D96120: [scudo] Port scudo sanitizer to Windows

2021-02-27 Thread Russell Gallop via Phabricator via cfe-commits
russell.gallop added a comment.

In D96120#2591418 , @vitalybuka wrote:

>>> This is intended as a step to porting scudo standalone.
>
> Why this is needed for scudo stadalone?

It’s not strictly needed. It seemed like it was easier, as some of the work had 
already been done, and some of the issues worked through on this would probably 
also come up when porting standalone.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96120

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


[PATCH] D97617: [clangd] ObjC fixes for semantic highlighting and xref highlights

2021-02-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: dgoldman.
Herald added subscribers: usaxena95, kadircet, arphaman.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

- highlight references to protocols in class/protocol/extension decls
- support multi-token selector highlights in semantic + xref highlights (method 
calls and declarations only)
- In `@interface I(C)`, I now references the interface and C the category
- highlight uses of interfaces as types
- added semantic highlightings of protocol names (as "interface") and category 
names (as "namespace"). These are both standard kinds, maybe "extension" will 
be standardized...
- highlight `auto` as "class" when it resolves to an ObjC pointer
- don't highlight `self` as a variable even though the AST models it as one

Not fixed: uses of protocols in type names (needs some refactoring of
unrelated code first)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97617

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -115,10 +115,23 @@
   f.[[^~]]Foo();
 }
   )cpp",
+  R"cpp(// ObjC methods with split selectors.
+@interface Foo
+  +(void) [[x]]:(int)a [[y]]:(int)b;
+@end
+@implementation Foo
+  +(void) [[x]]:(int)a [[y]]:(int)b {}
+@end
+void go() {
+  [Foo [[x]]:2 [[^y]]:4];
+}
+  )cpp",
   };
   for (const char *Test : Tests) {
 Annotations T(Test);
-auto AST = TestTU::withCode(T.code()).build();
+auto TU = TestTU::withCode(T.code());
+TU.ExtraArgs.push_back("-xobjective-c++");
+auto AST = TU.build();
 EXPECT_THAT(findDocumentHighlights(AST, T.point()), HighlightsFrom(T))
 << Test;
   }
Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -75,6 +75,7 @@
   TU.Code = std::string(Test.code());
 
   TU.ExtraArgs.push_back("-std=c++20");
+  TU.ExtraArgs.push_back("-xobjective-c++");
 
   for (auto File : AdditionalFiles)
 TU.AdditionalFiles.insert({File.first, std::string(File.second)});
@@ -645,6 +646,48 @@
   R"cpp(
   <:[deprecated]:> int $Variable_decl_deprecated[[x]];
   )cpp",
+  R"cpp(
+// ObjC: Classes and methods
+@class $Class_decl[[Forward]];
+
+@interface $Class_decl[[Foo]]
+@end
+@interface $Class_decl[[Bar]] : $Class[[Foo]]
+-($Class[[id]]) $Method_decl[[x]]:(int)$Parameter_decl[[a]] $Method_decl[[y]]:(int)$Parameter_decl[[b]];
++(void) $StaticMethod_decl_static[[explode]];
+@end
+@implementation $Class_decl[[Bar]]
+-($Class[[id]]) $Method_decl[[x]]:(int)$Parameter_decl[[a]] $Method_decl[[y]]:(int)$Parameter_decl[[b]] {
+  return self;
+}
++(void) $StaticMethod_decl_static[[explode]] {}
+@end
+
+void $Function_decl[[m]]($Class[[Bar]] *$Parameter_decl[[b]]) {
+  [$Parameter[[b]] $Method[[x]]:1 $Method[[y]]:2];
+  [$Class[[Bar]] $StaticMethod_static[[explode]]];
+}
+  )cpp",
+  R"cpp(
+// ObjC: Protocols
+@protocol $Interface_decl[[Protocol]]
+@end
+@protocol $Interface_decl[[Protocol2]] <$Interface[[Protocol]]>
+@end
+@interface $Class_decl[[Klass]] <$Interface[[Protocol]]>
+@end
+// FIXME: protocol list in ObjCObjectType should be highlighted.
+id $Variable_decl[[x]];
+  )cpp",
+  R"cpp(
+// ObjC: Categories
+@interface $Class_decl[[Foo]]
+@end
+@interface $Class[[Foo]]($Namespace_decl[[Bar]])
+@end
+@implementation $Class[[Foo]]($Namespace_decl[[Bar]])
+@end
+  )cpp",
   };
   for (const auto  : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -1593,6 +1593,35 @@
   "0: targets = {f}\n"
   "1: targets = {I::x}\n"
   "2: 

[PATCH] D96224: [clang-itdy] Simplify virtual near-miss check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added a comment.

Thanks for the heads-up. I've reverted it now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96224

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


[clang-tools-extra] 415acb2 - Revert "[clang-itdy] Simplify virtual near-miss check"

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T19:30:38Z
New Revision: 415acb2c5994a95be739b908785ea8260baa18fd

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

LOG: Revert "[clang-itdy] Simplify virtual near-miss check"

This reverts commit 9a4b574dd6a07d6811356529ebb8a3f15d6e40a2.

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
index dc810c694874..150b517811b6 100644
--- a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
@@ -216,9 +216,10 @@ bool VirtualNearMissCheck::isOverriddenByDerivedClass(
 
 void VirtualNearMissCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
-  cxxMethodDecl(unless(anyOf(isOverride(), cxxConstructorDecl(),
- cxxDestructorDecl(), cxxConversionDecl(),
- isStatic(), isOverloadedOperator(
+  cxxMethodDecl(
+  unless(anyOf(isOverride(), isImplicit(), cxxConstructorDecl(),
+   cxxDestructorDecl(), cxxConversionDecl(), isStatic(),
+   isOverloadedOperator(
   .bind("method"),
   this);
 }
@@ -233,15 +234,7 @@ void VirtualNearMissCheck::check(const 
MatchFinder::MatchResult ) {
   assert(DerivedRD);
 
   for (const auto  : DerivedRD->bases()) {
-const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl();
-if (const auto *TST =
-dyn_cast(BaseSpec.getType())) {
-  auto TN = TST->getTemplateName();
-  BaseRD =
-  dyn_cast(TN.getAsTemplateDecl()->getTemplatedDecl());
-}
-
-if (BaseRD) {
+if (const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl()) {
   for (const auto *BaseMD : BaseRD->methods()) {
 if (!isPossibleToBeOverridden(BaseMD))
   continue;
@@ -257,12 +250,16 @@ void VirtualNearMissCheck::check(const 
MatchFinder::MatchResult ) {
 auto Range = CharSourceRange::getTokenRange(
 SourceRange(DerivedMD->getLocation()));
 
-diag(DerivedMD->getBeginLoc(),
- "method '%0' has a similar name and the same signature as "
- "virtual method '%1'; did you mean to override it?")
+bool ApplyFix = !BaseMD->isTemplateInstantiation() &&
+!DerivedMD->isTemplateInstantiation();
+auto Diag =
+diag(DerivedMD->getBeginLoc(),
+ "method '%0' has a similar name and the same signature as 
"
+ "virtual method '%1'; did you mean to override it?")
 << DerivedMD->getQualifiedNameAsString()
-<< BaseMD->getQualifiedNameAsString()
-<< FixItHint::CreateReplacement(Range, BaseMD->getName());
+<< BaseMD->getQualifiedNameAsString();
+if (ApplyFix)
+  Diag << FixItHint::CreateReplacement(Range, BaseMD->getName());
   }
 }
   }

diff  --git a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
index ec902515f706..69ae278f2e2c 100644
--- a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
@@ -32,9 +32,6 @@ class VirtualNearMissCheck : public ClangTidyCheck {
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
-  llvm::Optional getCheckTraversalKind() const override {
-return TK_IgnoreUnlessSpelledInSource;
-  }
 
 private:
   /// Check if the given method is possible to be overridden by some other

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
index f3f8d3225847..553d2f45a98b 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
@@ -44,8 +44,9 @@ template 
 struct TDerived : TBase {
   virtual void tfunk(T t);
   // Should not apply fix for template.
-  // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: method 'TDerived::tfunk' has 
{{.*}} 'TBase::tfunc'
-  // CHECK-FIXES: virtual void tfunc(T t);
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: method 'TDerived::tfunk' 
has {{.*}} 'TBase::tfunc'
+  // 

[PATCH] D97605: [Lifetimes] Fix false positive warning from BUG 49342

2021-02-27 Thread Gábor Horváth via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdd6738d93de1: [clang][Lifetimes] Fix false positive warning 
from BUG 49342 (authored by xazax.hun).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97605

Files:
  clang/lib/Sema/SemaInit.cpp
  clang/test/Sema/warn-lifetime-analysis-nocfg.cpp


Index: clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
===
--- clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -171,12 +171,22 @@
   const T *begin() const;
 };
 
+template struct iter {
+iter& operator-=(int);
+
+iter operator-(int _Off) const {
+iter _Tmp = *this;
+return _Tmp -= _Off;
+}
+};
+
 template
 struct basic_string {
   basic_string();
   basic_string(const T *);
   const T *c_str() const;
   operator basic_string_view () const;
+  using const_iterator = iter;
 };
 
 
@@ -455,3 +465,8 @@
   std::vector::iterator> iters;
   return iters.at(0);
 }
+
+void testForBug49342()
+{
+  auto it = std::iter{} - 2; // Used to be false positive.
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -7521,6 +7521,8 @@
   continue;
 if (It->Kind == IndirectLocalPathEntry::AddressOf)
   continue;
+if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall)
+  continue;
 return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
It->Kind == IndirectLocalPathEntry::GslReferenceInit;
   }


Index: clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
===
--- clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -171,12 +171,22 @@
   const T *begin() const;
 };
 
+template struct iter {
+iter& operator-=(int);
+
+iter operator-(int _Off) const {
+iter _Tmp = *this;
+return _Tmp -= _Off;
+}
+};
+
 template
 struct basic_string {
   basic_string();
   basic_string(const T *);
   const T *c_str() const;
   operator basic_string_view () const;
+  using const_iterator = iter;
 };
 
 
@@ -455,3 +465,8 @@
   std::vector::iterator> iters;
   return iters.at(0);
 }
+
+void testForBug49342()
+{
+  auto it = std::iter{} - 2; // Used to be false positive.
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -7521,6 +7521,8 @@
   continue;
 if (It->Kind == IndirectLocalPathEntry::AddressOf)
   continue;
+if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall)
+  continue;
 return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
It->Kind == IndirectLocalPathEntry::GslReferenceInit;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] dd6738d - [clang][Lifetimes] Fix false positive warning from BUG 49342

2021-02-27 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2021-02-27T08:09:57-08:00
New Revision: dd6738d93de148f2239ef5be82a61cf8f5f71124

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

LOG: [clang][Lifetimes] Fix false positive warning from BUG 49342

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

Added: 


Modified: 
clang/lib/Sema/SemaInit.cpp
clang/test/Sema/warn-lifetime-analysis-nocfg.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index c1a2be744853..f387e9a33708 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -7521,6 +7521,8 @@ static bool 
pathOnlyInitializesGslPointer(IndirectLocalPath ) {
   continue;
 if (It->Kind == IndirectLocalPathEntry::AddressOf)
   continue;
+if (It->Kind == IndirectLocalPathEntry::LifetimeBoundCall)
+  continue;
 return It->Kind == IndirectLocalPathEntry::GslPointerInit ||
It->Kind == IndirectLocalPathEntry::GslReferenceInit;
   }

diff  --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index 3319d5aa2db8..b3ca173c1fdb 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -171,12 +171,22 @@ struct basic_string_view {
   const T *begin() const;
 };
 
+template struct iter {
+iter& operator-=(int);
+
+iter operator-(int _Off) const {
+iter _Tmp = *this;
+return _Tmp -= _Off;
+}
+};
+
 template
 struct basic_string {
   basic_string();
   basic_string(const T *);
   const T *c_str() const;
   operator basic_string_view () const;
+  using const_iterator = iter;
 };
 
 
@@ -455,3 +465,8 @@ std::vector::iterator 
noFalsePositiveWithVectorOfPointers() {
   std::vector::iterator> iters;
   return iters.at(0);
 }
+
+void testForBug49342()
+{
+  auto it = std::iter{} - 2; // Used to be false positive.
+}



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


[PATCH] D97246: [ASTMatchers] Fix matching failure in IgnoreUnlessSpelledInSource mode

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
steveire accepted this revision.
steveire added a comment.
This revision is now accepted and ready to land.

Thanks for this change! I don't feel strongly about whether a new method or a 
new parameter is appropriate, so it's a +1 from me already. Giving other AST 
nodes consistent API about whether they're spelled in source sounds good to me 
too at some point so the new method or param may be changed/removed again in 
the future.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97246

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


[PATCH] D97246: [ASTMatchers] Fix matching failure in IgnoreUnlessSpelledInSource mode

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:4358
   internal::Matcher, InnerMatcher) {
-  auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
-Node.init_end(), Finder, Builder);
-  if (MatchIt == Node.init_end())
-return false;
-  return (*MatchIt)->isWritten() || 
!Finder->isTraversalIgnoringImplicitNodes();
+  auto MatchIt = matchesFirstInPointerRangeIgnoreUnspelled(
+  InnerMatcher, Node.init_begin(), Node.init_end(), Finder, Builder);

aaron.ballman wrote:
> Since you're touching the line anyway, might as well fix the lint warning and 
> use `const auto *`.
This is iteration from a `begin()` to an `end()`. It's appropriate to use 
`auto` for an iterator type instead of `const auto *`.

You don't have to change it back now, but the request to change it in the first 
place isn't consistent. I also don't think it's ever appropriate to use `const 
auto *` or `auto *` instead of just `auto`, so make of that what you wish :).

Anyway, to completely dodge the issue you can inline it and get rid of the 
`MatchIt` altogether without changing the meaning of the code.



Comment at: clang/include/clang/ASTMatchers/ASTMatchersInternal.h:817-819
+/// Finds the first node in a pointer range that matches the given
+/// matcher. Ignores any nodes that aren't spelled in source if Finder is 
ignore
+/// them.

aaron.ballman wrote:
> njames93 wrote:
> > aaron.ballman wrote:
> > > Comment looks like it can be re-flowed to 80 cols.
> > > 
> > > "if Finder is ignore them" -> "if Finder is ignoring them"
> > > 
> > > This comment is a bit odd because I would expect the same behavior from 
> > > `matchesFirstInPointerRange` -- e.g., if the finder says "ignore unless 
> > > spelled in source", I would not expect to have to call a function that 
> > > also says to honor that, so this feels a bit fragile. I was sort of 
> > > thinking that an (optional?) parameter to `matchesFirstInPointerPair` 
> > > would be slightly better (and reduce code duplication), but that feels 
> > > similarly fragile.
> > > 
> > > Would the logic be wrong to always honor what the `Finder` says about 
> > > ignoring implicit nodes?
> > The issue is not all nodes have a nice way to say they are implicit and 
> > should be ignored.
> This compounds the problem by making the AST matchers harder to write because 
> now we're enshrining that there's two different APIs that do the same thing 
> but you have to remember which one needs to be called in what mode and for 
> which kinds of nodes.
> 
> "Go fix the AST nodes" is not a solution for this patch, but I think our 
> long-term goal should be to try to add some uniformity at the AST node level 
> so that we can eventually remove APIs like this and hopefully reduce the 
> amount of places we're doing `isa<>` checks for specific node types to try to 
> decide whether it was spelled in the source or not. Obviously, I'm not asking 
> you to do that work -- just trying to see if we have some agreement on an 
> aspirational goal.
> 
> Concretely, what do you think about an API like:
> ```
> // FIXME: This is necessary only because there's no good general way to know 
> // whether an AST node was spelled in source or not, so callers of 
> matchesFirstInPointerRange
> // need to decide whether they want to ignore implicit nodes or not. Ideally, 
> we could use the
> // Finder object only to make this decision, but we're not there quite yet.
> enum class MatchFirstPointerInRangeMode {
>   AsIs,
>   IgnoreUnlessSpelledInSource
> };
> 
> template 
> IteratorT matchesFirstInPointerRange(const MatcherT , IteratorT Start,
>  IteratorT End, ASTMatchFinder *Finder,
>  BoundNodesTreeBuilder *Builder,
>  MatchFirstPointerInRangeMode Mode = 
> MatchFirstPointerInRangeMode::AsIs);
> ```
> ```
> enum class MatchFirstPointerInRangeMode {
>   AsIs,
>   IgnoreUnlessSpelledInSource
> };
> ```

Why introduce a new enum instead of just using `clang::TraversalKind`?



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97246

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


[PATCH] D97535: [clangd] Use URIs instead of paths in the index file list

2021-02-27 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX marked an inline comment as done.
ArcsinX added inline comments.



Comment at: clang-tools-extra/clangd/index/FileIndex.cpp:279
   SymbolSlabs.push_back(FileAndSymbols.second);
+  for (const auto  : *FileAndSymbols.second) {
+if (S.Definition)

kadircet wrote:
> iterating over all the symbols here (and refs below) seems really 
> unfortunate. But looking at the previous discussions that seems to be best of 
> both worlds until we populate a file list in SymbolCollector. However, I 
> think it would be better to do the looping after releasing the lock (we 
> already have the information copied over to our snapshots).
> 
> moreover we seem to be still inserting keys of the Symbol and RefSlabs into 
> Files, but not doing that for RelationSlabs, why? (i believe we shouldn't be 
> inserting the keys at all, if we indeed want to just insert URIs and keep 
> treating the keys as opaque objects).
> However, I think it would be better to do the looping after releasing the 
> lock (we already have the information copied over to our snapshots).
Done

> we seem to be still inserting keys of the Symbol and RefSlabs into Files, but 
> not doing that for RelationSlabs
Forgot to remove these insertions, thanks, fixed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97535

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


[PATCH] D97535: [clangd] Use URIs instead of paths in the index file list

2021-02-27 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 326903.
ArcsinX added a comment.

- Do not insert the keys into the file list
- Iterate through refs and symbols to create the file list after releasing the 
lock


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97535

Files:
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/MemIndex.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/unittests/DexTests.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp

Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -229,7 +229,7 @@
   RefSlab Refs;
   auto Size = Symbols.bytes() + Refs.bytes();
   auto Data = std::make_pair(std::move(Symbols), std::move(Refs));
-  llvm::StringSet<> Files = {testPath("foo.cc"), testPath("bar.cc")};
+  llvm::StringSet<> Files = {"unittest:///foo.cc", "unittest:///bar.cc"};
   MemIndex I(std::move(Data.first), std::move(Data.second), RelationSlab(),
  std::move(Files), IndexContents::All, std::move(Data), Size);
   auto ContainsFile = I.indexedFiles();
@@ -339,21 +339,21 @@
   FileIndex DynamicIndex, StaticIndex;
   MergedIndex Merge(, );
 
-  const char *HeaderCode = "class Foo;";
+  const char *HeaderCode = "class Foo; class Bar;";
   auto HeaderSymbols = TestTU::withHeaderCode(HeaderCode).headerSymbols();
   auto Foo = findSymbol(HeaderSymbols, "Foo");
 
-  // Build static index for test.cc with Foo symbol
+  // Build static index for test.cc with Foo and Bar symbols
   TestTU Test;
   Test.HeaderCode = HeaderCode;
-  Test.Code = "class Foo {};";
+  Test.Code = "class Foo {}; class Bar {};";
   Test.Filename = "test.cc";
   auto AST = Test.build();
   StaticIndex.updateMain(testPath(Test.Filename), AST);
 
-  // Remove Foo symbol, i.e. build dynamic index for test.cc, which is empty.
-  Test.HeaderCode = "";
-  Test.Code = "";
+  // Remove Foo symbol.
+  Test.HeaderCode = "class Bar;";
+  Test.Code = "class Bar {};";
   AST = Test.build();
   DynamicIndex.updateMain(testPath(Test.Filename), AST);
 
@@ -487,7 +487,7 @@
 
   // Remove all refs for test.cc from dynamic index,
   // merged index should not return results from static index for test.cc.
-  Test.Code = "";
+  Test.Code = "int I;"; // test.cc should not be empty
   AST = Test.build();
   Dyn.updateMain(testPath(Test.Filename), AST);
 
@@ -506,7 +506,7 @@
   RefSlab DynRefs;
   auto DynSize = DynSymbols.bytes() + DynRefs.bytes();
   auto DynData = std::make_pair(std::move(DynSymbols), std::move(DynRefs));
-  llvm::StringSet<> DynFiles = {testPath("foo.cc")};
+  llvm::StringSet<> DynFiles = {"unittest:///foo.cc"};
   MemIndex DynIndex(std::move(DynData.first), std::move(DynData.second),
 RelationSlab(), std::move(DynFiles), IndexContents::Symbols,
 std::move(DynData), DynSize);
@@ -514,7 +514,7 @@
   RefSlab StaticRefs;
   auto StaticData =
   std::make_pair(std::move(StaticSymbols), std::move(StaticRefs));
-  llvm::StringSet<> StaticFiles = {testPath("foo.cc"), testPath("bar.cc")};
+  llvm::StringSet<> StaticFiles = {"unittest:///foo.cc", "unittest:///bar.cc"};
   MemIndex StaticIndex(
   std::move(StaticData.first), std::move(StaticData.second), RelationSlab(),
   std::move(StaticFiles), IndexContents::References, std::move(StaticData),
Index: clang-tools-extra/clangd/unittests/DexTests.cpp
===
--- clang-tools-extra/clangd/unittests/DexTests.cpp
+++ clang-tools-extra/clangd/unittests/DexTests.cpp
@@ -737,7 +737,7 @@
   RefSlab Refs;
   auto Size = Symbols.bytes() + Refs.bytes();
   auto Data = std::make_pair(std::move(Symbols), std::move(Refs));
-  llvm::StringSet<> Files = {testPath("foo.cc"), testPath("bar.cc")};
+  llvm::StringSet<> Files = {"unittest:///foo.cc", "unittest:///bar.cc"};
   Dex I(std::move(Data.first), std::move(Data.second), RelationSlab(),
 std::move(Files), IndexContents::All, std::move(Data), Size);
   auto ContainsFile = I.indexedFiles();
Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -316,14 +316,7 @@
 llvm::unique_function
 Dex::indexedFiles() const {
   return [this](llvm::StringRef FileURI) {
-if (Files.empty())
-  return IndexContents::None;
-auto Path = URI::resolve(FileURI, Files.begin()->first());
-if (!Path) {
-  vlog("Failed to resolve the URI {0} : {1}", FileURI, Path.takeError());
-  return IndexContents::None;
-}
-return Files.contains(*Path) ? IdxContents : IndexContents::None;
+return Files.contains(FileURI) ? IdxContents : IndexContents::None;

[PATCH] D93594: [X86] Pass to transform amx intrinsics to scalar operation.

2021-02-27 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke added inline comments.



Comment at: llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp:88
+
+template  LuoYuanke wrote:
> > pengfei wrote:
> > > Can we just use `template `? I think it also can reduce the 
> > > branch.
> > Why do we need a template instead of passing a parameter `bool IsLoad`?
> Bing thought template instantiation can avoid the condition code to turn into 
> branch instructions.
That may be arguable what benefit more. Code size saving or branch instructions 
avoiding. :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93594

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


[PATCH] D93594: [X86] Pass to transform amx intrinsics to scalar operation.

2021-02-27 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp:88
+
+template  pengfei wrote:
> > Can we just use `template `? I think it also can reduce the 
> > branch.
> Why do we need a template instead of passing a parameter `bool IsLoad`?
Bing thought template instantiation can avoid the condition code to turn into 
branch instructions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93594

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


[PATCH] D97615: [clangd] Include macro expansions in documentSymbol hierarchy

2021-02-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Before: F15668515: 2021-02-27-141552_903x356_scrot.png 

After: F15668516: 2021-02-27-141523_815x430_scrot.png 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97615

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


[PATCH] D97615: [clangd] Include macro expansions in documentSymbol hierarchy

2021-02-27 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Browsing macro-generated symbols is confusing.
On the one hand, it seems very *useful* to be able to see the summary of
symbols that were generated.
On the other hand, some macros spew a lot of confusing symbols into the
namespace and when used repeatedly (ABSL_FLAG) can create a lot of spam
that's hard to navigate.

Design constraints:

- the macro expansion tree need not align with the AST, though it often does in 
practice. We address this by defining the nesting based on the *primary* 
location of decls, rather than their ranges.
- DocumentSymbol.children[*].range should nest within DocumentSymbol.range 
(This constraint is not in LSP "breadcrumbs" breaks without it) We adjust macro 
ranges so they cover their "children", rather than just the macro expansion
- LSP does not have a "macro expansion" symbolkind, nor does it allow a symbol 
to have no kind. I've arbitrarily picked "null" as this is unlikely to conflict 
with anything useful.

This patch makes all macros and children visible for simplicity+consistency,
though in some cases it may be better to elide the macro node.
We may consider adding heuristics for this in future (e.g. when it expands
to one decl only?) but it doesn't seem clear-cut to me.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97615

Files:
  clang-tools-extra/clangd/FindSymbols.cpp
  clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp

Index: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -662,7 +662,76 @@
   WithDetail("(unnamed)";
 }
 
-TEST(DocumentSymbols, FromMacro) {
+TEST(DocumentSymbols, Macro) {
+  struct Test {
+const char *Code;
+testing::Matcher Matcher;
+  } Tests[] = {
+  {
+  R"cpp(
+// Basic macro that generates symbols.
+#define DEFINE_FLAG(X) bool FLAGS_##X; bool FLAGS_no##X
+DEFINE_FLAG(pretty);
+  )cpp",
+  AllOf(WithName("DEFINE_FLAG"), WithDetail("(pretty)"),
+Children(WithName("FLAGS_pretty"), WithName("FLAGS_nopretty"))),
+  },
+  {
+  R"cpp(
+// Hierarchy is determined by primary (name) location.
+#define ID(X) X
+namespace ID(ns) { int ID(y); }
+  )cpp",
+  AllOf(WithName("ID"), WithDetail("(ns)"),
+Children(AllOf(WithName("ns"),
+   Children(AllOf(WithName("ID"), WithDetail("(y)"),
+  Children(WithName("y"))),
+  },
+  {
+  R"cpp(
+// More typical example where macro only generates part of a decl.
+#define TEST(A, B) class A##_##B { void go(); }; void A##_##B::go()
+TEST(DocumentSymbols, Macro) { }
+  )cpp",
+  AllOf(WithName("TEST"), WithDetail("(DocumentSymbols, Macro)"),
+Children(AllOf(WithName("DocumentSymbols_Macro"),
+   Children(WithName("go"))),
+ WithName("DocumentSymbols_Macro::go"))),
+  },
+  {
+  R"cpp(
+// Nested macros.
+#define NAMESPACE(NS, BODY) namespace NS { BODY }
+NAMESPACE(a, NAMESPACE(b, int x;))
+  )cpp",
+  AllOf(
+  WithName("NAMESPACE"), WithDetail("(a, NAMESPACE(b, int x;))"),
+  Children(AllOf(
+  WithName("a"),
+  Children(AllOf(WithName("NAMESPACE"),
+ // FIXME: nested expansions not in TokenBuffer
+ WithDetail(""),
+ Children(AllOf(WithName("b"),
+Children(WithName("x"),
+  },
+  {
+  R"cpp(
+// Macro invoked from body is not exposed.
+#define INNER(X) int X
+#define OUTER(X) INNER(X)
+OUTER(foo);
+  )cpp",
+  AllOf(WithName("OUTER"), WithDetail("(foo)"),
+Children(WithName("foo"))),
+  },
+  };
+  for (const Test  : Tests) {
+auto TU = TestTU::withCode(T.Code);
+EXPECT_THAT(getSymbols(TU.build()), ElementsAre(T.Matcher)) << T.Code;
+  }
+}
+
+TEST(DocumentSymbols, RangeFromMacro) {
   TestTU TU;
   Annotations Main(R"(
 #define FF(name) \
@@ -671,9 +740,9 @@
 $expansion1[[FF]](abc);
 
 #define FF2() \
-  class Test {};
+  class Test {}
 
-$expansion2[[FF2]]();
+$expansion2parens[[$expansion2[[FF2]]()]];
 
 

[PATCH] D97614: [clang-tidy] Remove OptionError

2021-02-27 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh.
Herald added a subscriber: xazax.hun.
njames93 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The interface served a purpose, but since the ability to emit diagnostics when 
parsing configuration was added, its become mostly redundant. Emitting the 
diagnostic and removing the boilerplate is much cleaner.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D97614

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -190,6 +190,7 @@
 
 using ::testing::AllOf;
 using ::testing::ElementsAre;
+using ::testing::UnorderedElementsAre;
 
 TEST(ParseConfiguration, CollectDiags) {
   DiagCollecter Collector;
@@ -243,7 +244,6 @@
 return Options.getLocalOrGlobal(std::forward(Arguments)...);
   }
 };
-} // namespace
 
 #define CHECK_VAL(Value, Expected) \
   do { \
@@ -252,17 +252,22 @@
 EXPECT_EQ(*Item, Expected);\
   } while (false)
 
-#define CHECK_ERROR(Value, ErrorType, ExpectedMessage) \
-  do { \
-auto Item = Value; \
-ASSERT_FALSE(Item);\
-ASSERT_TRUE(Item.errorIsA());   \
-ASSERT_FALSE(llvm::handleErrors(   \
-Item.takeError(), [&](const ErrorType ) -> llvm::Error {   \
-  EXPECT_EQ(Err.message(), ExpectedMessage);   \
-  return llvm::Error::success();   \
-}));   \
-  } while (false)
+MATCHER_P(ToolDiagMessage, M, "") { return arg.Message.Message == M; }
+MATCHER_P(ToolDiagLevel, L, "") { return arg.DiagLevel == L; }
+
+} // namespace
+
+} // namespace test
+
+static constexpr auto Warning = tooling::Diagnostic::Warning;
+static constexpr auto Error = tooling::Diagnostic::Error;
+
+static void PrintTo(const ClangTidyError , ::std::ostream *OS) {
+  *OS << (Err.DiagLevel == Error ? "error: " : "warning: ")
+  << Err.Message.Message;
+}
+
+namespace test {
 
 TEST(CheckOptionsValidation, MissingOptions) {
   ClangTidyOptions Options;
@@ -273,21 +278,21 @@
, false);
   Context.setDiagnosticsEngine();
   TestCheck TestCheck();
-  CHECK_ERROR(TestCheck.getLocal("Opt"), MissingOptionError,
-  "option not found 'test.Opt'");
+  EXPECT_FALSE(TestCheck.getLocal("Opt").hasValue());
   EXPECT_EQ(TestCheck.getLocal("Opt", "Unknown"), "Unknown");
+  // Missing options aren't errors.
+  EXPECT_TRUE(DiagConsumer.take().empty());
 }
 
 TEST(CheckOptionsValidation, ValidIntOptions) {
   ClangTidyOptions Options;
   auto  = Options.CheckOptions;
-  CheckOptions["test.IntExpected1"] = "1";
-  CheckOptions["test.IntExpected2"] = "1WithMore";
-  CheckOptions["test.IntExpected3"] = "NoInt";
-  CheckOptions["GlobalIntExpected1"] = "1";
-  CheckOptions["GlobalIntExpected2"] = "NoInt";
-  CheckOptions["test.DefaultedIntInvalid"] = "NoInt";
+  CheckOptions["test.IntExpected"] = "1";
+  CheckOptions["test.IntInvalid1"] = "1WithMore";
+  CheckOptions["test.IntInvalid2"] = "NoInt";
+  CheckOptions["GlobalIntExpected"] = "1";
   CheckOptions["GlobalIntInvalid"] = "NoInt";
+  CheckOptions["test.DefaultedIntInvalid"] = "NoInt";
   CheckOptions["test.BoolITrueValue"] = "1";
   CheckOptions["test.BoolIFalseValue"] = "0";
   CheckOptions["test.BoolTrueValue"] = "true";
@@ -304,22 +309,12 @@
   Context.setDiagnosticsEngine();
   TestCheck TestCheck();
 
-#define CHECK_ERROR_INT(Name, Expected)\
-  CHECK_ERROR(Name, UnparseableIntegerOptionError, Expected)
-
-  CHECK_VAL(TestCheck.getIntLocal("IntExpected1"), 1);
-  CHECK_VAL(TestCheck.getIntGlobal("GlobalIntExpected1"), 1);
-  CHECK_ERROR_INT(TestCheck.getIntLocal("IntExpected2"),
-  "invalid configuration value '1WithMore' for option "
-  "'test.IntExpected2'; expected an integer value");
-  CHECK_ERROR_INT(TestCheck.getIntLocal("IntExpected3"),
-  "invalid configuration value 'NoInt' for option "
-  "'test.IntExpected3'; 

[PATCH] D93594: [X86] Pass to transform amx intrinsics to scalar operation.

2021-02-27 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke added inline comments.



Comment at: llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp:88
+
+template  Can we just use `template `? I think it also can reduce the 
> branch.
Why do we need a template instead of passing a parameter `bool IsLoad`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93594

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


[PATCH] D97150: [clang-tidy] Simplify suspicious memset usage check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG42ce00ec3947: [clang-tidy] Simplify suspicious memset usage 
check (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97150

Files:
  clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h


Index: clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
@@ -25,6 +25,9 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace bugprone
Index: clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
@@ -35,27 +35,24 @@
   callee(MemsetDecl),
   hasArgument(1, characterLiteral(equals(static_cast('0')))
  .bind("char-zero-fill")),
-  unless(
-  eachOf(hasArgument(0, anyOf(hasType(pointsTo(isAnyCharacter())),
-  hasType(arrayType(hasElementType(
-  isAnyCharacter()),
- isInTemplateInstantiation(,
+  unless(hasArgument(
+  0, anyOf(hasType(pointsTo(isAnyCharacter())),
+   
hasType(arrayType(hasElementType(isAnyCharacter(,
   this);
 
   // Look for memset with an integer literal in its fill_char argument.
   // Will check if it gets truncated.
-  Finder->addMatcher(callExpr(callee(MemsetDecl),
-  hasArgument(1, 
integerLiteral().bind("num-fill")),
-  unless(isInTemplateInstantiation())),
- this);
+  Finder->addMatcher(
+  callExpr(callee(MemsetDecl),
+   hasArgument(1, integerLiteral().bind("num-fill"))),
+  this);
 
   // Look for memset(x, y, 0) as that is most likely an argument swap.
   Finder->addMatcher(
   callExpr(callee(MemsetDecl),
unless(hasArgument(1, anyOf(characterLiteral(equals(
static_cast('0'))),
-   integerLiteral(,
-   unless(isInTemplateInstantiation()))
+   integerLiteral()
   .bind("call"),
   this);
 }


Index: clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
@@ -25,6 +25,9 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace bugprone
Index: clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
@@ -35,27 +35,24 @@
   callee(MemsetDecl),
   hasArgument(1, characterLiteral(equals(static_cast('0')))
  .bind("char-zero-fill")),
-  unless(
-  eachOf(hasArgument(0, anyOf(hasType(pointsTo(isAnyCharacter())),
-  hasType(arrayType(hasElementType(
-  isAnyCharacter()),
- isInTemplateInstantiation(,
+  unless(hasArgument(
+  0, anyOf(hasType(pointsTo(isAnyCharacter())),
+   hasType(arrayType(hasElementType(isAnyCharacter(,
   this);
 
   // Look for memset with an integer literal in its fill_char argument.
   // Will check if it gets truncated.
-  Finder->addMatcher(callExpr(callee(MemsetDecl),
-  hasArgument(1, integerLiteral().bind("num-fill")),
-  unless(isInTemplateInstantiation())),
- this);
+  Finder->addMatcher(
+  

[clang-tools-extra] 42ce00e - [clang-tidy] Simplify suspicious memset usage check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:17:09Z
New Revision: 42ce00ec3947de89c1cda0138fe6adfface3

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

LOG: [clang-tidy] Simplify suspicious memset usage check

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
index 37748d9fa8cc..341ba6ccc09f 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp
@@ -35,27 +35,24 @@ void 
SuspiciousMemsetUsageCheck::registerMatchers(MatchFinder *Finder) {
   callee(MemsetDecl),
   hasArgument(1, characterLiteral(equals(static_cast('0')))
  .bind("char-zero-fill")),
-  unless(
-  eachOf(hasArgument(0, anyOf(hasType(pointsTo(isAnyCharacter())),
-  hasType(arrayType(hasElementType(
-  isAnyCharacter()),
- isInTemplateInstantiation(,
+  unless(hasArgument(
+  0, anyOf(hasType(pointsTo(isAnyCharacter())),
+   
hasType(arrayType(hasElementType(isAnyCharacter(,
   this);
 
   // Look for memset with an integer literal in its fill_char argument.
   // Will check if it gets truncated.
-  Finder->addMatcher(callExpr(callee(MemsetDecl),
-  hasArgument(1, 
integerLiteral().bind("num-fill")),
-  unless(isInTemplateInstantiation())),
- this);
+  Finder->addMatcher(
+  callExpr(callee(MemsetDecl),
+   hasArgument(1, integerLiteral().bind("num-fill"))),
+  this);
 
   // Look for memset(x, y, 0) as that is most likely an argument swap.
   Finder->addMatcher(
   callExpr(callee(MemsetDecl),
unless(hasArgument(1, anyOf(characterLiteral(equals(
static_cast('0'))),
-   integerLiteral(,
-   unless(isInTemplateInstantiation()))
+   integerLiteral()
   .bind("call"),
   this);
 }

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
index 40746413485f..0a46f0620ef8 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.h
@@ -25,6 +25,9 @@ class SuspiciousMemsetUsageCheck : public ClangTidyCheck {
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace bugprone



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


[PATCH] D97153: [clang-tidy] Simplify boolean expr check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG302cc8421ee4: [clang-tidy] Simplify boolean expr check 
(authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97153

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h

Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
@@ -27,6 +27,9 @@
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   class Visitor;
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -71,10 +71,10 @@
 }
 
 internal::BindableMatcher literalOrNegatedBool(bool Value) {
-  return expr(anyOf(cxxBoolLiteral(equals(Value)),
-unaryOperator(hasUnaryOperand(ignoringParenImpCasts(
-  cxxBoolLiteral(equals(!Value,
-  hasOperatorName("!";
+  return expr(
+  anyOf(cxxBoolLiteral(equals(Value)),
+unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(!Value))),
+  hasOperatorName("!";
 }
 
 internal::Matcher returnsBool(bool Value, StringRef Id = "ignored") {
@@ -443,8 +443,7 @@
   bool Value,
   StringRef BooleanId) {
   Finder->addMatcher(
-  ifStmt(unless(isInTemplateInstantiation()),
- hasCondition(literalOrNegatedBool(Value).bind(BooleanId)))
+  ifStmt(hasCondition(literalOrNegatedBool(Value).bind(BooleanId)))
   .bind(IfStmtId),
   this);
 }
@@ -453,8 +452,7 @@
   bool Value,
   StringRef TernaryId) {
   Finder->addMatcher(
-  conditionalOperator(unless(isInTemplateInstantiation()),
-  hasTrueExpression(literalOrNegatedBool(Value)),
+  conditionalOperator(hasTrueExpression(literalOrNegatedBool(Value)),
   hasFalseExpression(literalOrNegatedBool(!Value)))
   .bind(TernaryId),
   this);
@@ -463,14 +461,12 @@
 void SimplifyBooleanExprCheck::matchIfReturnsBool(MatchFinder *Finder,
   bool Value, StringRef Id) {
   if (ChainedConditionalReturn)
-Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
-  hasThen(returnsBool(Value, ThenLiteralId)),
+Finder->addMatcher(ifStmt(hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
this);
   else
-Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
-  unless(hasParent(ifStmt())),
+Finder->addMatcher(ifStmt(unless(hasParent(ifStmt())),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
@@ -495,16 +491,12 @@
   auto Else = anyOf(SimpleElse, compoundStmt(statementCountIs(1),
  hasAnySubstatement(SimpleElse)));
   if (ChainedConditionalAssignment)
-Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
-  hasThen(Then), hasElse(Else))
-   .bind(Id),
-   this);
+Finder->addMatcher(ifStmt(hasThen(Then), hasElse(Else)).bind(Id), this);
   else
-Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
-  unless(hasParent(ifStmt())), hasThen(Then),
-  hasElse(Else))
-   .bind(Id),
-   this);
+Finder->addMatcher(
+ifStmt(unless(hasParent(ifStmt())), hasThen(Then), hasElse(Else))
+.bind(Id),
+this);
 }
 
 void SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
@@ -512,11 +504,9 @@
   StringRef Id) {
   Finder->addMatcher(
   compoundStmt(
-   

[PATCH] D97152: [clang-tidy] Simplify special member functions check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb67287088664: [clang-tidy] Simplify special member functions 
check (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97152

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h


Index: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
@@ -32,7 +32,9 @@
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
   void onEndOfTranslationUnit() override;
-
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
   enum class SpecialMemberFunctionKind : uint8_t {
 Destructor,
 DefaultDestructor,
Index: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
===
--- 
clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
+++ 
clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
@@ -40,18 +40,13 @@
 void SpecialMemberFunctionsCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   cxxRecordDecl(
-  eachOf(
-  has(cxxDestructorDecl(unless(isImplicit())).bind("dtor")),
-  has(cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))
-  .bind("copy-ctor")),
-  has(cxxMethodDecl(isCopyAssignmentOperator(),
-unless(isImplicit()))
-  .bind("copy-assign")),
-  has(cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))
-  .bind("move-ctor")),
-  has(cxxMethodDecl(isMoveAssignmentOperator(),
-unless(isImplicit()))
-  .bind("move-assign"
+  eachOf(has(cxxDestructorDecl().bind("dtor")),
+ 
has(cxxConstructorDecl(isCopyConstructor()).bind("copy-ctor")),
+ has(cxxMethodDecl(isCopyAssignmentOperator())
+ .bind("copy-assign")),
+ 
has(cxxConstructorDecl(isMoveConstructor()).bind("move-ctor")),
+ has(cxxMethodDecl(isMoveAssignmentOperator())
+ .bind("move-assign"
   .bind("class-def"),
   this);
 }


Index: clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
@@ -32,7 +32,9 @@
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
   void onEndOfTranslationUnit() override;
-
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
   enum class SpecialMemberFunctionKind : uint8_t {
 Destructor,
 DefaultDestructor,
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
@@ -40,18 +40,13 @@
 void SpecialMemberFunctionsCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   cxxRecordDecl(
-  eachOf(
-  has(cxxDestructorDecl(unless(isImplicit())).bind("dtor")),
-  has(cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))
-  .bind("copy-ctor")),
-  has(cxxMethodDecl(isCopyAssignmentOperator(),
-unless(isImplicit()))
-  .bind("copy-assign")),
-  has(cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))
-  .bind("move-ctor")),
-  has(cxxMethodDecl(isMoveAssignmentOperator(),
-unless(isImplicit()))
-  .bind("move-assign"
+  eachOf(has(cxxDestructorDecl().bind("dtor")),
+ has(cxxConstructorDecl(isCopyConstructor()).bind("copy-ctor")),
+ has(cxxMethodDecl(isCopyAssignmentOperator())
+ .bind("copy-assign")),
+ 

[PATCH] D97151: [clang-tidy] Simplify redundant branch condition check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa5feefa3c72e: [clang-tidy] Simplify redundant branch 
condition check (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97151

Files:
  clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h


Index: clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
@@ -26,6 +26,9 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace bugprone
Index: clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
@@ -48,23 +48,23 @@
   .bind(CondVarStr);
   Finder->addMatcher(
   ifStmt(
-  hasCondition(ignoringParenImpCasts(anyOf(
+  hasCondition(anyOf(
   declRefExpr(hasDeclaration(ImmutableVar)).bind(OuterIfVar1Str),
-  binaryOperator(hasOperatorName("&&"),
- hasEitherOperand(ignoringParenImpCasts(
- declRefExpr(hasDeclaration(ImmutableVar))
- .bind(OuterIfVar2Str))),
+  binaryOperator(
+  hasOperatorName("&&"),
+  hasEitherOperand(declRefExpr(hasDeclaration(ImmutableVar))
+   .bind(OuterIfVar2Str),
   hasThen(hasDescendant(
-  ifStmt(hasCondition(ignoringParenImpCasts(
- anyOf(declRefExpr(hasDeclaration(varDecl(
-equalsBoundNode(CondVarStr
-.bind(InnerIfVar1Str),
-   binaryOperator(
-   hasAnyOperatorName("&&", "||"),
-   hasEitherOperand(ignoringParenImpCasts(
-   declRefExpr(hasDeclaration(varDecl(
+  ifStmt(hasCondition(anyOf(
+ declRefExpr(hasDeclaration(
+ varDecl(equalsBoundNode(CondVarStr
+ .bind(InnerIfVar1Str),
+ binaryOperator(
+ hasAnyOperatorName("&&", "||"),
+ hasEitherOperand(
+ declRefExpr(hasDeclaration(varDecl(
  equalsBoundNode(CondVarStr
- .bind(InnerIfVar2Str
+ .bind(InnerIfVar2Str))
   .bind(InnerIfStr))),
   forFunction(functionDecl().bind(FuncStr)))
   .bind(OuterIfStr),


Index: clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
@@ -26,6 +26,9 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace bugprone
Index: clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
@@ -48,23 +48,23 @@
   .bind(CondVarStr);
   Finder->addMatcher(
   ifStmt(
-  hasCondition(ignoringParenImpCasts(anyOf(
+  hasCondition(anyOf(
   declRefExpr(hasDeclaration(ImmutableVar)).bind(OuterIfVar1Str),
-  binaryOperator(hasOperatorName("&&"),
- hasEitherOperand(ignoringParenImpCasts(
- declRefExpr(hasDeclaration(ImmutableVar))
- .bind(OuterIfVar2Str))),
+  binaryOperator(
+   

[PATCH] D97149: [clang-tidy] Simplify suspicious enum usage check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdf42f9950d5e: [clang-tidy] Simplify suspicious enum usage 
check (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97149

Files:
  clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h


Index: clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
@@ -25,6 +25,9 @@
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
   void storeOptions(ClangTidyOptions::OptionMap ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   void checkSuspiciousBitmaskUsage(const Expr*, const EnumDecl*);
Index: clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
@@ -118,30 +118,28 @@
 
 void SuspiciousEnumUsageCheck::registerMatchers(MatchFinder *Finder) {
   const auto EnumExpr = [](StringRef RefName, StringRef DeclName) {
-return expr(ignoringImpCasts(expr().bind(RefName)),
-ignoringImpCasts(hasType(enumDecl().bind(DeclName;
+return expr(hasType(enumDecl().bind(DeclName))).bind(RefName);
   };
 
   Finder->addMatcher(
-  binaryOperator(hasOperatorName("|"), hasLHS(EnumExpr("", "enumDecl")),
- hasRHS(expr(EnumExpr("", "otherEnumDecl"),
- ignoringImpCasts(hasType(enumDecl(
- unless(equalsBoundNode("enumDecl"
+  binaryOperator(
+  hasOperatorName("|"), hasLHS(hasType(enumDecl().bind("enumDecl"))),
+  hasRHS(hasType(enumDecl(unless(equalsBoundNode("enumDecl")))
+ .bind("otherEnumDecl"
   .bind("diffEnumOp"),
   this);
 
   Finder->addMatcher(
   binaryOperator(hasAnyOperatorName("+", "|"),
  hasLHS(EnumExpr("lhsExpr", "enumDecl")),
- hasRHS(expr(EnumExpr("rhsExpr", ""),
- ignoringImpCasts(hasType(
- 
enumDecl(equalsBoundNode("enumDecl"))),
+ 
hasRHS(expr(hasType(enumDecl(equalsBoundNode("enumDecl"
+.bind("rhsExpr"))),
   this);
 
   Finder->addMatcher(
   binaryOperator(
   hasAnyOperatorName("+", "|"),
-  hasOperands(expr(hasType(isInteger()), unless(EnumExpr("", ""))),
+  hasOperands(expr(hasType(isInteger()), unless(hasType(enumDecl(,
   EnumExpr("enumExpr", "enumDecl"))),
   this);
 


Index: clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
@@ -25,6 +25,9 @@
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
   void storeOptions(ClangTidyOptions::OptionMap ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   void checkSuspiciousBitmaskUsage(const Expr*, const EnumDecl*);
Index: clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
@@ -118,30 +118,28 @@
 
 void SuspiciousEnumUsageCheck::registerMatchers(MatchFinder *Finder) {
   const auto EnumExpr = [](StringRef RefName, StringRef DeclName) {
-return expr(ignoringImpCasts(expr().bind(RefName)),
-ignoringImpCasts(hasType(enumDecl().bind(DeclName;
+return expr(hasType(enumDecl().bind(DeclName))).bind(RefName);
   };
 
   Finder->addMatcher(
-  binaryOperator(hasOperatorName("|"), hasLHS(EnumExpr("", "enumDecl")),
- hasRHS(expr(EnumExpr("", "otherEnumDecl"),
- ignoringImpCasts(hasType(enumDecl(
- unless(equalsBoundNode("enumDecl"
+  binaryOperator(
+  hasOperatorName("|"), hasLHS(hasType(enumDecl().bind("enumDecl"))),
+  

[PATCH] D97147: [clang-tidy] Simplify redundant member init check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG35763baf9aa9: [clang-tidy] Simplify redundant member init 
check (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97147

Files:
  clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
  clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h


Index: clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
===
--- clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
+++ clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
@@ -32,6 +32,9 @@
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   bool IgnoreBaseInCopyConstructors;
Index: clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
@@ -26,26 +26,21 @@
 }
 
 void RedundantMemberInitCheck::registerMatchers(MatchFinder *Finder) {
-  auto Construct =
-  cxxConstructExpr(
-  hasDeclaration(cxxConstructorDecl(hasParent(
-  cxxRecordDecl(unless(isTriviallyDefaultConstructible()))
-  .bind("construct");
-
   Finder->addMatcher(
-  traverse(
-  TK_AsIs,
-  cxxConstructorDecl(
-  unless(isDelegatingConstructor()),
-  ofClass(unless(
-  anyOf(isUnion(), ast_matchers::isTemplateInstantiation(,
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  isWritten(), 
withInitializer(ignoringImplicit(Construct)),
-  unless(forField(hasType(isConstQualified(,
-  unless(forField(hasParent(recordDecl(isUnion())
-  .bind("init")))
-  .bind("constructor")),
+  cxxConstructorDecl(
+  unless(isDelegatingConstructor()), ofClass(unless(isUnion())),
+  forEachConstructorInitializer(
+  cxxCtorInitializer(
+  withInitializer(
+  cxxConstructExpr(
+  hasDeclaration(
+  cxxConstructorDecl(ofClass(cxxRecordDecl(
+  
unless(isTriviallyDefaultConstructible()))
+  .bind("construct")),
+  unless(forField(hasType(isConstQualified(,
+  unless(forField(hasParent(recordDecl(isUnion())
+  .bind("init")))
+  .bind("constructor"),
   this);
 }
 


Index: clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
===
--- clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
+++ clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
@@ -32,6 +32,9 @@
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   bool IgnoreBaseInCopyConstructors;
Index: clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
@@ -26,26 +26,21 @@
 }
 
 void RedundantMemberInitCheck::registerMatchers(MatchFinder *Finder) {
-  auto Construct =
-  cxxConstructExpr(
-  hasDeclaration(cxxConstructorDecl(hasParent(
-  cxxRecordDecl(unless(isTriviallyDefaultConstructible()))
-  .bind("construct");
-
   Finder->addMatcher(
-  traverse(
-  TK_AsIs,
-  cxxConstructorDecl(
-  unless(isDelegatingConstructor()),
-  ofClass(unless(
-  anyOf(isUnion(), ast_matchers::isTemplateInstantiation(,
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  isWritten(), withInitializer(ignoringImplicit(Construct)),
-  unless(forField(hasType(isConstQualified(,
-  unless(forField(hasParent(recordDecl(isUnion())
-  .bind("init")))
-  

[clang-tools-extra] 302cc84 - [clang-tidy] Simplify boolean expr check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:13:24Z
New Revision: 302cc8421ee4ac1cf910dd6cd3306c6eae8d0d3e

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

LOG: [clang-tidy] Simplify boolean expr check

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

Added: 


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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
index d450df55c6a0..4ea8ef65d3f8 100644
--- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -71,10 +71,10 @@ const Expr *getBoolLiteral(const MatchFinder::MatchResult 
,
 }
 
 internal::BindableMatcher literalOrNegatedBool(bool Value) {
-  return expr(anyOf(cxxBoolLiteral(equals(Value)),
-unaryOperator(hasUnaryOperand(ignoringParenImpCasts(
-  cxxBoolLiteral(equals(!Value,
-  hasOperatorName("!";
+  return expr(
+  anyOf(cxxBoolLiteral(equals(Value)),
+unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(!Value))),
+  hasOperatorName("!";
 }
 
 internal::Matcher returnsBool(bool Value, StringRef Id = "ignored") {
@@ -443,8 +443,7 @@ void 
SimplifyBooleanExprCheck::matchBoolCondition(MatchFinder *Finder,
   bool Value,
   StringRef BooleanId) {
   Finder->addMatcher(
-  ifStmt(unless(isInTemplateInstantiation()),
- hasCondition(literalOrNegatedBool(Value).bind(BooleanId)))
+  ifStmt(hasCondition(literalOrNegatedBool(Value).bind(BooleanId)))
   .bind(IfStmtId),
   this);
 }
@@ -453,8 +452,7 @@ void 
SimplifyBooleanExprCheck::matchTernaryResult(MatchFinder *Finder,
   bool Value,
   StringRef TernaryId) {
   Finder->addMatcher(
-  conditionalOperator(unless(isInTemplateInstantiation()),
-  hasTrueExpression(literalOrNegatedBool(Value)),
+  conditionalOperator(hasTrueExpression(literalOrNegatedBool(Value)),
   hasFalseExpression(literalOrNegatedBool(!Value)))
   .bind(TernaryId),
   this);
@@ -463,14 +461,12 @@ void 
SimplifyBooleanExprCheck::matchTernaryResult(MatchFinder *Finder,
 void SimplifyBooleanExprCheck::matchIfReturnsBool(MatchFinder *Finder,
   bool Value, StringRef Id) {
   if (ChainedConditionalReturn)
-Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
-  hasThen(returnsBool(Value, ThenLiteralId)),
+Finder->addMatcher(ifStmt(hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
this);
   else
-Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
-  unless(hasParent(ifStmt())),
+Finder->addMatcher(ifStmt(unless(hasParent(ifStmt())),
   hasThen(returnsBool(Value, ThenLiteralId)),
   hasElse(returnsBool(!Value)))
.bind(Id),
@@ -495,16 +491,12 @@ void 
SimplifyBooleanExprCheck::matchIfAssignsBool(MatchFinder *Finder,
   auto Else = anyOf(SimpleElse, compoundStmt(statementCountIs(1),
  hasAnySubstatement(SimpleElse)));
   if (ChainedConditionalAssignment)
-Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
-  hasThen(Then), hasElse(Else))
-   .bind(Id),
-   this);
+Finder->addMatcher(ifStmt(hasThen(Then), hasElse(Else)).bind(Id), this);
   else
-Finder->addMatcher(ifStmt(unless(isInTemplateInstantiation()),
-  unless(hasParent(ifStmt())), hasThen(Then),
-  hasElse(Else))
-   .bind(Id),
-   this);
+Finder->addMatcher(
+ifStmt(unless(hasParent(ifStmt())), hasThen(Then), hasElse(Else))
+.bind(Id),
+this);
 }
 
 void SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
@@ -512,11 +504,9 @@ void 
SimplifyBooleanExprCheck::matchCompoundIfReturnsBool(MatchFinder *Finder,
   StringRef Id) {
   

[clang-tools-extra] b672870 - [clang-tidy] Simplify special member functions check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:13:24Z
New Revision: b672870886643a99dd74f3114995f2a091eab813

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

LOG: [clang-tidy] Simplify special member functions check

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
index c4684d41f78f..823075f6ff18 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp
@@ -40,18 +40,13 @@ void SpecialMemberFunctionsCheck::storeOptions(
 void SpecialMemberFunctionsCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   cxxRecordDecl(
-  eachOf(
-  has(cxxDestructorDecl(unless(isImplicit())).bind("dtor")),
-  has(cxxConstructorDecl(isCopyConstructor(), unless(isImplicit()))
-  .bind("copy-ctor")),
-  has(cxxMethodDecl(isCopyAssignmentOperator(),
-unless(isImplicit()))
-  .bind("copy-assign")),
-  has(cxxConstructorDecl(isMoveConstructor(), unless(isImplicit()))
-  .bind("move-ctor")),
-  has(cxxMethodDecl(isMoveAssignmentOperator(),
-unless(isImplicit()))
-  .bind("move-assign"
+  eachOf(has(cxxDestructorDecl().bind("dtor")),
+ 
has(cxxConstructorDecl(isCopyConstructor()).bind("copy-ctor")),
+ has(cxxMethodDecl(isCopyAssignmentOperator())
+ .bind("copy-assign")),
+ 
has(cxxConstructorDecl(isMoveConstructor()).bind("move-ctor")),
+ has(cxxMethodDecl(isMoveAssignmentOperator())
+ .bind("move-assign"
   .bind("class-def"),
   this);
 }

diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
index f232a0a09fbb..ada765df3c4c 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h
@@ -32,7 +32,9 @@ class SpecialMemberFunctionsCheck : public ClangTidyCheck {
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
   void onEndOfTranslationUnit() override;
-
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
   enum class SpecialMemberFunctionKind : uint8_t {
 Destructor,
 DefaultDestructor,



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


[PATCH] D97145: [clang-tidy] Simplify default member init check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9ba557cc0370: [clang-tidy] Simplify default member init 
check (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97145

Files:
  clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h


Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
@@ -30,6 +30,9 @@
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   void checkDefaultInit(const ast_matchers::MatchFinder::MatchResult ,
Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -207,14 +207,13 @@
 declRefExpr(to(enumConstantDecl(;
 
   auto Init =
-  anyOf(initListExpr(anyOf(
-allOf(initCountIs(1), hasInit(0, ignoringImplicit(InitBase))),
-initCountIs(0))),
+  anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)),
+   initCountIs(0))),
 InitBase);
 
   Finder->addMatcher(
   cxxConstructorDecl(
-  isDefaultConstructor(), unless(isInstantiated()),
+  isDefaultConstructor(),
   forEachConstructorInitializer(
   cxxCtorInitializer(
   forField(unless(anyOf(getLangOpts().CPlusPlus20
@@ -222,18 +221,15 @@
 : isBitField(),
 hasInClassInitializer(anything()),
 hasParent(recordDecl(isUnion()),
-  isWritten(), withInitializer(ignoringImplicit(Init)))
+  withInitializer(Init))
   .bind("default"))),
   this);
 
   Finder->addMatcher(
-  cxxConstructorDecl(
-  unless(ast_matchers::isTemplateInstantiation()),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(forField(hasInClassInitializer(anything())),
- isWritten(),
- withInitializer(ignoringImplicit(Init)))
-  .bind("existing"))),
+  cxxConstructorDecl(forEachConstructorInitializer(
+  cxxCtorInitializer(forField(hasInClassInitializer(anything())),
+ withInitializer(Init))
+  .bind("existing"))),
   this);
 }
 


Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
@@ -30,6 +30,9 @@
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   void checkDefaultInit(const ast_matchers::MatchFinder::MatchResult ,
Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -207,14 +207,13 @@
 declRefExpr(to(enumConstantDecl(;
 
   auto Init =
-  anyOf(initListExpr(anyOf(
-allOf(initCountIs(1), hasInit(0, ignoringImplicit(InitBase))),
-initCountIs(0))),
+  anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)),
+   initCountIs(0))),
 InitBase);
 
   Finder->addMatcher(
   cxxConstructorDecl(
-  isDefaultConstructor(), unless(isInstantiated()),
+  isDefaultConstructor(),
   forEachConstructorInitializer(
   cxxCtorInitializer(
   forField(unless(anyOf(getLangOpts().CPlusPlus20
@@ -222,18 +221,15 @@
 : isBitField(),
 

[clang-tools-extra] a5feefa - [clang-tidy] Simplify redundant branch condition check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:13:23Z
New Revision: a5feefa3c72e67ea94b50addf8f0975dae9a9696

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

LOG: [clang-tidy] Simplify redundant branch condition check

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
index 2b0d9630527b..3998e2bc1de0 100644
--- a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp
@@ -48,23 +48,23 @@ void 
RedundantBranchConditionCheck::registerMatchers(MatchFinder *Finder) {
   .bind(CondVarStr);
   Finder->addMatcher(
   ifStmt(
-  hasCondition(ignoringParenImpCasts(anyOf(
+  hasCondition(anyOf(
   declRefExpr(hasDeclaration(ImmutableVar)).bind(OuterIfVar1Str),
-  binaryOperator(hasOperatorName("&&"),
- hasEitherOperand(ignoringParenImpCasts(
- declRefExpr(hasDeclaration(ImmutableVar))
- .bind(OuterIfVar2Str))),
+  binaryOperator(
+  hasOperatorName("&&"),
+  hasEitherOperand(declRefExpr(hasDeclaration(ImmutableVar))
+   .bind(OuterIfVar2Str),
   hasThen(hasDescendant(
-  ifStmt(hasCondition(ignoringParenImpCasts(
- anyOf(declRefExpr(hasDeclaration(varDecl(
-equalsBoundNode(CondVarStr
-.bind(InnerIfVar1Str),
-   binaryOperator(
-   hasAnyOperatorName("&&", "||"),
-   hasEitherOperand(ignoringParenImpCasts(
-   declRefExpr(hasDeclaration(varDecl(
+  ifStmt(hasCondition(anyOf(
+ declRefExpr(hasDeclaration(
+ varDecl(equalsBoundNode(CondVarStr
+ .bind(InnerIfVar1Str),
+ binaryOperator(
+ hasAnyOperatorName("&&", "||"),
+ hasEitherOperand(
+ declRefExpr(hasDeclaration(varDecl(
  equalsBoundNode(CondVarStr
- .bind(InnerIfVar2Str
+ .bind(InnerIfVar2Str))
   .bind(InnerIfStr))),
   forFunction(functionDecl().bind(FuncStr)))
   .bind(OuterIfStr),

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
index 7b38d59a0121..a086b269e64d 100644
--- a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.h
@@ -26,6 +26,9 @@ class RedundantBranchConditionCheck : public ClangTidyCheck {
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace bugprone



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


[clang-tools-extra] df42f99 - [clang-tidy] Simplify suspicious enum usage check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:11:45Z
New Revision: df42f9950d5e4aaea2038581188ed9d786d09213

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

LOG: [clang-tidy] Simplify suspicious enum usage check

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
index 3faa28c0158a..73068610a53b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.cpp
@@ -118,30 +118,28 @@ void 
SuspiciousEnumUsageCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 
 void SuspiciousEnumUsageCheck::registerMatchers(MatchFinder *Finder) {
   const auto EnumExpr = [](StringRef RefName, StringRef DeclName) {
-return expr(ignoringImpCasts(expr().bind(RefName)),
-ignoringImpCasts(hasType(enumDecl().bind(DeclName;
+return expr(hasType(enumDecl().bind(DeclName))).bind(RefName);
   };
 
   Finder->addMatcher(
-  binaryOperator(hasOperatorName("|"), hasLHS(EnumExpr("", "enumDecl")),
- hasRHS(expr(EnumExpr("", "otherEnumDecl"),
- ignoringImpCasts(hasType(enumDecl(
- unless(equalsBoundNode("enumDecl"
+  binaryOperator(
+  hasOperatorName("|"), hasLHS(hasType(enumDecl().bind("enumDecl"))),
+  hasRHS(hasType(enumDecl(unless(equalsBoundNode("enumDecl")))
+ .bind("otherEnumDecl"
   .bind("
diff EnumOp"),
   this);
 
   Finder->addMatcher(
   binaryOperator(hasAnyOperatorName("+", "|"),
  hasLHS(EnumExpr("lhsExpr", "enumDecl")),
- hasRHS(expr(EnumExpr("rhsExpr", ""),
- ignoringImpCasts(hasType(
- 
enumDecl(equalsBoundNode("enumDecl"))),
+ 
hasRHS(expr(hasType(enumDecl(equalsBoundNode("enumDecl"
+.bind("rhsExpr"))),
   this);
 
   Finder->addMatcher(
   binaryOperator(
   hasAnyOperatorName("+", "|"),
-  hasOperands(expr(hasType(isInteger()), unless(EnumExpr("", ""))),
+  hasOperands(expr(hasType(isInteger()), unless(hasType(enumDecl(,
   EnumExpr("enumExpr", "enumDecl"))),
   this);
 

diff  --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
index f05f3e1c54e0..7541810cdb1b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h
@@ -25,6 +25,9 @@ class SuspiciousEnumUsageCheck : public ClangTidyCheck {
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
   void storeOptions(ClangTidyOptions::OptionMap ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   void checkSuspiciousBitmaskUsage(const Expr*, const EnumDecl*);



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


[PATCH] D97144: [clang-tidy] Simplify shrink to fit check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG296c6e85c19b: [clang-tidy] Simplify shrink to fit check 
(authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97144

Files:
  clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h


Index: clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
+++ clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
@@ -30,6 +30,9 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
@@ -21,31 +21,24 @@
 void ShrinkToFitCheck::registerMatchers(MatchFinder *Finder) {
   // Swap as a function need not to be considered, because rvalue can not
   // be bound to a non-const reference.
-  const auto ShrinkableAsMember =
-  memberExpr(member(valueDecl().bind("ContainerDecl")));
-  const auto ShrinkableAsDecl =
-  declRefExpr(hasDeclaration(valueDecl().bind("ContainerDecl")));
-  const auto CopyCtorCall = cxxConstructExpr(hasArgument(
-  0, anyOf(ShrinkableAsMember, ShrinkableAsDecl,
-   unaryOperator(has(ignoringParenImpCasts(ShrinkableAsMember))),
-   unaryOperator(has(ignoringParenImpCasts(ShrinkableAsDecl));
-  const auto SwapParam =
-  expr(anyOf(memberExpr(member(equalsBoundNode("ContainerDecl"))),
- declRefExpr(hasDeclaration(equalsBoundNode("ContainerDecl"))),
- unaryOperator(has(ignoringParenImpCasts(
- memberExpr(member(equalsBoundNode("ContainerDecl")),
- unaryOperator(has(ignoringParenImpCasts(declRefExpr(
- hasDeclaration(equalsBoundNode("ContainerDecl";
+  const auto ShrinkableExpr = mapAnyOf(memberExpr, declRefExpr);
+  const auto Shrinkable =
+  ShrinkableExpr.with(hasDeclaration(valueDecl().bind("ContainerDecl")));
+  const auto BoundShrinkable = ShrinkableExpr.with(
+  hasDeclaration(valueDecl(equalsBoundNode("ContainerDecl";
 
   Finder->addMatcher(
   cxxMemberCallExpr(
-  on(hasType(hasCanonicalType(hasDeclaration(namedDecl(
-  hasAnyName("std::basic_string", "std::deque", 
"std::vector")),
   callee(cxxMethodDecl(hasName("swap"))),
-  has(ignoringParenImpCasts(
-  memberExpr(traverse(TK_AsIs, hasDescendant(CopyCtorCall),
-  hasArgument(0, SwapParam.bind("ContainerToShrink")),
-  unless(isInTemplateInstantiation()))
+  hasArgument(
+  0, anyOf(Shrinkable, 
unaryOperator(hasUnaryOperand(Shrinkable,
+  on(cxxConstructExpr(hasArgument(
+  0,
+  expr(anyOf(BoundShrinkable,
+ unaryOperator(hasUnaryOperand(BoundShrinkable))),
+   
hasType(hasCanonicalType(hasDeclaration(namedDecl(hasAnyName(
+   "std::basic_string", "std::deque", "std::vector"))
+  .bind("ContainerToShrink")
   .bind("CopyAndSwapTrick"),
   this);
 }


Index: clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
+++ clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
@@ -30,6 +30,9 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
@@ -21,31 +21,24 @@
 void ShrinkToFitCheck::registerMatchers(MatchFinder *Finder) {
   // Swap as a function need not to be considered, because rvalue can not
   // be bound to a non-const reference.
-  const auto ShrinkableAsMember =
-  memberExpr(member(valueDecl().bind("ContainerDecl")));
-  const auto ShrinkableAsDecl =
-  declRefExpr(hasDeclaration(valueDecl().bind("ContainerDecl")));
-  const auto CopyCtorCall = 

[clang-tools-extra] 35763ba - [clang-tidy] Simplify redundant member init check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:11:44Z
New Revision: 35763baf9aa927c2e8fc0a4af484c51391ecc30c

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

LOG: [clang-tidy] Simplify redundant member init check

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
index df6e57bfb9ed..0af9a0478ab9 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.cpp
@@ -26,26 +26,21 @@ void 
RedundantMemberInitCheck::storeOptions(ClangTidyOptions::OptionMap ) {
 }
 
 void RedundantMemberInitCheck::registerMatchers(MatchFinder *Finder) {
-  auto Construct =
-  cxxConstructExpr(
-  hasDeclaration(cxxConstructorDecl(hasParent(
-  cxxRecordDecl(unless(isTriviallyDefaultConstructible()))
-  .bind("construct");
-
   Finder->addMatcher(
-  traverse(
-  TK_AsIs,
-  cxxConstructorDecl(
-  unless(isDelegatingConstructor()),
-  ofClass(unless(
-  anyOf(isUnion(), ast_matchers::isTemplateInstantiation(,
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  isWritten(), 
withInitializer(ignoringImplicit(Construct)),
-  unless(forField(hasType(isConstQualified(,
-  unless(forField(hasParent(recordDecl(isUnion())
-  .bind("init")))
-  .bind("constructor")),
+  cxxConstructorDecl(
+  unless(isDelegatingConstructor()), ofClass(unless(isUnion())),
+  forEachConstructorInitializer(
+  cxxCtorInitializer(
+  withInitializer(
+  cxxConstructExpr(
+  hasDeclaration(
+  cxxConstructorDecl(ofClass(cxxRecordDecl(
+  
unless(isTriviallyDefaultConstructible()))
+  .bind("construct")),
+  unless(forField(hasType(isConstQualified(,
+  unless(forField(hasParent(recordDecl(isUnion())
+  .bind("init")))
+  .bind("constructor"),
   this);
 }
 

diff  --git 
a/clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h 
b/clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
index 9454278ca244..6d40a94f59ca 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/RedundantMemberInitCheck.h
@@ -32,6 +32,9 @@ class RedundantMemberInitCheck : public ClangTidyCheck {
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   bool IgnoreBaseInCopyConstructors;



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


[clang-tools-extra] 9ba557c - [clang-tidy] Simplify default member init check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:11:43Z
New Revision: 9ba557cc0370ee5fa93dca04a20bd2b05bf19f45

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

LOG: [clang-tidy] Simplify default member init check

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

Added: 


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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
index 9ce56d953c9e..6e7e37236b19 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -207,14 +207,13 @@ void 
UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
 declRefExpr(to(enumConstantDecl(;
 
   auto Init =
-  anyOf(initListExpr(anyOf(
-allOf(initCountIs(1), hasInit(0, ignoringImplicit(InitBase))),
-initCountIs(0))),
+  anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)),
+   initCountIs(0))),
 InitBase);
 
   Finder->addMatcher(
   cxxConstructorDecl(
-  isDefaultConstructor(), unless(isInstantiated()),
+  isDefaultConstructor(),
   forEachConstructorInitializer(
   cxxCtorInitializer(
   forField(unless(anyOf(getLangOpts().CPlusPlus20
@@ -222,18 +221,15 @@ void 
UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
 : isBitField(),
 hasInClassInitializer(anything()),
 hasParent(recordDecl(isUnion()),
-  isWritten(), withInitializer(ignoringImplicit(Init)))
+  withInitializer(Init))
   .bind("default"))),
   this);
 
   Finder->addMatcher(
-  cxxConstructorDecl(
-  unless(ast_matchers::isTemplateInstantiation()),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(forField(hasInClassInitializer(anything())),
- isWritten(),
- withInitializer(ignoringImplicit(Init)))
-  .bind("existing"))),
+  cxxConstructorDecl(forEachConstructorInitializer(
+  cxxCtorInitializer(forField(hasInClassInitializer(anything())),
+ withInitializer(Init))
+  .bind("existing"))),
   this);
 }
 

diff  --git 
a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h 
b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
index fc26eb55c83a..1da57d8cd594 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.h
@@ -30,6 +30,9 @@ class UseDefaultMemberInitCheck : public ClangTidyCheck {
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   void checkDefaultInit(const ast_matchers::MatchFinder::MatchResult ,



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


[clang-tools-extra] 296c6e8 - [clang-tidy] Simplify shrink to fit check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:11:42Z
New Revision: 296c6e85c19b7fc224109fe43af2fd9ed1d3d510

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

LOG: [clang-tidy] Simplify shrink to fit check

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

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
index 7911a56a9a75..411f04eb5ee9 100644
--- a/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp
@@ -21,31 +21,24 @@ namespace modernize {
 void ShrinkToFitCheck::registerMatchers(MatchFinder *Finder) {
   // Swap as a function need not to be considered, because rvalue can not
   // be bound to a non-const reference.
-  const auto ShrinkableAsMember =
-  memberExpr(member(valueDecl().bind("ContainerDecl")));
-  const auto ShrinkableAsDecl =
-  declRefExpr(hasDeclaration(valueDecl().bind("ContainerDecl")));
-  const auto CopyCtorCall = cxxConstructExpr(hasArgument(
-  0, anyOf(ShrinkableAsMember, ShrinkableAsDecl,
-   unaryOperator(has(ignoringParenImpCasts(ShrinkableAsMember))),
-   unaryOperator(has(ignoringParenImpCasts(ShrinkableAsDecl));
-  const auto SwapParam =
-  expr(anyOf(memberExpr(member(equalsBoundNode("ContainerDecl"))),
- declRefExpr(hasDeclaration(equalsBoundNode("ContainerDecl"))),
- unaryOperator(has(ignoringParenImpCasts(
- memberExpr(member(equalsBoundNode("ContainerDecl")),
- unaryOperator(has(ignoringParenImpCasts(declRefExpr(
- hasDeclaration(equalsBoundNode("ContainerDecl";
+  const auto ShrinkableExpr = mapAnyOf(memberExpr, declRefExpr);
+  const auto Shrinkable =
+  ShrinkableExpr.with(hasDeclaration(valueDecl().bind("ContainerDecl")));
+  const auto BoundShrinkable = ShrinkableExpr.with(
+  hasDeclaration(valueDecl(equalsBoundNode("ContainerDecl";
 
   Finder->addMatcher(
   cxxMemberCallExpr(
-  on(hasType(hasCanonicalType(hasDeclaration(namedDecl(
-  hasAnyName("std::basic_string", "std::deque", 
"std::vector")),
   callee(cxxMethodDecl(hasName("swap"))),
-  has(ignoringParenImpCasts(
-  memberExpr(traverse(TK_AsIs, hasDescendant(CopyCtorCall),
-  hasArgument(0, SwapParam.bind("ContainerToShrink")),
-  unless(isInTemplateInstantiation()))
+  hasArgument(
+  0, anyOf(Shrinkable, 
unaryOperator(hasUnaryOperand(Shrinkable,
+  on(cxxConstructExpr(hasArgument(
+  0,
+  expr(anyOf(BoundShrinkable,
+ unaryOperator(hasUnaryOperand(BoundShrinkable))),
+   
hasType(hasCanonicalType(hasDeclaration(namedDecl(hasAnyName(
+   "std::basic_string", "std::deque", "std::vector"))
+  .bind("ContainerToShrink")
   .bind("CopyAndSwapTrick"),
   this);
 }

diff  --git a/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h 
b/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
index 336485572bb8..6ea0522d6571 100644
--- a/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.h
@@ -30,6 +30,9 @@ class ShrinkToFitCheck : public ClangTidyCheck {
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace modernize



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


[PATCH] D96222: Handle uninstantiated templates in redundant get check

2021-02-27 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa5e3d87f66a1: [clang-tidy] Handle uninstantiated templates 
in redundant get check (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96222

Files:
  clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
  clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp
@@ -168,6 +168,42 @@
   // CHECK-FIXES: if (NULL == x);
 }
 
+template 
+void testTemplate() {
+  T().get()->Do();
+}
+
+template 
+void testTemplate2() {
+  std::unique_ptr up;
+  up.get()->Do();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant get() call
+  // CHECK-FIXES: up->Do();
+}
+
+void instantiate() {
+  testTemplate();
+  testTemplate>();
+  testTemplate();
+
+  testTemplate2();
+}
+
+struct S {
+
+  void foo() {
+m_up.get()->Do();
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant get() call
+// CHECK-FIXES: m_up->Do();
+m_bp.get()->Do();
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant get() call
+// CHECK-FIXES: m_bp->Do();
+  }
+
+  std::unique_ptr m_up;
+  BarPtr m_bp;
+};
+
 #define MACRO(p) p.get()
 
 void Negative() {
Index: clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
===
--- clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
+++ clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
@@ -35,6 +35,9 @@
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   const bool IgnoreMacros;
Index: clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
@@ -18,15 +18,30 @@
 
 namespace {
 internal::Matcher callToGet(const internal::Matcher ) {
-  return cxxMemberCallExpr(
- on(expr(anyOf(hasType(OnClass),
-   hasType(qualType(
-   pointsTo(decl(OnClass).bind("ptr_to_ptr"))
-.bind("smart_pointer")),
- unless(callee(memberExpr(hasObjectExpression(cxxThisExpr(),
- callee(cxxMethodDecl(
- hasName("get"),
- returns(qualType(pointsTo(type().bind("getType")))
+  return expr(
+ anyOf(cxxMemberCallExpr(
+   on(expr(anyOf(hasType(OnClass),
+ hasType(qualType(pointsTo(
+ decl(OnClass).bind("ptr_to_ptr"))
+  .bind("smart_pointer")),
+   unless(callee(
+   memberExpr(hasObjectExpression(cxxThisExpr(),
+   callee(cxxMethodDecl(hasName("get"),
+returns(qualType(pointsTo(
+type().bind("getType"))),
+   cxxDependentScopeMemberExpr(
+   hasMemberName("get"),
+   hasObjectExpression(
+   expr(hasType(qualType(hasCanonicalType(
+templateSpecializationType(hasDeclaration(
+classTemplateDecl(has(cxxRecordDecl(
+OnClass,
+hasMethod(cxxMethodDecl(
+hasName("get"),
+returns(qualType(
+pointsTo(type().bind(
+"getType")))
+   .bind("smart_pointer")
   .bind("redundant_get");
 }
 
@@ -47,10 +62,9 @@
   const auto Smartptr = anyOf(knownSmartptr(), QuacksLikeASmartptr);
 
   // Catch 'ptr.get()->Foo()'
-  Finder->addMatcher(
-  memberExpr(expr().bind("memberExpr"), isArrow(),
- 

[clang-tools-extra] a5e3d87 - [clang-tidy] Handle uninstantiated templates in redundant get check

2021-02-27 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-27T12:08:41Z
New Revision: a5e3d87f66a1b833594f121fbd8c7334df5a1eeb

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

LOG: [clang-tidy] Handle uninstantiated templates in redundant get check

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h

clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
index bf78acdc5f68..e663f055f30d 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
@@ -18,15 +18,30 @@ namespace readability {
 
 namespace {
 internal::Matcher callToGet(const internal::Matcher ) {
-  return cxxMemberCallExpr(
- on(expr(anyOf(hasType(OnClass),
-   hasType(qualType(
-   pointsTo(decl(OnClass).bind("ptr_to_ptr"))
-.bind("smart_pointer")),
- unless(callee(memberExpr(hasObjectExpression(cxxThisExpr(),
- callee(cxxMethodDecl(
- hasName("get"),
- returns(qualType(pointsTo(type().bind("getType")))
+  return expr(
+ anyOf(cxxMemberCallExpr(
+   on(expr(anyOf(hasType(OnClass),
+ hasType(qualType(pointsTo(
+ decl(OnClass).bind("ptr_to_ptr"))
+  .bind("smart_pointer")),
+   unless(callee(
+   memberExpr(hasObjectExpression(cxxThisExpr(),
+   callee(cxxMethodDecl(hasName("get"),
+returns(qualType(pointsTo(
+type().bind("getType"))),
+   cxxDependentScopeMemberExpr(
+   hasMemberName("get"),
+   hasObjectExpression(
+   expr(hasType(qualType(hasCanonicalType(
+templateSpecializationType(hasDeclaration(
+classTemplateDecl(has(cxxRecordDecl(
+OnClass,
+hasMethod(cxxMethodDecl(
+hasName("get"),
+returns(qualType(
+pointsTo(type().bind(
+
"getType")))
+   .bind("smart_pointer")
   .bind("redundant_get");
 }
 
@@ -47,10 +62,9 @@ void registerMatchersForGetArrowStart(MatchFinder *Finder,
   const auto Smartptr = anyOf(knownSmartptr(), QuacksLikeASmartptr);
 
   // Catch 'ptr.get()->Foo()'
-  Finder->addMatcher(
-  memberExpr(expr().bind("memberExpr"), isArrow(),
- hasObjectExpression(ignoringImpCasts(callToGet(Smartptr,
-  Callback);
+  Finder->addMatcher(memberExpr(expr().bind("memberExpr"), isArrow(),
+hasObjectExpression(callToGet(Smartptr))),
+ Callback);
 
   // Catch '*ptr.get()' or '*ptr->get()'
   Finder->addMatcher(
@@ -58,8 +72,8 @@ void registerMatchersForGetArrowStart(MatchFinder *Finder,
   Callback);
 
   // Catch '!ptr.get()'
-  const auto CallToGetAsBool = ignoringParenImpCasts(callToGet(
-  recordDecl(Smartptr, has(cxxConversionDecl(returns(booleanType()));
+  const auto CallToGetAsBool = callToGet(
+  recordDecl(Smartptr, has(cxxConversionDecl(returns(booleanType());
   Finder->addMatcher(
   unaryOperator(hasOperatorName("!"), hasUnaryOperand(CallToGetAsBool)),
   Callback);
@@ -70,6 +84,10 @@ void registerMatchersForGetArrowStart(MatchFinder *Finder,
   // Catch 'ptr.get() ? X : Y'
   Finder->addMatcher(conditionalOperator(hasCondition(CallToGetAsBool)),
  Callback);
+
+  Finder->addMatcher(cxxDependentScopeMemberExpr(hasObjectExpression(
+ callExpr(has(callToGet(Smartptr))).bind("obj"))),
+ Callback);
 }
 
 void registerMatchersForGetEquals(MatchFinder *Finder,
@@ -82,9 +100,8 @@ void registerMatchersForGetEquals(MatchFinder *Finder,
   // Matches against nullptr.
   Finder->addMatcher(
   binaryOperator(hasAnyOperatorName("==", "!="),
- 

[PATCH] D97563: [clang-tidy] Enable modernize-concat-nested-namespaces also on headers

2021-02-27 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 326888.
DmitryPolukhin added a comment.

Use -DAG checks to make test stable


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97563

Files:
  clang-tools-extra/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h
  
clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-concat-nested-namespaces.cpp
@@ -1,4 +1,13 @@
-// RUN: %check_clang_tidy -std=c++17-or-later %s modernize-concat-nested-namespaces %t
+// RUN: cp %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++17 %s modernize-concat-nested-namespaces %t -- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h -check-prefix=CHECK-FIXES
+// Restore header file and re-run with c++20:
+// RUN: cp %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h %T/modernize-concat-nested-namespaces.h
+// RUN: %check_clang_tidy -std=c++20 %s modernize-concat-nested-namespaces %t -- -header-filter=".*" -- -I %T
+// RUN: FileCheck -input-file=%T/modernize-concat-nested-namespaces.h %S/Inputs/modernize-concat-nested-namespaces/modernize-concat-nested-namespaces.h -check-prefix=CHECK-FIXES
+
+#include "modernize-concat-nested-namespaces.h"
+// CHECK-MESSAGES-DAG: modernize-concat-nested-namespaces.h:1:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
 
 namespace n1 {}
 
@@ -27,7 +36,7 @@
 
 namespace n9 {
 namespace n10 {
-// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-MESSAGES-DAG: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
 // CHECK-FIXES: namespace n9::n10
 void t();
 } // namespace n10
@@ -36,7 +45,7 @@
 
 namespace n11 {
 namespace n12 {
-// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-MESSAGES-DAG: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
 // CHECK-FIXES: namespace n11::n12
 namespace n13 {
 void t();
@@ -60,7 +69,7 @@
 namespace n18 {
 namespace n19 {
 namespace n20 {
-// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-MESSAGES-DAG: :[[@LINE-3]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
 // CHECK-FIXES: namespace n18::n19::n20
 void t();
 } // namespace n20
@@ -83,7 +92,7 @@
 namespace {
 namespace n24 {
 namespace n25 {
-// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-MESSAGES-DAG: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
 // CHECK-FIXES: namespace n24::n25
 void t();
 } // namespace n25
@@ -95,7 +104,7 @@
 namespace n26::n27 {
 namespace n28 {
 namespace n29::n30 {
-// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-MESSAGES-DAG: :[[@LINE-3]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
 // CHECK-FIXES: namespace n26::n27::n28::n29::n30
 void t() {}
 } // namespace n29::n30
@@ -105,14 +114,14 @@
 
 namespace n31 {
 namespace n32 {}
-// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-MESSAGES-DAG: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
 } // namespace n31
 // CHECK-FIXES-EMPTY
 
 namespace n33 {
 namespace n34 {
 namespace n35 {}
-// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-MESSAGES-DAG: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
 } // namespace n34
 // CHECK-FIXES-EMPTY
 namespace n36 {
@@ -127,7 +136,7 @@
 #define IEXIST
 namespace n39 {
 namespace n40 {
-// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-MESSAGES-DAG: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated 

[PATCH] D84924: [clang-tidy] Added command line option `fix-notes`

2021-02-27 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp:186
-  // Emit a fix and a fix description of the check;
-  diag(Context.FoundUsingDecl->getLocation(),
-   /*Description=*/"remove the using", DiagnosticIDs::Note)

aaron.ballman wrote:
> Should this change be a separate patch?
It's either modify the check to put the fix in the warning, or modify the test 
so that fix notes is specified. 



Comment at: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp:500
+  // --fix-errors and --fix-notes imply --fix.
+  FixBehaviour Behaviour = FixNotes ? FB_FixNotes
+   : (Fix || FixErrors) ? FB_Fix

aaron.ballman wrote:
> Might as well fix this clang-format warning.
I think this is a discrepancy with the clang format in using (truck) and the 
pre merge. Mine isn't complaining about format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84924

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


[PATCH] D97362: [clang][parser] Allow attributes in explicit template instantiations

2021-02-27 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 326882.
tbaeder added a comment.

You are right of course. I changed the diff to allow GNU-style attributes and 
reject everything else.

This is a bit hairy because `[[]]` is an empty attribute list but the 
`SourceRange` is still valid. We don't know if the source range was for `[[]]` 
or `__attribute__(())` though. I opted for simply rejecting the empty GNU-style 
attribute list anyway.


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

https://reviews.llvm.org/D97362

Files:
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/test/Parser/cxx0x-attributes.cpp


Index: clang/test/Parser/cxx0x-attributes.cpp
===
--- clang/test/Parser/cxx0x-attributes.cpp
+++ clang/test/Parser/cxx0x-attributes.cpp
@@ -179,6 +179,7 @@
 struct [[]] Template t; // expected-error {{an attribute list cannot 
appear here}}
 struct [[]] ::template Template u; // expected-error {{an attribute list 
cannot appear here}}
 template struct [[]] Template; // expected-error {{an attribute list 
cannot appear here}}
+template struct __attribute__((pure)) Template; // We still allow 
GNU-style attributes here
 template <> struct [[]] Template;
 
 enum [[]] E1 {};
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -1824,7 +1824,10 @@
 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation 
&&
 TUK == Sema::TUK_Declaration) {
   // This is an explicit instantiation of a class template.
-  ProhibitAttributes(attrs);
+
+  // Allow only GNU attributes here.
+  if (!attrs.hasOnlyGNUAttributes())
+ProhibitAttributes(attrs);
 
   TagOrTempResult = Actions.ActOnExplicitInstantiation(
   getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
Index: clang/include/clang/Parse/Parser.h
===
--- clang/include/clang/Parse/Parser.h
+++ clang/include/clang/Parse/Parser.h
@@ -1581,6 +1581,19 @@
   Range = SourceRange();
 }
 
+/// Returns whether all attributes are GNU attributes.
+bool hasOnlyGNUAttributes() const {
+  for (const ParsedAttr  : *this) {
+if (A.getSyntax() != ParsedAttr::Syntax::AS_GNU)
+  return false;
+  }
+
+  // If the attr list is empty, but the range is still set, we did parse
+  // some attributes. Return false in this case, even though we might've
+  // parsed [[]].
+  return Range.isInvalid();
+}
+
 SourceRange Range;
   };
   struct ParsedAttributesViewWithRange : ParsedAttributesView {


Index: clang/test/Parser/cxx0x-attributes.cpp
===
--- clang/test/Parser/cxx0x-attributes.cpp
+++ clang/test/Parser/cxx0x-attributes.cpp
@@ -179,6 +179,7 @@
 struct [[]] Template t; // expected-error {{an attribute list cannot appear here}}
 struct [[]] ::template Template u; // expected-error {{an attribute list cannot appear here}}
 template struct [[]] Template; // expected-error {{an attribute list cannot appear here}}
+template struct __attribute__((pure)) Template; // We still allow GNU-style attributes here
 template <> struct [[]] Template;
 
 enum [[]] E1 {};
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -1824,7 +1824,10 @@
 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
 TUK == Sema::TUK_Declaration) {
   // This is an explicit instantiation of a class template.
-  ProhibitAttributes(attrs);
+
+  // Allow only GNU attributes here.
+  if (!attrs.hasOnlyGNUAttributes())
+ProhibitAttributes(attrs);
 
   TagOrTempResult = Actions.ActOnExplicitInstantiation(
   getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
Index: clang/include/clang/Parse/Parser.h
===
--- clang/include/clang/Parse/Parser.h
+++ clang/include/clang/Parse/Parser.h
@@ -1581,6 +1581,19 @@
   Range = SourceRange();
 }
 
+/// Returns whether all attributes are GNU attributes.
+bool hasOnlyGNUAttributes() const {
+  for (const ParsedAttr  : *this) {
+if (A.getSyntax() != ParsedAttr::Syntax::AS_GNU)
+  return false;
+  }
+
+  // If the attr list is empty, but the range is still set, we did parse
+  // some attributes. Return false in this case, even though we might've
+  // parsed [[]].
+  return Range.isInvalid();
+}
+
 SourceRange Range;
   };
   struct ParsedAttributesViewWithRange : ParsedAttributesView {
___
cfe-commits mailing list