[clang] be5c7c5 - Widen `name` stencil to support `TypeLoc` nodes.

2021-05-13 Thread Stephen Kelly via cfe-commits

Author: Weston Carvalho
Date: 2021-05-13T23:23:12+01:00
New Revision: be5c7c5d8230428f024bd656beb48ef8462985ff

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

LOG: Widen `name` stencil to support `TypeLoc` nodes.

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

Added: 


Modified: 
clang/include/clang/Tooling/Transformer/RangeSelector.h
clang/lib/Tooling/Transformer/RangeSelector.cpp
clang/unittests/Tooling/RangeSelectorTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/Transformer/RangeSelector.h 
b/clang/include/clang/Tooling/Transformer/RangeSelector.h
index f17fb8c7b5c69..8ff31f7a03428 100644
--- a/clang/include/clang/Tooling/Transformer/RangeSelector.h
+++ b/clang/include/clang/Tooling/Transformer/RangeSelector.h
@@ -73,9 +73,9 @@ RangeSelector statement(std::string ID);
 /// binding in the match result.
 RangeSelector member(std::string ID);
 
-/// Given a node with a "name", (like \c NamedDecl, \c DeclRefExpr or \c
-/// CxxCtorInitializer) selects the name's token.  Only selects the final
-/// identifier of a qualified name, but not any qualifiers or template
+/// Given a node with a "name", (like \c NamedDecl, \c DeclRefExpr, \c
+/// CxxCtorInitializer, and \c TypeLoc) selects the name's token.  Only selects
+/// the final identifier of a qualified name, but not any qualifiers or 
template
 /// arguments.  For example, for `::foo::bar::baz` and `::foo::bar::baz`,
 /// it selects only `baz`.
 ///

diff  --git a/clang/lib/Tooling/Transformer/RangeSelector.cpp 
b/clang/lib/Tooling/Transformer/RangeSelector.cpp
index 0f3138db218af..753e89e0e1f33 100644
--- a/clang/lib/Tooling/Transformer/RangeSelector.cpp
+++ b/clang/lib/Tooling/Transformer/RangeSelector.cpp
@@ -8,6 +8,7 @@
 
 #include "clang/Tooling/Transformer/RangeSelector.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/Lexer.h"
@@ -228,8 +229,16 @@ RangeSelector transformer::name(std::string ID) {
   SourceLocation L = I->getMemberLocation();
   return CharSourceRange::getTokenRange(L, L);
 }
+if (const auto *T = Node.get()) {
+  TypeLoc Loc = *T;
+  auto ET = Loc.getAs();
+  if (!ET.isNull()) {
+Loc = ET.getNamedTypeLoc();
+  }
+  return CharSourceRange::getTokenRange(Loc.getSourceRange());
+}
 return typeError(ID, Node.getNodeKind(),
- "DeclRefExpr, NamedDecl, CXXCtorInitializer");
+ "DeclRefExpr, NamedDecl, CXXCtorInitializer, TypeLoc");
   };
 }
 

diff  --git a/clang/unittests/Tooling/RangeSelectorTest.cpp 
b/clang/unittests/Tooling/RangeSelectorTest.cpp
index 0dded6963ee1b..a7fea004c3d3b 100644
--- a/clang/unittests/Tooling/RangeSelectorTest.cpp
+++ b/clang/unittests/Tooling/RangeSelectorTest.cpp
@@ -457,6 +457,35 @@ TEST(RangeSelectorTest, NameOpCtorInitializer) {
   EXPECT_THAT_EXPECTED(select(name(Init), Match), HasValue("field"));
 }
 
+TEST(RangeSelectorTest, NameOpTypeLoc) {
+  StringRef Code = R"cc(
+namespace ns {
+struct Foo {
+  Foo();
+  Foo(int);
+  Foo(int, int);
+};
+}  // namespace ns
+
+ns::Foo a;
+auto b = ns::Foo(3);
+auto c = ns::Foo(1, 2);
+  )cc";
+  const char *CtorTy = "ctor_ty";
+  // Matches declaration of `a`
+  TestMatch MatchA = matchCode(
+  Code, varDecl(hasName("a"), hasTypeLoc(typeLoc().bind(CtorTy;
+  EXPECT_THAT_EXPECTED(select(name(CtorTy), MatchA), HasValue("Foo"));
+  // Matches call of Foo(int)
+  TestMatch MatchB = matchCode(
+  Code, cxxFunctionalCastExpr(hasTypeLoc(typeLoc().bind(CtorTy;
+  EXPECT_THAT_EXPECTED(select(name(CtorTy), MatchB), HasValue("Foo"));
+  // Matches call of Foo(int, int)
+  TestMatch MatchC = matchCode(
+  Code, cxxTemporaryObjectExpr(hasTypeLoc(typeLoc().bind(CtorTy;
+  EXPECT_THAT_EXPECTED(select(name(CtorTy), MatchC), HasValue("Foo"));
+}
+
 TEST(RangeSelectorTest, NameOpErrors) {
   EXPECT_THAT_EXPECTED(selectFromTrivial(name("unbound_id")),
Failed(withUnboundNodeMessage()));



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


[clang] 1f65f42 - Make `hasTypeLoc` matcher support more node types.

2021-05-07 Thread Stephen Kelly via cfe-commits

Author: Weston Carvalho
Date: 2021-05-08T00:35:22+01:00
New Revision: 1f65f42dd37ab6a950d3ec110e3efca0ace1b615

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

LOG: Make `hasTypeLoc` matcher support more node types.

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

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/include/clang/ASTMatchers/ASTMatchersInternal.h
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index ab36402e4bca5..6647c4a902950 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -6137,6 +6137,34 @@ AST Traversal Matchers
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1BlockDecl.html;>BlockDeclhasTypeLocMatcherhttps://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html;>TypeLoc
 Inner
+Matches if the type 
location of a node matches the inner matcher.
+
+Examples:
+  int x;
+declaratorDecl(hasTypeLoc(loc(asString("int"
+  matches int x
+
+auto x = int(3);
+cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"
+  matches int(3)
+
+struct Foo { Foo(int, int); };
+auto x = Foo(1, 2);
+cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"
+  matches Foo(1, 2)
+
+Usable as: Matcherhttps://clang.llvm.org/doxygen/classclang_1_1BlockDecl.html;>BlockDecl,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html;>CXXBaseSpecifier,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html;>CXXCtorInitializer,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXFunctionalCastExpr.html;>CXXFunctionalCastExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXNewExpr.html;>CXXNewExpr,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXTemporaryObjectExpr.html;>CXXTemporaryObjectExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXUnresolvedConstructExpr.html;>CXXUnresolvedConstructExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ClassTemplateSpecializationDecl.html;>ClassTemplateSpecializationDecl,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CompoundLiteralExpr.html;>CompoundLiteralExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1DeclaratorDecl.html;>DeclaratorDecl,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ExplicitCastExpr.html;>ExplicitCastExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ObjCPropertyDecl.html;>ObjCPropertyDecl,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1TemplateArgumentLoc.html;>TemplateArgumentLoc,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1TypedefNameDecl.html;>TypedefNameDecl
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html;>BlockPointerTypepointeeMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Type.html;>Type
 Narrows PointerType (and 
similar) matchers to those where the
 pointee matches a given matcher.
@@ -6153,6 +6181,34 @@ AST Traversal Matchers
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html;>CXXBaseSpecifierhasTypeLocMatcherhttps://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html;>TypeLoc
 Inner
+Matches if the type 
location of a node matches the inner matcher.
+
+Examples:
+  int x;
+declaratorDecl(hasTypeLoc(loc(asString("int"
+  matches int x
+
+auto x = int(3);
+cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"
+  matches int(3)
+
+struct Foo { Foo(int, int); };
+auto x = Foo(1, 2);
+cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"
+  matches Foo(1, 2)
+
+Usable as: Matcherhttps://clang.llvm.org/doxygen/classclang_1_1BlockDecl.html;>BlockDecl,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html;>CXXBaseSpecifier,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html;>CXXCtorInitializer,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXFunctionalCastExpr.html;>CXXFunctionalCastExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXNewExpr.html;>CXXNewExpr,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXTemporaryObjectExpr.html;>CXXTemporaryObjectExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXUnresolvedConstructExpr.html;>CXXUnresolvedConstructExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ClassTemplateSpecializationDecl.html;>ClassTemplateSpecializationDecl,
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CompoundLiteralExpr.html;>CompoundLiteralExpr,
+  Matcherhttps://clang.llvm.org/doxygen/classclang_1_1DeclaratorDecl.html;>DeclaratorDecl,
 

[clang] 0ad4948 - NFC: Move TypeList implementation up the file

2021-05-07 Thread Stephen Kelly via cfe-commits

Author: Weston Carvalho
Date: 2021-05-08T00:35:13+01:00
New Revision: 0ad494838b8576de14144776490faa710fa2a099

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

LOG: NFC: Move TypeList implementation up the file

This will make it possible for more code to use it.

Added: 


Modified: 
clang/include/clang/ASTMatchers/ASTMatchersInternal.h

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h 
b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
index e8f427bafa257..8d346a6b9315a 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -83,6 +83,37 @@ class BoundNodes;
 
 namespace internal {
 
+/// A type-list implementation.
+///
+/// A "linked list" of types, accessible by using the ::head and ::tail
+/// typedefs.
+template  struct TypeList {}; // Empty sentinel type list.
+
+template  struct TypeList {
+  /// The first type on the list.
+  using head = T1;
+
+  /// A sublist with the tail. ie everything but the head.
+  ///
+  /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
+  /// end of the list.
+  using tail = TypeList;
+};
+
+/// The empty type list.
+using EmptyTypeList = TypeList<>;
+
+/// Helper meta-function to determine if some type \c T is present or
+///   a parent type in the list.
+template  struct TypeListContainsSuperOf {
+  static const bool value =
+  std::is_base_of::value ||
+  TypeListContainsSuperOf::value;
+};
+template  struct TypeListContainsSuperOf {
+  static const bool value = false;
+};
+
 /// Variadic function object.
 ///
 /// Most of the functions below that use VariadicFunction could be implemented
@@ -1120,39 +1151,6 @@ struct IsBaseType {
 template 
 const bool IsBaseType::value;
 
-/// A type-list implementation.
-///
-/// A "linked list" of types, accessible by using the ::head and ::tail
-/// typedefs.
-template  struct TypeList {}; // Empty sentinel type list.
-
-template  struct TypeList {
-  /// The first type on the list.
-  using head = T1;
-
-  /// A sublist with the tail. ie everything but the head.
-  ///
-  /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
-  /// end of the list.
-  using tail = TypeList;
-};
-
-/// The empty type list.
-using EmptyTypeList = TypeList<>;
-
-/// Helper meta-function to determine if some type \c T is present or
-///   a parent type in the list.
-template 
-struct TypeListContainsSuperOf {
-  static const bool value =
-  std::is_base_of::value ||
-  TypeListContainsSuperOf::value;
-};
-template 
-struct TypeListContainsSuperOf {
-  static const bool value = false;
-};
-
 /// A "type list" that contains all types.
 ///
 /// Useful for matchers like \c anything and \c unless.



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


[clang] 50b523c - [AST] Fix DeclarationNameInfo introspection

2021-04-26 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-26T18:49:13+01:00
New Revision: 50b523cb2ceee4ca7279b4ce22ddb0d0b05df313

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

LOG: [AST] Fix DeclarationNameInfo introspection

Some AST classes return `const DeclarationNameInfo &` instead of
returning by value (eg CXXDependentScopeMemberExpr).

Added: 


Modified: 
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index 0aeb3a7703f7..0a7fb9b52f23 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -225,6 +225,9 @@ void ASTSrcLocProcessor::run(const MatchFinder::MatchResult 
) {
   CaptureMethods("class clang::NestedNameSpecifierLoc", ASTClass, Result);
   CD.DeclNameInfos =
   CaptureMethods("struct clang::DeclarationNameInfo", ASTClass, Result);
+  auto DI = CaptureMethods("const struct clang::DeclarationNameInfo &",
+   ASTClass, Result);
+  CD.DeclNameInfos.insert(CD.DeclNameInfos.end(), DI.begin(), DI.end());
 
   if (const auto *DerivedFrom =
   Result.Nodes.getNodeAs("derivedFrom")) {

diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index 521520c9a7c7..d4f626bfeb74 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -1456,6 +1456,72 @@ 
getNamedTypeInfo()->getTypeLoc().getAs().getNameLoc()),
   STRING_LOCATION_PAIR((), getSourceRange(;
 }
 
+TEST(Introspection, SourceLocations_DeclarationNameInfo_CRef) {
+  if (!NodeIntrospection::hasIntrospectionSupport())
+return;
+
+  auto AST = buildASTFromCodeWithArgs(
+  R"cpp(
+template
+struct MyContainer
+{
+template 
+void pushBack();
+};
+
+template
+void foo()
+{
+MyContainer mc;
+mc.template pushBack();
+}
+)cpp",
+  {"-fno-delayed-template-parsing"}, "foo.cpp", "clang-tool",
+  std::make_shared());
+
+  auto  = AST->getASTContext();
+  auto  = *Ctx.getTranslationUnitDecl();
+
+  auto BoundNodes = ast_matchers::match(
+  
decl(hasDescendant(cxxDependentScopeMemberExpr(hasMemberName("pushBack")).bind("member"))),
 TU,
+  Ctx);
+
+  EXPECT_EQ(BoundNodes.size(), 1u);
+
+  const auto *Member = 
BoundNodes[0].getNodeAs("member");
+  auto Result = NodeIntrospection::GetLocations(Member);
+
+  auto ExpectedLocations =
+  FormatExpected(Result.LocationAccessors);
+
+  llvm::sort(ExpectedLocations);
+
+  EXPECT_EQ(
+  llvm::makeArrayRef(ExpectedLocations),
+  (ArrayRef>{
+STRING_LOCATION_STDPAIR(Member, getBeginLoc()),
+STRING_LOCATION_STDPAIR(Member, getEndLoc()),
+STRING_LOCATION_STDPAIR(Member, getExprLoc()),
+STRING_LOCATION_STDPAIR(Member, getLAngleLoc()),
+STRING_LOCATION_STDPAIR(Member, getMemberLoc()),
+STRING_LOCATION_STDPAIR(Member, getMemberNameInfo().getBeginLoc()),
+STRING_LOCATION_STDPAIR(Member, getMemberNameInfo().getEndLoc()),
+STRING_LOCATION_STDPAIR(Member, getMemberNameInfo().getLoc()),
+STRING_LOCATION_STDPAIR(Member, getOperatorLoc()),
+STRING_LOCATION_STDPAIR(Member, getRAngleLoc()),
+STRING_LOCATION_STDPAIR(Member, getTemplateKeywordLoc())
+}));
+
+  auto ExpectedRanges = FormatExpected(Result.RangeAccessors);
+
+  EXPECT_THAT(
+  ExpectedRanges,
+  UnorderedElementsAre(
+  STRING_LOCATION_PAIR(Member, getMemberNameInfo().getSourceRange()),
+  STRING_LOCATION_PAIR(Member, getSourceRange())
+  ));
+}
+
 TEST(Introspection, SourceLocations_DeclarationNameInfo_ConvOp) {
   if (!NodeIntrospection::hasIntrospectionSupport())
 return;



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


[clang-tools-extra] 8d018c7 - Add srcloc output to clang-query

2021-04-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-25T12:12:04+01:00
New Revision: 8d018c79ee5f14e1433b8cbb02dd89d0941516ff

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

LOG: Add srcloc output to clang-query

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

Added: 


Modified: 
clang-tools-extra/clang-query/CMakeLists.txt
clang-tools-extra/clang-query/Query.cpp
clang-tools-extra/clang-query/Query.h
clang-tools-extra/clang-query/QueryParser.cpp
clang-tools-extra/clang-query/QuerySession.h
clang-tools-extra/unittests/clang-query/QueryParserTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-query/CMakeLists.txt 
b/clang-tools-extra/clang-query/CMakeLists.txt
index 043d26147a7f..8355ef0aba5e 100644
--- a/clang-tools-extra/clang-query/CMakeLists.txt
+++ b/clang-tools-extra/clang-query/CMakeLists.txt
@@ -19,6 +19,7 @@ clang_target_link_libraries(clangQuery
   clangBasic
   clangDynamicASTMatchers
   clangFrontend
+  clangTooling
   clangSerialization
   )
 

diff  --git a/clang-tools-extra/clang-query/Query.cpp 
b/clang-tools-extra/clang-query/Query.cpp
index 5cf24dbb58a7..2c169b1f9a7f 100644
--- a/clang-tools-extra/clang-query/Query.cpp
+++ b/clang-tools-extra/clang-query/Query.cpp
@@ -12,6 +12,7 @@
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/TextDiagnostic.h"
+#include "clang/Tooling/NodeIntrospection.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace clang::ast_matchers;
@@ -66,6 +67,8 @@ bool HelpQuery::run(llvm::raw_ostream , QuerySession ) 
const {
 "Diagnostic location for bound nodes.\n"
 "  detailed-ast  "
 "Detailed AST output for bound nodes.\n"
+"  srcloc"
+"Source locations and ranges for bound nodes.\n"
 "  dump  "
 "Detailed AST output for bound nodes (alias of detailed-ast).\n\n";
   return true;
@@ -86,6 +89,90 @@ struct CollectBoundNodes : MatchFinder::MatchCallback {
   }
 };
 
+void dumpLocations(llvm::raw_ostream , DynTypedNode Node, ASTContext ,
+   const DiagnosticsEngine , SourceManager const ) {
+  auto Locs = clang::tooling::NodeIntrospection::GetLocations(Node);
+
+  auto PrintLocations = [](llvm::raw_ostream , auto Iter, auto End) {
+auto CommonEntry = Iter->first;
+auto Scout = Iter;
+SmallVector LocationStrings;
+while (Scout->first == CommonEntry) {
+  LocationStrings.push_back(
+  tooling::LocationCallFormatterCpp::format(*Iter->second));
+  if (Scout == End)
+break;
+  ++Scout;
+  if (Scout->first == CommonEntry)
+++Iter;
+}
+llvm::sort(LocationStrings);
+for (auto  : LocationStrings) {
+  OS << " * \"" << LS << "\"\n";
+}
+return Iter;
+  };
+
+  TextDiagnostic TD(OS, Ctx.getLangOpts(), ());
+
+  for (auto Iter = Locs.LocationAccessors.begin();
+   Iter != Locs.LocationAccessors.end(); ++Iter) {
+if (!Iter->first.isValid())
+  continue;
+
+TD.emitDiagnostic(FullSourceLoc(Iter->first, SM), DiagnosticsEngine::Note,
+  "source locations here", None, None);
+
+Iter = PrintLocations(OS, Iter, Locs.LocationAccessors.end());
+OS << '\n';
+  }
+
+  for (auto Iter = Locs.RangeAccessors.begin();
+   Iter != Locs.RangeAccessors.end(); ++Iter) {
+
+if (!Iter->first.getBegin().isValid())
+  continue;
+
+if (SM.getPresumedLineNumber(Iter->first.getBegin()) !=
+SM.getPresumedLineNumber(Iter->first.getEnd()))
+  continue;
+
+TD.emitDiagnostic(FullSourceLoc(Iter->first.getBegin(), SM),
+  DiagnosticsEngine::Note,
+  "source ranges here " + Iter->first.printToString(SM),
+  CharSourceRange::getTokenRange(Iter->first), None);
+
+Iter = PrintLocations(OS, Iter, Locs.RangeAccessors.end());
+  }
+  for (auto Iter = Locs.RangeAccessors.begin();
+   Iter != Locs.RangeAccessors.end(); ++Iter) {
+
+if (!Iter->first.getBegin().isValid())
+  continue;
+
+if (SM.getPresumedLineNumber(Iter->first.getBegin()) ==
+SM.getPresumedLineNumber(Iter->first.getEnd()))
+  continue;
+
+TD.emitDiagnostic(
+FullSourceLoc(Iter->first.getBegin(), SM), DiagnosticsEngine::Note,
+"source range " + Iter->first.printToString(SM) + " starting here...",
+CharSourceRange::getTokenRange(Iter->first), None);
+
+auto ColNum = SM.getPresumedColumnNumber(Iter->first.getEnd());
+auto LastLineLoc = Iter->first.getEnd().getLocWithOffset(-(ColNum - 1));
+
+TD.emitDiagnostic(FullSourceLoc(Iter->first.getEnd(), SM),
+  DiagnosticsEngine::Note, "... ending here",
+ 

[clang] a9676fe - [AST] Add DeclarationNameInfo to node introspection

2021-04-25 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-25T12:12:03+01:00
New Revision: a9676febb99d54289117a497c3fea4ba35cef2b4

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

LOG: [AST] Add DeclarationNameInfo to node introspection

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

Added: 


Modified: 
clang/include/clang/Tooling/NodeIntrospection.h
clang/lib/Tooling/DumpTool/APIData.h
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
clang/lib/Tooling/EmptyNodeIntrospection.inc.in
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
index 7e0d5e8d14f5..91552cad2eca 100644
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -26,6 +26,7 @@ class CXXCtorInitializer;
 class NestedNameSpecifierLoc;
 class TemplateArgumentLoc;
 class CXXBaseSpecifier;
+struct DeclarationNameInfo;
 
 namespace tooling {
 
@@ -92,6 +93,7 @@ NodeLocationAccessors 
GetLocations(clang::NestedNameSpecifierLoc const &);
 NodeLocationAccessors GetLocations(clang::TemplateArgumentLoc const &);
 NodeLocationAccessors GetLocations(clang::CXXBaseSpecifier const *);
 NodeLocationAccessors GetLocations(clang::TypeLoc const &);
+NodeLocationAccessors GetLocations(clang::DeclarationNameInfo const &);
 NodeLocationAccessors GetLocations(clang::DynTypedNode const );
 } // namespace NodeIntrospection
 } // namespace tooling

diff  --git a/clang/lib/Tooling/DumpTool/APIData.h 
b/clang/lib/Tooling/DumpTool/APIData.h
index ada19d6f1e46..03e247a8bd95 100644
--- a/clang/lib/Tooling/DumpTool/APIData.h
+++ b/clang/lib/Tooling/DumpTool/APIData.h
@@ -22,7 +22,7 @@ struct ClassData {
   std::vector TypeSourceInfos;
   std::vector TypeLocs;
   std::vector NestedNameLocs;
-  // TODO: Extend this with locations available via typelocs etc.
+  std::vector DeclNameInfos;
 };
 
 } // namespace tooling

diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index dcad05745eca..0aeb3a7703f7 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -23,19 +23,18 @@ ASTSrcLocProcessor::ASTSrcLocProcessor(StringRef JsonPath)
 
   Finder = std::make_unique(std::move(FinderOptions));
   Finder->addMatcher(
-  cxxRecordDecl(
-  isDefinition(),
-  isSameOrDerivedFrom(
-  // TODO: Extend this with other clades
-  namedDecl(hasAnyName("clang::Stmt", "clang::Decl",
-   "clang::CXXCtorInitializer",
-   "clang::NestedNameSpecifierLoc",
-   "clang::TemplateArgumentLoc",
-   "clang::CXXBaseSpecifier",
-   "clang::TypeLoc"))
-  .bind("nodeClade")),
-  optionally(isDerivedFrom(cxxRecordDecl().bind("derivedFrom"
-  .bind("className"),
+  cxxRecordDecl(
+  isDefinition(),
+  isSameOrDerivedFrom(
+  namedDecl(
+  hasAnyName(
+  "clang::Stmt", "clang::Decl", 
"clang::CXXCtorInitializer",
+  "clang::NestedNameSpecifierLoc",
+  "clang::TemplateArgumentLoc", "clang::CXXBaseSpecifier",
+  "clang::DeclarationNameInfo", "clang::TypeLoc"))
+  .bind("nodeClade")),
+  optionally(isDerivedFrom(cxxRecordDecl().bind("derivedFrom"
+  .bind("className"),
   this);
   Finder->addMatcher(
   cxxRecordDecl(isDefinition(), hasAnyName("clang::PointerLikeTypeLoc",
@@ -85,6 +84,8 @@ llvm::json::Object toJSON(ClassData const ) {
 JsonObj["typeLocs"] = Obj.TypeLocs;
   if (!Obj.NestedNameLocs.empty())
 JsonObj["nestedNameLocs"] = Obj.NestedNameLocs;
+  if (!Obj.DeclNameInfos.empty())
+JsonObj["declNameInfos"] = Obj.DeclNameInfos;
   return JsonObj;
 }
 
@@ -222,6 +223,8 @@ void ASTSrcLocProcessor::run(const MatchFinder::MatchResult 
) {
   CD.TypeLocs = CaptureMethods("class clang::TypeLoc", ASTClass, Result);
   CD.NestedNameLocs =
   CaptureMethods("class clang::NestedNameSpecifierLoc", ASTClass, Result);
+  CD.DeclNameInfos =
+  CaptureMethods("struct clang::DeclarationNameInfo", ASTClass, Result);
 
   if (const auto *DerivedFrom =
   Result.Nodes.getNodeAs("derivedFrom")) {

diff  --git a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py 
b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
index 

[clang] 94340dd - Enable AST introspection on non-X86

2021-04-23 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-23T21:56:36+01:00
New Revision: 94340dd5bb23fb7c4bc7d91d5ac0608eb25660a8

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

LOG: Enable AST introspection on non-X86

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 8d77b233233d5..558385b0eb5ac 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -28,7 +28,6 @@ if (NOT Python3_EXECUTABLE
 OR CMAKE_CROSSCOMPILING
 OR GENERATOR_IS_MULTI_CONFIG
 OR NOT LLVM_NATIVE_ARCH IN_LIST LLVM_TARGETS_TO_BUILD
-OR NOT X86 IN_LIST LLVM_TARGETS_TO_BUILD
 )
 configure_file(
   EmptyNodeIntrospection.inc.in



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


[clang] df82fa8 - [AST] Update tests to query for introspection support

2021-04-23 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-23T17:51:10+01:00
New Revision: df82fa8d9ba6891c0ad1061fc452ea9f271d8ad4

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

LOG: [AST] Update tests to query for introspection support

Added: 


Modified: 
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index 0abfe983fd13f..62198f56ac7da 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -1226,6 +1226,8 @@ STRING_LOCATION_PAIR(Base, 
getTypeSourceInfo()->getTypeLoc().getLocalSourceRange
 }
 
 TEST(Introspection, SourceLocations_FunctionProtoTypeLoc) {
+  if (!NodeIntrospection::hasIntrospectionSupport())
+return;
   auto AST =
   buildASTFromCode(R"cpp(
 int foo();
@@ -1242,10 +1244,6 @@ int foo();
   const auto *TL = BoundNodes[0].getNodeAs("tl");
   auto Result = NodeIntrospection::GetLocations(*TL);
 
-  if (Result.LocationAccessors.empty() && Result.RangeAccessors.empty()) {
-return;
-  }
-
   auto ExpectedLocations =
   FormatExpected(Result.LocationAccessors);
 
@@ -1290,6 +1288,8 @@ STRING_LOCATION_PAIR(TL, getSourceRange())
 }
 
 TEST(Introspection, SourceLocations_PointerTypeLoc) {
+  if (!NodeIntrospection::hasIntrospectionSupport())
+return;
   auto AST =
   buildASTFromCode(R"cpp(
 int* i;
@@ -1308,10 +1308,6 @@ int* i;
   const auto *TL = BoundNodes[0].getNodeAs("tl");
   auto Result = NodeIntrospection::GetLocations(*TL);
 
-  if (Result.LocationAccessors.empty() && Result.RangeAccessors.empty()) {
-return;
-  }
-
   auto ExpectedLocations =
   FormatExpected(Result.LocationAccessors);
 
@@ -1355,6 +1351,8 @@ STRING_LOCATION_PAIR(TL, getSourceRange())
 #ifndef _WIN32
 // This test doesn't work on windows due to use of the typeof extension.
 TEST(Introspection, SourceLocations_TypeOfTypeLoc) {
+  if (!NodeIntrospection::hasIntrospectionSupport())
+return;
   auto AST =
   buildASTFromCode(R"cpp(
 typeof (static_cast(0)) i;
@@ -1373,10 +1371,6 @@ typeof (static_cast(0)) i;
   const auto *TL = BoundNodes[0].getNodeAs("tl");
   auto Result = NodeIntrospection::GetLocations(*TL);
 
-  if (Result.LocationAccessors.empty() && Result.RangeAccessors.empty()) {
-return;
-  }
-
   auto ExpectedLocations =
   FormatExpected(Result.LocationAccessors);
 



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


[clang] 35918bc - [AST] Sort introspection results without instantiating other data

2021-04-23 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-23T16:21:01+01:00
New Revision: 35918bcb6f507cb3d28f80ab4408125ba292400c

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

LOG: [AST] Sort introspection results without instantiating other data

Avoid string allocation in particular, but also avoid attempting to
impose any particular ordering based on formatted results.

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

Added: 


Modified: 
clang/lib/Tooling/NodeIntrospection.cpp

Removed: 




diff  --git a/clang/lib/Tooling/NodeIntrospection.cpp 
b/clang/lib/Tooling/NodeIntrospection.cpp
index 8e2d446c3efec..f01bb1cb9c3ca 100644
--- a/clang/lib/Tooling/NodeIntrospection.cpp
+++ b/clang/lib/Tooling/NodeIntrospection.cpp
@@ -41,6 +41,23 @@ std::string LocationCallFormatterCpp::format(const 
LocationCall ) {
 }
 
 namespace internal {
+
+static bool locationCallLessThan(const LocationCall *LHS,
+ const LocationCall *RHS) {
+  if (!LHS && !RHS)
+return false;
+  if (LHS && !RHS)
+return true;
+  if (!LHS && RHS)
+return false;
+  auto compareResult = LHS->name().compare(RHS->name());
+  if (compareResult < 0)
+return true;
+  if (compareResult > 0)
+return false;
+  return locationCallLessThan(LHS->on(), RHS->on());
+}
+
 bool RangeLessThan::operator()(
 std::pair const ,
 std::pair const ) const {
@@ -54,15 +71,13 @@ bool RangeLessThan::operator()(
   else if (LHS.first.getEnd() != RHS.first.getEnd())
 return false;
 
-  return LocationCallFormatterCpp::format(*LHS.second) <
- LocationCallFormatterCpp::format(*RHS.second);
+  return locationCallLessThan(LHS.second.get(), RHS.second.get());
 }
 bool RangeLessThan::operator()(
 std::pair const ,
 std::pair const ) const {
   if (LHS.first == RHS.first)
-return LocationCallFormatterCpp::format(*LHS.second) <
-   LocationCallFormatterCpp::format(*RHS.second);
+return locationCallLessThan(LHS.second.get(), RHS.second.get());
   return LHS.first < RHS.first;
 }
 } // namespace internal



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


[clang] af91065 - Revert "[AST] Enable AST node introspection on Apple"

2021-04-22 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-22T23:54:16+01:00
New Revision: af91065ce5e6fd3069029ba9d077f2b21bacb545

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

LOG: Revert "[AST] Enable AST node introspection on Apple"

This reverts commit 907409a536cd66a09a91ee28e1f6f8bcc7127bc7.

This caused a failure

  
http://green.lab.llvm.org/green//job/lldb-cmake-standalone/2827/consoleFull#-210109660a1ca8a51-895e-46c6-af87-ce24fa4cd561

Assertion failed: (!CodeSynthesisContexts.empty() && "Cannot perform an
instantiation without some context on the " "instantiation stack"),
function SubstType, file
/Users/buildslave/jenkins/workspace/lldb-cmake-standalone/llvm-project/clang/lib/Sema/SemaTemplateInstantiate.cpp,
line 2071.

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 053caa319466..8d77b233233d 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -24,6 +24,7 @@ string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} ${PATH_LIB_END} 
-1 PATH_TAIL)
 string(CONCAT BINARY_INCLUDE_DIR ${PATH_HEAD} "/include/clang/" ${PATH_TAIL})
 
 if (NOT Python3_EXECUTABLE
+OR APPLE
 OR CMAKE_CROSSCOMPILING
 OR GENERATOR_IS_MULTI_CONFIG
 OR NOT LLVM_NATIVE_ARCH IN_LIST LLVM_TARGETS_TO_BUILD



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


[clang] 907409a - [AST] Enable AST node introspection on Apple

2021-04-22 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-22T22:19:21+01:00
New Revision: 907409a536cd66a09a91ee28e1f6f8bcc7127bc7

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

LOG: [AST] Enable AST node introspection on Apple

This was previously excluded due to possible buildbot failures.

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 8d77b233233d..053caa319466 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -24,7 +24,6 @@ string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} ${PATH_LIB_END} 
-1 PATH_TAIL)
 string(CONCAT BINARY_INCLUDE_DIR ${PATH_HEAD} "/include/clang/" ${PATH_TAIL})
 
 if (NOT Python3_EXECUTABLE
-OR APPLE
 OR CMAKE_CROSSCOMPILING
 OR GENERATOR_IS_MULTI_CONFIG
 OR NOT LLVM_NATIVE_ARCH IN_LIST LLVM_TARGETS_TO_BUILD



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


[clang] 6f48d6a - [AST] Make comment a bit more specific

2021-04-22 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-22T13:40:56+01:00
New Revision: 6f48d6a9df69b489a741e3f8f72a4559c033b23c

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

LOG: [AST] Make comment a bit more specific

Added: 


Modified: 
clang/include/clang/Tooling/NodeIntrospection.h

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
index 9fe10c659243..7e0d5e8d14f5 100644
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -68,9 +68,10 @@ struct RangeLessThan {
 } // namespace internal
 
 // Note that this container stores unique results in a deterministic, but
-// unspecified order.  Clients which desire a particular order, such as
-// alphabetical, should sort results after retrieval, because the order
-// is dependent on how the LocationCalls are formatted.
+// the location calls are in an unspecified order.  Clients which desire
+// a particular order for the location calls, such as alphabetical,
+// should sort results after retrieval, because the order is dependent
+// on how the LocationCalls are formatted.
 template 
 using UniqueMultiMap = std::set, internal::RangeLessThan>;
 



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


[clang] 5e50f47 - [AST] Add clarification comment

2021-04-22 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-22T12:51:25+01:00
New Revision: 5e50f473d9597e8d14bda2f8659f512376ed9027

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

LOG: [AST] Add clarification comment

Added: 


Modified: 
clang/include/clang/Tooling/NodeIntrospection.h

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
index a04c08823339..9fe10c659243 100644
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -67,6 +67,10 @@ struct RangeLessThan {
 
 } // namespace internal
 
+// Note that this container stores unique results in a deterministic, but
+// unspecified order.  Clients which desire a particular order, such as
+// alphabetical, should sort results after retrieval, because the order
+// is dependent on how the LocationCalls are formatted.
 template 
 using UniqueMultiMap = std::set, internal::RangeLessThan>;
 



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


[clang] aee6c86 - [AST] De-duplicate empty node introspection

2021-04-22 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-22T12:30:04+01:00
New Revision: aee6c86c4dc78da6ca75e0e6e6cfd50f95f2d956

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

LOG: [AST] De-duplicate empty node introspection

This way we can add support for other nodes without duplication.

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

Added: 
clang/lib/Tooling/EmptyNodeIntrospection.inc.in

Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 2baea134271e..8d77b233233d 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -30,46 +30,10 @@ if (NOT Python3_EXECUTABLE
 OR NOT LLVM_NATIVE_ARCH IN_LIST LLVM_TARGETS_TO_BUILD
 OR NOT X86 IN_LIST LLVM_TARGETS_TO_BUILD
 )
-  file(GENERATE OUTPUT ${BINARY_INCLUDE_DIR}/NodeIntrospection.inc
-CONTENT "
-namespace clang {
-namespace tooling {
-
-bool NodeIntrospection::hasIntrospectionSupport() { return false; }
-
-NodeLocationAccessors NodeIntrospection::GetLocations(clang::Stmt const *) {
-  return {};
-}
-NodeLocationAccessors NodeIntrospection::GetLocations(clang::Decl const *) {
-  return {};
-}
-NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::CXXCtorInitializer const *) {
-  return {};
-}
-NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::NestedNameSpecifierLoc const&) {
-  return {};
-}
-NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::TemplateArgumentLoc const&) {
-  return {};
-}
-NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::CXXBaseSpecifier const*) {
-  return {};
-}
-NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::TypeLoc const&) {
-  return {};
-}
-NodeLocationAccessors
-NodeIntrospection::GetLocations(clang::DynTypedNode const &) {
-  return {};
-}
-} // namespace tooling
-} // namespace clang
-"
+configure_file(
+  EmptyNodeIntrospection.inc.in
+  ${BINARY_INCLUDE_DIR}/NodeIntrospection.inc
+  COPYONLY
 )
 set(CLANG_TOOLING_BUILD_AST_INTROSPECTION "OFF" CACHE BOOL "")
 else()
@@ -115,11 +79,14 @@ else()
   OUTPUT ${BINARY_INCLUDE_DIR}/NodeIntrospection.inc
   DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/ASTNodeAPI.json
 ${CMAKE_CURRENT_SOURCE_DIR}/DumpTool/generate_cxx_src_locs.py
+${CMAKE_CURRENT_SOURCE_DIR}/EmptyNodeIntrospection.inc.in
   COMMAND
   ${Python3_EXECUTABLE} 
${CMAKE_CURRENT_SOURCE_DIR}/DumpTool/generate_cxx_src_locs.py
 --json-input-path ${CMAKE_CURRENT_BINARY_DIR}/ASTNodeAPI.json
 --output-file NodeIntrospection.inc
---empty-implementation ${skip_expensive_processing}
+--use-empty-implementation ${skip_expensive_processing}
+--empty-implementation
+  "${CMAKE_CURRENT_SOURCE_DIR}/EmptyNodeIntrospection.inc.in"
   COMMAND
   ${CMAKE_COMMAND} -E copy_if_
diff erent
 ${CMAKE_CURRENT_BINARY_DIR}/NodeIntrospection.inc

diff  --git a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py 
b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
index c06835d8c710..94795cfeb816 100755
--- a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
+++ b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
@@ -4,7 +4,8 @@
 import os
 import sys
 import json
-
+import filecmp
+import shutil
 import argparse
 
 class Generator(object):
@@ -326,13 +327,16 @@ def main():
   help='Read API description from FILE', metavar='FILE')
 parser.add_argument('--output-file', help='Generate output in FILEPATH',
   metavar='FILEPATH')
-parser.add_argument('--empty-implementation',
+parser.add_argument('--use-empty-implementation',
   help='Generate empty implementation',
   action="store", type=int)
+parser.add_argument('--empty-implementation',
+  help='Copy empty implementation from FILEPATH',
+  action="store", metavar='FILEPATH')
 
 options = parser.parse_args()
 
-use_empty_implementation = options.empty_implementation
+use_empty_implementation = options.use_empty_implementation
 
 if (not use_empty_implementation
 and not os.path.exists(options.json_input_path)):
@@ -346,47 +350,9 @@ def main():
 use_empty_implementation = True
 
 if use_empty_implementation:
-with open(os.path.join(os.getcwd(),
-  options.output_file), 'w') as f:
-f.write("""
-namespace clang {
-namespace tooling {
-
-bool NodeIntrospection::hasIntrospectionSupport() { return false; }
-
-NodeLocationAccessors NodeIntrospection::GetLocations(clang::Stmt const *) {
-  

[clang] 21ce124 - [AST] Add NestedNameSpecifierLoc accessors to node introspection

2021-04-22 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-22T11:27:19+01:00
New Revision: 21ce124e1e638e380ce56dbcc97d174c58530566

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

LOG: [AST] Add NestedNameSpecifierLoc accessors to node introspection

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

Added: 


Modified: 
clang/lib/Tooling/DumpTool/APIData.h
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/APIData.h 
b/clang/lib/Tooling/DumpTool/APIData.h
index 6ebf017b5c8f..ada19d6f1e46 100644
--- a/clang/lib/Tooling/DumpTool/APIData.h
+++ b/clang/lib/Tooling/DumpTool/APIData.h
@@ -21,6 +21,7 @@ struct ClassData {
   std::vector TemplateParms;
   std::vector TypeSourceInfos;
   std::vector TypeLocs;
+  std::vector NestedNameLocs;
   // TODO: Extend this with locations available via typelocs etc.
 };
 

diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index a06f4ff9c4a3..dcad05745eca 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -83,6 +83,8 @@ llvm::json::Object toJSON(ClassData const ) {
 JsonObj["typeSourceInfos"] = Obj.TypeSourceInfos;
   if (!Obj.TypeLocs.empty())
 JsonObj["typeLocs"] = Obj.TypeLocs;
+  if (!Obj.NestedNameLocs.empty())
+JsonObj["nestedNameLocs"] = Obj.NestedNameLocs;
   return JsonObj;
 }
 
@@ -218,6 +220,8 @@ void ASTSrcLocProcessor::run(const MatchFinder::MatchResult 
) {
   CD.TypeSourceInfos =
   CaptureMethods("class clang::TypeSourceInfo *", ASTClass, Result);
   CD.TypeLocs = CaptureMethods("class clang::TypeLoc", ASTClass, Result);
+  CD.NestedNameLocs =
+  CaptureMethods("class clang::NestedNameSpecifierLoc", ASTClass, Result);
 
   if (const auto *DerivedFrom =
   Result.Nodes.getNodeAs("derivedFrom")) {

diff  --git a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py 
b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
index fdf586e7e115..c06835d8c710 100755
--- a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
+++ b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
@@ -119,7 +119,8 @@ def GenerateSrcLocMethod(self,
 
 self.implementationContent += '\n'
 
-if 'typeLocs' in ClassData or 'typeSourceInfos' in ClassData:
+if 'typeLocs' in ClassData or 'typeSourceInfos' in ClassData \
+or 'nestedNameLocs' in ClassData:
 if CreateLocalRecursionGuard:
 self.implementationContent += \
 'std::vector TypeLocRecursionGuard;\n'
@@ -153,6 +154,17 @@ def GenerateSrcLocMethod(self,
 
 self.implementationContent += '\n'
 
+if 'nestedNameLocs' in ClassData:
+for NN in ClassData['nestedNameLocs']:
+self.implementationContent += \
+"""
+  if (Object.{0}())
+GetLocationsImpl(
+llvm::makeIntrusiveRefCnt(Prefix, "{0}"),
+Object.{0}(), Locs, Rngs, TypeLocRecursionGuard);
+  """.format(NN)
+
+
 self.implementationContent += '}\n'
 
 def GenerateFiles(self, OutputFile):

diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index 76b47b34a791..0abfe983fd13 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -210,15 +210,37 @@ ns1::ns2::Foo ns1::ns2::Bar::Nested::method(int i, bool b) const
   llvm::sort(ExpectedLocations);
 
   // clang-format off
-  EXPECT_EQ(
-  llvm::makeArrayRef(ExpectedLocations),
-  (ArrayRef>{
+  std::vector> ActualLocations{
 STRING_LOCATION_STDPAIR(MethodDecl, getBeginLoc()),
 STRING_LOCATION_STDPAIR(MethodDecl, getBodyRBrace()),
 STRING_LOCATION_STDPAIR(MethodDecl, getEndLoc()),
 STRING_LOCATION_STDPAIR(MethodDecl, getInnerLocStart()),
 STRING_LOCATION_STDPAIR(MethodDecl, getLocation()),
 STRING_LOCATION_STDPAIR(MethodDecl, getOuterLocStart()),
+STRING_LOCATION_STDPAIR(MethodDecl, getQualifierLoc().getBeginLoc()),
+STRING_LOCATION_STDPAIR(MethodDecl, getQualifierLoc().getEndLoc()),
+STRING_LOCATION_STDPAIR(MethodDecl, getQualifierLoc().getLocalBeginLoc()),
+STRING_LOCATION_STDPAIR(MethodDecl, getQualifierLoc().getLocalEndLoc()),
+STRING_LOCATION_STDPAIR(MethodDecl, 
getQualifierLoc().getPrefix().getBeginLoc()),
+STRING_LOCATION_STDPAIR(MethodDecl, getQualifierLoc().getPrefix().getEndLoc()),
+STRING_LOCATION_STDPAIR(MethodDecl, 
getQualifierLoc().getPrefix().getLocalBeginLoc()),

[clang] 782c3e2 - [AST] Fix comparison to of SourceRanges in container

2021-04-19 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-19T21:19:21+01:00
New Revision: 782c3e23ba09ca7b01034d0fbf0b34044c1c79a3

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

LOG: [AST] Fix comparison to of SourceRanges in container

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

Added: 


Modified: 
clang/lib/Tooling/NodeIntrospection.cpp
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/NodeIntrospection.cpp 
b/clang/lib/Tooling/NodeIntrospection.cpp
index 6a8d7267f8ae4..8e2d446c3efec 100644
--- a/clang/lib/Tooling/NodeIntrospection.cpp
+++ b/clang/lib/Tooling/NodeIntrospection.cpp
@@ -44,9 +44,6 @@ namespace internal {
 bool RangeLessThan::operator()(
 std::pair const ,
 std::pair const ) const {
-  if (!LHS.first.isValid() || !RHS.first.isValid())
-return false;
-
   if (LHS.first.getBegin() < RHS.first.getBegin())
 return true;
   else if (LHS.first.getBegin() != RHS.first.getBegin())

diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index 1db3e6a8e6d65..76b47b34a7916 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -91,6 +91,20 @@ TEST(Introspection, SourceLocations_CallContainer) {
   EXPECT_EQ(slm.size(), 2u);
 }
 
+TEST(Introspection, SourceLocations_CallContainer2) {
+  SourceRangeMap slm;
+  SharedLocationCall Prefix;
+  slm.insert(
+  std::make_pair(SourceRange(), llvm::makeIntrusiveRefCnt(
+Prefix, "getCXXOperatorNameRange")));
+  EXPECT_EQ(slm.size(), 1u);
+
+  slm.insert(std::make_pair(
+  SourceRange(),
+  llvm::makeIntrusiveRefCnt(Prefix, "getSourceRange")));
+  EXPECT_EQ(slm.size(), 2u);
+}
+
 TEST(Introspection, SourceLocations_CallChainFormatting) {
   SharedLocationCall Prefix;
   auto chainedCall = llvm::makeIntrusiveRefCnt(



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


[clang] abacaef - [AST] Update introspection API to use const-ref for copyable types

2021-04-19 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-19T21:07:47+01:00
New Revision: abacaef1816254fc425fa81d137a8d54215d5913

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

LOG: [AST] Update introspection API to use const-ref for copyable types

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

Added: 


Modified: 
clang/include/clang/Tooling/NodeIntrospection.h
clang/lib/Tooling/CMakeLists.txt
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
index dd7ffe3991207..a04c08823339d 100644
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -83,8 +83,8 @@ bool hasIntrospectionSupport();
 NodeLocationAccessors GetLocations(clang::Stmt const *Object);
 NodeLocationAccessors GetLocations(clang::Decl const *Object);
 NodeLocationAccessors GetLocations(clang::CXXCtorInitializer const *Object);
-NodeLocationAccessors GetLocations(clang::NestedNameSpecifierLoc const *);
-NodeLocationAccessors GetLocations(clang::TemplateArgumentLoc const *);
+NodeLocationAccessors GetLocations(clang::NestedNameSpecifierLoc const &);
+NodeLocationAccessors GetLocations(clang::TemplateArgumentLoc const &);
 NodeLocationAccessors GetLocations(clang::CXXBaseSpecifier const *);
 NodeLocationAccessors GetLocations(clang::TypeLoc const &);
 NodeLocationAccessors GetLocations(clang::DynTypedNode const );

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index a0bb108a2b6c4..2baea134271e5 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -48,11 +48,11 @@ NodeLocationAccessors NodeIntrospection::GetLocations(
   return {};
 }
 NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::NestedNameSpecifierLoc const*) {
+clang::NestedNameSpecifierLoc const&) {
   return {};
 }
 NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::TemplateArgumentLoc const*) {
+clang::TemplateArgumentLoc const&) {
   return {};
 }
 NodeLocationAccessors NodeIntrospection::GetLocations(

diff  --git a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py 
b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
index 3664f521e27b7..fdf586e7e1150 100755
--- a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
+++ b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
@@ -11,6 +11,8 @@ class Generator(object):
 
 implementationContent = ''
 
+RefClades = {"NestedNameSpecifierLoc", "TemplateArgumentLoc", "TypeLoc"}
+
 def __init__(self, templateClasses):
 self.templateClasses = templateClasses
 
@@ -54,7 +56,7 @@ def GeneratePrologue(self):
 
 def GenerateBaseGetLocationsDeclaration(self, CladeName):
 InstanceDecoration = "*"
-if CladeName == "TypeLoc":
+if CladeName in self.RefClades:
 InstanceDecoration = "&"
 
 self.implementationContent += \
@@ -164,7 +166,7 @@ def GenerateBaseGetLocationsFunction(self, ASTClassNames,
 
 MethodReturnType = 'NodeLocationAccessors'
 InstanceDecoration = "*"
-if CladeName == "TypeLoc":
+if CladeName in self.RefClades:
 InstanceDecoration = "&"
 
 Signature = \
@@ -196,7 +198,7 @@ def GenerateBaseGetLocationsFunction(self, ASTClassNames,
 RecursionGuardParam = ', TypeLocRecursionGuard'
 
 ArgPrefix = '*'
-if CladeName == "TypeLoc":
+if CladeName in self.RefClades:
 ArgPrefix = ''
 self.implementationContent += \
 'GetLocations{0}(Prefix, {1}Object, Locs, Rngs {2});'.format(
@@ -290,7 +292,7 @@ def GenerateDynNodeVisitor(self, CladeNames):
 if (const auto *N = Node.get<{0}>())
 """.format(CladeName)
 ArgPrefix = ""
-if CladeName == "TypeLoc":
+if CladeName in self.RefClades:
 ArgPrefix = "*"
 self.implementationContent += \
 """
@@ -351,11 +353,11 @@ def main():
   return {};
 }
 NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::NestedNameSpecifierLoc const*) {
+clang::NestedNameSpecifierLoc const&) {
   return {};
 }
 NodeLocationAccessors NodeIntrospection::GetLocations(
-clang::TemplateArgumentLoc const*) {
+clang::TemplateArgumentLoc const&) {
   return {};
 }
 NodeLocationAccessors NodeIntrospection::GetLocations(

diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index 57431668a19f4..1db3e6a8e6d65 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ 

[clang] dd68942 - [AST] Add TypeLoc support to node introspection

2021-04-17 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-17T22:58:02+01:00
New Revision: dd68942f1d79986267a58c9a9924522680d5c82b

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

LOG: [AST] Add TypeLoc support to node introspection

Extend the matchers gathering API for types to record template
parameters.  The TypeLoc type hierarchy has some types which are
templates used in CRTP such as PointerLikeTypeLoc.  Record the inherited
template and template arguments of types inheriting those CRTP types in
the ClassInheritance map.  Because the name inherited from is now
computed, the value type in that map changes from StringRef to
std::string.  This also causes the toJSON override signature used to
serialize that map to change.

Remove the logic for skipping over empty ClassData instances.  Several
classes such as TypeOfExprTypeLoc inherit a CRTP class which provides
interesting locations though the derived class does not.  Record it as a
class to make the locations it inherits available.

Record the typeSourceInfo accessors too as they provide access to
TypeLocs in many classes.

The existing unit tests use UnorderedElementsAre to compare the
introspection result with the expected result.  Our current
implementation of google mock (in gmock-generated-matchers.h) is limited
to support for comparing a container of 10 elements.  As we are now
returning more than 10 results for one of the introspection tests,
change it to instead compare against an ordered vector of pairs.

Because a macro is used to generate API strings and API calls, disable
clang-format in blocks of expected results.  Otherwise clang-format
would insert whitespaces which would then be compared against the
introspected strings and fail the test.

Introduce a recursion guard in the generated code.  The TypeLoc class
has IgnoreParens() API which by default returns itself, so it would
otherwise recurse infinitely.

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

Added: 


Modified: 
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/generate_cxx_src_locs.py
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
index c8518ea635461..dd7ffe3991207 100644
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -86,6 +86,7 @@ NodeLocationAccessors GetLocations(clang::CXXCtorInitializer 
const *Object);
 NodeLocationAccessors GetLocations(clang::NestedNameSpecifierLoc const *);
 NodeLocationAccessors GetLocations(clang::TemplateArgumentLoc const *);
 NodeLocationAccessors GetLocations(clang::CXXBaseSpecifier const *);
+NodeLocationAccessors GetLocations(clang::TypeLoc const &);
 NodeLocationAccessors GetLocations(clang::DynTypedNode const );
 } // namespace NodeIntrospection
 } // namespace tooling

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index e90b681e16f42..dfb732371dfbf 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -58,6 +58,10 @@ NodeLocationAccessors NodeIntrospection::GetLocations(
 clang::CXXBaseSpecifier const*) {
   return {};
 }
+NodeLocationAccessors NodeIntrospection::GetLocations(
+clang::TypeLoc const&) {
+  return {};
+}
 NodeLocationAccessors
 NodeIntrospection::GetLocations(clang::DynTypedNode const &) {
   return {};

diff  --git a/clang/lib/Tooling/DumpTool/APIData.h 
b/clang/lib/Tooling/DumpTool/APIData.h
index 0ec53f6e7dc3c..6ebf017b5c8f7 100644
--- a/clang/lib/Tooling/DumpTool/APIData.h
+++ b/clang/lib/Tooling/DumpTool/APIData.h
@@ -16,13 +16,11 @@ namespace clang {
 namespace tooling {
 
 struct ClassData {
-
-  bool isEmpty() const {
-return ASTClassLocations.empty() && ASTClassRanges.empty();
-  }
-
   std::vector ASTClassLocations;
   std::vector ASTClassRanges;
+  std::vector TemplateParms;
+  std::vector TypeSourceInfos;
+  std::vector TypeLocs;
   // TODO: Extend this with locations available via typelocs etc.
 };
 

diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index a19114a060645..497cd3bdce2ca 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -22,18 +22,24 @@ ASTSrcLocProcessor::ASTSrcLocProcessor(StringRef JsonPath)
 
   Finder = std::make_unique(std::move(FinderOptions));
   Finder->addMatcher(
-  cxxRecordDecl(
-  isDefinition(),
-  isSameOrDerivedFrom(
-  

[clang] 141945f - [AST] Enable AST node introspection on WIN32

2021-04-17 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-17T18:59:35+01:00
New Revision: 141945f950e2f3fd58bc6db3afb5d3b10cb2b0c9

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

LOG: [AST] Enable AST node introspection on WIN32

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 0da3dbd0b927c..e90b681e16f42 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -24,7 +24,6 @@ string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} ${PATH_LIB_END} 
-1 PATH_TAIL)
 string(CONCAT BINARY_INCLUDE_DIR ${PATH_HEAD} "/include/clang/" ${PATH_TAIL})
 
 if (NOT Python3_EXECUTABLE
-OR WIN32
 OR APPLE
 OR GENERATOR_IS_MULTI_CONFIG
 OR NOT LLVM_NATIVE_ARCH IN_LIST LLVM_TARGETS_TO_BUILD



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


[clang] ebc6608 - [AST] Remove args from LocationCall

2021-04-17 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-17T17:21:55+01:00
New Revision: ebc6608fb79057eaed27435d62d5dea0979bd9d3

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

LOG: [AST] Remove args from LocationCall

This class initially had args to be generic to future needs. In
particular, I thought that source location introspection should show the
getBeginLoc of CallExpr args and the getArgLoc of
TemplateSpecializationLocInfo etc.  However, that is probably best left
out of source location introspection because it involves node traversal.

If something like this is needed in the future, it can be added in the
future.

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

Added: 


Modified: 
clang/include/clang/Tooling/NodeIntrospection.h
clang/lib/Tooling/NodeIntrospection.cpp
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
index 5489a67efa22..c8518ea63546 100644
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -38,14 +38,9 @@ class LocationCall : public 
llvm::ThreadSafeRefCountedBase {
   LocationCall(SharedLocationCall on, std::string name,
LocationCallFlags flags = NoFlags)
   : m_flags(flags), m_on(std::move(on)), m_name(std::move(name)) {}
-  LocationCall(SharedLocationCall on, std::string name,
-   std::vector args, LocationCallFlags flags = 
NoFlags)
-  : m_flags(flags), m_on(std::move(on)), m_name(std::move(name)),
-m_args(std::move(args)) {}
 
   LocationCall *on() const { return m_on.get(); }
   StringRef name() const { return m_name; }
-  ArrayRef args() const { return m_args; }
   bool returnsPointer() const { return m_flags & ReturnsPointer; }
   bool isCast() const { return m_flags & IsCast; }
 
@@ -53,7 +48,6 @@ class LocationCall : public 
llvm::ThreadSafeRefCountedBase {
   LocationCallFlags m_flags;
   SharedLocationCall m_on;
   std::string m_name;
-  std::vector m_args;
 };
 
 class LocationCallFormatterCpp {

diff  --git a/clang/lib/Tooling/NodeIntrospection.cpp 
b/clang/lib/Tooling/NodeIntrospection.cpp
index 0e3ef3c6a01e..6a8d7267f8ae 100644
--- a/clang/lib/Tooling/NodeIntrospection.cpp
+++ b/clang/lib/Tooling/NodeIntrospection.cpp
@@ -29,16 +29,7 @@ void LocationCallFormatterCpp::print(const LocationCall 
,
   OS << '.';
   }
 
-  OS << Call.name();
-  if (Call.args().empty()) {
-OS << "()";
-return;
-  }
-  OS << '(' << Call.args().front();
-  for (const std::string  : Call.args().drop_front()) {
-OS << ", " << Arg;
-  }
-  OS << ')';
+  OS << Call.name() << "()";
 }
 
 std::string LocationCallFormatterCpp::format(const LocationCall ) {

diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index ad21748f11f8..e56963aa41a6 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -61,16 +61,7 @@ class LocationCallFormatterSimple {
   print(*On, OS);
   OS << '.';
 }
-OS << Call.name();
-if (Call.args().empty()) {
-  OS << "()";
-  return;
-}
-OS << '(' << Call.args().front();
-for (const std::string  : Call.args().drop_front()) {
-  OS << ", " << Arg;
-}
-OS << ')';
+OS << Call.name() << "()";
   }
 
   static std::string format(const LocationCall ) {



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


[clang] f62ad15 - NFC: Add a simple test for introspection call formatting

2021-04-15 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-15T23:45:54+01:00
New Revision: f62ad15cd7df0ca7681e0dbb894ee1c1d2465c51

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

LOG: NFC: Add a simple test for introspection call formatting

Added: 


Modified: 
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index be58945c9a8d..ad21748f11f8 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -45,6 +45,43 @@ FormatExpected(const MapType ) {
 
 #define STRING_LOCATION_PAIR(INSTANCE, LOC) Pair(#LOC, INSTANCE->LOC)
 
+/**
+  A test formatter for a hypothetical language which needs
+  neither casts nor '->'.
+*/
+class LocationCallFormatterSimple {
+public:
+  static void print(const LocationCall , llvm::raw_ostream ) {
+if (Call.isCast()) {
+  if (const LocationCall *On = Call.on())
+print(*On, OS);
+  return;
+}
+if (const LocationCall *On = Call.on()) {
+  print(*On, OS);
+  OS << '.';
+}
+OS << Call.name();
+if (Call.args().empty()) {
+  OS << "()";
+  return;
+}
+OS << '(' << Call.args().front();
+for (const std::string  : Call.args().drop_front()) {
+  OS << ", " << Arg;
+}
+OS << ')';
+  }
+
+  static std::string format(const LocationCall ) {
+std::string Result;
+llvm::raw_string_ostream OS(Result);
+print(Call, OS);
+OS.flush();
+return Result;
+  }
+};
+
 TEST(Introspection, SourceLocations_CallContainer) {
   SourceLocationMap slm;
   SharedLocationCall Prefix;
@@ -70,6 +107,24 @@ TEST(Introspection, SourceLocations_CallChainFormatting) {
 "getTypeLoc().getSourceRange()");
 }
 
+TEST(Introspection, SourceLocations_Formatter) {
+  SharedLocationCall Prefix;
+  auto chainedCall = llvm::makeIntrusiveRefCnt(
+  llvm::makeIntrusiveRefCnt(
+  llvm::makeIntrusiveRefCnt(
+  llvm::makeIntrusiveRefCnt(
+  Prefix, "getTypeSourceInfo", LocationCall::ReturnsPointer),
+  "getTypeLoc"),
+  "getAs", LocationCall::IsCast),
+  "getNameLoc");
+
+  
EXPECT_EQ("getTypeSourceInfo()->getTypeLoc().getAs()."
+"getNameLoc()",
+LocationCallFormatterCpp::format(*chainedCall));
+  EXPECT_EQ("getTypeSourceInfo().getTypeLoc().getNameLoc()",
+LocationCallFormatterSimple::format(*chainedCall));
+}
+
 TEST(Introspection, SourceLocations_Stmt) {
   if (!NodeIntrospection::hasIntrospectionSupport())
 return;



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


[clang] be65347 - NFC: Add missing matcher for test method

2021-04-15 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-15T23:26:00+01:00
New Revision: be65347326084ad1c309d4330e94d671f011b35b

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

LOG: NFC: Add missing matcher for test method

The intention is to match the definition.

Added: 


Modified: 
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index 2df401c8d813..be58945c9a8d 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -133,7 +133,7 @@ ns1::ns2::Foo ns1::ns2::Bar::Nested::method(int 
i, bool b) const
 
   auto BoundNodes = ast_matchers::match(
   decl(hasDescendant(
-  cxxMethodDecl(hasName("method")).bind("method"))),
+  cxxMethodDecl(hasName("method"), isDefinition()).bind("method"))),
   TU, Ctx);
 
   EXPECT_EQ(BoundNodes.size(), 1u);



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


[clang] 4f6d698 - [AST] Fix location call storage with common last-invocation

2021-04-15 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-15T23:15:11+01:00
New Revision: 4f6d69846747dd53a54a5de0da7eca38df52d5ca

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

LOG: [AST] Fix location call storage with common last-invocation

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

Added: 


Modified: 
clang/lib/Tooling/NodeIntrospection.cpp
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/NodeIntrospection.cpp 
b/clang/lib/Tooling/NodeIntrospection.cpp
index 2ee0b1cae55b..0e3ef3c6a01e 100644
--- a/clang/lib/Tooling/NodeIntrospection.cpp
+++ b/clang/lib/Tooling/NodeIntrospection.cpp
@@ -66,13 +66,15 @@ bool RangeLessThan::operator()(
   else if (LHS.first.getEnd() != RHS.first.getEnd())
 return false;
 
-  return LHS.second->name() < RHS.second->name();
+  return LocationCallFormatterCpp::format(*LHS.second) <
+ LocationCallFormatterCpp::format(*RHS.second);
 }
 bool RangeLessThan::operator()(
 std::pair const ,
 std::pair const ) const {
   if (LHS.first == RHS.first)
-return LHS.second->name() < RHS.second->name();
+return LocationCallFormatterCpp::format(*LHS.second) <
+   LocationCallFormatterCpp::format(*RHS.second);
   return LHS.first < RHS.first;
 }
 } // namespace internal

diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index 880068c43b6e..2df401c8d813 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -45,6 +45,31 @@ FormatExpected(const MapType ) {
 
 #define STRING_LOCATION_PAIR(INSTANCE, LOC) Pair(#LOC, INSTANCE->LOC)
 
+TEST(Introspection, SourceLocations_CallContainer) {
+  SourceLocationMap slm;
+  SharedLocationCall Prefix;
+  slm.insert(std::make_pair(
+  SourceLocation(),
+  llvm::makeIntrusiveRefCnt(Prefix, "getSourceRange")));
+  EXPECT_EQ(slm.size(), 1u);
+
+  auto callTypeLoc =
+  llvm::makeIntrusiveRefCnt(Prefix, "getTypeLoc");
+  slm.insert(std::make_pair(
+  SourceLocation(),
+  llvm::makeIntrusiveRefCnt(callTypeLoc, "getSourceRange")));
+  EXPECT_EQ(slm.size(), 2u);
+}
+
+TEST(Introspection, SourceLocations_CallChainFormatting) {
+  SharedLocationCall Prefix;
+  auto chainedCall = llvm::makeIntrusiveRefCnt(
+  llvm::makeIntrusiveRefCnt(Prefix, "getTypeLoc"),
+  "getSourceRange");
+  EXPECT_EQ(LocationCallFormatterCpp::format(*chainedCall),
+"getTypeLoc().getSourceRange()");
+}
+
 TEST(Introspection, SourceLocations_Stmt) {
   if (!NodeIntrospection::hasIntrospectionSupport())
 return;



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


[clang] c960c38 - NFC: Remove condition to simplify code

2021-04-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-14T23:38:04+01:00
New Revision: c960c3836c6a28ba8f8c0b21db0474bf7d674a18

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

LOG: NFC: Remove condition to simplify code

The run method is only called if there is a match with a binding.

Added: 


Modified: 
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index 5121740cd7c3..a19114a06064 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -157,29 +157,28 @@ CaptureMethods(std::string TypeString, const 
clang::CXXRecordDecl *ASTClass,
 
 void ASTSrcLocProcessor::run(const MatchFinder::MatchResult ) {
 
-  if (const auto *ASTClass =
-  Result.Nodes.getNodeAs("className")) {
+  const auto *ASTClass =
+  Result.Nodes.getNodeAs("className");
 
-StringRef ClassName = ASTClass->getName();
+  StringRef ClassName = ASTClass->getName();
 
-ClassData CD;
+  ClassData CD;
 
-const auto *NodeClade =
-Result.Nodes.getNodeAs("nodeClade");
-StringRef CladeName = NodeClade->getName();
+  const auto *NodeClade =
+  Result.Nodes.getNodeAs("nodeClade");
+  StringRef CladeName = NodeClade->getName();
 
-if (const auto *DerivedFrom =
-Result.Nodes.getNodeAs("derivedFrom"))
-  ClassInheritance[ClassName] = DerivedFrom->getName();
+  if (const auto *DerivedFrom =
+  Result.Nodes.getNodeAs("derivedFrom"))
+ClassInheritance[ClassName] = DerivedFrom->getName();
 
-CD.ASTClassLocations =
-CaptureMethods("class clang::SourceLocation", ASTClass, Result);
-CD.ASTClassRanges =
-CaptureMethods("class clang::SourceRange", ASTClass, Result);
+  CD.ASTClassLocations =
+  CaptureMethods("class clang::SourceLocation", ASTClass, Result);
+  CD.ASTClassRanges =
+  CaptureMethods("class clang::SourceRange", ASTClass, Result);
 
-if (!CD.isEmpty()) {
-  ClassEntries[ClassName] = CD;
-  ClassesInClade[CladeName].push_back(ClassName);
-}
+  if (!CD.isEmpty()) {
+ClassEntries[ClassName] = CD;
+ClassesInClade[CladeName].push_back(ClassName);
   }
 }



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


[clang] f347f0e - [AST] Add introspection support for more base nodes

2021-04-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-14T21:31:23+01:00
New Revision: f347f0e0b869be4f9b97f26663cf8e4eac2c4868

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

LOG: [AST] Add introspection support for more base nodes

Fix the logic of detecting pseudo-virtual getBeginLoc etc on Stmt and
Decl subclasses.

Adjust the test infrastructure to filter out invalid source locations.
This makes the tests more clear about which nodes have which locations.

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

Added: 


Modified: 
clang/include/clang/Tooling/NodeIntrospection.h
clang/lib/Tooling/CMakeLists.txt
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
index 3b40e68df24e7..28007c4468295 100644
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -23,6 +23,10 @@ namespace clang {
 
 class Stmt;
 class Decl;
+class CXXCtorInitializer;
+class NestedNameSpecifierLoc;
+class TemplateArgumentLoc;
+class CXXBaseSpecifier;
 
 namespace tooling {
 
@@ -80,6 +84,10 @@ struct NodeLocationAccessors {
 namespace NodeIntrospection {
 NodeLocationAccessors GetLocations(clang::Stmt const *Object);
 NodeLocationAccessors GetLocations(clang::Decl const *Object);
+NodeLocationAccessors GetLocations(clang::CXXCtorInitializer const *Object);
+NodeLocationAccessors GetLocations(clang::NestedNameSpecifierLoc const *);
+NodeLocationAccessors GetLocations(clang::TemplateArgumentLoc const *);
+NodeLocationAccessors GetLocations(clang::CXXBaseSpecifier const *);
 NodeLocationAccessors GetLocations(clang::DynTypedNode const );
 } // namespace NodeIntrospection
 } // namespace tooling

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index ce7936a53671c..3598a44f13054 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -41,6 +41,22 @@ NodeLocationAccessors 
NodeIntrospection::GetLocations(clang::Stmt const *) {
 NodeLocationAccessors NodeIntrospection::GetLocations(clang::Decl const *) {
   return {};
 }
+NodeLocationAccessors NodeIntrospection::GetLocations(
+clang::CXXCtorInitializer const *) {
+  return {};
+}
+NodeLocationAccessors NodeIntrospection::GetLocations(
+clang::NestedNameSpecifierLoc const*) {
+  return {};
+}
+NodeLocationAccessors NodeIntrospection::GetLocations(
+clang::TemplateArgumentLoc const*) {
+  return {};
+}
+NodeLocationAccessors NodeIntrospection::GetLocations(
+clang::CXXBaseSpecifier const*) {
+  return {};
+}
 NodeLocationAccessors
 NodeIntrospection::GetLocations(clang::DynTypedNode const &) {
   return {};

diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index d611261dd1a74..5121740cd7c3f 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -26,7 +26,11 @@ ASTSrcLocProcessor::ASTSrcLocProcessor(StringRef JsonPath)
   isDefinition(),
   isSameOrDerivedFrom(
   // TODO: Extend this with other clades
-  namedDecl(hasAnyName("clang::Stmt", "clang::Decl"))
+  namedDecl(hasAnyName("clang::Stmt", "clang::Decl",
+   "clang::CXXCtorInitializer",
+   "clang::NestedNameSpecifierLoc",
+   "clang::TemplateArgumentLoc",
+   "clang::CXXBaseSpecifier"))
   .bind("nodeClade")),
   optionally(isDerivedFrom(cxxRecordDecl().bind("derivedFrom"
   .bind("className"),
@@ -116,22 +120,30 @@ CaptureMethods(std::string TypeString, const 
clang::CXXRecordDecl *ASTClass,
  InnerMatcher...);
   };
 
-  auto BoundNodesVec =
-  match(findAll(publicAccessor(ofClass(equalsNode(ASTClass)),
-   returns(asString(TypeString)))
-.bind("classMethod")),
-*ASTClass, *Result.Context);
+  auto BoundNodesVec = match(
+  findAll(
+  publicAccessor(
+  ofClass(cxxRecordDecl(
+  equalsNode(ASTClass),
+  optionally(isDerivedFrom(
+  cxxRecordDecl(hasAnyName("clang::Stmt", "clang::Decl"))
+  .bind("stmtOrDeclBase"),
+  returns(asString(TypeString)))
+  .bind("classMethod")),
+  *ASTClass, *Result.Context);
 
   std::vector Methods;
   for (const auto  : BoundNodesVec) {

[clang] 6559ebd - [AST] Replace asserts with a condition

2021-04-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-04-14T21:14:05+01:00
New Revision: 6559ebd91b70f8d2ed82e19539ee09c5220159c2

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

LOG: [AST] Replace asserts with a condition

As was done for other locations in commit 54272e5b (NFC:
Replace asserts with if() in SourceLocation accessors, 2019-01-07).

Extracted from  https://reviews.llvm.org/D99231

Added: 


Modified: 
clang/include/clang/AST/DeclCXX.h
clang/include/clang/AST/TemplateBase.h

Removed: 




diff  --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index bb99ab1373ba5..bbf7ecf6712a3 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -2267,7 +2267,8 @@ class CXXCtorInitializer final {
 
   // For a pack expansion, returns the location of the ellipsis.
   SourceLocation getEllipsisLoc() const {
-assert(isPackExpansion() && "Initializer is not a pack expansion");
+if (!isPackExpansion())
+  return {};
 return MemberOrEllipsisLocation;
   }
 

diff  --git a/clang/include/clang/AST/TemplateBase.h 
b/clang/include/clang/AST/TemplateBase.h
index 1671637521e24..19f2cadc1f2b7 100644
--- a/clang/include/clang/AST/TemplateBase.h
+++ b/clang/include/clang/AST/TemplateBase.h
@@ -512,7 +512,8 @@ class TemplateArgumentLoc {
   }
 
   TypeSourceInfo *getTypeSourceInfo() const {
-assert(Argument.getKind() == TemplateArgument::Type);
+if (Argument.getKind() != TemplateArgument::Type)
+  return nullptr;
 return LocInfo.getAsTypeSourceInfo();
   }
 



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


[clang] 2f18108 - [ASTMatchers] Add `cxxBaseSpecifier` matcher (non-top-level)

2021-04-08 Thread Stephen Kelly via cfe-commits

Author: Nikita Kniazev
Date: 2021-04-09T00:05:36+01:00
New Revision: 2f181086b5cbbe83c4492aa44484a77ed06ec812

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

LOG: [ASTMatchers] Add `cxxBaseSpecifier` matcher (non-top-level)

Required for capturing base specifier in matchers:
  `cxxRecordDecl(hasDirectBase(cxxBaseSpecifier().bind("base")))`

Reviewed By: steveire, aaron.ballman

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

Added: 


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

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index b8fb27b126fc1..ab36402e4bca5 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -573,6 +573,15 @@ Node Matchers
 Return 
typeNameParameters
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html;>CXXBaseSpecifiercxxBaseSpecifierMatcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html;>CXXBaseSpecifier...
+Matches class 
bases.
+
+Examples matches public virtual B.
+  class B {};
+  class C : public virtual B {};
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html;>CXXCtorInitializercxxCtorInitializerMatcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html;>CXXCtorInitializer...
 Matches 
constructor initializers.
 
@@ -6144,8 +6153,8 @@ AST Traversal Matchers
 
 
 
-Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html;>CXXBaseSpecifierhasTypeMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl 
InnerMatcher
-Overloaded to match the 
declaration of the expression's or value
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html;>CXXBaseSpecifierhasTypeMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl 
InnerMatcher
+Overloaded to match the 
declaration of the expression's or value
 declaration's type.
 
 In case of a value declaration (for example a variable declaration),
@@ -6157,9 +6166,12 @@ AST Traversal Matchers
 Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
 and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
 and friend class X (matcher = friendDecl(hasType("X"))
+and public virtual X (matcher = cxxBaseSpecifier(hasType(
+  cxxRecordDecl(hasName("X"
  class X {};
  void y(X x) { x; X z; }
  class Y { friend class X; };
+ class Z : public virtual X {};
 
 Example matches class Derived
 (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))
@@ -6171,6 +6183,24 @@ AST Traversal Matchers
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html;>CXXBaseSpecifierhasTypeMatcherhttps://clang.llvm.org/doxygen/classclang_1_1QualType.html;>QualType
 InnerMatcher
+Matches if the expression's 
or declaration's type matches a type
+matcher.
+
+Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
+and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
+and U (matcher = typedefDecl(hasType(asString("int")))
+and friend class X (matcher = friendDecl(hasType("X"))
+and public virtual X (matcher = cxxBaseSpecifier(hasType(
+  asString("class X")))
+ class X {};
+ void y(X x) { x; X z; }
+ typedef int U;
+ class Y { friend class X; };
+ class Z : public virtual X {};
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html;>CXXConstructExprforEachArgumentWithParamMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Expr.html;>Expr 
ArgMatcher, Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ParmVarDecl.html;>ParmVarDecl
 ParamMatcher
 Matches 
all arguments and their respective ParmVarDecl.
 
@@ -7282,8 +7312,8 @@ AST Traversal Matchers
 
 
 
-Matcherhttps://clang.llvm.org/doxygen/classclang_1_1Expr.html;>ExprhasTypeMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl 
InnerMatcher
-Overloaded to match the 
declaration of the expression's or value
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1Expr.html;>ExprhasTypeMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl 
InnerMatcher
+Overloaded to match the 
declaration of the expression's or value
 declaration's type.
 
 In case of a value declaration (for 

[clang-tools-extra] ea2225a - [clang-tidy] Simplify readability checks to not need ignoring* matchers

2021-03-28 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-28T11:25:41+01:00
New Revision: ea2225a10be986d226e041d20d36dff17e78daed

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

LOG: [clang-tidy] Simplify readability checks to not need ignoring* matchers

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

Added: 


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

clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp

clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.h
clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.cpp
clang-tools-extra/clang-tidy/readability/MisleadingIndentationCheck.h
clang-tools-extra/clang-tidy/readability/NamedParameterCheck.cpp
clang-tools-extra/clang-tidy/readability/NamedParameterCheck.h
clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.cpp
clang-tools-extra/clang-tidy/readability/NonConstParameterCheck.h
clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.h
clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.cpp
clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.h

clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp

clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.h
clang-tools-extra/clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp
clang-tools-extra/clang-tidy/readability/UniqueptrDeleteReleaseCheck.h
clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp
clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
index 2c78258078eae..fe25f7a7ccbcc 100644
--- a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
@@ -105,10 +105,7 @@ void BracesAroundStatementsCheck::storeOptions(
 }
 
 void BracesAroundStatementsCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(
-  ifStmt(unless(allOf(isConstexpr(), isInTemplateInstantiation(
-  .bind("if"),
-  this);
+  Finder->addMatcher(ifStmt().bind("if"), this);
   Finder->addMatcher(whileStmt().bind("while"), this);
   Finder->addMatcher(doStmt().bind("do"), this);
   Finder->addMatcher(forStmt().bind("for"), this);

diff  --git 
a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.h 
b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.h
index 7c019c6cb5521..1270cfe10d193 100644
--- a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.h
@@ -55,6 +55,9 @@ class BracesAroundStatementsCheck : public ClangTidyCheck {
   template 
   SourceLocation findRParenLoc(const IfOrWhileStmt *S, const SourceManager ,
const ASTContext *Context);
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   std::set ForceBracesStmts;

diff  --git a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
index 89bb02e78cc63..0558b41016379 100644
--- a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.cpp
@@ -171,8 +171,7 @@ void ElseAfterReturnCheck::registerPPCallbacks(const 
SourceManager ,
 void ElseAfterReturnCheck::registerMatchers(MatchFinder *Finder) {
   const auto InterruptsControlFlow = stmt(anyOf(
   returnStmt().bind(InterruptingStr), continueStmt().bind(InterruptingStr),
-  breakStmt().bind(InterruptingStr),
-  expr(ignoringImplicit(cxxThrowExpr().bind(InterruptingStr);
+  breakStmt().bind(InterruptingStr), 
cxxThrowExpr().bind(InterruptingStr)));
   Finder->addMatcher(
   compoundStmt(
   forEach(ifStmt(unless(isConstexpr()),

diff  --git a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.h 
b/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.h
index 440cf4b637b73..d3fbc0ac0abe0 100644
--- a/clang-tools-extra/clang-tidy/readability/ElseAfterReturnCheck.h
+++ 

[clang] 4c65dfc - [AST] Add introspection support for Decls

2021-03-22 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-22T23:16:02Z
New Revision: 4c65dfc895d03d1c3bfa1ccfe9567c9ea8557492

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

LOG: [AST] Add introspection support for Decls

The test code has lots of interesting locations which are not yet
introspected, but those will come later:

 http://ce.steveire.com/z/3T90hR

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

Added: 


Modified: 
clang/include/clang/Tooling/NodeIntrospection.h
clang/lib/Tooling/CMakeLists.txt
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
index abaa58b674a1..3b40e68df24e 100644
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -22,6 +22,7 @@
 namespace clang {
 
 class Stmt;
+class Decl;
 
 namespace tooling {
 
@@ -78,6 +79,7 @@ struct NodeLocationAccessors {
 
 namespace NodeIntrospection {
 NodeLocationAccessors GetLocations(clang::Stmt const *Object);
+NodeLocationAccessors GetLocations(clang::Decl const *Object);
 NodeLocationAccessors GetLocations(clang::DynTypedNode const );
 } // namespace NodeIntrospection
 } // namespace tooling

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index e820f63d5b3d..0a6fb99152dc 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -40,6 +40,9 @@ namespace tooling {
 NodeLocationAccessors NodeIntrospection::GetLocations(clang::Stmt const *) {
   return {};
 }
+NodeLocationAccessors NodeIntrospection::GetLocations(clang::Decl const *) {
+  return {};
+}
 NodeLocationAccessors
 NodeIntrospection::GetLocations(clang::DynTypedNode const &) {
   return {};

diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index e7400e958716..d611261dd1a7 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -26,7 +26,8 @@ ASTSrcLocProcessor::ASTSrcLocProcessor(StringRef JsonPath)
   isDefinition(),
   isSameOrDerivedFrom(
   // TODO: Extend this with other clades
-  namedDecl(hasName("clang::Stmt")).bind("nodeClade")),
+  namedDecl(hasAnyName("clang::Stmt", "clang::Decl"))
+  .bind("nodeClade")),
   optionally(isDerivedFrom(cxxRecordDecl().bind("derivedFrom"
   .bind("className"),
   this);

diff  --git a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py 
b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
index b4d31d3e49a9..15a373e52480 100755
--- a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
+++ b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
@@ -177,6 +177,9 @@ def main():
 NodeLocationAccessors NodeIntrospection::GetLocations(clang::Stmt const *) {
   return {};
 }
+NodeLocationAccessors NodeIntrospection::GetLocations(clang::Decl const *) {
+  return {};
+}
 NodeLocationAccessors
 NodeIntrospection::GetLocations(clang::DynTypedNode const &) {
   return {};

diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index a1280d9da535..5e32d7d593c7 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -42,7 +42,7 @@ FormatExpected(const MapType ) {
 
 #define STRING_LOCATION_PAIR(INSTANCE, LOC) Pair(#LOC, INSTANCE->LOC)
 
-TEST(Introspection, SourceLocations) {
+TEST(Introspection, SourceLocations_Stmt) {
   auto AST = buildASTFromCode("void foo() {} void bar() { foo(); }", "foo.cpp",
   std::make_shared());
   auto  = AST->getASTContext();
@@ -79,3 +79,69 @@ TEST(Introspection, SourceLocations) {
   EXPECT_THAT(ExpectedRanges, UnorderedElementsAre(STRING_LOCATION_PAIR(
   FooCall, getSourceRange(;
 }
+
+TEST(Introspection, SourceLocations_Decl) {
+  auto AST =
+  buildASTFromCode(R"cpp(
+namespace ns1 {
+namespace ns2 {
+template  struct Foo {};
+template  struct Bar {
+  struct Nested {
+template 
+Foo method(int i, bool b) const noexcept(true);
+  };
+};
+} // namespace ns2
+} // namespace ns1
+
+template 
+template 
+ns1::ns2::Foo ns1::ns2::Bar::Nested::method(int i, bool b) const
+noexcept(true) {}
+)cpp",
+   "foo.cpp", std::make_shared());
+  auto  = AST->getASTContext();
+  auto  = *Ctx.getTranslationUnitDecl();
+
+  auto BoundNodes = ast_matchers::match(
+  decl(hasDescendant(
+  

[clang] 188405b - [AST] Ensure that an empty json file is generated if compile errors

2021-03-20 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-20T18:08:01Z
New Revision: 188405bc192df54fbf048ddd3da071c9fff4d0d1

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

LOG: [AST] Ensure that an empty json file is generated if compile errors

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

Added: 


Modified: 
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index ff279d9425d8..e7400e958716 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -79,17 +79,16 @@ llvm::json::Object toJSON(llvm::StringMap const 
) {
   return JsonObj;
 }
 
-void WriteJSON(std::string JsonPath,
-   llvm::StringMap const ,
-   llvm::StringMap> const ,
-   llvm::StringMap const ) {
+void WriteJSON(std::string JsonPath, llvm::json::Object &,
+   llvm::json::Object &,
+   llvm::json::Object &) {
   llvm::json::Object JsonObj;
 
   using llvm::json::toJSON;
 
-  JsonObj["classInheritance"] = ::toJSON(ClassInheritance);
-  JsonObj["classesInClade"] = ::toJSON(ClassesInClade);
-  JsonObj["classEntries"] = ::toJSON(ClassEntries);
+  JsonObj["classInheritance"] = std::move(ClassInheritance);
+  JsonObj["classesInClade"] = std::move(ClassesInClade);
+  JsonObj["classEntries"] = std::move(ClassEntries);
 
   std::error_code EC;
   llvm::raw_fd_ostream JsonOut(JsonPath, EC, llvm::sys::fs::F_Text);
@@ -101,9 +100,12 @@ void WriteJSON(std::string JsonPath,
 }
 
 void ASTSrcLocProcessor::generate() {
-  WriteJSON(JsonPath, ClassInheritance, ClassesInClade, ClassEntries);
+  WriteJSON(JsonPath, ::toJSON(ClassInheritance), ::toJSON(ClassesInClade),
+::toJSON(ClassEntries));
 }
 
+void ASTSrcLocProcessor::generateEmpty() { WriteJSON(JsonPath, {}, {}, {}); }
+
 std::vector
 CaptureMethods(std::string TypeString, const clang::CXXRecordDecl *ASTClass,
const MatchFinder::MatchResult ) {

diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
index 00994758e03c..5d848f48ed54 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
@@ -30,6 +30,7 @@ class ASTSrcLocProcessor : public 
ast_matchers::MatchFinder::MatchCallback {
  StringRef File);
 
   void generate();
+  void generateEmpty();
 
 private:
   void run(const ast_matchers::MatchFinder::MatchResult ) override;

diff  --git a/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp 
b/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
index 06b58c6382ed..8328977178cc 100644
--- a/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
+++ b/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
@@ -48,7 +48,13 @@ class ASTSrcLocGenerationAction : public 
clang::ASTFrontendAction {
 public:
   ASTSrcLocGenerationAction() : Processor(JsonOutputPath) {}
 
-  ~ASTSrcLocGenerationAction() { Processor.generate(); }
+  void ExecuteAction() override {
+clang::ASTFrontendAction::ExecuteAction();
+if (getCompilerInstance().getDiagnostics().getNumErrors() > 0)
+  Processor.generateEmpty();
+else
+  Processor.generate();
+  }
 
   std::unique_ptr
   CreateASTConsumer(clang::CompilerInstance ,



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


[clang] b90e7bf - NFC: Use a simple macro to test AST node introspection

2021-03-17 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-17T12:08:55Z
New Revision: b90e7bf25dc3cc056331dfe5fca21b3ea1713299

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

LOG: NFC: Use a simple macro to test AST node introspection

Added: 


Modified: 
clang/unittests/Introspection/IntrospectionTest.cpp

Removed: 




diff  --git a/clang/unittests/Introspection/IntrospectionTest.cpp 
b/clang/unittests/Introspection/IntrospectionTest.cpp
index 7977e870101f..a1280d9da535 100644
--- a/clang/unittests/Introspection/IntrospectionTest.cpp
+++ b/clang/unittests/Introspection/IntrospectionTest.cpp
@@ -40,6 +40,8 @@ FormatExpected(const MapType ) {
   return Result;
 }
 
+#define STRING_LOCATION_PAIR(INSTANCE, LOC) Pair(#LOC, INSTANCE->LOC)
+
 TEST(Introspection, SourceLocations) {
   auto AST = buildASTFromCode("void foo() {} void bar() { foo(); }", "foo.cpp",
   std::make_shared());
@@ -67,14 +69,13 @@ TEST(Introspection, SourceLocations) {
 
   EXPECT_THAT(
   ExpectedLocations,
-  UnorderedElementsAre(Pair("getBeginLoc()", FooCall->getBeginLoc()),
-   Pair("getEndLoc()", FooCall->getEndLoc()),
-   Pair("getExprLoc()", FooCall->getExprLoc()),
-   Pair("getRParenLoc()", FooCall->getRParenLoc(;
+  UnorderedElementsAre(STRING_LOCATION_PAIR(FooCall, getBeginLoc()),
+   STRING_LOCATION_PAIR(FooCall, getEndLoc()),
+   STRING_LOCATION_PAIR(FooCall, getExprLoc()),
+   STRING_LOCATION_PAIR(FooCall, getRParenLoc(;
 
   auto ExpectedRanges = FormatExpected(Result.RangeAccessors);
 
-  EXPECT_THAT(ExpectedRanges,
-  UnorderedElementsAre(
-  Pair("getSourceRange()", FooCall->getSourceRange(;
+  EXPECT_THAT(ExpectedRanges, UnorderedElementsAre(STRING_LOCATION_PAIR(
+  FooCall, getSourceRange(;
 }



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


[clang] f5030f1 - [AST] Suppress diagnostic output when generating code

2021-03-16 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-17T01:30:22Z
New Revision: f5030f1a8e4affef2ab92b3268292f46d0052fd5

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

LOG: [AST] Suppress diagnostic output when generating code

Added: 


Modified: 
clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp 
b/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
index 74ba70eefa04..06b58c6382ed 100644
--- a/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
+++ b/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
@@ -135,6 +135,8 @@ int main(int argc, const char **argv) {
   if (!Compiler.hasDiagnostics())
 return 1;
 
+  // Suppress "2 errors generated" or similar messages
+  Compiler.getDiagnosticOpts().ShowCarets = false;
   Compiler.createSourceManager(Files);
 
   ASTSrcLocGenerationAction ScopedToolAction;



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


[clang] a00d440 - [AST] Hide errors from the attempt to introspect nodes

2021-03-16 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-16T23:46:31Z
New Revision: a00d44012820e9ed2eba623dd61ca9cf5a2ce115

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

LOG: [AST] Hide errors from the attempt to introspect nodes

Added: 


Modified: 
clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp 
b/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
index 6615f865221d..74ba70eefa04 100644
--- a/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
+++ b/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
@@ -92,7 +92,13 @@ int main(int argc, const char **argv) {
   auto ParsedArgs = Opts.ParseArgs(llvm::makeArrayRef(Argv).slice(1),
MissingArgIndex, MissingArgCount);
   ParseDiagnosticArgs(*DiagOpts, ParsedArgs);
-  TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
+
+  // Don't output diagnostics, because common scenarios such as
+  // cross-compiling fail with diagnostics.  This is not fatal, but
+  // just causes attempts to use the introspection API to return no data.
+  std::string Str;
+  llvm::raw_string_ostream OS(Str);
+  TextDiagnosticPrinter DiagnosticPrinter(OS, &*DiagOpts);
   DiagnosticsEngine Diagnostics(
   IntrusiveRefCntPtr(new DiagnosticIDs()), &*DiagOpts,
   , false);



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


[clang] 1974065 - [AST] Add generator for source location introspection

2021-03-15 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-15T10:52:44Z
New Revision: 19740652c4c4329e2b9e77f96e5e31c360b4e8bb

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

LOG: [AST] Add generator for source location introspection

Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

The JSON file can also be used to generate bindings for other languages,
such as Python and Javascript:

  https://steveire.wordpress.com/2019/04/30/the-future-of-ast-matching

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

Also in this version, the platforms/cmake configurations are excluded as
much as possible so that support can be added iteratively.  Currently a
break on any platform causes a revert of the entire feature.  This way,
the `OR WIN32` can be removed in a future commit and if it breaks the
buildbots, only that commit gets reverted, making the entire process
easier to manage.

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

Added: 
clang/include/clang/Tooling/NodeIntrospection.h
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/NodeIntrospection.cpp
clang/unittests/Introspection/CMakeLists.txt
clang/unittests/Introspection/IntrospectionTest.cpp
llvm/utils/gn/secondary/clang/lib/Tooling/DumpTool/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/Introspection/BUILD.gn

Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/unittests/CMakeLists.txt
llvm/utils/gn/secondary/clang/lib/Tooling/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/BUILD.gn

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
new file mode 100644
index ..abaa58b674a1
--- /dev/null
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -0,0 +1,85 @@
+//===- NodeIntrospection.h *- C++ 
-*---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file contains the implementation of the NodeIntrospection.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+#define LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/DeclarationName.h"
+
+#include 
+#include 
+
+namespace clang {
+
+class Stmt;
+
+namespace tooling {
+
+class LocationCall {
+public:
+  enum LocationCallFlags { NoFlags, ReturnsPointer, IsCast };
+  LocationCall(std::shared_ptr on, std::string name,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+  LocationCall(std::shared_ptr on, std::string name,
+   std::vector const ,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+
+  LocationCall *on() const { return m_on.get(); }
+  StringRef name() const { return m_name; }
+  std::vector const () const { return m_args; }
+  bool returnsPointer() const { return m_flags & ReturnsPointer; }
+  bool isCast() const { return m_flags & IsCast; }
+
+private:
+  std::shared_ptr m_on;
+  std::string m_name;
+  std::vector m_args;
+  LocationCallFlags m_flags;
+};
+
+class LocationCallFormatterCpp {
+public:
+  static std::string format(LocationCall *Call);
+};
+
+namespace internal {
+struct RangeLessThan {
+  bool operator()(
+  std::pair> const ,
+  std::pair> const ) const;
+};
+} // namespace internal
+
+template >>
+using UniqueMultiMap = std::set, Comp>;
+
+using SourceLocationMap =
+UniqueMultiMap>;
+using SourceRangeMap =
+UniqueMultiMap,
+   internal::RangeLessThan>;
+
+struct NodeLocationAccessors {
+  SourceLocationMap LocationAccessors;
+  SourceRangeMap RangeAccessors;
+};
+
+namespace NodeIntrospection 

[clang] 6e303a9 - Revert "[AST] Add generator for source location introspection"

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-15T01:16:10Z
New Revision: 6e303a982d6ce5a281ba95238ed376a2caf27a52

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

LOG: Revert "[AST] Add generator for source location introspection"

This reverts commit 91abaa1f8d97e8efa249c31686fd643ff5f1e2c2.

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/unittests/CMakeLists.txt
llvm/utils/gn/secondary/clang/lib/Tooling/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/BUILD.gn

Removed: 
clang/include/clang/Tooling/NodeIntrospection.h
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/NodeIntrospection.cpp
clang/unittests/Introspection/CMakeLists.txt
clang/unittests/Introspection/IntrospectionTest.cpp
llvm/utils/gn/secondary/clang/lib/Tooling/DumpTool/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/Introspection/BUILD.gn



diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
deleted file mode 100644
index abaa58b674a1..
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ /dev/null
@@ -1,85 +0,0 @@
-//===- NodeIntrospection.h *- C++ 
-*---===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-//  This file contains the implementation of the NodeIntrospection.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
-#define LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
-
-#include "clang/AST/ASTTypeTraits.h"
-#include "clang/AST/DeclarationName.h"
-
-#include 
-#include 
-
-namespace clang {
-
-class Stmt;
-
-namespace tooling {
-
-class LocationCall {
-public:
-  enum LocationCallFlags { NoFlags, ReturnsPointer, IsCast };
-  LocationCall(std::shared_ptr on, std::string name,
-   LocationCallFlags flags = NoFlags)
-  : m_on(on), m_name(name), m_flags(flags) {}
-  LocationCall(std::shared_ptr on, std::string name,
-   std::vector const ,
-   LocationCallFlags flags = NoFlags)
-  : m_on(on), m_name(name), m_flags(flags) {}
-
-  LocationCall *on() const { return m_on.get(); }
-  StringRef name() const { return m_name; }
-  std::vector const () const { return m_args; }
-  bool returnsPointer() const { return m_flags & ReturnsPointer; }
-  bool isCast() const { return m_flags & IsCast; }
-
-private:
-  std::shared_ptr m_on;
-  std::string m_name;
-  std::vector m_args;
-  LocationCallFlags m_flags;
-};
-
-class LocationCallFormatterCpp {
-public:
-  static std::string format(LocationCall *Call);
-};
-
-namespace internal {
-struct RangeLessThan {
-  bool operator()(
-  std::pair> const ,
-  std::pair> const ) const;
-};
-} // namespace internal
-
-template >>
-using UniqueMultiMap = std::set, Comp>;
-
-using SourceLocationMap =
-UniqueMultiMap>;
-using SourceRangeMap =
-UniqueMultiMap,
-   internal::RangeLessThan>;
-
-struct NodeLocationAccessors {
-  SourceLocationMap LocationAccessors;
-  SourceRangeMap RangeAccessors;
-};
-
-namespace NodeIntrospection {
-NodeLocationAccessors GetLocations(clang::Stmt const *Object);
-NodeLocationAccessors GetLocations(clang::DynTypedNode const );
-} // namespace NodeIntrospection
-} // namespace tooling
-} // namespace clang
-#endif

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index e8a2e35b6215..7a58af59dad1 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -8,112 +8,10 @@ add_subdirectory(Core)
 add_subdirectory(Inclusions)
 add_subdirectory(Refactoring)
 add_subdirectory(ASTDiff)
-add_subdirectory(DumpTool)
 add_subdirectory(Syntax)
 add_subdirectory(DependencyScanning)
 add_subdirectory(Transformer)
 
-find_package(Python3 COMPONENTS Interpreter)
-
-# Replace the last lib component of the current binary directory with include
-string(FIND ${CMAKE_CURRENT_BINARY_DIR} "/lib/" PATH_LIB_START REVERSE)
-if(PATH_LIB_START EQUAL -1)
-  message(FATAL_ERROR "Couldn't find lib component in binary directory")
-endif()
-math(EXPR PATH_LIB_END "${PATH_LIB_START}+5")
-string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD)
-string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 

[clang] 370b9b4 - Revert "Attempt to fix ARM buildbot"

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-15T01:16:07Z
New Revision: 370b9b4aea5fe1c9ca25e4c00f104eba75ac5c7b

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

LOG: Revert "Attempt to fix ARM buildbot"

This reverts commit 12dac66f6b33dd14b72076800726817f682ab785.

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index e820f63d5b3d..e8a2e35b6215 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -30,7 +30,6 @@ if (NOT Python3_EXECUTABLE
 OR APPLE
 OR GENERATOR_IS_MULTI_CONFIG
 OR NOT LLVM_NATIVE_ARCH IN_LIST LLVM_TARGETS_TO_BUILD
-OR NOT X86 IN_LIST LLVM_TARGETS_TO_BUILD
 )
   file(GENERATE OUTPUT ${BINARY_INCLUDE_DIR}/NodeIntrospection.inc
 CONTENT "



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


[clang] 12dac66 - Attempt to fix ARM buildbot

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-15T00:20:39Z
New Revision: 12dac66f6b33dd14b72076800726817f682ab785

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

LOG: Attempt to fix ARM buildbot

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index e8a2e35b6215..e820f63d5b3d 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -30,6 +30,7 @@ if (NOT Python3_EXECUTABLE
 OR APPLE
 OR GENERATOR_IS_MULTI_CONFIG
 OR NOT LLVM_NATIVE_ARCH IN_LIST LLVM_TARGETS_TO_BUILD
+OR NOT X86 IN_LIST LLVM_TARGETS_TO_BUILD
 )
   file(GENERATE OUTPUT ${BINARY_INCLUDE_DIR}/NodeIntrospection.inc
 CONTENT "



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


[clang] 91abaa1 - [AST] Add generator for source location introspection

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-15T00:00:29Z
New Revision: 91abaa1f8d97e8efa249c31686fd643ff5f1e2c2

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

LOG: [AST] Add generator for source location introspection

Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

The JSON file can also be used to generate bindings for other languages,
such as Python and Javascript:

  https://steveire.wordpress.com/2019/04/30/the-future-of-ast-matching

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

Also in this version, the platforms/cmake configurations are excluded as
much as possible so that support can be added iteratively.  Currently a
break on any platform causes a revert of the entire feature.  This way,
the `OR WIN32` can be removed in a future commit and if it breaks the
buildbots, only that commit gets reverted, making the entire process
easier to manage.

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

Added: 
clang/include/clang/Tooling/NodeIntrospection.h
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/NodeIntrospection.cpp
clang/unittests/Introspection/CMakeLists.txt
clang/unittests/Introspection/IntrospectionTest.cpp
llvm/utils/gn/secondary/clang/lib/Tooling/DumpTool/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/Introspection/BUILD.gn

Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/unittests/CMakeLists.txt
llvm/utils/gn/secondary/clang/lib/Tooling/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/BUILD.gn

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
new file mode 100644
index ..abaa58b674a1
--- /dev/null
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -0,0 +1,85 @@
+//===- NodeIntrospection.h *- C++ 
-*---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file contains the implementation of the NodeIntrospection.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+#define LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/DeclarationName.h"
+
+#include 
+#include 
+
+namespace clang {
+
+class Stmt;
+
+namespace tooling {
+
+class LocationCall {
+public:
+  enum LocationCallFlags { NoFlags, ReturnsPointer, IsCast };
+  LocationCall(std::shared_ptr on, std::string name,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+  LocationCall(std::shared_ptr on, std::string name,
+   std::vector const ,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+
+  LocationCall *on() const { return m_on.get(); }
+  StringRef name() const { return m_name; }
+  std::vector const () const { return m_args; }
+  bool returnsPointer() const { return m_flags & ReturnsPointer; }
+  bool isCast() const { return m_flags & IsCast; }
+
+private:
+  std::shared_ptr m_on;
+  std::string m_name;
+  std::vector m_args;
+  LocationCallFlags m_flags;
+};
+
+class LocationCallFormatterCpp {
+public:
+  static std::string format(LocationCall *Call);
+};
+
+namespace internal {
+struct RangeLessThan {
+  bool operator()(
+  std::pair> const ,
+  std::pair> const ) const;
+};
+} // namespace internal
+
+template >>
+using UniqueMultiMap = std::set, Comp>;
+
+using SourceLocationMap =
+UniqueMultiMap>;
+using SourceRangeMap =
+UniqueMultiMap,
+   internal::RangeLessThan>;
+
+struct NodeLocationAccessors {
+  SourceLocationMap LocationAccessors;
+  SourceRangeMap RangeAccessors;
+};
+
+namespace NodeIntrospection 

[clang] e312b4b - Revert "[AST] Add generator for source location introspection"

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-14T22:51:45Z
New Revision: e312b4b6c74d455ba8193f46d7f0f8f1c8ac4757

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

LOG: Revert "[AST] Add generator for source location introspection"

This reverts commit 477e4b974653f92960c0bf569d88da7baacef68a.

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/unittests/CMakeLists.txt
llvm/utils/gn/secondary/clang/lib/Tooling/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/BUILD.gn

Removed: 
clang/include/clang/Tooling/NodeIntrospection.h
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/NodeIntrospection.cpp
clang/unittests/Introspection/CMakeLists.txt
clang/unittests/Introspection/IntrospectionTest.cpp
llvm/utils/gn/secondary/clang/lib/Tooling/DumpTool/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/Introspection/BUILD.gn



diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
deleted file mode 100644
index abaa58b674a1..
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ /dev/null
@@ -1,85 +0,0 @@
-//===- NodeIntrospection.h *- C++ 
-*---===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-//  This file contains the implementation of the NodeIntrospection.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
-#define LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
-
-#include "clang/AST/ASTTypeTraits.h"
-#include "clang/AST/DeclarationName.h"
-
-#include 
-#include 
-
-namespace clang {
-
-class Stmt;
-
-namespace tooling {
-
-class LocationCall {
-public:
-  enum LocationCallFlags { NoFlags, ReturnsPointer, IsCast };
-  LocationCall(std::shared_ptr on, std::string name,
-   LocationCallFlags flags = NoFlags)
-  : m_on(on), m_name(name), m_flags(flags) {}
-  LocationCall(std::shared_ptr on, std::string name,
-   std::vector const ,
-   LocationCallFlags flags = NoFlags)
-  : m_on(on), m_name(name), m_flags(flags) {}
-
-  LocationCall *on() const { return m_on.get(); }
-  StringRef name() const { return m_name; }
-  std::vector const () const { return m_args; }
-  bool returnsPointer() const { return m_flags & ReturnsPointer; }
-  bool isCast() const { return m_flags & IsCast; }
-
-private:
-  std::shared_ptr m_on;
-  std::string m_name;
-  std::vector m_args;
-  LocationCallFlags m_flags;
-};
-
-class LocationCallFormatterCpp {
-public:
-  static std::string format(LocationCall *Call);
-};
-
-namespace internal {
-struct RangeLessThan {
-  bool operator()(
-  std::pair> const ,
-  std::pair> const ) const;
-};
-} // namespace internal
-
-template >>
-using UniqueMultiMap = std::set, Comp>;
-
-using SourceLocationMap =
-UniqueMultiMap>;
-using SourceRangeMap =
-UniqueMultiMap,
-   internal::RangeLessThan>;
-
-struct NodeLocationAccessors {
-  SourceLocationMap LocationAccessors;
-  SourceRangeMap RangeAccessors;
-};
-
-namespace NodeIntrospection {
-NodeLocationAccessors GetLocations(clang::Stmt const *Object);
-NodeLocationAccessors GetLocations(clang::DynTypedNode const );
-} // namespace NodeIntrospection
-} // namespace tooling
-} // namespace clang
-#endif

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index c7fe324a39df..7a58af59dad1 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -8,107 +8,10 @@ add_subdirectory(Core)
 add_subdirectory(Inclusions)
 add_subdirectory(Refactoring)
 add_subdirectory(ASTDiff)
-add_subdirectory(DumpTool)
 add_subdirectory(Syntax)
 add_subdirectory(DependencyScanning)
 add_subdirectory(Transformer)
 
-find_package(Python3 COMPONENTS Interpreter)
-
-# Replace the last lib component of the current binary directory with include
-string(FIND ${CMAKE_CURRENT_BINARY_DIR} "/lib/" PATH_LIB_START REVERSE)
-if(PATH_LIB_START EQUAL -1)
-  message(FATAL_ERROR "Couldn't find lib component in binary directory")
-endif()
-math(EXPR PATH_LIB_END "${PATH_LIB_START}+5")
-string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD)
-string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 

[clang] 9249861 - Revert "Ensure that cache variable is set when not building introspection"

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-14T22:51:40Z
New Revision: 9249861437c0355c79c27c86229b9b92cd8eea5f

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

LOG: Revert "Ensure that cache variable is set when not building introspection"

This reverts commit 6b010c6f6e354966569e02841180c77df45bbd76.

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index efee9227a2c1..c7fe324a39df 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -47,7 +47,6 @@ NodeIntrospection::GetLocations(clang::DynTypedNode const &) {
 } // namespace clang
 "
 )
-set(CLANG_TOOLING_BUILD_AST_INTROSPECTION "OFF" CACHE BOOL "")
 else()
   # The generation of ASTNodeAPI.json takes a long time in a
   # Debug build due to parsing AST.h. Disable the processing



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


[clang] 6b010c6 - Ensure that cache variable is set when not building introspection

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-14T22:46:07Z
New Revision: 6b010c6f6e354966569e02841180c77df45bbd76

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

LOG: Ensure that cache variable is set when not building introspection

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index c7fe324a39df..efee9227a2c1 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -47,6 +47,7 @@ NodeIntrospection::GetLocations(clang::DynTypedNode const &) {
 } // namespace clang
 "
 )
+set(CLANG_TOOLING_BUILD_AST_INTROSPECTION "OFF" CACHE BOOL "")
 else()
   # The generation of ASTNodeAPI.json takes a long time in a
   # Debug build due to parsing AST.h. Disable the processing



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


[clang] 477e4b9 - [AST] Add generator for source location introspection

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-14T22:32:42Z
New Revision: 477e4b974653f92960c0bf569d88da7baacef68a

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

LOG: [AST] Add generator for source location introspection

Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

The JSON file can also be used to generate bindings for other languages,
such as Python and Javascript:

  https://steveire.wordpress.com/2019/04/30/the-future-of-ast-matching

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

Also in this version, the platforms/cmake configurations are excluded as
much as possible so that support can be added iteratively.  Currently a
break on any platform causes a revert of the entire feature.  This way,
the `OR WIN32` can be removed in a future commit and if it breaks the
buildbots, only that commit gets reverted, making the entire process
easier to manage.

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

Added: 
clang/include/clang/Tooling/NodeIntrospection.h
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/NodeIntrospection.cpp
clang/unittests/Introspection/CMakeLists.txt
clang/unittests/Introspection/IntrospectionTest.cpp
llvm/utils/gn/secondary/clang/lib/Tooling/DumpTool/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/Introspection/BUILD.gn

Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/unittests/CMakeLists.txt
llvm/utils/gn/secondary/clang/lib/Tooling/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/BUILD.gn

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
new file mode 100644
index ..abaa58b674a1
--- /dev/null
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -0,0 +1,85 @@
+//===- NodeIntrospection.h *- C++ 
-*---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file contains the implementation of the NodeIntrospection.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+#define LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/DeclarationName.h"
+
+#include 
+#include 
+
+namespace clang {
+
+class Stmt;
+
+namespace tooling {
+
+class LocationCall {
+public:
+  enum LocationCallFlags { NoFlags, ReturnsPointer, IsCast };
+  LocationCall(std::shared_ptr on, std::string name,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+  LocationCall(std::shared_ptr on, std::string name,
+   std::vector const ,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+
+  LocationCall *on() const { return m_on.get(); }
+  StringRef name() const { return m_name; }
+  std::vector const () const { return m_args; }
+  bool returnsPointer() const { return m_flags & ReturnsPointer; }
+  bool isCast() const { return m_flags & IsCast; }
+
+private:
+  std::shared_ptr m_on;
+  std::string m_name;
+  std::vector m_args;
+  LocationCallFlags m_flags;
+};
+
+class LocationCallFormatterCpp {
+public:
+  static std::string format(LocationCall *Call);
+};
+
+namespace internal {
+struct RangeLessThan {
+  bool operator()(
+  std::pair> const ,
+  std::pair> const ) const;
+};
+} // namespace internal
+
+template >>
+using UniqueMultiMap = std::set, Comp>;
+
+using SourceLocationMap =
+UniqueMultiMap>;
+using SourceRangeMap =
+UniqueMultiMap,
+   internal::RangeLessThan>;
+
+struct NodeLocationAccessors {
+  SourceLocationMap LocationAccessors;
+  SourceRangeMap RangeAccessors;
+};
+
+namespace NodeIntrospection 

[clang] cefe711 - Fix license headers

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-14T15:45:53Z
New Revision: cefe711135c40b6fb9670cf92118f94f88964b23

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

LOG: Fix license headers

Added: 


Modified: 
clang/lib/Tooling/DumpTool/APIData.h
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/APIData.h 
b/clang/lib/Tooling/DumpTool/APIData.h
index bf68a3b2a89e..0ec53f6e7dc3 100644
--- a/clang/lib/Tooling/DumpTool/APIData.h
+++ b/clang/lib/Tooling/DumpTool/APIData.h
@@ -1,9 +1,8 @@
 //===- APIData.h -*- C++ 
-*===//
 //
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 
//===--===//
 

diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
index 3f97b7d9d798..ff279d9425d8 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.cpp
@@ -1,9 +1,8 @@
 //===- ASTSrcLocProcessor.cpp *- C++ 
-*===//
 //
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 
//===--===//
 

diff  --git a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h 
b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
index a4a9856485c8..00994758e03c 100644
--- a/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
+++ b/clang/lib/Tooling/DumpTool/ASTSrcLocProcessor.h
@@ -1,9 +1,8 @@
 //===- ASTSrcLocProcessor.h -*- C++ 
-*-===//
 //
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 
//===--===//
 

diff  --git a/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp 
b/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
index e987de7c800e..28337eae9e85 100644
--- a/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
+++ b/clang/lib/Tooling/DumpTool/ClangSrcLocDump.cpp
@@ -1,9 +1,8 @@
 //===- ClangSrcLocDump.cpp *- C++ 
-*---===//
 //
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
+// 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
 //
 
//===--===//
 



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


[clang] 970c21e - Remove unneeded targets dependency

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-14T15:37:30Z
New Revision: 970c21e345548a967c1bc000462198330982ed7e

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

LOG: Remove unneeded targets dependency

Added: 


Modified: 
clang/unittests/Introspection/CMakeLists.txt

Removed: 




diff  --git a/clang/unittests/Introspection/CMakeLists.txt 
b/clang/unittests/Introspection/CMakeLists.txt
index 2010379ae51c..3dd8aec56b76 100644
--- a/clang/unittests/Introspection/CMakeLists.txt
+++ b/clang/unittests/Introspection/CMakeLists.txt
@@ -1,5 +1,4 @@
 set(LLVM_LINK_COMPONENTS
-  ${LLVM_TARGETS_TO_BUILD}
   FrontendOpenMP
   Support
   )



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


[clang] f72f122 - Update python script per review comments

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-14T15:37:30Z
New Revision: f72f122feebe7f980c22ed4a7e04fc274ce2c976

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

LOG: Update python script per review comments

Wrap to 80 cols, introduce main() function and use argparse instead of
optparse.

Added: 


Modified: 
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py 
b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
index aafae2c15b29..0740db0c7629 100755
--- a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
+++ b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
@@ -5,40 +5,7 @@
 import sys
 import json
 
-from optparse import OptionParser
-
-parser = OptionParser()
-parser.add_option('--json-input-path',
-  help='Read API description from FILE', metavar='FILE')
-parser.add_option('--output-file', help='Generate output in FILEPATH',
-  metavar='FILEPATH')
-parser.add_option('--empty-implementation', help='Generate empty 
implementation',
-  action="store", type="int", metavar='FILEPATH')
-
-(options, args) = parser.parse_args()
-
-if options.empty_implementation:
-with open(os.path.join(os.getcwd(),
-  options.output_file), 'w') as f:
-f.write("""
-namespace clang {
-namespace tooling {
-
-NodeLocationAccessors NodeIntrospection::GetLocations(clang::Stmt const *) {
-  return {};
-}
-NodeLocationAccessors
-NodeIntrospection::GetLocations(clang::DynTypedNode const &) {
-  return {};
-}
-} // namespace tooling
-} // namespace clang
-""")
-sys.exit(0)
-
-with open(options.json_input_path) as f:
-jsonData = json.load(f)
-
+import argparse
 
 class Generator(object):
 
@@ -66,7 +33,8 @@ def GeneratePrologue(self):
 def GenerateBaseGetLocationsDeclaration(self, CladeName):
 self.implementationContent += \
 """
-void GetLocationsImpl(std::shared_ptr const& Prefix, clang::{0} 
const *Object, SourceLocationMap ,
+void GetLocationsImpl(std::shared_ptr const& Prefix,
+clang::{0} const *Object, SourceLocationMap ,
 SourceRangeMap );
 """.format(CladeName)
 
@@ -84,7 +52,8 @@ def GenerateSrcLocMethod(self, ClassName, ClassData):
 for locName in ClassData['sourceLocations']:
 self.implementationContent += \
 """
-  Locs.insert(LocationAndString(Object.{0}(), 
std::make_shared(Prefix, "{0}")));
+  Locs.insert(LocationAndString(Object.{0}(),
+std::make_shared(Prefix, "{0}")));
 """.format(locName)
 
 self.implementationContent += '\n'
@@ -93,7 +62,8 @@ def GenerateSrcLocMethod(self, ClassName, ClassData):
 for rngName in ClassData['sourceRanges']:
 self.implementationContent += \
 """
-  Rngs.insert(RangeAndString(Object.{0}(), 
std::make_shared(Prefix, "{0}")));
+  Rngs.insert(RangeAndString(Object.{0}(),
+std::make_shared(Prefix, "{0}")));
 """.format(rngName)
 
 self.implementationContent += '\n'
@@ -105,16 +75,6 @@ def GenerateFiles(self, OutputFile):
   OutputFile), 'w') as f:
 f.write(self.implementationContent)
 
-def GenerateTrivialBaseGetLocationsFunction(self, CladeName):
-MethodReturnType = 'NodeLocationAccessors'
-
-Signature = \
-'GetLocations(clang::{0} const *Object)'.format(CladeName)
-
-self.implementationContent += \
-'{0} NodeIntrospection::{1} {{ return {{}}; 
}}'.format(MethodReturnType,
-Signature)
-
 def GenerateBaseGetLocationsFunction(self, ASTClassNames, CladeName):
 
 MethodReturnType = 'NodeLocationAccessors'
@@ -129,7 +89,8 @@ def GenerateBaseGetLocationsFunction(self, ASTClassNames, 
CladeName):
 """.format(CladeName)
 
 self.implementationContent += \
-'void {0} {{ GetLocations{1}(Prefix, *Object, Locs, 
Rngs);'.format(ImplSignature,
+'void {0} {{ GetLocations{1}(Prefix, *Object, Locs, Rngs);'.format(
+ImplSignature,
 CladeName)
 
 for ASTClassName in ASTClassNames:
@@ -180,29 +141,61 @@ def GenerateEpilogue(self):
 }
 '''
 
+def main():
+
+parser = argparse.ArgumentParser()
+parser.add_argument('--json-input-path',
+  help='Read API description from FILE', metavar='FILE')
+parser.add_argument('--output-file', help='Generate output in FILEPATH',
+  metavar='FILEPATH')
+parser.add_argument('--empty-implementation',
+  help='Generate empty implementation',
+  action="store", type=int)
+
+options = parser.parse_args()
+
+if options.empty_implementation:
+with 

[clang] 77f7d2b - [AST] Add generator for source location introspection

2021-03-14 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-14T10:54:33Z
New Revision: 77f7d2be214a1de29d583c75739f563593991fc3

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

LOG: [AST] Add generator for source location introspection

Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

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

Added: 
clang/include/clang/Tooling/NodeIntrospection.h
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/NodeIntrospection.cpp
clang/unittests/Introspection/CMakeLists.txt
clang/unittests/Introspection/IntrospectionTest.cpp

Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
new file mode 100644
index ..abaa58b674a1
--- /dev/null
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -0,0 +1,85 @@
+//===- NodeIntrospection.h *- C++ 
-*---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file contains the implementation of the NodeIntrospection.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+#define LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/DeclarationName.h"
+
+#include 
+#include 
+
+namespace clang {
+
+class Stmt;
+
+namespace tooling {
+
+class LocationCall {
+public:
+  enum LocationCallFlags { NoFlags, ReturnsPointer, IsCast };
+  LocationCall(std::shared_ptr on, std::string name,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+  LocationCall(std::shared_ptr on, std::string name,
+   std::vector const ,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+
+  LocationCall *on() const { return m_on.get(); }
+  StringRef name() const { return m_name; }
+  std::vector const () const { return m_args; }
+  bool returnsPointer() const { return m_flags & ReturnsPointer; }
+  bool isCast() const { return m_flags & IsCast; }
+
+private:
+  std::shared_ptr m_on;
+  std::string m_name;
+  std::vector m_args;
+  LocationCallFlags m_flags;
+};
+
+class LocationCallFormatterCpp {
+public:
+  static std::string format(LocationCall *Call);
+};
+
+namespace internal {
+struct RangeLessThan {
+  bool operator()(
+  std::pair> const ,
+  std::pair> const ) const;
+};
+} // namespace internal
+
+template >>
+using UniqueMultiMap = std::set, Comp>;
+
+using SourceLocationMap =
+UniqueMultiMap>;
+using SourceRangeMap =
+UniqueMultiMap,
+   internal::RangeLessThan>;
+
+struct NodeLocationAccessors {
+  SourceLocationMap LocationAccessors;
+  SourceRangeMap RangeAccessors;
+};
+
+namespace NodeIntrospection {
+NodeLocationAccessors GetLocations(clang::Stmt const *Object);
+NodeLocationAccessors GetLocations(clang::DynTypedNode const );
+} // namespace NodeIntrospection
+} // namespace tooling
+} // namespace clang
+#endif

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 7a58af59dad1..9572ad09df0a 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -8,10 +8,83 @@ add_subdirectory(Core)
 add_subdirectory(Inclusions)
 add_subdirectory(Refactoring)
 add_subdirectory(ASTDiff)
+add_subdirectory(DumpTool)
 add_subdirectory(Syntax)
 add_subdirectory(DependencyScanning)
 add_subdirectory(Transformer)
 
+find_package(Python3 COMPONENTS Interpreter)
+
+# The generation of ASTNodeAPI.json takes a long time in a
+# Debug 

[clang] 774b707 - Revert "Workaround a -Wmisleading-indentation warning"

2021-03-10 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-10T23:35:41Z
New Revision: 774b707564e1eed8fec5b5874d0aa82628de0651

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

LOG: Revert "Workaround a -Wmisleading-indentation warning"

This reverts commit 5c22e2bec008760cc7078d8d14382ef4762c5d54.

Added: 


Modified: 
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py 
b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
index aafae2c15b29..dee7a416e69a 100755
--- a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
+++ b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
@@ -171,7 +171,7 @@ def GenerateDynNodeVisitor(self, CladeNames):
 if (const auto *N = Node.get<{0}>())
   return GetLocations(const_cast<{0} *>(N));""".format(CladeName)
 
-self.implementationContent += '\nreturn {}; }'
+self.implementationContent += 'return {}; }'
 
 def GenerateEpilogue(self):
 



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


[clang] 14050dd - Revert "[AST] Add generator for source location introspection"

2021-03-10 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-10T23:36:06Z
New Revision: 14050ddc4080beb7a9143340be37ec05890cd537

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

LOG: Revert "[AST] Add generator for source location introspection"

This reverts commit d627a27d264b47eda3f15f086ff419dfe053ebf7.

This fails to link on Windows somehow.

Added: 


Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/unittests/CMakeLists.txt

Removed: 
clang/include/clang/Tooling/NodeIntrospection.h
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/NodeIntrospection.cpp
clang/unittests/Introspection/CMakeLists.txt
clang/unittests/Introspection/IntrospectionTest.cpp



diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
deleted file mode 100644
index abaa58b674a1..
--- a/clang/include/clang/Tooling/NodeIntrospection.h
+++ /dev/null
@@ -1,85 +0,0 @@
-//===- NodeIntrospection.h *- C++ 
-*---===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-//  This file contains the implementation of the NodeIntrospection.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
-#define LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
-
-#include "clang/AST/ASTTypeTraits.h"
-#include "clang/AST/DeclarationName.h"
-
-#include 
-#include 
-
-namespace clang {
-
-class Stmt;
-
-namespace tooling {
-
-class LocationCall {
-public:
-  enum LocationCallFlags { NoFlags, ReturnsPointer, IsCast };
-  LocationCall(std::shared_ptr on, std::string name,
-   LocationCallFlags flags = NoFlags)
-  : m_on(on), m_name(name), m_flags(flags) {}
-  LocationCall(std::shared_ptr on, std::string name,
-   std::vector const ,
-   LocationCallFlags flags = NoFlags)
-  : m_on(on), m_name(name), m_flags(flags) {}
-
-  LocationCall *on() const { return m_on.get(); }
-  StringRef name() const { return m_name; }
-  std::vector const () const { return m_args; }
-  bool returnsPointer() const { return m_flags & ReturnsPointer; }
-  bool isCast() const { return m_flags & IsCast; }
-
-private:
-  std::shared_ptr m_on;
-  std::string m_name;
-  std::vector m_args;
-  LocationCallFlags m_flags;
-};
-
-class LocationCallFormatterCpp {
-public:
-  static std::string format(LocationCall *Call);
-};
-
-namespace internal {
-struct RangeLessThan {
-  bool operator()(
-  std::pair> const ,
-  std::pair> const ) const;
-};
-} // namespace internal
-
-template >>
-using UniqueMultiMap = std::set, Comp>;
-
-using SourceLocationMap =
-UniqueMultiMap>;
-using SourceRangeMap =
-UniqueMultiMap,
-   internal::RangeLessThan>;
-
-struct NodeLocationAccessors {
-  SourceLocationMap LocationAccessors;
-  SourceRangeMap RangeAccessors;
-};
-
-namespace NodeIntrospection {
-NodeLocationAccessors GetLocations(clang::Stmt const *Object);
-NodeLocationAccessors GetLocations(clang::DynTypedNode const );
-} // namespace NodeIntrospection
-} // namespace tooling
-} // namespace clang
-#endif

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 9600bf7fa16d..7a58af59dad1 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -8,78 +8,10 @@ add_subdirectory(Core)
 add_subdirectory(Inclusions)
 add_subdirectory(Refactoring)
 add_subdirectory(ASTDiff)
-add_subdirectory(DumpTool)
 add_subdirectory(Syntax)
 add_subdirectory(DependencyScanning)
 add_subdirectory(Transformer)
 
-find_package(Python3 COMPONENTS Interpreter)
-
-# The generation of ASTNodeAPI.json takes a long time in a
-# Debug build due to parsing AST.h. Disable the processing
-# but setting CLANG_TOOLING_BUILD_AST_INTROSPECTION as an
-# internal hidden setting to override.
-# When the processing is disabled, a trivial/empty JSON
-# file is generated by clang-ast-dump and generate_cxx_src_locs.py
-# generates the same API, but with a trivial implementation.
-
-option(CLANG_TOOLING_BUILD_AST_INTROSPECTION "Enable AST introspection" TRUE)
-set(skip_expensive_processing 
$,$>>)
-
-add_custom_command(
-COMMENT Generate ASTNodeAPI.json
-OUTPUT ${CMAKE_BINARY_DIR}/ASTNodeAPI.json
-   

[clang] 5c22e2b - Workaround a -Wmisleading-indentation warning

2021-03-10 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-10T23:12:31Z
New Revision: 5c22e2bec008760cc7078d8d14382ef4762c5d54

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

LOG: Workaround a -Wmisleading-indentation warning

Because the generated code is not formatted, it can cause warnings.

Added: 


Modified: 
clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py

Removed: 




diff  --git a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py 
b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
index dee7a416e69a..aafae2c15b29 100755
--- a/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
+++ b/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py
@@ -171,7 +171,7 @@ def GenerateDynNodeVisitor(self, CladeNames):
 if (const auto *N = Node.get<{0}>())
   return GetLocations(const_cast<{0} *>(N));""".format(CladeName)
 
-self.implementationContent += 'return {}; }'
+self.implementationContent += '\nreturn {}; }'
 
 def GenerateEpilogue(self):
 



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


[clang] d627a27 - [AST] Add generator for source location introspection

2021-03-10 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-10T22:38:39Z
New Revision: d627a27d264b47eda3f15f086ff419dfe053ebf7

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

LOG: [AST] Add generator for source location introspection

Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

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

Added: 
clang/include/clang/Tooling/NodeIntrospection.h
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/NodeIntrospection.cpp
clang/unittests/Introspection/CMakeLists.txt
clang/unittests/Introspection/IntrospectionTest.cpp

Modified: 
clang/lib/Tooling/CMakeLists.txt
clang/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang/include/clang/Tooling/NodeIntrospection.h 
b/clang/include/clang/Tooling/NodeIntrospection.h
new file mode 100644
index ..abaa58b674a1
--- /dev/null
+++ b/clang/include/clang/Tooling/NodeIntrospection.h
@@ -0,0 +1,85 @@
+//===- NodeIntrospection.h *- C++ 
-*---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file contains the implementation of the NodeIntrospection.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+#define LLVM_CLANG_TOOLING_NODEINTROSPECTION_H
+
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/DeclarationName.h"
+
+#include 
+#include 
+
+namespace clang {
+
+class Stmt;
+
+namespace tooling {
+
+class LocationCall {
+public:
+  enum LocationCallFlags { NoFlags, ReturnsPointer, IsCast };
+  LocationCall(std::shared_ptr on, std::string name,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+  LocationCall(std::shared_ptr on, std::string name,
+   std::vector const ,
+   LocationCallFlags flags = NoFlags)
+  : m_on(on), m_name(name), m_flags(flags) {}
+
+  LocationCall *on() const { return m_on.get(); }
+  StringRef name() const { return m_name; }
+  std::vector const () const { return m_args; }
+  bool returnsPointer() const { return m_flags & ReturnsPointer; }
+  bool isCast() const { return m_flags & IsCast; }
+
+private:
+  std::shared_ptr m_on;
+  std::string m_name;
+  std::vector m_args;
+  LocationCallFlags m_flags;
+};
+
+class LocationCallFormatterCpp {
+public:
+  static std::string format(LocationCall *Call);
+};
+
+namespace internal {
+struct RangeLessThan {
+  bool operator()(
+  std::pair> const ,
+  std::pair> const ) const;
+};
+} // namespace internal
+
+template >>
+using UniqueMultiMap = std::set, Comp>;
+
+using SourceLocationMap =
+UniqueMultiMap>;
+using SourceRangeMap =
+UniqueMultiMap,
+   internal::RangeLessThan>;
+
+struct NodeLocationAccessors {
+  SourceLocationMap LocationAccessors;
+  SourceRangeMap RangeAccessors;
+};
+
+namespace NodeIntrospection {
+NodeLocationAccessors GetLocations(clang::Stmt const *Object);
+NodeLocationAccessors GetLocations(clang::DynTypedNode const );
+} // namespace NodeIntrospection
+} // namespace tooling
+} // namespace clang
+#endif

diff  --git a/clang/lib/Tooling/CMakeLists.txt 
b/clang/lib/Tooling/CMakeLists.txt
index 7a58af59dad1..9600bf7fa16d 100644
--- a/clang/lib/Tooling/CMakeLists.txt
+++ b/clang/lib/Tooling/CMakeLists.txt
@@ -8,10 +8,78 @@ add_subdirectory(Core)
 add_subdirectory(Inclusions)
 add_subdirectory(Refactoring)
 add_subdirectory(ASTDiff)
+add_subdirectory(DumpTool)
 add_subdirectory(Syntax)
 add_subdirectory(DependencyScanning)
 add_subdirectory(Transformer)
 
+find_package(Python3 COMPONENTS Interpreter)
+
+# The generation of ASTNodeAPI.json takes a long time in a
+# Debug 

[clang] 243cd0a - [ASTMatchers] Make Param functors variadic

2021-03-03 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-03-03T11:41:20Z
New Revision: 243cd0afadc7b406ed6c314f7645b1d72748ddd1

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

LOG: [ASTMatchers] Make Param functors variadic

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

Added: 


Modified: 
clang/docs/tools/dump_ast_matchers.py
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/include/clang/ASTMatchers/ASTMatchersInternal.h
clang/include/clang/ASTMatchers/ASTMatchersMacros.h

Removed: 




diff  --git a/clang/docs/tools/dump_ast_matchers.py 
b/clang/docs/tools/dump_ast_matchers.py
index 18afbdd36c6e..2a26d10f7a04 100755
--- a/clang/docs/tools/dump_ast_matchers.py
+++ b/clang/docs/tools/dump_ast_matchers.py
@@ -351,13 +351,17 @@ def act_on_decl(declaration, comment, allowed_types):
 
 m = re.match(
 r"""^.*internal::VariadicFunction\s*<\s*
-  internal::PolymorphicMatcherWithParam1<[\S\s]+
-  AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)>,\s*([^,]+),
-  \s*[^>]+>\s*([a-zA-Z]*);$""", 
+  internal::PolymorphicMatcher<[\S\s]+
+  AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\),\s*(.*);$""",
 declaration, flags=re.X)
 
 if m:
-  results, arg, name = m.groups()[:3]
+  results, trailing = m.groups()
+  trailing, name = trailing.rsplit(">", 1)
+  name = name.strip()
+  trailing, _ = trailing.rsplit(",", 1)
+  _, arg = trailing.rsplit(",", 1)
+  arg = arg.strip()
 
   result_types = [r.strip() for r in results.split(',')]
   for result_type in result_types:

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index b82929019f6c..885bc74ad3ea 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -835,26 +835,16 @@ traverse(TraversalKind TK, const 
internal::ArgumentAdaptingMatcherFuncAdaptor<
ToTypes>>(TK, InnerMatcher);
 }
 
-template  class MatcherT, typename P1,
+template  class MatcherT, typename... P,
   typename ReturnTypesF>
 internal::TraversalWrapper<
-internal::PolymorphicMatcherWithParam1>
-traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam1<
-   MatcherT, P1, ReturnTypesF> ) {
-  return internal::TraversalWrapper<
-  internal::PolymorphicMatcherWithParam1>(
-  TK, InnerMatcher);
-}
-
-template  class MatcherT,
-  typename P1, typename P2, typename ReturnTypesF>
-internal::TraversalWrapper<
-internal::PolymorphicMatcherWithParam2>
-traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam2<
-   MatcherT, P1, P2, ReturnTypesF> ) {
+internal::PolymorphicMatcher>
+traverse(TraversalKind TK,
+ const internal::PolymorphicMatcher
+ ) {
   return internal::TraversalWrapper<
-  internal::PolymorphicMatcherWithParam2>(
-  TK, InnerMatcher);
+  internal::PolymorphicMatcher>(TK,
+  
InnerMatcher);
 }
 
 template 
@@ -2996,14 +2986,15 @@ AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
 /// matches the declaration of \c A.
 ///
 /// Usable as: Matcher, Matcher
-inline internal::PolymorphicMatcherWithParam1<
-internal::HasOverloadedOperatorNameMatcher, std::vector,
-AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
+inline internal::PolymorphicMatcher<
+internal::HasOverloadedOperatorNameMatcher,
+AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl),
+std::vector>
 hasOverloadedOperatorName(StringRef Name) {
-  return internal::PolymorphicMatcherWithParam1<
-  internal::HasOverloadedOperatorNameMatcher, std::vector,
-  AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(
-  {std::string(Name)});
+  return internal::PolymorphicMatcher<
+  internal::HasOverloadedOperatorNameMatcher,
+  AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl),
+  std::vector>({std::string(Name)});
 }
 
 /// Matches overloaded operator names.
@@ -3015,9 +3006,10 @@ hasOverloadedOperatorName(StringRef Name) {
 /// Is equivalent to
 ///   anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
 extern const internal::VariadicFunction<
-internal::PolymorphicMatcherWithParam1<
-internal::HasOverloadedOperatorNameMatcher, std::vector,
-AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>,
+internal::PolymorphicMatcher>,
 StringRef, internal::hasAnyOverloadedOperatorNameFunc>
 hasAnyOverloadedOperatorName;
 
@@ -3506,13 +3498,14 @@ extern const 

[clang-tools-extra] 7b6fc9a - [clang-tidy] Simplify unused RAII check

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

Author: Stephen Kelly
Date: 2021-03-02T21:33:34Z
New Revision: 7b6fc9a1055a7eae07645fb7d3085dc89a8d54ab

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

LOG: [clang-tidy] Simplify unused RAII check

Fix handling of default construction where the constructor has a default arg.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp
clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.h
clang-tools-extra/test/clang-tidy/checkers/bugprone-unused-raii.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp
index 3a52180cf04d..b87bb9e8ca95 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp
@@ -25,25 +25,37 @@ AST_MATCHER(CXXRecordDecl, hasNonTrivialDestructor) {
 
 void UnusedRaiiCheck::registerMatchers(MatchFinder *Finder) {
   // Look for temporaries that are constructed in-place and immediately
-  // destroyed. Look for temporaries created by a functional cast but not for
-  // those returned from a call.
-  auto BindTemp = cxxBindTemporaryExpr(
-  unless(has(ignoringParenImpCasts(callExpr(,
-  unless(has(ignoringParenImpCasts(objcMessageExpr()
-  .bind("temp");
+  // destroyed.
   Finder->addMatcher(
-  traverse(TK_AsIs,
-   exprWithCleanups(
-   unless(isInTemplateInstantiation()),
-   hasParent(compoundStmt().bind("compound")),
-   hasType(cxxRecordDecl(hasNonTrivialDestructor())),
-   anyOf(has(ignoringParenImpCasts(BindTemp)),
- has(ignoringParenImpCasts(cxxFunctionalCastExpr(
- has(ignoringParenImpCasts(BindTemp)))
-   .bind("expr")),
+  mapAnyOf(cxxConstructExpr, cxxUnresolvedConstructExpr)
+  .with(hasParent(compoundStmt().bind("compound")),
+anyOf(hasType(cxxRecordDecl(hasNonTrivialDestructor())),
+  hasType(templateSpecializationType(
+  hasDeclaration(classTemplateDecl(has(
+  cxxRecordDecl(hasNonTrivialDestructor()
+  .bind("expr"),
   this);
 }
 
+template 
+void reportDiagnostic(DiagnosticBuilder D, const T *Node, SourceRange SR,
+  bool DefaultConstruction) {
+  const char *Replacement = " give_me_a_name";
+
+  // If this is a default ctor we have to remove the parens or we'll introduce 
a
+  // most vexing parse.
+  if (DefaultConstruction) {
+D << FixItHint::CreateReplacement(CharSourceRange::getTokenRange(SR),
+  Replacement);
+return;
+  }
+
+  // Otherwise just suggest adding a name. To find the place to insert the name
+  // find the first TypeLoc in the children of E, which always points to the
+  // written type.
+  D << FixItHint::CreateInsertion(SR.getBegin(), Replacement);
+}
+
 void UnusedRaiiCheck::check(const MatchFinder::MatchResult ) {
   const auto *E = Result.Nodes.getNodeAs("expr");
 
@@ -55,35 +67,32 @@ void UnusedRaiiCheck::check(const MatchFinder::MatchResult 
) {
   // Don't emit a warning for the last statement in the surrounding compound
   // statement.
   const auto *CS = Result.Nodes.getNodeAs("compound");
-  if (E == CS->body_back())
+  const auto *LastExpr = dyn_cast(CS->body_back());
+
+  if (LastExpr && E == LastExpr->IgnoreUnlessSpelledInSource())
 return;
 
   // Emit a warning.
   auto D = diag(E->getBeginLoc(), "object destroyed immediately after "
   "creation; did you mean to name the 
object?");
-  const char *Replacement = " give_me_a_name";
 
-  // If this is a default ctor we have to remove the parens or we'll introduce 
a
-  // most vexing parse.
-  const auto *BTE = Result.Nodes.getNodeAs("temp");
-  if (const auto *TOE = dyn_cast(BTE->getSubExpr()))
-if (TOE->getNumArgs() == 0) {
-  D << FixItHint::CreateReplacement(
-  CharSourceRange::getTokenRange(TOE->getParenOrBraceRange()),
-  Replacement);
-  return;
+  if (const auto *Node = dyn_cast(E))
+reportDiagnostic(D, Node, Node->getParenOrBraceRange(),
+ Node->getNumArgs() == 0 ||
+ isa(Node->getArg(0)));
+  if (const auto *Node = dyn_cast(E)) {
+auto SR = SourceRange(Node->getLParenLoc(), Node->getRParenLoc());
+auto DefaultConstruction = Node->getNumArgs() == 0;
+if (!DefaultConstruction) {
+  auto FirstArg = Node->getArg(0);
+  DefaultConstruction = isa(FirstArg);
+  if 

[clang-tools-extra] 40cee38 - Add tests which include brace initialization

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

Author: Stephen Kelly
Date: 2021-03-01T00:34:58Z
New Revision: 40cee381c1779256e039d66ea5d01ad7d344efb7

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

LOG: Add tests which include brace initialization

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-unused-raii.cpp

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-unused-raii.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-unused-raii.cpp
index d637806ba20a..3428d453c63d 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone-unused-raii.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone-unused-raii.cpp
@@ -64,6 +64,13 @@ void test() {
 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after 
creation; did you mean to name the object?
 // CHECK-FIXES: FooBar give_me_a_name;
 
+  Foo{42};
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately 
after creation; did you mean to name the object?
+  // CHECK-FIXES: Foo give_me_a_name{42};
+  FooBar{};
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately 
after creation; did you mean to name the object?
+  // CHECK-FIXES: FooBar give_me_a_name;
+
   templ();
   templ();
 



___
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'
+  // 

[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


[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


[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


[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


[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("==", "!="),
- 

[clang] b5b3243 - Regenerate documentation

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

Author: Stephen Kelly
Date: 2021-02-22T11:07:45Z
New Revision: b5b3243bf783f07415c5e2838fa1a948e126f643

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

LOG: Regenerate documentation

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index a956091318a1..0becf5ebfb8c 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -7152,7 +7152,8 @@ AST Traversal Matchers
 f = 42;
 }
 The matcher:
-  decompositionDecl(hasBinding(0, bindingDecl(hasName("f").bind("fBinding"
+  decompositionDecl(hasBinding(0,
+  bindingDecl(hasName("f").bind("fBinding"
 matches the decomposition decl with 'f' bound to "fBinding".
 
 



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


[clang-tools-extra] 77056fe - [clang-tidy] Simplify throw keyword missing check

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

Author: Stephen Kelly
Date: 2021-02-20T22:07:20Z
New Revision: 77056fe58e83100b902216d7bc6274129f80abda

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

LOG: [clang-tidy] Simplify throw keyword missing check

Extend test to verify that it does not match in template instantiations.

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

Added: 


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

clang-tools-extra/test/clang-tidy/checkers/bugprone-throw-keyword-missing.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp
index 25e7bc9d91e0..462a33a374a5 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ThrowKeywordMissingCheck.cpp
@@ -21,17 +21,16 @@ void ThrowKeywordMissingCheck::registerMatchers(MatchFinder 
*Finder) {
   cxxConstructorDecl(hasAnyConstructorInitializer(anything()));
 
   Finder->addMatcher(
-  expr(anyOf(cxxFunctionalCastExpr(), cxxBindTemporaryExpr(),
- cxxTemporaryObjectExpr()),
-   hasType(cxxRecordDecl(
-   isSameOrDerivedFrom(matchesName("[Ee]xception|EXCEPTION",
-   unless(anyOf(hasAncestor(stmt(
-anyOf(cxxThrowExpr(), callExpr(), returnStmt(,
-hasAncestor(varDecl()),
-allOf(hasAncestor(CtorInitializerList),
-  unless(hasAncestor(cxxCatchStmt()))
+  cxxConstructExpr(
+  hasType(cxxRecordDecl(
+  isSameOrDerivedFrom(matchesName("[Ee]xception|EXCEPTION",
+  unless(anyOf(hasAncestor(stmt(
+   anyOf(cxxThrowExpr(), callExpr(), returnStmt(,
+   hasAncestor(varDecl()),
+   allOf(hasAncestor(CtorInitializerList),
+ unless(hasAncestor(cxxCatchStmt()))
   .bind("temporary-exception-not-thrown"),
-  this); 
+  this);
 }
 
 void ThrowKeywordMissingCheck::check(const MatchFinder::MatchResult ) {

diff  --git a/clang-tools-extra/clang-tidy/bugprone/ThrowKeywordMissingCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/ThrowKeywordMissingCheck.h
index 0ea1faab249c..fc2203765f1c 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ThrowKeywordMissingCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/ThrowKeywordMissingCheck.h
@@ -29,6 +29,9 @@ class ThrowKeywordMissingCheck : 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 bugprone

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-throw-keyword-missing.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-throw-keyword-missing.cpp
index 7780089ce8f3..5fae036fc5a3 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-throw-keyword-missing.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-throw-keyword-missing.cpp
@@ -94,8 +94,17 @@ void nameContainsExceptionThrownTest(int i) {
 template 
 void f(int i, Exception excToBeThrown) {}
 
+template 
+void templ(int i) {
+  if (i > 0)
+SomeType();
+}
+
 void funcCallWithTempExcTest() {
   f(5, RegularException());
+
+  templ(4);
+  templ(4);
 }
 
 // Global variable initialization test.



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


[clang-tools-extra] 6852a29 - [clang-tidy] Simplify function complexity check

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

Author: Stephen Kelly
Date: 2021-02-20T22:06:16Z
New Revision: 6852a29a3b5b7858757c175f39e04676fb856dab

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

LOG: [clang-tidy] Simplify function complexity check

Update test to note use of lambda instead of the invisible operator().

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.h

clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
index 88a422ab45a3..3a4758302406 100644
--- 
a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
@@ -502,27 +502,40 @@ void FunctionCognitiveComplexityCheck::storeOptions(
 void FunctionCognitiveComplexityCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(isDefinition(),
-   unless(anyOf(isDefaulted(), isDeleted(), isImplicit(),
-isInstantiated(), isWeak(
+   unless(anyOf(isDefaulted(), isDeleted(), isWeak(
   .bind("func"),
   this);
+  Finder->addMatcher(lambdaExpr().bind("lambda"), this);
 }
 
 void FunctionCognitiveComplexityCheck::check(
 const MatchFinder::MatchResult ) {
-  const auto *Func = Result.Nodes.getNodeAs("func");
-  assert(Func->hasBody() && "The matchers should only match the functions that 
"
-"have user-provided body.");
 
   FunctionASTVisitor Visitor;
-  Visitor.TraverseDecl(const_cast(Func), true);
+  SourceLocation Loc;
+
+  const auto *TheDecl = Result.Nodes.getNodeAs("func");
+  const auto *TheLambdaExpr = Result.Nodes.getNodeAs("lambda");
+  if (TheDecl) {
+assert(TheDecl->hasBody() &&
+   "The matchers should only match the functions that "
+   "have user-provided body.");
+Loc = TheDecl->getLocation();
+Visitor.TraverseDecl(const_cast(TheDecl), true);
+  } else {
+Loc = TheLambdaExpr->getBeginLoc();
+Visitor.TraverseLambdaExpr(const_cast(TheLambdaExpr));
+  }
 
   if (Visitor.CC.Total <= Threshold)
 return;
 
-  diag(Func->getLocation(),
-   "function %0 has cognitive complexity of %1 (threshold %2)")
-  << Func << Visitor.CC.Total << Threshold;
+  if (TheDecl)
+diag(Loc, "function %0 has cognitive complexity of %1 (threshold %2)")
+<< TheDecl << Visitor.CC.Total << Threshold;
+  else
+diag(Loc, "lambda has cognitive complexity of %0 (threshold %1)")
+<< Visitor.CC.Total << Threshold;
 
   // Output all the basic increments of complexity.
   for (const auto  : Visitor.CC.Details) {

diff  --git 
a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.h 
b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.h
index 96b6723d2a6a..a21b8447029b 100644
--- 
a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.h
+++ 
b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.h
@@ -31,6 +31,9 @@ class FunctionCognitiveComplexityCheck : 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:
   const unsigned Threshold;

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity.cpp
index 79bc0c3dc4de..021330ccf9fd 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity.cpp
@@ -666,7 +666,7 @@ void unittest_b2_08_02() {
 // CHECK-NOTES: :[[@LINE-1]]:5: note: +2, including nesting penalty of 1, 
nesting level increased to 2{{$}}
 }
   };
-// CHECK-NOTES: :[[@LINE-6]]:14: warning: function 'operator()' has cognitive 
complexity of 1 (threshold 0) [readability-function-cognitive-complexity]
+// CHECK-NOTES: :[[@LINE-6]]:14: warning: lambda has cognitive complexity of 1 
(threshold 0) [readability-function-cognitive-complexity]
 // CHECK-NOTES: :[[@LINE-5]]:5: note: +1, including nesting penalty of 0, 

[clang-tools-extra] 9a4b574 - [clang-itdy] Simplify virtual near-miss check

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

Author: Stephen Kelly
Date: 2021-02-20T22:02:00Z
New Revision: 9a4b574dd6a07d6811356529ebb8a3f15d6e40a2

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

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

Diagnose the problem in templates in the context of the template
declaration instead of in the context of all of the (possibly very many)
template instantiations.

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

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 150b517811b6..dc810c694874 100644
--- a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
@@ -216,10 +216,9 @@ bool VirtualNearMissCheck::isOverriddenByDerivedClass(
 
 void VirtualNearMissCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
-  cxxMethodDecl(
-  unless(anyOf(isOverride(), isImplicit(), cxxConstructorDecl(),
-   cxxDestructorDecl(), cxxConversionDecl(), isStatic(),
-   isOverloadedOperator(
+  cxxMethodDecl(unless(anyOf(isOverride(), cxxConstructorDecl(),
+ cxxDestructorDecl(), cxxConversionDecl(),
+ isStatic(), isOverloadedOperator(
   .bind("method"),
   this);
 }
@@ -234,7 +233,15 @@ void VirtualNearMissCheck::check(const 
MatchFinder::MatchResult ) {
   assert(DerivedRD);
 
   for (const auto  : DerivedRD->bases()) {
-if (const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl()) {
+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) {
   for (const auto *BaseMD : BaseRD->methods()) {
 if (!isPossibleToBeOverridden(BaseMD))
   continue;
@@ -250,16 +257,12 @@ void VirtualNearMissCheck::check(const 
MatchFinder::MatchResult ) {
 auto Range = CharSourceRange::getTokenRange(
 SourceRange(DerivedMD->getLocation()));
 
-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?")
+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();
-if (ApplyFix)
-  Diag << FixItHint::CreateReplacement(Range, BaseMD->getName());
+<< BaseMD->getQualifiedNameAsString()
+<< 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 69ae278f2e2c..ec902515f706 100644
--- a/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
@@ -32,6 +32,9 @@ 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 553d2f45a98b..f3f8d3225847 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,9 +44,8 @@ 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'
-  // 

[clang-tools-extra] e8b8f89 - [clang-tidy] Simplify braced init check

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

Author: Stephen Kelly
Date: 2021-02-20T20:09:13Z
New Revision: e8b8f896024620eb86bf924be73100d83c74c736

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

LOG: [clang-tidy] Simplify braced init check

The normalization of matchers means that this now works in all language
modes.

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

Added: 


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

clang-tools-extra/test/clang-tidy/checkers/modernize-return-braced-init-list.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.cpp
index 6dc91e91ffde..4c8b9571e4c7 100644
--- a/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.cpp
@@ -23,21 +23,14 @@ void 
ReturnBracedInitListCheck::registerMatchers(MatchFinder *Finder) {
   auto ConstructExpr =
   cxxConstructExpr(
   unless(anyOf(hasDeclaration(cxxConstructorDecl(isExplicit())),
-   isListInitialization(), hasDescendant(initListExpr()),
-   isInTemplateInstantiation(
+   isListInitialization(), hasDescendant(initListExpr()
   .bind("ctor");
 
-  auto CtorAsArgument = materializeTemporaryExpr(anyOf(
-  has(ConstructExpr), has(cxxFunctionalCastExpr(has(ConstructExpr);
-
   Finder->addMatcher(
-  traverse(TK_AsIs,
-   functionDecl(
-   isDefinition(), // Declarations don't have return 
statements.
-   returns(unless(anyOf(builtinType(), autoType(,
-   hasDescendant(returnStmt(hasReturnValue(
-   has(cxxConstructExpr(has(CtorAsArgument)))
-   .bind("fn")),
+  returnStmt(hasReturnValue(ConstructExpr),
+ forFunction(functionDecl(returns(unless(anyOf(builtinType(),
+   autoType()
+ .bind("fn"))),
   this);
 }
 

diff  --git 
a/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.h 
b/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.h
index 12bd694cd3ae..da863891bdee 100644
--- a/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/ReturnBracedInitListCheck.h
@@ -29,6 +29,9 @@ class ReturnBracedInitListCheck : 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

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-return-braced-init-list.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-return-braced-init-list.cpp
index 29d81c6df1f0..4db1d49da2ea 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-return-braced-init-list.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-return-braced-init-list.cpp
@@ -1,5 +1,4 @@
-// RUN: %check_clang_tidy -std=c++14 %s modernize-return-braced-init-list %t
-// FIXME: Fix the checker to work in C++17 mode.
+// RUN: %check_clang_tidy -std=c++14-or-later %s 
modernize-return-braced-init-list %t
 
 namespace std {
 typedef decltype(sizeof(int)) size_t;



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


[clang] 559f372 - [ASTMatchers] Fix hasUnaryOperand matcher for postfix operators

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

Author: Stephen Kelly
Date: 2021-02-20T17:54:12Z
New Revision: 559f3728441d4b8342c71ef554d84a2804575d9d

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

LOG: [ASTMatchers] Fix hasUnaryOperand matcher for postfix operators

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

Added: 


Modified: 
clang/include/clang/ASTMatchers/ASTMatchersInternal.h
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h 
b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
index 2af4e6e88109..5e3af4a2a34b 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -2039,7 +2039,8 @@ equivalentUnaryOperator(const NodeType ) {
 template <>
 inline Optional
 equivalentUnaryOperator(const CXXOperatorCallExpr ) {
-  if (Node.getNumArgs() != 1)
+  if (Node.getNumArgs() != 1 && Node.getOperator() != OO_PlusPlus &&
+  Node.getOperator() != OO_MinusMinus)
 return None;
   switch (Node.getOperator()) {
   default:

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 8a6e94cf5624..9909cec2065c 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -1630,6 +1630,84 @@ void opFree()

cxxOperatorCallExpr(forFunction(functionDecl(hasName("opFree"))),
hasAnyOperatorName("+", "!"),
hasUnaryOperand(s1Expr);
+
+  Code = R"cpp(
+struct HasIncOperatorsMem
+{
+HasIncOperatorsMem& operator++();
+HasIncOperatorsMem operator++(int);
+};
+struct HasIncOperatorsFree
+{
+};
+HasIncOperatorsFree& operator++(HasIncOperatorsFree&);
+HasIncOperatorsFree operator++(HasIncOperatorsFree&, int);
+
+void prefixIncOperatorMem()
+{
+HasIncOperatorsMem s1;
+++s1;
+}
+void prefixIncOperatorFree()
+{
+HasIncOperatorsFree s1;
+++s1;
+}
+void postfixIncOperatorMem()
+{
+HasIncOperatorsMem s1;
+s1++;
+}
+void postfixIncOperatorFree()
+{
+HasIncOperatorsFree s1;
+s1++;
+}
+
+struct HasOpPlusInt
+{
+HasOpPlusInt& operator+(int);
+};
+void plusIntOperator()
+{
+HasOpPlusInt s1;
+s1+1;
+}
+)cpp";
+
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   cxxOperatorCallExpr(
+   forFunction(functionDecl(hasName("prefixIncOperatorMem"))),
+   hasOperatorName("++"), hasUnaryOperand(declRefExpr());
+
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   cxxOperatorCallExpr(
+   forFunction(functionDecl(hasName("prefixIncOperatorFree"))),
+   hasOperatorName("++"), hasUnaryOperand(declRefExpr());
+
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   cxxOperatorCallExpr(
+   forFunction(functionDecl(hasName("postfixIncOperatorMem"))),
+   hasOperatorName("++"), hasUnaryOperand(declRefExpr());
+
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   cxxOperatorCallExpr(
+   
forFunction(functionDecl(hasName("postfixIncOperatorFree"))),
+   hasOperatorName("++"), hasUnaryOperand(declRefExpr());
+
+  EXPECT_FALSE(matches(
+  Code, traverse(TK_IgnoreUnlessSpelledInSource,
+ cxxOperatorCallExpr(
+ forFunction(functionDecl(hasName("plusIntOperator"))),
+ hasOperatorName("+"), hasUnaryOperand(expr());
 }
 
 TEST(Matcher, UnaryOperatorTypes) {



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


[clang] 6984e0d - Revert "Implement nullPointerConstant() using a better API."

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

Author: Stephen Kelly
Date: 2021-02-20T17:33:07Z
New Revision: 6984e0d4398592a20055cb12842fc72462ce01a5

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

LOG: Revert "Implement nullPointerConstant() using a better API."

This reverts commit 9148302a (2019-08-22) which broke the pre-existing
unit test for the matcher.  Also revert commit 518b2266 (Fix the
nullPointerConstant() test to get bots back to green., 2019-08-22) which
incorrectly changed the test to expect the broken behavior.

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

Added: 


Modified: 
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 6cd4d26768b5..b82929019f6c 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -7384,9 +7384,10 @@ extern const internal::VariadicDynCastAllOfMatcher
 /// expr(nullPointerConstant())
 ///   matches the initializer for v1, v2, v3, cp, and ip. Does not match the
 ///   initializer for i.
-AST_MATCHER(Expr, nullPointerConstant) {
-  return Node.isNullPointerConstant(Finder->getASTContext(),
-Expr::NPC_ValueDependentIsNull);
+AST_MATCHER_FUNCTION(internal::Matcher, nullPointerConstant) {
+  return anyOf(
+  gnuNullExpr(), cxxNullPtrLiteralExpr(),
+  integerLiteral(equals(0), hasParent(expr(hasType(pointerType());
 }
 
 /// Matches the DecompositionDecl the binding belongs to.

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
index 1c6947acf0ab..c26e8f8d4d22 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -3663,7 +3663,7 @@ TEST_P(ASTMatchersTest, NullPointerConstant) {
   expr(nullPointerConstant(;
   EXPECT_TRUE(matches("char *cp = (char *)0;", expr(nullPointerConstant(;
   EXPECT_TRUE(matches("int *ip = 0;", expr(nullPointerConstant(;
-  EXPECT_TRUE(matches("int i = 0;", expr(nullPointerConstant(;
+  EXPECT_FALSE(matches("int i = 0;", expr(nullPointerConstant(;
 }
 
 TEST_P(ASTMatchersTest, NullPointerConstant_GNUNull) {



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


[clang] e4d5f00 - [ASTMatchers] Fix hasParent while ignoring unwritten nodes

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

Author: Stephen Kelly
Date: 2021-02-18T15:04:03Z
New Revision: e4d5f00093bec4099f1d0496181dc670c42ac220

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

LOG: [ASTMatchers] Fix hasParent while ignoring unwritten nodes

For example, before this patch we can use has() to get from a
cxxRewrittenBinaryOperator to its operand, but hasParent doesn't get
back to the cxxRewrittenBinaryOperator.  This patch fixes that.

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

Added: 


Modified: 
clang/include/clang/AST/ParentMapContext.h
clang/lib/AST/ParentMapContext.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ParentMapContext.h 
b/clang/include/clang/AST/ParentMapContext.h
index a0412380a864..2edbc987850d 100644
--- a/clang/include/clang/AST/ParentMapContext.h
+++ b/clang/include/clang/AST/ParentMapContext.h
@@ -64,9 +64,10 @@ class ParentMapContext {
   Expr *traverseIgnored(Expr *E) const;
   DynTypedNode traverseIgnored(const DynTypedNode ) const;
 
+  class ParentMap;
+
 private:
   ASTContext 
-  class ParentMap;
   TraversalKind Traversal = TK_AsIs;
   std::unique_ptr Parents;
 };

diff  --git a/clang/lib/AST/ParentMapContext.cpp 
b/clang/lib/AST/ParentMapContext.cpp
index cb4995312efa..4a3e0a99c8a6 100644
--- a/clang/lib/AST/ParentMapContext.cpp
+++ b/clang/lib/AST/ParentMapContext.cpp
@@ -49,7 +49,17 @@ DynTypedNode ParentMapContext::traverseIgnored(const 
DynTypedNode ) const {
   return N;
 }
 
+template 
+std::tuple
+matchParents(const DynTypedNodeList ,
+ ParentMapContext::ParentMap *ParentMap);
+
+template  struct MatchParents;
+
 class ParentMapContext::ParentMap {
+
+  template  friend struct ::MatchParents;
+
   /// Contains parents of a node.
   using ParentVector = llvm::SmallVector;
 
@@ -117,11 +127,72 @@ class ParentMapContext::ParentMap {
 if (Node.getNodeKind().hasPointerIdentity()) {
   auto ParentList =
   getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
-  if (ParentList.size() == 1 && TK == TK_IgnoreUnlessSpelledInSource) {
-const auto *E = ParentList[0].get();
-const auto *Child = Node.get();
-if (E && Child)
-  return AscendIgnoreUnlessSpelledInSource(E, Child);
+  if (ParentList.size() > 0 && TK == TK_IgnoreUnlessSpelledInSource) {
+
+const auto *ChildExpr = Node.get();
+
+{
+  // Don't match explicit node types because 
diff erent stdlib
+  // implementations implement this in 
diff erent ways and have
+  // 
diff erent intermediate nodes.
+  // Look up 4 levels for a cxxRewrittenBinaryOperator as that is
+  // enough for the major stdlib implementations.
+  auto RewrittenBinOpParentsList = ParentList;
+  int I = 0;
+  while (ChildExpr && RewrittenBinOpParentsList.size() == 1 &&
+ I++ < 4) {
+const auto *S = RewrittenBinOpParentsList[0].get();
+if (!S)
+  break;
+
+const auto *RWBO = dyn_cast(S);
+if (!RWBO) {
+  RewrittenBinOpParentsList = getDynNodeFromMap(S, PointerParents);
+  continue;
+}
+if (RWBO->getLHS()->IgnoreUnlessSpelledInSource() != ChildExpr &&
+RWBO->getRHS()->IgnoreUnlessSpelledInSource() != ChildExpr)
+  break;
+return DynTypedNode::create(*RWBO);
+  }
+}
+
+const auto *ParentExpr = ParentList[0].get();
+if (ParentExpr && ChildExpr)
+  return AscendIgnoreUnlessSpelledInSource(ParentExpr, ChildExpr);
+
+{
+  auto AncestorNodes =
+  matchParents(ParentList, this);
+  if (std::get(AncestorNodes) &&
+  std::get(AncestorNodes)
+  ->getLoopVarStmt() ==
+  std::get(AncestorNodes))
+return std::get(AncestorNodes);
+}
+{
+  auto AncestorNodes = matchParents(
+  ParentList, this);
+  if (std::get(AncestorNodes) &&
+  std::get(AncestorNodes)
+  ->getRangeStmt() ==
+  std::get(AncestorNodes))
+return std::get(AncestorNodes);
+}
+{
+  auto AncestorNodes =
+  matchParents(ParentList,
+ this);
+  if (std::get(AncestorNodes))
+return std::get(AncestorNodes);
+}
+{
+  auto AncestorNodes =
+  matchParents(
+  ParentList, this);
+  if (std::get(AncestorNodes))
+return std::get(AncestorNodes);
+}
   }
   return 

[clang-tools-extra] ca4485d - [clang-tidy] Simplify const params check

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

Author: Stephen Kelly
Date: 2021-02-17T10:20:12Z
New Revision: ca4485d9fc3449f7bb9522ee16ccf63f2219732c

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

LOG: [clang-tidy] Simplify const params check

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

Added: 


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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp 
b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
index aed01ab7ae7c..d35cc079d78a 100644
--- a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
+++ b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.cpp
@@ -33,14 +33,6 @@ void AvoidConstParamsInDecls::registerMatchers(MatchFinder 
*Finder) {
   parmVarDecl(hasType(qualType(isConstQualified(.bind("param");
   Finder->addMatcher(
   functionDecl(unless(isDefinition()),
-   // Lambdas are always their own definition, but they
-   // generate a non-definition FunctionDecl too. Ignore those.
-   // Class template instantiations have a non-definition
-   // CXXMethodDecl for methods that aren't used in this
-   // translation unit. Ignore those, as the template will have
-   // already been checked.
-   unless(cxxMethodDecl(ofClass(cxxRecordDecl(anyOf(
-   isLambda(), 
ast_matchers::isTemplateInstantiation()),
has(typeLoc(forEach(ConstParamDecl
   .bind("func"),
   this);

diff  --git 
a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.h 
b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.h
index 08aac949f98e..d366949e4a16 100644
--- a/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.h
+++ b/clang-tools-extra/clang-tidy/readability/AvoidConstParamsInDecls.h
@@ -24,6 +24,9 @@ class AvoidConstParamsInDecls : 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 readability



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


[clang-tools-extra] 6c2eca9 - [clang-tidy] Simplify inefficient algorithm check

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

Author: Stephen Kelly
Date: 2021-02-17T10:19:44Z
New Revision: 6c2eca96a2a59f69889a9d4133a819ab2e4fa1ef

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

LOG: [clang-tidy] Simplify inefficient algorithm check

The normalization of matchers means that this now works in all language
modes.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.cpp
clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.h

clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-algorithm.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.cpp
index 8381ed0b1553..05ef855de7e7 100644
--- a/clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.cpp
@@ -35,27 +35,24 @@ void 
InefficientAlgorithmCheck::registerMatchers(MatchFinder *Finder) {
   "::std::unordered_set", "::std::unordered_map",
   "::std::unordered_multiset", "::std::unordered_multimap"));
 
-  const auto Matcher = traverse(
-  TK_AsIs,
+  const auto Matcher =
   callExpr(
   callee(functionDecl(Algorithms)),
   hasArgument(
-  0, cxxConstructExpr(has(ignoringParenImpCasts(cxxMemberCallExpr(
+  0, cxxMemberCallExpr(
  callee(cxxMethodDecl(hasName("begin"))),
  on(declRefExpr(
 hasDeclaration(decl().bind("IneffContObj")),
 anyOf(hasType(ContainerMatcher.bind("IneffCont")),
   hasType(pointsTo(
   ContainerMatcher.bind("IneffContPtr")
-.bind("IneffContExpr"))),
+.bind("IneffContExpr",
   hasArgument(
-  1, cxxConstructExpr(has(ignoringParenImpCasts(cxxMemberCallExpr(
- callee(cxxMethodDecl(hasName("end"))),
- on(declRefExpr(
- 
hasDeclaration(equalsBoundNode("IneffContObj"),
-  hasArgument(2, expr().bind("AlgParam")),
-  unless(isInTemplateInstantiation()))
-  .bind("IneffAlg"));
+  1, cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"))),
+   on(declRefExpr(hasDeclaration(
+   equalsBoundNode("IneffContObj")),
+  hasArgument(2, expr().bind("AlgParam")))
+  .bind("IneffAlg");
 
   Finder->addMatcher(Matcher, this);
 }

diff  --git 
a/clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.h 
b/clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.h
index 14f8fbbab2ae..5a7536ad76aa 100644
--- a/clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.h
+++ b/clang-tools-extra/clang-tidy/performance/InefficientAlgorithmCheck.h
@@ -29,6 +29,9 @@ class InefficientAlgorithmCheck : 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 performance

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-algorithm.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-algorithm.cpp
index aa4e30d6f3fe..19a6701c5b6a 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-algorithm.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/performance-inefficient-algorithm.cpp
@@ -1,5 +1,4 @@
-// RUN: %check_clang_tidy -std=c++11,c++14 %s 
performance-inefficient-algorithm %t
-// FIXME: Fix the checker to work in C++17 mode.
+// RUN: %check_clang_tidy %s performance-inefficient-algorithm %t
 
 namespace std {
 template  struct less {



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


[clang-tools-extra] d20961c - [clang-tidy] Simplify delete null ptr check

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

Author: Stephen Kelly
Date: 2021-02-17T10:18:36Z
New Revision: d20961c6575c00fc998d901ded78c1a41edd61b1

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

LOG: [clang-tidy] Simplify delete null ptr check

Because it no longer relies on finding implicit casts, this check now
works on templates which are not instantiated in the translation unit.

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

Added: 


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

clang-tools-extra/test/clang-tidy/checkers/readability-delete-null-pointer.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.cpp
index 16e86c201ff1..9f3350409d06 100644
--- a/clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.cpp
@@ -20,34 +20,30 @@ namespace readability {
 
 void DeleteNullPointerCheck::registerMatchers(MatchFinder *Finder) {
   const auto DeleteExpr =
-  cxxDeleteExpr(has(castExpr(has(declRefExpr(
-to(decl(equalsBoundNode("deletedPointer"
+  cxxDeleteExpr(
+  has(declRefExpr(to(decl(equalsBoundNode("deletedPointer"))
   .bind("deleteExpr");
 
   const auto DeleteMemberExpr =
-  cxxDeleteExpr(has(castExpr(has(memberExpr(hasDeclaration(
-
fieldDecl(equalsBoundNode("deletedMemberPointer"
+  cxxDeleteExpr(has(memberExpr(hasDeclaration(
+fieldDecl(equalsBoundNode("deletedMemberPointer"))
   .bind("deleteMemberExpr");
 
-  const auto PointerExpr = ignoringImpCasts(anyOf(
+  const auto PointerExpr = anyOf(
   declRefExpr(to(decl().bind("deletedPointer"))),
-  memberExpr(hasDeclaration(fieldDecl().bind("deletedMemberPointer");
+  memberExpr(hasDeclaration(fieldDecl().bind("deletedMemberPointer";
 
-  const auto PointerCondition = castExpr(hasCastKind(CK_PointerToBoolean),
- hasSourceExpression(PointerExpr));
-  const auto BinaryPointerCheckCondition = binaryOperator(
-  hasOperands(castExpr(hasCastKind(CK_NullToPointer)), PointerExpr));
+  const auto BinaryPointerCheckCondition = binaryOperator(hasOperands(
+  anyOf(cxxNullPtrLiteralExpr(), integerLiteral(equals(0))), PointerExpr));
 
   Finder->addMatcher(
-  traverse(TK_AsIs,
-   ifStmt(hasCondition(
-  anyOf(PointerCondition, 
BinaryPointerCheckCondition)),
-  hasThen(anyOf(DeleteExpr, DeleteMemberExpr,
-compoundStmt(anyOf(has(DeleteExpr),
-   has(DeleteMemberExpr)),
- statementCountIs(1))
-.bind("compound"
-   .bind("ifWithDelete")),
+  ifStmt(hasCondition(anyOf(PointerExpr, BinaryPointerCheckCondition)),
+ hasThen(anyOf(
+ DeleteExpr, DeleteMemberExpr,
+ compoundStmt(anyOf(has(DeleteExpr), has(DeleteMemberExpr)),
+  statementCountIs(1))
+ .bind("compound"
+  .bind("ifWithDelete"),
   this);
 }
 

diff  --git a/clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.h 
b/clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.h
index 0e310f797a4c..c0d07d5d71b6 100644
--- a/clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/DeleteNullPointerCheck.h
@@ -26,6 +26,9 @@ class DeleteNullPointerCheck : 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 readability

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-delete-null-pointer.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability-delete-null-pointer.cpp
index 1c044e9d25f0..36e8f059c22b 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-delete-null-pointer.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-delete-null-pointer.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s readability-delete-null-pointer %t
+// RUN: %check_clang_tidy %s readability-delete-null-pointer %t -- -- 
-fno-delayed-template-parsing
 
 #define NULL 0
 

[clang] 39ff002 - [ASTMatchers] Clarify example in docs

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

Author: Stephen Kelly
Date: 2021-02-14T13:49:06Z
New Revision: 39ff002e526e1df3e4bebbfdd2beebf0440d7d92

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

LOG: [ASTMatchers] Clarify example in docs

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index ac816d28970b..a956091318a1 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -508,7 +508,7 @@ Traverse Mode
 
 binaryOperator(
   hasOperatorName(""),
-  hasRHS(integerLiteral(equals(0)))
+  hasRHS(hasDescendant(integerLiteral(equals(0
   )
 
 given:
@@ -529,6 +529,12 @@ Traverse Mode
 
 
 1 match found.
+
+
+   return a < b;
+  ^
+
+
 
 
 No match found.



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


[clang-tools-extra] f2f920b - [clang-tidy] Simplify inaccurate erase check

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

Author: Stephen Kelly
Date: 2021-02-13T13:51:27Z
New Revision: f2f920b987f3810863b9d0160cbb52df3fa2ab6f

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

LOG: [clang-tidy] Simplify inaccurate erase check

The normalization of matchers means that this now works in all language
modes.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp
clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.h
clang-tools-extra/test/clang-tidy/checkers/bugprone-inaccurate-erase.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp
index 8e5a53280183..96fa7ef48348 100644
--- a/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp
@@ -22,25 +22,18 @@ void InaccurateEraseCheck::registerMatchers(MatchFinder 
*Finder) {
   callExpr(
   callee(functionDecl(hasAnyName("remove", "remove_if", "unique"))),
   hasArgument(
-  1,
-  anyOf(cxxConstructExpr(has(ignoringImplicit(
-
cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"
-.bind("end",
-anything(
+  1, 
optionally(cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"
+   .bind("end"
   .bind("alg");
 
   const auto DeclInStd = type(hasUnqualifiedDesugaredType(
   tagType(hasDeclaration(decl(isInStdNamespace());
   Finder->addMatcher(
-  traverse(
-  TK_AsIs,
-  cxxMemberCallExpr(
-  on(anyOf(hasType(DeclInStd), hasType(pointsTo(DeclInStd,
-  callee(cxxMethodDecl(hasName("erase"))), argumentCountIs(1),
-  hasArgument(0, has(ignoringImplicit(anyOf(
- EndCall, has(ignoringImplicit(EndCall)),
-  unless(isInTemplateInstantiation()))
-  .bind("erase")),
+  cxxMemberCallExpr(
+  on(anyOf(hasType(DeclInStd), hasType(pointsTo(DeclInStd,
+  callee(cxxMethodDecl(hasName("erase"))), argumentCountIs(1),
+  hasArgument(0, EndCall))
+  .bind("erase"),
   this);
 }
 

diff  --git a/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.h
index ef6006dca888..dd6eb80a41d1 100644
--- a/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.h
@@ -31,6 +31,9 @@ class InaccurateEraseCheck : 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 bugprone

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-inaccurate-erase.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-inaccurate-erase.cpp
index eff57eaabf7a..d29fa9cdd4e9 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone-inaccurate-erase.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone-inaccurate-erase.cpp
@@ -1,5 +1,4 @@
-// RUN: %check_clang_tidy -std=c++11,c++14 %s bugprone-inaccurate-erase %t
-// FIXME: Fix the checker to work in C++17 mode.
+// RUN: %check_clang_tidy %s bugprone-inaccurate-erase %t
 
 namespace std {
 template  struct vec_iterator {



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


[clang-tools-extra] 1709bb8 - [clang-tidy] Simplify static assert check

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

Author: Stephen Kelly
Date: 2021-02-13T13:49:01Z
New Revision: 1709bb8c7395418236ec94fe3b9d91fed746452b

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

LOG: [clang-tidy] Simplify static assert check

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
index 3e3f8dbf02ff5..2d6504cae689a 100644
--- a/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
@@ -27,48 +27,37 @@ StaticAssertCheck::StaticAssertCheck(StringRef Name, 
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context) {}
 
 void StaticAssertCheck::registerMatchers(MatchFinder *Finder) {
-  auto NegatedString = unaryOperator(
-  hasOperatorName("!"), 
hasUnaryOperand(ignoringImpCasts(stringLiteral(;
+  auto NegatedString =
+  unaryOperator(hasOperatorName("!"), hasUnaryOperand(stringLiteral()));
   auto IsAlwaysFalse =
   expr(anyOf(cxxBoolLiteral(equals(false)), integerLiteral(equals(0)),
  cxxNullPtrLiteralExpr(), gnuNullExpr(), NegatedString))
   .bind("isAlwaysFalse");
-  auto IsAlwaysFalseWithCast = ignoringParenImpCasts(anyOf(
-  IsAlwaysFalse, cStyleCastExpr(has(ignoringParenImpCasts(IsAlwaysFalse)))
- .bind("castExpr")));
-  auto AssertExprRoot = anyOf(
-  binaryOperator(
-  hasAnyOperatorName("&&", "=="),
-  
hasEitherOperand(ignoringImpCasts(stringLiteral().bind("assertMSG"))),
-  anyOf(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)),
-anything()))
-  .bind("assertExprRoot"),
-  IsAlwaysFalse);
+  auto IsAlwaysFalseWithCast =
+  anyOf(IsAlwaysFalse, 
cStyleCastExpr(has(IsAlwaysFalse)).bind("castExpr"));
+  auto AssertExprRoot =
+  anyOf(binaryOperator(
+hasAnyOperatorName("&&", "=="),
+hasEitherOperand(stringLiteral().bind("assertMSG")),
+anyOf(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)),
+  anything()))
+.bind("assertExprRoot"),
+IsAlwaysFalse);
   auto NonConstexprFunctionCall =
   callExpr(hasDeclaration(functionDecl(unless(isConstexpr();
   auto AssertCondition =
-  expr(
-  anyOf(expr(ignoringParenCasts(anyOf(
-AssertExprRoot, unaryOperator(hasUnaryOperand(
-
ignoringParenCasts(AssertExprRoot)),
-anything()),
-  unless(findAll(NonConstexprFunctionCall)))
+  expr(optionally(expr(anyOf(AssertExprRoot,
+unaryOperator(hasUnaryOperand(AssertExprRoot),
+   unless(findAll(NonConstexprFunctionCall)))
   .bind("condition");
   auto Condition =
-  anyOf(ignoringParenImpCasts(callExpr(
-hasDeclaration(functionDecl(hasName("__builtin_expect"))),
-hasArgument(0, AssertCondition))),
+  anyOf(callExpr(traverse(TK_AsIs, callExpr(hasDeclaration(functionDecl(
+   hasName("__builtin_expect"),
+ hasArgument(0, AssertCondition)),
 AssertCondition);
 
-  Finder->addMatcher(conditionalOperator(hasCondition(Condition),
- unless(isInTemplateInstantiation()))
- .bind("condStmt"),
- this);
-
   Finder->addMatcher(
-  ifStmt(hasCondition(Condition), unless(isInTemplateInstantiation()))
-  .bind("condStmt"),
-  this);
+  mapAnyOf(ifStmt, 
conditionalOperator).with(hasCondition(Condition)).bind("condStmt"), this);
 }
 
 void StaticAssertCheck::check(const MatchFinder::MatchResult ) {

diff  --git a/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h 
b/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
index 0168d1fcd107f..796fc4827db42 100644
--- a/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
+++ b/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
@@ -30,6 +30,9 @@ class StaticAssertCheck : 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:
   SourceLocation getLastParenLoc(const ASTContext *ASTCtx,



___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[clang] ddca007 - Add code complete support for mapAnyOf

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

Author: Stephen Kelly
Date: 2021-02-07T16:03:05Z
New Revision: ddca007a291b0e224fe5a492ae8d78c6a933b4fe

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

LOG: Add code complete support for mapAnyOf

Added: 


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

Removed: 




diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index ef5fd64a36667..4300eb8d8b983 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -656,20 +656,40 @@ Registry::getMatcherCompletions(ArrayRef 
AcceptedTypes) {
 bool IsPolymorphic = Matcher.isPolymorphic();
 std::vector> ArgsKinds(NumArgs);
 unsigned MaxSpecificity = 0;
+bool NodeArgs = false;
 for (const ArgKind& Kind : AcceptedTypes) {
-  if (Kind.getArgKind() != Kind.AK_Matcher)
+  if (Kind.getArgKind() != Kind.AK_Matcher &&
+  Kind.getArgKind() != Kind.AK_Node) {
 continue;
-  unsigned Specificity;
-  ASTNodeKind LeastDerivedKind;
-  if (Matcher.isConvertibleTo(Kind.getMatcherKind(), ,
-  )) {
-if (MaxSpecificity < Specificity)
-  MaxSpecificity = Specificity;
-RetKinds.insert(LeastDerivedKind);
-for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
-  Matcher.getArgKinds(Kind.getMatcherKind(), Arg, ArgsKinds[Arg]);
-if (IsPolymorphic)
-  break;
+  }
+
+  if (Kind.getArgKind() == Kind.AK_Node) {
+NodeArgs = true;
+unsigned Specificity;
+ASTNodeKind LeastDerivedKind;
+if (Matcher.isConvertibleTo(Kind.getNodeKind(), ,
+)) {
+  if (MaxSpecificity < Specificity)
+MaxSpecificity = Specificity;
+  RetKinds.insert(LeastDerivedKind);
+  for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
+Matcher.getArgKinds(Kind.getNodeKind(), Arg, ArgsKinds[Arg]);
+  if (IsPolymorphic)
+break;
+}
+  } else {
+unsigned Specificity;
+ASTNodeKind LeastDerivedKind;
+if (Matcher.isConvertibleTo(Kind.getMatcherKind(), ,
+)) {
+  if (MaxSpecificity < Specificity)
+MaxSpecificity = Specificity;
+  RetKinds.insert(LeastDerivedKind);
+  for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
+Matcher.getArgKinds(Kind.getMatcherKind(), Arg, ArgsKinds[Arg]);
+  if (IsPolymorphic)
+break;
+}
   }
 }
 
@@ -677,42 +697,49 @@ Registry::getMatcherCompletions(ArrayRef 
AcceptedTypes) {
   std::string Decl;
   llvm::raw_string_ostream OS(Decl);
 
-  if (IsPolymorphic) {
-OS << "Matcher " << Name << "(Matcher";
+  std::string TypedText = std::string(Name);
+
+  if (NodeArgs) {
+OS << Name;
   } else {
-OS << "Matcher<" << RetKinds << "> " << Name << "(";
-for (const std::vector  : ArgsKinds) {
-  if ( != [0])
-OS << ", ";
-
-  bool FirstArgKind = true;
-  std::set MatcherKinds;
-  // Two steps. First all non-matchers, then matchers only.
-  for (const ArgKind  : Arg) {
-if (AK.getArgKind() == ArgKind::AK_Matcher) {
-  MatcherKinds.insert(AK.getMatcherKind());
-} else {
+
+if (IsPolymorphic) {
+  OS << "Matcher " << Name << "(Matcher";
+} else {
+  OS << "Matcher<" << RetKinds << "> " << Name << "(";
+  for (const std::vector  : ArgsKinds) {
+if ( != [0])
+  OS << ", ";
+
+bool FirstArgKind = true;
+std::set MatcherKinds;
+// Two steps. First all non-matchers, then matchers only.
+for (const ArgKind  : Arg) {
+  if (AK.getArgKind() == ArgKind::AK_Matcher) {
+MatcherKinds.insert(AK.getMatcherKind());
+  } else {
+if (!FirstArgKind)
+  OS << "|";
+FirstArgKind = false;
+OS << AK.asString();
+  }
+}
+if (!MatcherKinds.empty()) {
   if (!FirstArgKind) OS << "|";
-  FirstArgKind = false;
-  OS << AK.asString();
+  OS << "Matcher<" << MatcherKinds << ">";
 }
   }
-  if (!MatcherKinds.empty()) {
-if (!FirstArgKind) OS << "|";
-OS << "Matcher<" << MatcherKinds << ">";
-  }
 }
+if (Matcher.isVariadic())
+  OS << "...";
+OS << ")";
+
+TypedText += "(";
+if (ArgsKinds.empty())
+ 

[clang] 04b69d9 - Add clang-query support for mapAnyOf

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

Author: Stephen Kelly
Date: 2021-02-07T15:40:15Z
New Revision: 04b69d9a6013cbc39321452fa09e24fed4c98bc7

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

LOG: Add clang-query support for mapAnyOf

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

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
clang/include/clang/ASTMatchers/Dynamic/Parser.h
clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
clang/lib/ASTMatchers/Dynamic/Parser.cpp
clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h 
b/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
index f095dcdd60b0..10625311c1a5 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
@@ -66,6 +66,8 @@ class Diagnostics {
 ET_RegistryAmbiguousOverload = 5,
 ET_RegistryValueNotFound = 6,
 ET_RegistryUnknownEnumWithReplace = 7,
+ET_RegistryNonNodeMatcher = 8,
+ET_RegistryMatcherNoWithSupport = 9,
 
 ET_ParserStringError = 100,
 ET_ParserNoOpenParen = 101,
@@ -77,7 +79,9 @@ class Diagnostics {
 ET_ParserMalformedBindExpr = 107,
 ET_ParserTrailingCode = 108,
 ET_ParserNumberError = 109,
-ET_ParserOverloadedType = 110
+ET_ParserOverloadedType = 110,
+ET_ParserMalformedChainedExpr = 111,
+ET_ParserFailedToBuildMatcher = 112
   };
 
   /// Helper stream class.

diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Parser.h 
b/clang/include/clang/ASTMatchers/Dynamic/Parser.h
index 384e88ff5edf..af370d83782a 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Parser.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Parser.h
@@ -100,6 +100,14 @@ class Parser {
 virtual llvm::Optional
 lookupMatcherCtor(StringRef MatcherName) = 0;
 
+virtual bool isBuilderMatcher(MatcherCtor) const = 0;
+
+virtual ASTNodeKind nodeMatcherType(MatcherCtor) const = 0;
+
+virtual internal::MatcherDescriptorPtr
+buildMatcherCtor(MatcherCtor, SourceRange NameRange,
+ ArrayRef Args, Diagnostics *Error) const = 0;
+
 /// Compute the list of completion types for \p Context.
 ///
 /// Each element of \p Context represents a matcher invocation, going from
@@ -142,6 +150,15 @@ class Parser {
 std::vector getAcceptedCompletionTypes(
 llvm::ArrayRef> Context) override;
 
+bool isBuilderMatcher(MatcherCtor Ctor) const override;
+
+ASTNodeKind nodeMatcherType(MatcherCtor) const override;
+
+internal::MatcherDescriptorPtr
+buildMatcherCtor(MatcherCtor, SourceRange NameRange,
+ ArrayRef Args,
+ Diagnostics *Error) const override;
+
 std::vector
 getMatcherCompletions(llvm::ArrayRef AcceptedTypes) override;
   };
@@ -233,6 +250,8 @@ class Parser {
 
   bool parseBindID(std::string );
   bool parseExpressionImpl(VariantValue *Value);
+  bool parseMatcherBuilder(MatcherCtor Ctor, const TokenInfo ,
+   const TokenInfo , VariantValue *Value);
   bool parseMatcherExpressionImpl(const TokenInfo ,
   const TokenInfo ,
   llvm::Optional Ctor,

diff  --git a/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp 
b/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
index 88c2279afb2e..ba2f49e6b623 100644
--- a/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
@@ -100,6 +100,10 @@ static StringRef 
errorTypeToFormatString(Diagnostics::ErrorType Type) {
 return "Value not found: $0";
   case Diagnostics::ET_RegistryUnknownEnumWithReplace:
 return "Unknown value '$1' for arg $0; did you mean '$2'";
+  case Diagnostics::ET_RegistryNonNodeMatcher:
+return "Matcher not a node matcher: $0";
+  case Diagnostics::ET_RegistryMatcherNoWithSupport:
+return "Matcher does not support with call.";
 
   case Diagnostics::ET_ParserStringError:
 return "Error parsing string token: <$0>";
@@ -123,6 +127,10 @@ static StringRef 
errorTypeToFormatString(Diagnostics::ErrorType Type) {
 return "Error parsing numeric literal: <$0>";
   case Diagnostics::ET_ParserOverloadedType:
 return "Input value has unresolved overloaded type: $0";
+  case Diagnostics::ET_ParserMalformedChainedExpr:
+return "Period not followed by valid chained call.";
+  case Diagnostics::ET_ParserFailedToBuildMatcher:
+return "Failed to build matcher: $0.";
 
   case Diagnostics::ET_None:
 return "";

diff  --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp 
b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
index efe581284fb9..c6a77bb6c2e0 100644
--- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ 

[clang] 816cc43 - [ASTMatchers] Extract parsing of bind token from the bind id

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

Author: Stephen Kelly
Date: 2021-02-07T15:40:15Z
New Revision: 816cc432812724627835e66ed94a20a2478edef8

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

LOG: [ASTMatchers] Extract parsing of bind token from the bind id

This will be extended to be able to parse "with" for mapAnyOf in
addition to "bind".

Added: 


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

Removed: 




diff  --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp 
b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
index 7715e2a17799..efe581284fb9 100644
--- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
@@ -366,6 +366,17 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue 
*Value) {
   }
 
   std::string BindID;
+  Tokenizer->consumeNextToken();
+  TokenInfo BindToken = Tokenizer->consumeNextToken();
+  if (BindToken.Kind == TokenInfo::TK_CodeCompletion) {
+addCompletion(BindToken, MatcherCompletion("bind(\"", "bind", 1));
+return false;
+  }
+  if (BindToken.Kind != TokenInfo::TK_Ident ||
+BindToken.Text != TokenInfo::ID_Bind) {
+Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr);
+return false;
+  }
   if (!parseBindID(BindID))
 return false;
 
@@ -420,26 +431,13 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue 
*Value) {
 }
 
 bool Parser::parseBindID(std::string ) {
-  // Parse .bind("foo")
-  assert(Tokenizer->peekNextToken().Kind == TokenInfo::TK_Period);
-  Tokenizer->consumeNextToken(); // consume the period.
-  const TokenInfo BindToken = Tokenizer->consumeNextToken();
-  if (BindToken.Kind == TokenInfo::TK_CodeCompletion) {
-addCompletion(BindToken, MatcherCompletion("bind(\"", "bind", 1));
-return false;
-  }
-
+  // Parse the parenthesized argument to .bind("foo")
   const TokenInfo OpenToken = Tokenizer->consumeNextToken();
   const TokenInfo IDToken = Tokenizer->consumeNextTokenIgnoreNewlines();
   const TokenInfo CloseToken = Tokenizer->consumeNextTokenIgnoreNewlines();
 
   // TODO: We could use 
diff erent error codes for each/some to be more
   //   explicit about the syntax error.
-  if (BindToken.Kind != TokenInfo::TK_Ident ||
-  BindToken.Text != TokenInfo::ID_Bind) {
-Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr);
-return false;
-  }
   if (OpenToken.Kind != TokenInfo::TK_OpenParen) {
 Error->addError(OpenToken.Range, Error->ET_ParserMalformedBindExpr);
 return false;
@@ -518,6 +516,17 @@ bool Parser::parseMatcherExpressionImpl(const TokenInfo 
,
 
   std::string BindID;
   if (Tokenizer->peekNextToken().Kind == TokenInfo::TK_Period) {
+Tokenizer->consumeNextToken();
+TokenInfo BindToken = Tokenizer->consumeNextToken();
+if (BindToken.Kind == TokenInfo::TK_CodeCompletion) {
+  addCompletion(BindToken, MatcherCompletion("bind(\"", "bind", 1));
+  return false;
+}
+if (BindToken.Kind != TokenInfo::TK_Ident ||
+  BindToken.Text != TokenInfo::ID_Bind) {
+  Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr);
+  return false;
+}
 if (!parseBindID(BindID))
   return false;
   }



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


[clang] 8021078 - [ASTMatchers] Change internal method API

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

Author: Stephen Kelly
Date: 2021-02-07T15:37:35Z
New Revision: 8021078bc993073d703b91eae8f9b9ed8de478dc

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

LOG: [ASTMatchers] Change internal method API

This will make it possible to parse matchers built dynamically.

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/Parser.h
clang/lib/ASTMatchers/Dynamic/Parser.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Parser.h 
b/clang/include/clang/ASTMatchers/Dynamic/Parser.h
index 70bbe816accd..384e88ff5edf 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Parser.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Parser.h
@@ -234,6 +234,8 @@ class Parser {
   bool parseBindID(std::string );
   bool parseExpressionImpl(VariantValue *Value);
   bool parseMatcherExpressionImpl(const TokenInfo ,
+  const TokenInfo ,
+  llvm::Optional Ctor,
   VariantValue *Value);
   bool parseIdentifierPrefixImpl(VariantValue *Value);
 

diff  --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp 
b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
index a0037549ca61..7715e2a17799 100644
--- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
@@ -405,8 +405,18 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue 
*Value) {
 
   Tokenizer->SkipNewlines();
 
+  assert(NameToken.Kind == TokenInfo::TK_Ident);
+  TokenInfo OpenToken = Tokenizer->consumeNextToken();
+  if (OpenToken.Kind != TokenInfo::TK_OpenParen) {
+Error->addError(OpenToken.Range, Error->ET_ParserNoOpenParen)
+<< OpenToken.Text;
+return false;
+  }
+
+  llvm::Optional Ctor = S->lookupMatcherCtor(NameToken.Text);
+
   // Parse as a matcher expression.
-  return parseMatcherExpressionImpl(NameToken, Value);
+  return parseMatcherExpressionImpl(NameToken, OpenToken, Ctor, Value);
 }
 
 bool Parser::parseBindID(std::string ) {
@@ -451,17 +461,9 @@ bool Parser::parseBindID(std::string ) {
 ///   If the input is malformed, or some argument has an error, it
 ///   returns \c false.
 bool Parser::parseMatcherExpressionImpl(const TokenInfo ,
+const TokenInfo ,
+llvm::Optional Ctor,
 VariantValue *Value) {
-  assert(NameToken.Kind == TokenInfo::TK_Ident);
-  const TokenInfo OpenToken = Tokenizer->consumeNextToken();
-  if (OpenToken.Kind != TokenInfo::TK_OpenParen) {
-Error->addError(OpenToken.Range, Error->ET_ParserNoOpenParen)
-<< OpenToken.Text;
-return false;
-  }
-
-  llvm::Optional Ctor = S->lookupMatcherCtor(NameToken.Text);
-
   if (!Ctor) {
 Error->addError(NameToken.Range, Error->ET_RegistryMatcherNotFound)
 << NameToken.Text;



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


[clang] 45e210d - [ASTMatchers] Make it possible to build mapAnyOf through the registry

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

Author: Stephen Kelly
Date: 2021-02-07T15:36:15Z
New Revision: 45e210dbebfae916b213e52be15c276032aeb60d

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

LOG: [ASTMatchers] Make it possible to build mapAnyOf through the registry

Added: 


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

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Registry.h 
b/clang/include/clang/ASTMatchers/Dynamic/Registry.h
index 9ce77c33d6d8..f91f5fe01c4e 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Registry.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Registry.h
@@ -33,6 +33,23 @@ namespace internal {
 
 class MatcherDescriptor;
 
+/// A smart (owning) pointer for MatcherDescriptor. We can't use unique_ptr
+/// because MatcherDescriptor is forward declared
+class MatcherDescriptorPtr {
+public:
+  explicit MatcherDescriptorPtr(MatcherDescriptor *);
+  ~MatcherDescriptorPtr();
+  MatcherDescriptorPtr(MatcherDescriptorPtr &&) = default;
+  MatcherDescriptorPtr =(MatcherDescriptorPtr &&) = default;
+  MatcherDescriptorPtr(const MatcherDescriptorPtr &) = delete;
+  MatcherDescriptorPtr =(const MatcherDescriptorPtr &) = delete;
+
+  MatcherDescriptor *get() { return Ptr; }
+
+private:
+  MatcherDescriptor *Ptr;
+};
+
 } // namespace internal
 
 using MatcherCtor = const internal::MatcherDescriptor *;
@@ -68,6 +85,12 @@ class Registry {
 
   static ASTNodeKind nodeMatcherType(MatcherCtor);
 
+  static bool isBuilderMatcher(MatcherCtor Ctor);
+
+  static internal::MatcherDescriptorPtr
+  buildMatcherCtor(MatcherCtor, SourceRange NameRange,
+   ArrayRef Args, Diagnostics *Error);
+
   /// Look up a matcher in the registry by name,
   ///
   /// \return An opaque value which may be used to refer to the matcher

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index 71d7443c91ca..3ffa0d6af217 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -311,6 +311,14 @@ class MatcherDescriptor {
 
   virtual ASTNodeKind nodeMatcherType() const { return ASTNodeKind(); }
 
+  virtual bool isBuilderMatcher() const { return false; }
+
+  virtual std::unique_ptr
+  buildMatcherCtor(SourceRange NameRange, ArrayRef Args,
+   Diagnostics *Error) const {
+return {};
+  }
+
   /// Returns whether the matcher is variadic. Variadic matchers can take any
   /// number of arguments, but they must be of the same type.
   virtual bool isVariadic() const = 0;
@@ -996,6 +1004,62 @@ class MapAnyOfMatcherDescriptor : public 
MatcherDescriptor {
   }
 };
 
+class MapAnyOfBuilderDescriptor : public MatcherDescriptor {
+public:
+  VariantMatcher create(SourceRange, ArrayRef,
+Diagnostics *) const override {
+return {};
+  }
+
+  bool isBuilderMatcher() const override { return true; }
+
+  std::unique_ptr
+  buildMatcherCtor(SourceRange, ArrayRef Args,
+   Diagnostics *) const override {
+
+std::vector NodeKinds;
+for (auto Arg : Args) {
+  if (!Arg.Value.isNodeKind())
+return {};
+  NodeKinds.push_back(Arg.Value.getNodeKind());
+}
+
+if (NodeKinds.empty())
+  return {};
+
+ASTNodeKind CladeNodeKind = NodeKinds.front().getCladeKind();
+
+for (auto NK : NodeKinds)
+{
+  if (!NK.getCladeKind().isSame(CladeNodeKind))
+return {};
+}
+
+return std::make_unique(CladeNodeKind,
+   NodeKinds);
+  }
+
+  bool isVariadic() const override { return true; }
+
+  unsigned getNumArgs() const override { return 0; }
+
+  void getArgKinds(ASTNodeKind ThisKind, unsigned,
+   std::vector ) const override {
+ArgKinds.push_back(ArgKind::MakeNodeArg(ThisKind));
+return;
+  }
+  bool isConvertibleTo(ASTNodeKind Kind, unsigned *Specificity = nullptr,
+   ASTNodeKind *LeastDerivedKind = nullptr) const override 
{
+if (Specificity)
+  *Specificity = 1;
+if (LeastDerivedKind)
+  *LeastDerivedKind = Kind;
+return true;
+  }
+
+  bool isPolymorphic() const override { return false; }
+};
+
 /// Helper functions to select the appropriate marshaller functions.
 /// They detect the number of arguments, arguments types and return type.
 

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 908a9ee8ae62..ef5fd64a3666 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -102,6 +102,9 @@ 

[clang] d3bccdc - [ASTMatchers ]Make MatcherDescriptors indicate the node type they match

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

Author: Stephen Kelly
Date: 2021-02-07T15:13:28Z
New Revision: d3bccdcd50e392469c5d115eda29a308914e19ae

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

LOG: [ASTMatchers ]Make MatcherDescriptors indicate the node type they match

Added: 


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

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Registry.h 
b/clang/include/clang/ASTMatchers/Dynamic/Registry.h
index 215206b2f50c..9ce77c33d6d8 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Registry.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Registry.h
@@ -66,6 +66,8 @@ class Registry {
 public:
   Registry() = delete;
 
+  static ASTNodeKind nodeMatcherType(MatcherCtor);
+
   /// Look up a matcher in the registry by name,
   ///
   /// \return An opaque value which may be used to refer to the matcher

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index 411062392dad..71d7443c91ca 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -309,6 +309,8 @@ class MatcherDescriptor {
 ArrayRef Args,
 Diagnostics *Error) const = 0;
 
+  virtual ASTNodeKind nodeMatcherType() const { return ASTNodeKind(); }
+
   /// Returns whether the matcher is variadic. Variadic matchers can take any
   /// number of arguments, but they must be of the same type.
   virtual bool isVariadic() const = 0;
@@ -576,6 +578,8 @@ class VariadicFuncMatcherDescriptor : public 
MatcherDescriptor {
   LeastDerivedKind);
   }
 
+  ASTNodeKind nodeMatcherType() const override { return RetKinds[0]; }
+
 private:
   const RunFunc Func;
   const std::string MatcherName;
@@ -611,6 +615,8 @@ class DynCastAllOfMatcherDescriptor : public 
VariadicFuncMatcherDescriptor {
 }
   }
 
+  ASTNodeKind nodeMatcherType() const override { return DerivedKind; }
+
 private:
   const ASTNodeKind DerivedKind;
 };

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 0887eb7e0881..908a9ee8ae62 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -562,6 +562,10 @@ RegistryMaps::~RegistryMaps() = default;
 
 static llvm::ManagedStatic RegistryData;
 
+ASTNodeKind Registry::nodeMatcherType(MatcherCtor Ctor) {
+  return Ctor->nodeMatcherType();
+}
+
 // static
 llvm::Optional Registry::lookupMatcherCtor(StringRef MatcherName) 
{
   auto it = RegistryData->constructors().find(MatcherName);

diff  --git a/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp 
b/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
index 7d6c51f965ec..386fd523bb24 100644
--- a/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
+++ b/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
@@ -497,6 +497,12 @@ TEST_F(RegistryTest, Completion) {
   "Matcher 
isSameOrDerivedFrom(string|Matcher)"));
 }
 
+TEST_F(RegistryTest, NodeType) {
+  
EXPECT_TRUE(Registry::nodeMatcherType(*lookupMatcherCtor("callExpr")).isSame(ASTNodeKind::getFromNodeKind()));
+  EXPECT_TRUE(Registry::nodeMatcherType(*lookupMatcherCtor("has")).isNone());
+  EXPECT_TRUE(Registry::nodeMatcherType(*lookupMatcherCtor("allOf")).isNone());
+}
+
 TEST_F(RegistryTest, HasArgs) {
   Matcher Value = constructMatcher(
   "decl", constructMatcher("hasAttr", StringRef("attr::WarnUnused")))



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


[clang] e12d827 - Make it possible to store NodeKinds in ArgKind

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

Author: Stephen Kelly
Date: 2021-02-07T14:00:45Z
New Revision: e12d8279915c323f3727085ccfd0f2c54ad82bdd

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

LOG: Make it possible to store NodeKinds in ArgKind

Added: 


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

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h 
b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
index abfb29707924..5b3f8a7ca5eb 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
@@ -35,6 +35,7 @@ class ArgKind {
  public:
   enum Kind {
 AK_Matcher,
+AK_Node,
 AK_Boolean,
 AK_Double,
 AK_Unsigned,
@@ -48,11 +49,19 @@ class ArgKind {
 return ArgKind{AK_Matcher, MatcherKind};
   }
 
+  static ArgKind MakeNodeArg(ASTNodeKind MatcherKind) {
+return ArgKind{AK_Node, MatcherKind};
+  }
+
   Kind getArgKind() const { return K; }
   ASTNodeKind getMatcherKind() const {
 assert(K == AK_Matcher);
 return NodeKind;
   }
+  ASTNodeKind getNodeKind() const {
+assert(K == AK_Node);
+return NodeKind;
+  }
 
   /// Determines if this type can be converted to \p To.
   ///
@@ -63,7 +72,8 @@ class ArgKind {
   bool isConvertibleTo(ArgKind To, unsigned *Specificity) const;
 
   bool operator<(const ArgKind ) const {
-if (K == AK_Matcher && Other.K == AK_Matcher)
+if ((K == AK_Matcher && Other.K == AK_Matcher) ||
+(K == AK_Node && Other.K == AK_Node))
   return NodeKind < Other.NodeKind;
 return K < Other.K;
   }

diff  --git a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp 
b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
index d367ad0e3233..813eb1597756 100644
--- a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
@@ -23,6 +23,8 @@ std::string ArgKind::asString() const {
   switch (getArgKind()) {
   case AK_Matcher:
 return (Twine("Matcher<") + NodeKind.asStringRef() + ">").str();
+  case AK_Node:
+return NodeKind.asStringRef().str();
   case AK_Boolean:
 return "boolean";
   case AK_Double:
@@ -38,7 +40,7 @@ std::string ArgKind::asString() const {
 bool ArgKind::isConvertibleTo(ArgKind To, unsigned *Specificity) const {
   if (K != To.K)
 return false;
-  if (K != AK_Matcher) {
+  if (K != AK_Matcher && K != AK_Node) {
 if (Specificity)
   *Specificity = 1;
 return true;
@@ -443,6 +445,11 @@ bool VariantValue::isConvertibleTo(ArgKind Kind, unsigned 
*Specificity) const {
 *Specificity = 1;
 return true;
 
+  case ArgKind::AK_Node:
+if (!isNodeKind())
+  return false;
+return getMatcher().isConvertibleTo(Kind.getNodeKind(), Specificity);
+
   case ArgKind::AK_Matcher:
 if (!isMatcher())
   return false;



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


[clang] 79fedad - [ASTMatchers] Add static constructor for ArgKinds of Matchers

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

Author: Stephen Kelly
Date: 2021-02-07T13:43:04Z
New Revision: 79fedadd6af84701e8c873c8d7b507e323d15a5e

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

LOG: [ASTMatchers] Add static constructor for ArgKinds of Matchers

It will soon be possible to store a node kind in an ArgKind, which will
also be contructed with an ASTNodeKind.  The desired Kind must be
expicit.

Added: 


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

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h 
b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
index fa033f49bc90..abfb29707924 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
@@ -44,12 +44,14 @@ class ArgKind {
   ArgKind(Kind K) : K(K) { assert(K != AK_Matcher); }
 
   /// Constructor for matcher types.
-  ArgKind(ASTNodeKind MatcherKind) : K(AK_Matcher), MatcherKind(MatcherKind) {}
+  static ArgKind MakeMatcherArg(ASTNodeKind MatcherKind) {
+return ArgKind{AK_Matcher, MatcherKind};
+  }
 
   Kind getArgKind() const { return K; }
   ASTNodeKind getMatcherKind() const {
 assert(K == AK_Matcher);
-return MatcherKind;
+return NodeKind;
   }
 
   /// Determines if this type can be converted to \p To.
@@ -62,7 +64,7 @@ class ArgKind {
 
   bool operator<(const ArgKind ) const {
 if (K == AK_Matcher && Other.K == AK_Matcher)
-  return MatcherKind < Other.MatcherKind;
+  return NodeKind < Other.NodeKind;
 return K < Other.K;
   }
 
@@ -70,8 +72,9 @@ class ArgKind {
   std::string asString() const;
 
 private:
+  ArgKind(Kind K, ASTNodeKind NK) : K(K), NodeKind(NK) {}
   Kind K;
-  ASTNodeKind MatcherKind;
+  ASTNodeKind NodeKind;
 };
 
 using ast_matchers::internal::DynTypedMatcher;

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index 690b52162e2b..411062392dad 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -93,7 +93,7 @@ template  struct 
ArgTypeTraits> {
   }
 
   static ArgKind getKind() {
-return ArgKind(ASTNodeKind::getFromNodeKind());
+return ArgKind::MakeMatcherArg(ASTNodeKind::getFromNodeKind());
   }
 
   static llvm::Optional getBestGuess(const VariantValue &) {
@@ -343,7 +343,8 @@ inline bool isRetKindConvertibleTo(ArrayRef 
RetKinds,
ASTNodeKind Kind, unsigned *Specificity,
ASTNodeKind *LeastDerivedKind) {
   for (const ASTNodeKind  : RetKinds) {
-if (ArgKind(NodeKind).isConvertibleTo(Kind, Specificity)) {
+if (ArgKind::MakeMatcherArg(NodeKind).isConvertibleTo(
+ArgKind::MakeMatcherArg(Kind), Specificity)) {
   if (LeastDerivedKind)
 *LeastDerivedKind = NodeKind;
   return true;
@@ -904,7 +905,7 @@ class VariadicOperatorMatcherDescriptor : public 
MatcherDescriptor {
 
   void getArgKinds(ASTNodeKind ThisKind, unsigned ArgNo,
std::vector ) const override {
-Kinds.push_back(ThisKind);
+Kinds.push_back(ArgKind::MakeMatcherArg(ThisKind));
   }
 
   bool isConvertibleTo(ASTNodeKind Kind, unsigned *Specificity,
@@ -976,7 +977,7 @@ class MapAnyOfMatcherDescriptor : public MatcherDescriptor {
 
   void getArgKinds(ASTNodeKind ThisKind, unsigned,
std::vector ) const override {
-Kinds.push_back(ThisKind);
+Kinds.push_back(ArgKind::MakeMatcherArg(ThisKind));
   }
 
   bool isConvertibleTo(ASTNodeKind Kind, unsigned *Specificity,

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 775f51b419a1..0887eb7e0881 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -599,7 +599,10 @@ std::vector Registry::getAcceptedCompletionTypes(
 
   // Starting with the above seed of acceptable top-level matcher types, 
compute
   // the acceptable type set for the argument indicated by each context 
element.
-  std::set TypeSet(std::begin(InitialTypes), std::end(InitialTypes));
+  std::set TypeSet;
+  for (auto IT : InitialTypes) {
+TypeSet.insert(ArgKind::MakeMatcherArg(IT));
+  }
   for (const auto  : Context) {
 MatcherCtor Ctor = CtxEntry.first;
 unsigned ArgNumber = CtxEntry.second;

diff  --git a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp 
b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
index d1ecb1e00b91..d367ad0e3233 100644
--- a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
@@ -22,7 

[clang] 4cbea09 - [ASTMatchers] Fix segfault when Action is nullptr

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

Author: Stephen Kelly
Date: 2021-02-05T15:17:13Z
New Revision: 4cbea09431cd7d976770348d8e3d67cf1d3637e8

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

LOG: [ASTMatchers] Fix segfault when Action is nullptr

It can be nullptr in unit tests.

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchFinder.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 9be275a528eb..5d6cea54b8ec 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -1336,7 +1336,10 @@ MatchFinder::~MatchFinder() {}
 
 void MatchFinder::addMatcher(const DeclarationMatcher ,
  MatchCallback *Action) {
-  if (auto TK = Action->getCheckTraversalKind())
+  llvm::Optional TK;
+  if (Action)
+TK = Action->getCheckTraversalKind();
+  if (TK)
 Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
   else
 Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
@@ -1351,7 +1354,10 @@ void MatchFinder::addMatcher(const TypeMatcher 
,
 
 void MatchFinder::addMatcher(const StatementMatcher ,
  MatchCallback *Action) {
-  if (auto TK = Action->getCheckTraversalKind())
+  llvm::Optional TK;
+  if (Action)
+TK = Action->getCheckTraversalKind();
+  if (TK)
 Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
   else
 Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);



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


[clang] 538677a - Add an API to simplify setting TraversalKind in clang-tidy matchers

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

Author: Stephen Kelly
Date: 2021-02-05T14:03:40Z
New Revision: 538677abbde4e74795d0bc21a77a3d263893c37d

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

LOG: Add an API to simplify setting TraversalKind in clang-tidy matchers

Reviewers: sammccall

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/ASTMatchers/ASTMatchFinder.h
clang/lib/ASTMatchers/ASTMatchFinder.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/ASTMatchFinder.h 
b/clang/include/clang/ASTMatchers/ASTMatchFinder.h
index 81125ad8d96d..91024f9425e0 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchFinder.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchFinder.h
@@ -110,6 +110,12 @@ class MatchFinder {
 /// This id is used, for example, for the profiling output.
 /// It defaults to "".
 virtual StringRef getID() const;
+
+/// TraversalKind to use while matching and processing
+/// the result nodes. This API is temporary to facilitate
+/// third parties porting existing code to the default
+/// behavior of clang-tidy.
+virtual llvm::Optional getCheckTraversalKind() const;
   };
 
   /// Called when parsing is finished. Intended for testing only.
@@ -280,6 +286,11 @@ class CollectMatchesCallback : public 
MatchFinder::MatchCallback {
   void run(const MatchFinder::MatchResult ) override {
 Nodes.push_back(Result.Nodes);
   }
+
+  llvm::Optional getCheckTraversalKind() const override {
+return llvm::None;
+  }
+
   SmallVector Nodes;
 };
 }

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 58e69bb29df6..9be275a528eb 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -1036,6 +1036,7 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 Callback(Callback) {}
 
 void visitMatch(const BoundNodes& BoundNodesView) override {
+  TraversalKindScope RAII(*Context, Callback->getCheckTraversalKind());
   Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
 }
 
@@ -1335,7 +1336,10 @@ MatchFinder::~MatchFinder() {}
 
 void MatchFinder::addMatcher(const DeclarationMatcher ,
  MatchCallback *Action) {
-  Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
+  if (auto TK = Action->getCheckTraversalKind())
+Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
+  else
+Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
   Matchers.AllCallbacks.insert(Action);
 }
 
@@ -1347,7 +1351,10 @@ void MatchFinder::addMatcher(const TypeMatcher 
,
 
 void MatchFinder::addMatcher(const StatementMatcher ,
  MatchCallback *Action) {
-  Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
+  if (auto TK = Action->getCheckTraversalKind())
+Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
+  else
+Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
   Matchers.AllCallbacks.insert(Action);
 }
 
@@ -1436,5 +1443,10 @@ void MatchFinder::registerTestCallbackAfterParsing(
 
 StringRef MatchFinder::MatchCallback::getID() const { return ""; }
 
+llvm::Optional
+MatchFinder::MatchCallback::getCheckTraversalKind() const {
+  return llvm::None;
+}
+
 } // end namespace ast_matchers
 } // end namespace clang



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


[clang-tools-extra] 2cba22c - [clang-tidy] Simplify implementation of container-size-empty

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

Author: Stephen Kelly
Date: 2021-02-05T14:03:41Z
New Revision: 2cba22c23a769103f4f0c31968620a488f13b625

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

LOG: [clang-tidy] Simplify implementation of container-size-empty

Use IgnoreUnlessSpelledInSource to make the matcher code smaller and
more visibly-related to the code.

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

Added: 


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

clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
index cd5e18913214..a1d8064d23a0 100644
--- a/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
@@ -83,6 +83,9 @@ AST_MATCHER(Expr, usedInBooleanContext) {
   });
   return Result;
 }
+AST_MATCHER(CXXConstructExpr, isDefaultConstruction) {
+  return Node.getConstructor()->isDefaultConstructor();
+}
 } // namespace ast_matchers
 namespace tidy {
 namespace readability {
@@ -116,24 +119,16 @@ void 
ContainerSizeEmptyCheck::registerMatchers(MatchFinder *Finder) {
   const auto ValidContainer = qualType(
   anyOf(ValidContainerNonTemplateType, ValidContainerTemplateType));
 
-  const auto WrongUse = traverse(
-  TK_AsIs,
-  anyOf(
-  hasParent(binaryOperator(isComparisonOperator(),
-   hasEitherOperand(ignoringImpCasts(
-   anyOf(integerLiteral(equals(1)),
- integerLiteral(equals(0))
-.bind("SizeBinaryOp")),
-  hasParent(implicitCastExpr(
-  hasImplicitDestinationType(booleanType()),
-  anyOf(hasParent(
-unaryOperator(hasOperatorName("!")).bind("NegOnSize")),
-anything(,
-  usedInBooleanContext()));
+  const auto WrongUse =
+  anyOf(hasParent(binaryOperator(
+  isComparisonOperator(),
+  hasEitherOperand(anyOf(integerLiteral(equals(1)),
+ integerLiteral(equals(0)
+  .bind("SizeBinaryOp")),
+usedInBooleanContext());
 
   Finder->addMatcher(
-  cxxMemberCallExpr(unless(isInTemplateInstantiation()),
-on(expr(anyOf(hasType(ValidContainer),
+  cxxMemberCallExpr(on(expr(anyOf(hasType(ValidContainer),
   hasType(pointsTo(ValidContainer)),
   hasType(references(ValidContainer
.bind("MemberCallObject")),
@@ -157,18 +152,9 @@ void ContainerSizeEmptyCheck::registerMatchers(MatchFinder 
*Finder) {
   .bind("SizeCallExpr"),
   this);
 
-  // Empty constructor matcher.
-  const auto DefaultConstructor = cxxConstructExpr(
-  hasDeclaration(cxxConstructorDecl(isDefaultConstructor(;
   // Comparison to empty string or empty constructor.
   const auto WrongComparend = anyOf(
-  ignoringImpCasts(stringLiteral(hasSize(0))),
-  ignoringImpCasts(cxxBindTemporaryExpr(has(DefaultConstructor))),
-  ignoringImplicit(DefaultConstructor),
-  cxxConstructExpr(hasDeclaration(cxxConstructorDecl(isCopyConstructor())),
-   has(expr(ignoringImpCasts(DefaultConstructor,
-  cxxConstructExpr(hasDeclaration(cxxConstructorDecl(isMoveConstructor())),
-   has(expr(ignoringImpCasts(DefaultConstructor,
+  stringLiteral(hasSize(0)), cxxConstructExpr(isDefaultConstruction()),
   cxxUnresolvedConstructExpr(argumentCountIs(0)));
   // Match the object being compared.
   const auto STLArg =
@@ -178,12 +164,11 @@ void 
ContainerSizeEmptyCheck::registerMatchers(MatchFinder *Finder) {
 expr(hasType(pointsTo(ValidContainer))).bind("Pointee"))),
 expr(hasType(ValidContainer)).bind("STLObject"));
   Finder->addMatcher(
-  binaryOperation(unless(isInTemplateInstantiation()),
-  hasAnyOperatorName("==", "!="),
-  hasOperands(ignoringParenImpCasts(WrongComparend),
-  ignoringParenImpCasts(STLArg)),
-  unless(hasAncestor(cxxMethodDecl(
-  ofClass(equalsBoundNode("container"))
+  binaryOperation(hasAnyOperatorName("==", "!="),
+  hasOperands(WrongComparend,
+  

[clang-tools-extra] c0199b2 - [clang-tidy] Use new mapping matchers

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

Author: Stephen Kelly
Date: 2021-02-03T23:21:17Z
New Revision: c0199b2a21705747c999a59bfa77d7fc6e4500a5

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

LOG: [clang-tidy] Use new mapping matchers

Use mapAnyOf() and matchers based on it.

Use of binaryOperation() means that modernize-loop-convert and
readability-container-size-empty can now be used with rewritten binary
operators.

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-rewritten-binop.cpp

clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty-cxx20.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SuspiciousStringCompareCheck.cpp
clang-tools-extra/clang-tidy/bugprone/UnhandledSelfAssignmentCheck.cpp
clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
clang-tools-extra/clang-tidy/cert/MutatingCopyCheck.cpp
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidGotoCheck.cpp
clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.cpp
clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
index bf1b51049c2c..777d309b5ccb 100644
--- a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
@@ -21,9 +21,9 @@ namespace bugprone {
 
 static internal::Matcher
 loopEndingStmt(internal::Matcher Internal) {
-  return stmt(anyOf(breakStmt(Internal), returnStmt(Internal),
-gotoStmt(Internal), cxxThrowExpr(Internal),
-callExpr(Internal, callee(functionDecl(isNoReturn());
+  return stmt(anyOf(
+  mapAnyOf(breakStmt, returnStmt, gotoStmt, cxxThrowExpr).with(Internal),
+  callExpr(Internal, callee(functionDecl(isNoReturn());
 }
 
 /// Return whether `Var` was changed in `LoopStmt`.
@@ -122,8 +122,8 @@ void InfiniteLoopCheck::registerMatchers(MatchFinder 
*Finder) {
   unless(hasBody(hasDescendant(
   loopEndingStmt(forFunction(equalsBoundNode("func")));
 
-  Finder->addMatcher(stmt(anyOf(whileStmt(LoopCondition), 
doStmt(LoopCondition),
-forStmt(LoopCondition)))
+  Finder->addMatcher(mapAnyOf(whileStmt, doStmt, forStmt)
+ .with(LoopCondition)
  .bind("loop-stmt"),
  this);
 }

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp
index 1a9bea6a5fc8..ee45461ed8f2 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp
@@ -59,34 +59,20 @@ void 
SpuriouslyWakeUpFunctionsCheck::registerMatchers(MatchFinder *Finder) {
   if (getLangOpts().CPlusPlus) {
 // Check for `CON54-CPP`
 Finder->addMatcher(
-ifStmt(
-allOf(HasWaitDescendantCpp,
-  unless(anyOf(hasDescendant(ifStmt(HasWaitDescendantCpp)),
-   hasDescendant(whileStmt(HasWaitDescendantCpp)),
-   hasDescendant(forStmt(HasWaitDescendantCpp)),
-   hasDescendant(doStmt(HasWaitDescendantCpp)
-
-),
+ifStmt(HasWaitDescendantCpp,
+   unless(hasDescendant(mapAnyOf(ifStmt, whileStmt, forStmt, 
doStmt)
+.with(HasWaitDescendantCpp,
 this);
   } else {
 // Check for `CON36-C`
 Finder->addMatcher(
-ifStmt(
-allOf(HasWaitDescendantC,
-  unless(anyOf(hasDescendant(ifStmt(HasWaitDescendantC)),
-   hasDescendant(whileStmt(HasWaitDescendantC)),
-   hasDescendant(forStmt(HasWaitDescendantC)),
-   hasDescendant(doStmt(HasWaitDescendantC)),
-   hasParent(whileStmt()),
-   hasParent(compoundStmt(hasParent(whileStmt(,
-   hasParent(forStmt()),

[clang] 903a153 - Ensure that the matcher is instantiated

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

Author: Stephen Kelly
Date: 2021-02-02T15:12:39Z
New Revision: 903a153409b8640aac30fa0b46b9a99ad90fe786

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

LOG: Ensure that the matcher is instantiated

Fix issue diagnosed by Windows linker.

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchersInternal.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp 
b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
index 6ebc72d450fe..b20a60425661 100644
--- a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -733,6 +733,7 @@ const internal::VariadicDynCastAllOfMatcher
 typeAliasTemplateDecl;
 const internal::VariadicAllOfMatcher decl;
 const internal::VariadicDynCastAllOfMatcher 
decompositionDecl;
+const internal::VariadicDynCastAllOfMatcher bindingDecl;
 const internal::VariadicDynCastAllOfMatcher
 linkageSpecDecl;
 const internal::VariadicDynCastAllOfMatcher namedDecl;



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


[clang] 9e5fc57 - [ASTMatchers] Ignore parts of BindingDecls which are not spelled in source

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

Author: Stephen Kelly
Date: 2021-02-02T14:23:13Z
New Revision: 9e5fc578f99aaa3f01374d3f09fda75fa7d0239e

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

LOG: [ASTMatchers] Ignore parts of BindingDecls which are not spelled in source

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

Added: 


Modified: 
clang/include/clang/AST/ASTNodeTraverser.h
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/AST/ASTTraverserTest.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTNodeTraverser.h 
b/clang/include/clang/AST/ASTNodeTraverser.h
index bb5b0c73f028..c4f0355b352e 100644
--- a/clang/include/clang/AST/ASTNodeTraverser.h
+++ b/clang/include/clang/AST/ASTNodeTraverser.h
@@ -438,6 +438,8 @@ class ASTNodeTraverser
   }
 
   void VisitBindingDecl(const BindingDecl *D) {
+if (Traversal == TK_IgnoreUnlessSpelledInSource)
+  return;
 if (const auto *E = D->getBinding())
   Visit(E);
   }

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 69957a952d17..58e69bb29df6 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -1216,6 +1216,8 @@ bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
   ScopedChildren = true;
 if (FD->isTemplateInstantiation())
   ScopedTraversal = true;
+  } else if (isa(DeclNode)) {
+ScopedChildren = true;
   }
 
   ASTNodeNotSpelledInSourceScope RAII1(this, ScopedTraversal);

diff  --git a/clang/unittests/AST/ASTTraverserTest.cpp 
b/clang/unittests/AST/ASTTraverserTest.cpp
index 94b9572ad50d..d633f90b57d2 100644
--- a/clang/unittests/AST/ASTTraverserTest.cpp
+++ b/clang/unittests/AST/ASTTraverserTest.cpp
@@ -1148,6 +1148,15 @@ void callDefaultArg()
 {
   hasDefaultArg(42);
 }
+
+void decomposition()
+{
+int arr[3];
+auto &[f, s, t] = arr;
+
+f = 42;
+}
+
 )cpp",
{"-std=c++20"});
 
@@ -1443,6 +1452,46 @@ CallExpr
 CallExpr
 |-DeclRefExpr 'hasDefaultArg'
 `-IntegerLiteral
+)cpp");
+  }
+
+  {
+auto FN = ast_matchers::match(
+functionDecl(hasName("decomposition"),
+ hasDescendant(decompositionDecl().bind("decomp"))),
+AST2->getASTContext());
+EXPECT_EQ(FN.size(), 1u);
+
+EXPECT_EQ(
+dumpASTString(TK_AsIs, FN[0].getNodeAs("decomp")),
+R"cpp(
+DecompositionDecl ''
+|-DeclRefExpr 'arr'
+|-BindingDecl 'f'
+| `-ArraySubscriptExpr
+|   |-ImplicitCastExpr
+|   | `-DeclRefExpr ''
+|   `-IntegerLiteral
+|-BindingDecl 's'
+| `-ArraySubscriptExpr
+|   |-ImplicitCastExpr
+|   | `-DeclRefExpr ''
+|   `-IntegerLiteral
+`-BindingDecl 't'
+  `-ArraySubscriptExpr
+|-ImplicitCastExpr
+| `-DeclRefExpr ''
+`-IntegerLiteral
+)cpp");
+
+EXPECT_EQ(dumpASTString(TK_IgnoreUnlessSpelledInSource,
+FN[0].getNodeAs("decomp")),
+  R"cpp(
+DecompositionDecl ''
+|-DeclRefExpr 'arr'
+|-BindingDecl 'f'
+|-BindingDecl 's'
+`-BindingDecl 't'
 )cpp");
   }
 }

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 06c2bbc29e5c..b756cf815aaf 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -2591,6 +2591,48 @@ B func1() { return 42; }
 Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
 std::make_unique>("allExprs", 1)));
   }
+
+  Code = R"cpp(
+void foo()
+{
+int arr[3];
+auto &[f, s, t] = arr;
+
+f = 42;
+}
+  )cpp";
+  {
+auto M = bindingDecl(hasName("f"));
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_AsIs, M), true, 
{"-std=c++17"}));
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+ true, {"-std=c++17"}));
+  }
+  {
+auto M = bindingDecl(hasName("f"), has(expr()));
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_AsIs, M), true, 
{"-std=c++17"}));
+EXPECT_FALSE(
+matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+ true, {"-std=c++17"}));
+  }
+  {
+auto M = integerLiteral(hasAncestor(bindingDecl(hasName("f";
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_AsIs, M), true, 
{"-std=c++17"}));
+EXPECT_FALSE(
+matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+ true, {"-std=c++17"}));
+  }
+  {
+auto M = declRefExpr(hasAncestor(bindingDecl(hasName("f";
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_AsIs, M), true, 

[clang] 467a045 - [ASTMatchers] Add matchers for decomposition decls

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

Author: Stephen Kelly
Date: 2021-02-02T14:11:02Z
New Revision: 467a045601430c81e1a7f41f6a134e751f17df55

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

LOG: [ASTMatchers] Add matchers for decomposition decls

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

Added: 


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

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index aac02bc4effe..ac816d28970b 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -591,6 +591,15 @@ Node Matchers
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1Decl.html;>DeclbindingDeclMatcherhttps://clang.llvm.org/doxygen/classclang_1_1BindingDecl.html;>BindingDecl...
+Matches binding 
declarations
+Example matches foo and bar
+(matcher = bindingDecl()
+
+  auto [foo, bar] = std::make_pair{42, 42};
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1Decl.html;>DeclblockDeclMatcherhttps://clang.llvm.org/doxygen/classclang_1_1BlockDecl.html;>BlockDecl...
 Matches block 
declarations.
 
@@ -6011,6 +6020,24 @@ AST Traversal Matchers
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1BindingDecl.html;>BindingDeclforDecompositionMatcherhttps://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html;>ValueDecl
 InnerMatcher
+Matches the 
DecompositionDecl the binding belongs to.
+
+For example, in:
+void foo()
+{
+int arr[3];
+auto [f, s, t] = arr;
+
+f = 42;
+}
+The matcher:
+  bindingDecl(hasName("f"),
+forDecomposition(decompositionDecl())
+matches 'f' in 'auto [f, s, t]'.
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1BlockDecl.html;>BlockDeclhasAnyParameterMatcherhttps://clang.llvm.org/doxygen/classclang_1_1ParmVarDecl.html;>ParmVarDecl
 InnerMatcher
 Matches any 
parameter of a function or an ObjC method declaration or a
 block.
@@ -7090,6 +7117,40 @@ AST Traversal Matchers
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1DecompositionDecl.html;>DecompositionDeclhasAnyBindingMatcherhttps://clang.llvm.org/doxygen/classclang_1_1BindingDecl.html;>BindingDecl
 InnerMatcher
+Matches any binding 
of a DecompositionDecl.
+
+For example, in:
+void foo()
+{
+int arr[3];
+auto [f, s, t] = arr;
+
+f = 42;
+}
+The matcher:
+  decompositionDecl(hasAnyBinding(bindingDecl(hasName("f").bind("fBinding"
+matches the decomposition decl with 'f' bound to "fBinding".
+
+
+
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1DecompositionDecl.html;>DecompositionDeclhasBindingunsigned N, Matcherhttps://clang.llvm.org/doxygen/classclang_1_1BindingDecl.html;>BindingDecl
 InnerMatcher
+Matches the Nth binding 
of a DecompositionDecl.
+
+For example, in:
+void foo()
+{
+int arr[3];
+auto [f, s, t] = arr;
+
+f = 42;
+}
+The matcher:
+  decompositionDecl(hasBinding(0, bindingDecl(hasName("f").bind("fBinding"
+matches the decomposition decl with 'f' bound to "fBinding".
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1DoStmt.html;>DoStmthasBodyMatcherhttps://clang.llvm.org/doxygen/classclang_1_1Stmt.html;>Stmt 
InnerMatcher
 
 

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index cbce6d7d0439..6cd4d26768b5 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -347,6 +347,16 @@ extern const internal::VariadicAllOfMatcher decl;
 extern const internal::VariadicDynCastAllOfMatcher
 decompositionDecl;
 
+/// Matches binding declarations
+/// Example matches \c foo and \c bar
+/// (matcher = bindingDecl()
+///
+/// \code
+///   auto [foo, bar] = std::make_pair{42, 42};
+/// \endcode
+extern const internal::VariadicDynCastAllOfMatcher
+bindingDecl;
+
 /// Matches a declaration of a linkage specification.
 ///
 /// Given
@@ -7379,6 +7389,80 @@ AST_MATCHER(Expr, nullPointerConstant) {
 Expr::NPC_ValueDependentIsNull);
 }
 
+/// Matches the DecompositionDecl the binding belongs to.
+///
+/// For example, in:
+/// \code
+/// void foo()
+/// {
+/// int arr[3];
+/// auto &[f, s, t] = arr;
+///
+/// f = 42;
+/// }
+/// \endcode
+/// The matcher:
+/// \code
+///   bindingDecl(hasName("f"),
+/// forDecomposition(decompositionDecl())
+/// \endcode
+/// matches 'f' in 'auto &[f, s, t]'.
+AST_MATCHER_P(BindingDecl, forDecomposition, internal::Matcher,
+  InnerMatcher) {
+  if (const ValueDecl *VD = Node.getDecomposedDecl())
+return InnerMatcher.matches(*VD, Finder, 

[clang] d6a0636 - [ASTMatchers] Fix matching after generic top-level matcher

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

Author: Stephen Kelly
Date: 2021-02-02T13:31:05Z
New Revision: d6a06365cf12bebe20a7d65cf3894608efc089b4

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

LOG: [ASTMatchers] Fix matching after generic top-level matcher

With a matcher like

  expr(anyOf(integerLiteral(equals(42)), unless(expr(

and code such as

  struct B {
B(int);
  };

  B func1() { return 42; }

the top-level expr() would match each of the nodes which are not spelled
in the source and then ignore-traverse to match the integerLiteral node.
This would result in multiple results reported for the integerLiteral.

Fix that by only running matching logic on nodes which are not skipped
with the top-level matcher.

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

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 41be3738e707..69957a952d17 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -837,6 +837,14 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
   if (EnableCheckProfiling)
 Timer.setBucket([MP.second->getID()]);
   BoundNodesTreeBuilder Builder;
+
+  {
+TraversalKindScope RAII(getASTContext(), MP.first.getTraversalKind());
+if (getASTContext().getParentMapContext().traverseIgnored(DynNode) !=
+DynNode)
+  continue;
+  }
+
   if (MP.first.matches(DynNode, this, )) {
 MatchVisitor Visitor(ActiveASTContext, MP.second);
 Builder.visitMatches();

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index c67c40ed960a..06c2bbc29e5c 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -2519,6 +2519,78 @@ template<> bool timesTwo(bool){
 EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
 EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
   }
+
+  Code = R"cpp(
+struct B {
+  B(int);
+};
+
+B func1() { return 42; }
+  )cpp";
+  {
+auto M = expr(ignoringImplicit(integerLiteral(equals(42)).bind("intLit")));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_AsIs, M),
+std::make_unique>("intLit", 1)));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+std::make_unique>("intLit", 1)));
+  }
+  {
+auto M = expr(unless(integerLiteral(equals(24.bind("intLit");
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_AsIs, M),
+std::make_unique>("intLit", 7)));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+std::make_unique>("intLit", 1)));
+  }
+  {
+auto M =
+expr(anyOf(integerLiteral(equals(42)).bind("intLit"), unless(expr(;
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_AsIs, M),
+std::make_unique>("intLit", 1)));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+std::make_unique>("intLit", 1)));
+  }
+  {
+auto M = expr(allOf(integerLiteral(equals(42)).bind("intLit"), expr()));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_AsIs, M),
+std::make_unique>("intLit", 1)));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+std::make_unique>("intLit", 1)));
+  }
+  {
+auto M = expr(integerLiteral(equals(42)).bind("intLit"), expr());
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_AsIs, M),
+std::make_unique>("intLit", 1)));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+std::make_unique>("intLit", 1)));
+  }
+  {
+auto M = expr(optionally(integerLiteral(equals(42)).bind("intLit")));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_AsIs, M),
+std::make_unique>("intLit", 1)));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+std::make_unique>("intLit", 1)));
+  }
+  {
+auto M = expr().bind("allExprs");
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_AsIs, M),
+std::make_unique>("allExprs", 7)));
+EXPECT_TRUE(matchAndVerifyResultTrue(
+Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+std::make_unique>("allExprs", 1)));
+  }
 }
 
 TEST(Traversal, traverseNoImplicit) {


[clang] 68b0595 - NFC: Re-generate out-of-date matchers docs

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

Author: Stephen Kelly
Date: 2021-02-01T21:25:29Z
New Revision: 68b0595ccb8de1b0a9459f958dda17164341ee87

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

LOG: NFC: Re-generate out-of-date matchers docs

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index ffad8acbeab6..aac02bc4effe 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -721,6 +721,18 @@ Node Matchers
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1Decl.html;>DecldecompositionDeclMatcherhttps://clang.llvm.org/doxygen/classclang_1_1DecompositionDecl.html;>DecompositionDecl...
+Matches 
decomposition-declarations.
+
+Examples matches the declaration node with foo and bar, but not
+number.
+(matcher = declStmt(has(decompositionDecl(
+
+  int number = 42;
+  auto [foo, bar] = std::make_pair{42, 42};
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1Decl.html;>DeclenumConstantDeclMatcherhttps://clang.llvm.org/doxygen/classclang_1_1EnumConstantDecl.html;>EnumConstantDecl...
 Matches enum 
constants.
 
@@ -1126,18 +1138,6 @@ Node Matchers
 
 
 
-Matcherhttps://clang.llvm.org/doxygen/classclang_1_1DecompositionDecl.html;>DecompositionDecldecompositionDeclMatcherhttps://clang.llvm.org/doxygen/classclang_1_1DecompositionDecl.html;>DecompositionDecl...
-Matches 
decomposition-declarations.
-
-Examples matches the declaration node with foo and bar, but not
-number.
-(matcher = declStmt(has(decompositionDecl(
-
-  int number = 42;
-  auto [foo, bar] = std::make_pair{42, 42};
-
-
-
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifierLoc.html;>NestedNameSpecifierLocnestedNameSpecifierLocMatcherhttps://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifierLoc.html;>NestedNameSpecifierLoc...
 Same as 
nestedNameSpecifier but matches NestedNameSpecifierLoc.
 
@@ -5613,40 +5613,6 @@ AST Traversal Matchers
 
 
 
-Matcher*invocationMatcher*...Matcher*
-Matches function calls 
and constructor calls
-
-Because CallExpr and CXXConstructExpr do not share a common
-base class with API accessing arguments etc, AST Matchers for code
-which should match both are typically duplicated. This matcher
-removes the need for duplication.
-
-Given code
-struct ConstructorTakesInt
-{
-  ConstructorTakesInt(int i) {}
-};
-
-void callTakesInt(int i)
-{
-}
-
-void doCall()
-{
-  callTakesInt(42);
-}
-
-void doConstruct()
-{
-  ConstructorTakesInt cti(42);
-}
-
-The matcher
-invocation(hasArgument(0, integerLiteral(equals(42
-matches the expression in both doCall and doConstruct
-
-
-
 Matcher*eachOfMatcher*, ..., 
Matcher*
 Matches if any of the given 
matchers matches.
 
@@ -5790,6 +5756,40 @@ AST Traversal Matchers
 
 
 
+Matcher*invocationMatcher*...Matcher*
+Matches function calls 
and constructor calls
+
+Because CallExpr and CXXConstructExpr do not share a common
+base class with API accessing arguments etc, AST Matchers for code
+which should match both are typically duplicated. This matcher
+removes the need for duplication.
+
+Given code
+struct ConstructorTakesInt
+{
+  ConstructorTakesInt(int i) {}
+};
+
+void callTakesInt(int i)
+{
+}
+
+void doCall()
+{
+  callTakesInt(42);
+}
+
+void doConstruct()
+{
+  ConstructorTakesInt cti(42);
+}
+
+The matcher
+invocation(hasArgument(0, integerLiteral(equals(42
+matches the expression in both doCall and doConstruct
+
+
+
 Matcher*optionallyMatcher*
 Matches any node 
regardless of the submatcher.
 



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


[clang] b10d445 - [ASTMatchers] Fix definition of decompositionDecl

2021-01-30 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-01-30T16:29:40Z
New Revision: b10d445307a0f3c7e5522836b4331090aacaf349

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

LOG: [ASTMatchers] Fix definition of decompositionDecl

Added: 


Modified: 
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/ASTMatchers/ASTMatchersInternal.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 10532b3da209..cbce6d7d0439 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -344,7 +344,7 @@ extern const internal::VariadicAllOfMatcher decl;
 ///   int number = 42;
 ///   auto [foo, bar] = std::make_pair{42, 42};
 /// \endcode
-extern const internal::VariadicAllOfMatcher
+extern const internal::VariadicDynCastAllOfMatcher
 decompositionDecl;
 
 /// Matches a declaration of a linkage specification.

diff  --git a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp 
b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
index 6e36842d0660..6ebc72d450fe 100644
--- a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -732,7 +732,7 @@ const internal::VariadicDynCastAllOfMatcher typeAliasDecl;
 const internal::VariadicDynCastAllOfMatcher
 typeAliasTemplateDecl;
 const internal::VariadicAllOfMatcher decl;
-const internal::VariadicAllOfMatcher decompositionDecl;
+const internal::VariadicDynCastAllOfMatcher 
decompositionDecl;
 const internal::VariadicDynCastAllOfMatcher
 linkageSpecDecl;
 const internal::VariadicDynCastAllOfMatcher namedDecl;



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


[clang] bb57a34 - Fix traversal with hasDescendant into lambdas

2021-01-30 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-01-30T13:57:41Z
New Revision: bb57a3422a09dcdd572ccb42767a0dabb5f966dd

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

LOG: Fix traversal with hasDescendant into lambdas

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

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 89e83ee61574..41be3738e707 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -295,7 +295,7 @@ class MatchChildASTVisitor
 if (!match(*Node->getBody()))
   return false;
 
-return true;
+return VisitorBase::TraverseStmt(Node->getBody());
   }
 
   bool shouldVisitTemplateInstantiations() const { return true; }

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index cbea274cecc9..c67c40ed960a 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3220,6 +3220,12 @@ void func14() {
   float i = 42.0;
 }
 
+void func15() {
+  int count = 0;
+  auto l = [&] { ++count; };
+  (void)l;
+}
+
 )cpp";
 
   EXPECT_TRUE(
@@ -3404,6 +3410,15 @@ void func14() {
functionDecl(hasName("func14"), hasDescendant(floatLiteral(,
   langCxx20OrLater()));
 
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   compoundStmt(
+   hasDescendant(varDecl(hasName("count")).bind("countVar")),
+   hasDescendant(
+   
declRefExpr(to(varDecl(equalsBoundNode("countVar"))),
+  langCxx20OrLater()));
+
   Code = R"cpp(
 void foo() {
 int explicit_captured = 0;



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


[clang] 7912508 - [ASTMatchers] Fix traversal below range-for elements

2021-01-30 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-01-30T13:47:14Z
New Revision: 79125085f16540579d27c7e4987f63eef9c4aa23

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

LOG: [ASTMatchers] Fix traversal below range-for elements

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

Added: 


Modified: 
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 5034203840fc..89e83ee61574 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -243,10 +243,14 @@ class MatchChildASTVisitor
   return true;
 ScopedIncrement ScopedDepth();
 if (auto *Init = Node->getInit())
-  if (!match(*Init))
+  if (!traverse(*Init))
 return false;
-if (!match(*Node->getLoopVariable()) || !match(*Node->getRangeInit()) ||
-!match(*Node->getBody()))
+if (!match(*Node->getLoopVariable()))
+  return false;
+if (match(*Node->getRangeInit()))
+  if (!VisitorBase::TraverseStmt(Node->getRangeInit()))
+return false;
+if (!match(*Node->getBody()))
   return false;
 return VisitorBase::TraverseStmt(Node->getBody());
   }
@@ -488,15 +492,21 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 
   bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue) {
 if (auto *RF = dyn_cast(S)) {
-  for (auto *SubStmt : RF->children()) {
-if (SubStmt == RF->getInit() || SubStmt == RF->getLoopVarStmt() ||
-SubStmt == RF->getRangeInit() || SubStmt == RF->getBody()) {
-  TraverseStmt(SubStmt, Queue);
-} else {
-  ASTNodeNotSpelledInSourceScope RAII(this, true);
-  TraverseStmt(SubStmt, Queue);
+  {
+ASTNodeNotAsIsSourceScope RAII(this, true);
+TraverseStmt(RF->getInit());
+// Don't traverse under the loop variable
+match(*RF->getLoopVariable());
+TraverseStmt(RF->getRangeInit());
+  }
+  {
+ASTNodeNotSpelledInSourceScope RAII(this, true);
+for (auto *SubStmt : RF->children()) {
+  if (SubStmt != RF->getBody())
+TraverseStmt(SubStmt);
 }
   }
+  TraverseStmt(RF->getBody());
   return true;
 } else if (auto *RBO = dyn_cast(S)) {
   {

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index a3a09c426673..cbea274cecc9 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -2820,6 +2820,36 @@ struct CtorInitsNonTrivial : NonTrivial
 EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
   }
 
+  Code = R"cpp(
+  struct Range {
+int* begin() const;
+int* end() const;
+  };
+  Range getRange(int);
+
+  void rangeFor()
+  {
+for (auto i : getRange(42))
+{
+}
+  }
+  )cpp";
+  {
+auto M = integerLiteral(equals(42));
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = callExpr(hasDescendant(integerLiteral(equals(42;
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = compoundStmt(hasDescendant(integerLiteral(equals(42;
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+
   Code = R"cpp(
   void rangeFor()
   {
@@ -2891,6 +2921,40 @@ struct CtorInitsNonTrivial : NonTrivial
 matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
  true, {"-std=c++20"}));
   }
+
+  Code = R"cpp(
+  struct Range {
+int* begin() const;
+int* end() const;
+  };
+  Range getRange(int);
+
+  int getNum(int);
+
+  void rangeFor()
+  {
+for (auto j = getNum(42); auto i : getRange(j))
+{
+}
+  }
+  )cpp";
+  {
+auto M = integerLiteral(equals(42));
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_AsIs, M), true, 
{"-std=c++20"}));
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+ true, {"-std=c++20"}));
+  }
+  {
+auto M = compoundStmt(hasDescendant(integerLiteral(equals(42;
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_AsIs, M), true, 
{"-std=c++20"}));
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+ true, {"-std=c++20"}));
+  }
+
  

[clang] 43cc4f1 - Ensure that we traverse non-op() method bodys of lambdas

2021-01-28 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-01-29T00:49:28Z
New Revision: 43cc4f15008f8c700497d3d2b7020bfd29f5750f

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

LOG: Ensure that we traverse non-op() method bodys of lambdas

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

Added: 


Modified: 
clang/include/clang/AST/RecursiveASTVisitor.h
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index db2ef21f4364..7870cea198a7 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -2062,7 +2062,8 @@ bool 
RecursiveASTVisitor::TraverseFunctionHelper(FunctionDecl *D) {
 
   if (const auto *MD = dyn_cast(D)) {
 if (const CXXRecordDecl *RD = MD->getParent()) {
-  if (RD->isLambda()) {
+  if (RD->isLambda() &&
+  declaresSameEntity(RD->getLambdaCallOperator(), MD)) {
 VisitBody = VisitBody && getDerived().shouldVisitLambdaBody();
   }
 }

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 8004599e01a2..a3a09c426673 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -474,6 +474,42 @@ TEST(Matcher, CapturesThis) {
   EXPECT_TRUE(notMatches("void f() { int z = 3; [](){}; }", HasCaptureThis));
 }
 
+TEST(Matcher, MatchesMethodsOnLambda) {
+  StringRef Code = R"cpp(
+struct A {
+  ~A() {}
+};
+void foo()
+{
+  A a;
+  auto l = [a] { };
+  auto lCopy = l;
+  auto lPtrDecay = +[] { };
+  (void)lPtrDecay;
+}
+)cpp";
+
+  EXPECT_TRUE(matches(
+  Code, cxxConstructorDecl(
+hasBody(compoundStmt()),
+hasAncestor(lambdaExpr(hasAncestor(varDecl(hasName("l"),
+isCopyConstructor(;
+  EXPECT_TRUE(matches(
+  Code, cxxConstructorDecl(
+hasBody(compoundStmt()),
+hasAncestor(lambdaExpr(hasAncestor(varDecl(hasName("l"),
+isMoveConstructor(;
+  EXPECT_TRUE(matches(
+  Code, cxxDestructorDecl(
+hasBody(compoundStmt()),
+hasAncestor(lambdaExpr(hasAncestor(varDecl(hasName("l";
+  EXPECT_TRUE(matches(
+  Code, cxxConversionDecl(hasBody(compoundStmt(has(returnStmt(
+  hasReturnValue(implicitCastExpr()),
+  hasAncestor(lambdaExpr(hasAncestor(
+  varDecl(hasName("lPtrDecay";
+}
+
 TEST(Matcher, isClassMessage) {
   EXPECT_TRUE(matchesObjC(
   "@interface NSString +(NSString *) stringWithFormat; @end "



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


[clang] 3c79734 - [ASTMatchers] Add invocation matcher

2021-01-28 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-01-28T20:47:09Z
New Revision: 3c79734f29284d6b54f1867a03428a3d9fd338d9

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

LOG: [ASTMatchers] Add invocation matcher

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

Added: 


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

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 912da6e62c2f..ffad8acbeab6 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -5613,6 +5613,40 @@ AST Traversal Matchers
 
 
 
+Matcher*invocationMatcher*...Matcher*
+Matches function calls 
and constructor calls
+
+Because CallExpr and CXXConstructExpr do not share a common
+base class with API accessing arguments etc, AST Matchers for code
+which should match both are typically duplicated. This matcher
+removes the need for duplication.
+
+Given code
+struct ConstructorTakesInt
+{
+  ConstructorTakesInt(int i) {}
+};
+
+void callTakesInt(int i)
+{
+}
+
+void doCall()
+{
+  callTakesInt(42);
+}
+
+void doConstruct()
+{
+  ConstructorTakesInt cti(42);
+}
+
+The matcher
+invocation(hasArgument(0, integerLiteral(equals(42
+matches the expression in both doCall and doConstruct
+
+
+
 Matcher*eachOfMatcher*, ..., 
Matcher*
 Matches if any of the given 
matchers matches.
 

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 6f6dfab59a39..10532b3da209 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2829,6 +2829,42 @@ extern const internal::MapAnyOfMatcher
 binaryOperation;
 
+/// Matches function calls and constructor calls
+///
+/// Because CallExpr and CXXConstructExpr do not share a common
+/// base class with API accessing arguments etc, AST Matchers for code
+/// which should match both are typically duplicated. This matcher
+/// removes the need for duplication.
+///
+/// Given code
+/// \code
+/// struct ConstructorTakesInt
+/// {
+///   ConstructorTakesInt(int i) {}
+/// };
+///
+/// void callTakesInt(int i)
+/// {
+/// }
+///
+/// void doCall()
+/// {
+///   callTakesInt(42);
+/// }
+///
+/// void doConstruct()
+/// {
+///   ConstructorTakesInt cti(42);
+/// }
+/// \endcode
+///
+/// The matcher
+/// \code
+/// invocation(hasArgument(0, integerLiteral(equals(42
+/// \endcode
+/// matches the expression in both doCall and doConstruct
+extern const internal::MapAnyOfMatcher invocation;
+
 /// Matches unary expressions that have a specific type of argument.
 ///
 /// Given

diff  --git a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp 
b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
index 6c7e14e3499a..6e36842d0660 100644
--- a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -924,6 +924,7 @@ const internal::VariadicDynCastAllOfMatcher
 const internal::MapAnyOfMatcher
 binaryOperation;
+const internal::MapAnyOfMatcher invocation;
 const internal::VariadicDynCastAllOfMatcher unaryOperator;
 const internal::VariadicDynCastAllOfMatcher
 conditionalOperator;

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 00a7c74a0b90..9ac9593e042b 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -358,6 +358,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(injectedClassNameType);
   REGISTER_MATCHER(innerType);
   REGISTER_MATCHER(integerLiteral);
+  REGISTER_MATCHER(invocation);
   REGISTER_MATCHER(isAllowedToContainClauseKind);
   REGISTER_MATCHER(isAnonymous);
   REGISTER_MATCHER(isAnyCharacter);

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
index d681620cf548..1c6947acf0ab 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -863,6 +863,47 @@ void opFree()
  mapAnyOf(unaryOperator, cxxOperatorCallExpr)
  .with(hasAnyOperatorName("+", "!"),

forFunction(functionDecl(hasName("opFree")));
+
+  Code = R"cpp(
+struct ConstructorTakesInt
+{
+  ConstructorTakesInt(int i) {}
+};
+
+void callTakesInt(int i)
+{
+
+}
+
+void doCall()
+{
+  callTakesInt(42);
+}
+
+void doConstruct()
+{
+  ConstructorTakesInt cti(42);
+}
+)cpp";
+
+  EXPECT_TRUE(matches(
+  

[clang] 6f0df3c - [ASTMatchers] Avoid pathological traversal over nested lambdas

2021-01-28 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-01-28T20:45:45Z
New Revision: 6f0df3cddb3e3f38df1baa7aa4d743a74bb46688

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

LOG: [ASTMatchers] Avoid pathological traversal over nested lambdas

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

Added: 


Modified: 
clang/include/clang/AST/RecursiveASTVisitor.h
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 505ea700fd0e..db2ef21f4364 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -186,6 +186,9 @@ template  class RecursiveASTVisitor {
   /// code, e.g., implicit constructors and destructors.
   bool shouldVisitImplicitCode() const { return false; }
 
+  /// Return whether this visitor should recurse into lambda body
+  bool shouldVisitLambdaBody() const { return true; }
+
   /// Return whether this visitor should traverse post-order.
   bool shouldTraversePostOrder() const { return false; }
 
@@ -2057,6 +2060,14 @@ bool 
RecursiveASTVisitor::TraverseFunctionHelper(FunctionDecl *D) {
   // by clang.
   (!D->isDefaulted() || getDerived().shouldVisitImplicitCode());
 
+  if (const auto *MD = dyn_cast(D)) {
+if (const CXXRecordDecl *RD = MD->getParent()) {
+  if (RD->isLambda()) {
+VisitBody = VisitBody && getDerived().shouldVisitLambdaBody();
+  }
+}
+  }
+
   if (VisitBody) {
 TRY_TO(TraverseStmt(D->getBody())); // Function body.
   }

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index 8ddd3c87e09d..5034203840fc 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -556,9 +556,9 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
 if (LE->hasExplicitResultType())
   TraverseTypeLoc(Proto.getReturnLoc());
 TraverseStmt(LE->getTrailingRequiresClause());
-
-TraverseStmt(LE->getBody());
   }
+
+  TraverseStmt(LE->getBody());
   return true;
 }
 return RecursiveASTVisitor::dataTraverseNode(S, Queue);
@@ -697,6 +697,10 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
   bool shouldVisitTemplateInstantiations() const { return true; }
   bool shouldVisitImplicitCode() const { return true; }
 
+  // We visit the lambda body explicitly, so instruct the RAV
+  // to not visit it on our behalf too.
+  bool shouldVisitLambdaBody() const { return false; }
+
   bool IsMatchingInASTNodeNotSpelledInSource() const override {
 return TraversingASTNodeNotSpelledInSource;
   }

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 92bf244b0e4a..8004599e01a2 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3853,6 +3853,78 @@ void binop()
   }
 }
 
+TEST(IgnoringImpCasts, PathologicalLambda) {
+
+  // Test that deeply nested lambdas are not a performance penalty
+  StringRef Code = R"cpp(
+void f() {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+  [] {
+int i = 42;
+(void)i;
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+  }();
+}
+  )cpp";
+
+  EXPECT_TRUE(matches(Code, integerLiteral(equals(42;
+  EXPECT_TRUE(matches(Code, 
functionDecl(hasDescendant(integerLiteral(equals(42));
+}
+
 TEST(IgnoringImpCasts, MatchesImpCasts) {
   // This test checks that ignoringImpCasts matches when implicit casts are
   // present and its inner matcher alone does not match.



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


  1   2   3   4   >