[PATCH] D80023: [clang-tidy] Add abseil-string-find-str-contains checker.

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



Comment at: 
clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp:72
+   binaryOperator(hasOperatorName("=="),
+  hasEitherOperand(ignoringParenImpCasts(StringNpos)),
+  hasEitherOperand(ignoringParenImpCasts(StringFind))),

ymandel wrote:
> Would `hasOperands` replace these two separate calls to `hasEitherOperand`? 
> Same below lines 79-80 (I think it's a new matcher, fwiw).
Just added, I added it to remove calls of multiple hasEitherOperand calls for 
the reason of preventing the matchers matching the same operand. I just got a 
little lost in my previous comment



Comment at: 
clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp:98
+const LangOptions &LangOpts) const {
+  return LangOpts.CPlusPlus;
+}

nit: as abseil requires c++11, should this check also require c++11 support


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80023



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


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

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

In D80202#2046266 , @klimek wrote:

> Given the extra complexity I'd like to see that it matters - bound nodes tend 
> to be small.


I put that in the description, but this is where i need help. whats the best 
way to benchmark the matchers? 
Also, do you know how it was benchmarked when `MaxMemoizationEntries` was 
decided upon?
There was also comments about some making some micro benchmarks but I don't 
think that was acted upon.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80202



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


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

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

Running most of the clang tidy checks on the clang-tidy folder yields these 
results

  
=BeforePatch===
  
  RUN1:
  4045.17user 83.93system 11:28.80elapsed 599%CPU (0avgtext+0avgdata 
534024maxresident)k
  0inputs+0outputs (0major+27584683minor)pagefaults 0swaps
  
  RUN2:
  4078.06user 84.99system 11:35.99elapsed 598%CPU (0avgtext+0avgdata 
506912maxresident)k
  55312inputs+0outputs (663major+27661947minor)pagefaults 0swaps
  
  RUN3:
  4040.77user 86.02system 11:28.85elapsed 599%CPU (0avgtext+0avgdata 
547096maxresident)k
  0inputs+0outputs (0major+27698937minor)pagefaults 0swaps



  
==AfterPatch===
  
  RUN1: 
  4025.33user 83.32system 11:27.00elapsed 598%CPU (0avgtext+0avgdata 
530568maxresident)k
  0inputs+0outputs (0major+27689512minor)pagefaults 0swaps
  
  RUN2:
  4056.93user 83.36system 11:32.31elapsed 598%CPU (0avgtext+0avgdata 
529120maxresident)k
  3752inputs+0outputs (19major+27794845minor)pagefaults 0swaps
  
  RUN3:
  4029.05user 85.45system 11:26.31elapsed 599%CPU (0avgtext+0avgdata 
533508maxresident)k
  0inputs+0outputs (0major+27730918minor)pagefaults 0swaps

Shows a consistent improvement but there tests are very noisy and dont focus on 
just the matching, they also include all the other boilderplate when running 
clang-tidy over a database. not to mention a small sample size


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80202



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


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

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

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80371

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


Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -27,22 +27,13 @@
 }
 
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(
-  functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
   Finder->addMatcher(
   functionDecl(
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +71,10 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  if (Range.isInvalid())
+return;
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());


Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -27,22 +27,13 @@
 }
 
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(
-  functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
   Finder->addMatcher(
   functionDecl(
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +71,10 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  if (Range.isInvalid())
+return;
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

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

Figured out the actual cause of this bug, `getExceptionSpecRange()` returns a 
null range if the function has an unknown return type

  undefined_type throws() throw();

This is the tidy output (where assertions are disabled)

  warning: dynamic exception specification '' is deprecated; consider using 
'noexcept' instead [modernize-use-noexcept]
  /home/ce/example.cpp:1:1: error: unknown type name 'undefined_type' 
[clang-diagnostic-error]
  undefined_type throws() throw();
  ^
  1 warning and 1 error generated.
  Error while processing /home/ce/example.cpp.
  Found compiler error(s).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371



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


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

2020-05-25 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 265899.
njames93 added a comment.

- Isolated exact cause of the assert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371

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


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


Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exceptio

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

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

In D80371#2052069 , @aaron.ballman 
wrote:

> LGTM, but please add a test case for the changes.


As this fix is preventing a crash in error causing code I can't include a 
specific test case as the clang-tidy tests will fail if there is any error 
emitted from clang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371



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


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

2020-05-25 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4c5818dd8cd9: [clang-tidy] Fix potential assert in 
use-noexcept check (authored by njames93).

Changed prior to commit:
  https://reviews.llvm.org/D80371?vs=265923&id=265924#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371

Files:
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' 
[clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exception Source Range is invalid.");
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' [clang-diagnostic-error]
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid)

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

2020-05-25 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 265923.
njames93 added a comment.

- Added test case


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80371

Files:
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' 
[clang-diagnostic-error]
\ No newline at end of file
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   NoexceptMacro(Options.get("ReplacementString", "")),
@@ -29,20 +33,12 @@
 void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   functionDecl(
-  cxxMethodDecl(
-  hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  anyOf(hasOverloadedOperatorName("delete[]"),
-hasOverloadedOperatorName("delete"), cxxDestructorDecl()))
-  .bind("del-dtor"))
-  .bind("funcDecl"),
-  this);
-
-  Finder->addMatcher(
-  functionDecl(
+  isValid(),
   hasTypeLoc(loc(functionProtoType(hasDynamicExceptionSpec(,
-  unless(anyOf(hasOverloadedOperatorName("delete[]"),
-   hasOverloadedOperatorName("delete"),
-   cxxDestructorDecl(
+  optionally(cxxMethodDecl(anyOf(hasAnyOverloadedOperatorName(
+ "delete[]", "delete"),
+ cxxDestructorDecl()))
+ .bind("del-dtor")))
   .bind("funcDecl"),
   this);
 
@@ -80,6 +76,9 @@
   .castAs()
   .getExceptionSpecRange();
   }
+
+  assert(Range.isValid() && "Exception Source Range is invalid.");
+
   CharSourceRange CRange = Lexer::makeFileCharRange(
   CharSourceRange::getTokenRange(Range), *Result.SourceManager,
   Result.Context->getLangOpts());


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-noexcept-error.cpp
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -expect-clang-tidy-error %s modernize-use-noexcept %t
+
+// We're not interested in the check issuing a warning here, just making sure
+// clang-tidy doesn't assert.
+undefined_type doesThrow() throw();
+// CHECK-MESSAGES: :[[@LINE-1]]:1: error: unknown type name 'undefined_type' [clang-diagnostic-error]
\ No newline at end of file
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.h
@@ -41,7 +41,7 @@
 
 private:
   const std::string NoexceptMacro;
-  bool UseNoexceptFalse;
+  const bool UseNoexceptFalse;
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNoexceptCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER(NamedDecl, isValid) { return !Node.isInvalidDecl(); }
+} // namespace
+
 UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *

[PATCH] D80514: [clang-tidy] modernize-use-trailing-return-type support for C++20 concepts and decltype

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



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-trailing-return-type.cpp:550
+
+#if __cplusplus > 201703L /* C++2a and later */
+

bernhardmgruber wrote:
> How do you want to handle these tests which require C++20? I have seen other 
> checks use a separate file for tests which require a different language 
> version.
Yes, move them into a seperate file and specify `-std=c++20` in the run line


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

https://reviews.llvm.org/D80514



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


[PATCH] D80531: [clang-tidy]: Added modernize-replace-disallow-copy-and-assign-macro

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

In D80531#2053969 , @kwk wrote:

> @Eugene.Zelenko thank you for the review. I've fixed all places that you've 
> mentioned. And have a question about one thing in particular. See inline.
>
> Do you by any chance know why `llvm-lit` keeps complaining when I use 
> `[[@LINE-1]]` in my tests as so many other tests do?


It's complaining because your check lines are 2 lines after the diagnostic so 
you should use `[[@LINE-2]]`




Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:28
+SourceRange Range, const MacroArgs *Args) override {
+IdentifierInfo *identifierInfo = MacroNameTok.getIdentifierInfo();
+if (!identifierInfo)

clang-tidy fail on the variables, please rename them to use `CamelCase` format.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:51
+// pre-written code snippet. But for now, this is okay.
+std::string Replacement =
+className + "(const " + className + " &) = delete;";

nit:
```
std::string Replacement = llvm::formatv(
R"cpp({0}(const {0} &) = delete;
const {0} &operator=(const {0} &) = delete{1})cpp",
classIdent->getNameStart(), FinalizeWithSemicolon ? ";" : "");```



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:66
+
+  ClangTidyCheck &Check;
+  Preprocessor &PP;

nit: Shouldn't this be a reference to a 
`ReplaceDisallowCopyAndAssignMacroCheck`? Doing so will allow you to use a 
getter in the Check for the `MacroName` option to save storing a copy of that 
as well inside the callback.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.h:52-53
+
+  std::string MacroName;
+  bool FinalizeWithSemicolon;
+};

These can both be marked `const`



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize-replace-disallow-copy-and-assign-macro.rst:41
+
+.. option:: FinalizeWithSemicolon
+

This option should be removed and instead infer the value dynamically by 
checking the token directly after the macro use to see if its a semi-colon.

Something like this in the PPCallback should get you there
```
  bool shouldAppendSemi(SourceRange MacroLoc) {
llvm::Optional Next =
Lexer::findNextToken(MacroLoc.getEnd(), SM, PP.getLangOpts());
return !(Next && Next->is(tok::semi));
  }```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80531



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


[PATCH] D80531: [clang-tidy]: Added modernize-replace-disallow-copy-and-assign-macro

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



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:32
+  return;
+if (std::string(Info->getNameStart()) != Check.MacroName)
+  return;

```
if (Info->getName() != Check.MacroName)```
Avoid constructing the string if you don't have to.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:36
+// be the class name.
+const Token *classNameTok = Args->getUnexpArgument(0);
+if (Args->ArgNeedsPreexpansion(classNameTok, PP))

s/classNameTok/ClassNameTok



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:41
+  return;
+clang::IdentifierInfo *classIdent = classNameTok->getIdentifierInfo();
+if (!classIdent)

s/classIndent/ClassIndent



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:49
+R"cpp({0}(const {0} &) = delete;
+const {0} &operator=(const {0} &) = delete{1})cpp",
+classIdent->getNameStart(), shouldAppendSemi(Range) ? ";" : "");

if you wanted to, you could format this quite easily to avoid the need of 
specifying a formatter in the checks
```{2}const {0} &operator=(const {0} &) = delete{1})cpp",...
Lexer::getIndentationForLine(Range.getBegin(), SM))```



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.h:52
+
+  const std::string MacroName;
+};

I'd prefer this to be private with a getter function



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-replace-disallow-copy-and-assign-macro.cpp:36-38
+// CHECK-MESSAGES-NEXT-DEFAULT: {{^}}  
DISALLOW_COPY_AND_ASSIGN(TestClass1);{{$}}
+// CHECK-MESSAGES-NEXT-DEFAULT: {{^}}  ^{{$}}
+// CHECK-MESSAGES-NEXT-DEFAULT: {{^}}  TestClass1(const TestClass1 &) = 
delete;const TestClass1 &operator=(const TestClass1 &) = delete{{$}}

These really aren't important to test for, so long as the diagnostic and fix it 
are checked, that's all you need to worry about. Like how you have it for 
`TestClass2`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80531



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


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

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

I'm having trouble with the reproduction of this - https://godbolt.org/z/tsMfcj.
Aside from that this needs some test cases to demonstrate the patch is indeed 
working


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80536



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


[PATCH] D69000: [clang-tidy] new check: modernize-deprecated-iterator-base

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

First of all I'd definitely wait until a patch to include ASTMatcher support 
for CXXBaseSpecifier lands before progressing with this. 
Secondly this issue should be warned on by clang when compiling with c++17 with 
some stdlib support, libc++ should mark iterator as deprecated when compiling 
with c++17.
Having said that this still has value as the fix its are helpful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69000



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


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

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

Fixes readability-identifier-naming option MacroDefinitionCase should ignore 
macros passed as parameters. 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80631

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -80,7 +80,7 @@
 // RUN: {key: readability-identifier-naming.LocalPointerPrefix, value: 
'l_'}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerCase, 
value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerPrefix, 
value: 'lc_'}, \
-// RUN:   ]}' -- -fno-delayed-template-parsing \
+// RUN:   ]}' -- -fno-delayed-template-parsing -Dbad_macro \
 // RUN:   -I%S/Inputs/readability-identifier-naming \
 // RUN:   -isystem %S/Inputs/readability-identifier-naming/system
 
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -73,6 +73,14 @@
   /// MacroDefined calls checkMacro for macros in the main file
   void MacroDefined(const Token &MacroNameTok,
 const MacroDirective *MD) override {
+if (MD->getMacroInfo()->isBuiltinMacro())
+  return;
+if (PP->getSourceManager().isWrittenInBuiltinFile(
+MacroNameTok.getLocation()))
+  return;
+if (PP->getSourceManager().isWrittenInCommandLineFile(
+MacroNameTok.getLocation()))
+  return;
 Check->checkMacro(PP->getSourceManager(), MacroNameTok, 
MD->getMacroInfo());
   }
 


Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -80,7 +80,7 @@
 // RUN: {key: readability-identifier-naming.LocalPointerPrefix, value: 'l_'}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerCase, value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerPrefix, value: 'lc_'}, \
-// RUN:   ]}' -- -fno-delayed-template-parsing \
+// RUN:   ]}' -- -fno-delayed-template-parsing -Dbad_macro \
 // RUN:   -I%S/Inputs/readability-identifier-naming \
 // RUN:   -isystem %S/Inputs/readability-identifier-naming/system
 
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -73,6 +73,14 @@
   /// MacroDefined calls checkMacro for macros in the main file
   void MacroDefined(const Token &MacroNameTok,
 const MacroDirective *MD) override {
+if (MD->getMacroInfo()->isBuiltinMacro())
+  return;
+if (PP->getSourceManager().isWrittenInBuiltinFile(
+MacroNameTok.getLocation()))
+  return;
+if (PP->getSourceManager().isWrittenInCommandLineFile(
+MacroNameTok.getLocation()))
+  return;
 Check->checkMacro(PP->getSourceManager(), MacroNameTok, MD->getMacroInfo());
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80023: [clang-tidy] Add abseil-string-find-str-contains checker.

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



Comment at: 
clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp:40-44
+  // FIXME(tdl-g): These options are being parsed redundantly with the
+  // constructor because TransformerClangTidyCheck forces us to provide 
MakeRule
+  // before "this" is fully constructed, but StoreOptions requires us to store
+  // the parsed options in "this".  We need to fix TransformerClangTidyCheck 
and
+  // then we can clean this up.

I've put in a patch to hopefully address this shortcoming D80697. Don't worry 
about this right now, but If that lands then it will make this a lot cleaner.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80023



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


[PATCH] D80697: [clang-tidy] Reworked TransformerClangTidyCheck to simplify usage of Options

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

Changed `TransformerClangTidyCheck` to have a virtual method generate the rule. 
This has the advantages of making handling of any check options much simpler.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80697

Files:
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -10,6 +10,7 @@
 #include "ClangTidyTest.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Transformer/RangeSelector.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
 #include "clang/Tooling/Transformer/Stencil.h"
 #include "clang/Tooling/Transformer/Transformer.h"
 #include "gtest/gtest.h"
@@ -28,23 +29,23 @@
 using transformer::statement;
 
 // Invert the code of an if-statement, while maintaining its semantics.
-RewriteRule invertIf() {
-  StringRef C = "C", T = "T", E = "E";
-  RewriteRule Rule = tooling::makeRule(
-  ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
- hasElse(stmt().bind(E))),
-  change(statement(std::string(RewriteRule::RootID)),
- cat("if(!(", node(std::string(C)), ")) ",
- statement(std::string(E)), " else ",
- statement(std::string(T,
-  cat("negate condition and reverse `then` and `else` branches"));
-  return Rule;
-}
-
 class IfInverterCheck : public TransformerClangTidyCheck {
 public:
   IfInverterCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(invertIf(), Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional makeRule() const override {
+StringRef C = "C", T = "T", E = "E";
+RewriteRule Rule = tooling::makeRule(
+ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
+   hasElse(stmt().bind(E))),
+change(statement(std::string(RewriteRule::RootID)),
+   cat("if(!(", node(std::string(C)), ")) ",
+   statement(std::string(E)), " else ",
+   statement(std::string(T,
+cat("negate condition and reverse `then` and `else` branches"));
+return Rule;
+  }
 };
 
 // Basic test of using a rewrite rule as a ClangTidy.
@@ -70,10 +71,12 @@
 class IntLitCheck : public TransformerClangTidyCheck {
 public:
   IntLitCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(tooling::makeRule(integerLiteral(),
-change(cat("LIT")),
-cat("no message")),
-  Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional makeRule() const override {
+return tooling::makeRule(integerLiteral(), change(cat("LIT")),
+ cat("no message"));
+  }
 };
 
 // Tests that two changes in a single macro expansion do not lead to conflicts
@@ -94,11 +97,13 @@
 class BinOpCheck : public TransformerClangTidyCheck {
 public:
   BinOpCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(
-tooling::makeRule(
-binaryOperator(hasOperatorName("+"), hasRHS(expr().bind("r"))),
-change(node("r"), cat("RIGHT")), cat("no message")),
-Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional makeRule() const override {
+return tooling::makeRule(
+binaryOperator(hasOperatorName("+"), hasRHS(expr().bind("r"))),
+change(node("r"), cat("RIGHT")), cat("no message"));
+  }
 };
 
 // Tests case where the rule's match spans both source from the macro and its
@@ -118,18 +123,20 @@
 }
 
 // A trivial rewrite-rule generator that requires Objective-C code.
-Optional needsObjC(const LangOptions &LangOpts,
-const ClangTidyCheck::OptionsView &Options) {
-  if (!LangOpts.ObjC)
-return None;
-  return tooling::makeRule(clang::ast_matchers::functionDecl(),
-   change(cat("void changed() {}")), cat("no message"));
-}
-
 class NeedsObjCCheck : public TransformerClangTidyCheck {
 public:
   NeedsObjCCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(needsObjC, Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  bool isLanguageVersionSupported(const LangOptions &LangOpts

[PATCH] D80531: [clang-tidy]: Added modernize-replace-disallow-copy-and-assign-macro

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

Few changes and nits then LGTM




Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:25
+  const SourceManager &SM)
+  : Check(Check), PP(PP), SM(SM) {}
+

nit: You don't need to store a reference to the `SourceManager` as the 
`Preprocessor` holds a reference to it.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:32
+  return;
+if (Info->getNameStart() != Check.MacroName)
+  return;

Use `Info->getName()` here, the Length is stored internally so its not 
expensive to get and makes the code look more readable.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:45-46
+
+// FIXME: Maybe someday I will know how to expand the macro and not use my
+// pre-written code snippet. But for now, this is okay.
+std::string Replacement = llvm::formatv(

This FIXME can probably be removed as expanding the macro isn't a good idea. 
The macro should expand to just defining the function rather than deleting it 
like we want.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:50
+const {0} &operator=(const {0} &) = delete{1})cpp",
+ClassIdent->getNameStart(), shouldAppendSemi(Range) ? ";" : "");
+

ditto: use `ClassIdent->getName()` as well.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:52
+
+Check.diag(MacroNameTok.getLocation(), "using copy and assign macro '%0'")
+<< Check.MacroName

nit: Not a fan of the warning message, would prefer something like
`prefer deleting copy constructor and assignment operator over using macro 
'%0'` to explain what we are trying to do. Though if someone can think of 
something shorter that gets the same point I'm open to that.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp:59
+private:
+  /// \returns \c true if the next token after the given \a MacroLoc is \b not 
a
+  /// semicolon.

Use `\p` before `MacroLoc` instead of `\a` as its a parameter.



Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.h:52
+
+  const std::string MacroName;
+};

Make this private with a get function and I'll be happy. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80531



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


[PATCH] D80697: [clang-tidy] Reworked TransformerClangTidyCheck to simplify usage of Options

2020-05-28 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 266957.
njames93 added a comment.

- Renamed makeRule to buildRule to avoid ambiguity with tooling::makeRule


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80697

Files:
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -10,6 +10,7 @@
 #include "ClangTidyTest.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Transformer/RangeSelector.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
 #include "clang/Tooling/Transformer/Stencil.h"
 #include "clang/Tooling/Transformer/Transformer.h"
 #include "gtest/gtest.h"
@@ -28,23 +29,23 @@
 using transformer::statement;
 
 // Invert the code of an if-statement, while maintaining its semantics.
-RewriteRule invertIf() {
-  StringRef C = "C", T = "T", E = "E";
-  RewriteRule Rule = tooling::makeRule(
-  ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
- hasElse(stmt().bind(E))),
-  change(statement(std::string(RewriteRule::RootID)),
- cat("if(!(", node(std::string(C)), ")) ",
- statement(std::string(E)), " else ",
- statement(std::string(T,
-  cat("negate condition and reverse `then` and `else` branches"));
-  return Rule;
-}
-
 class IfInverterCheck : public TransformerClangTidyCheck {
 public:
   IfInverterCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(invertIf(), Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional buildRule() const override {
+StringRef C = "C", T = "T", E = "E";
+RewriteRule Rule = tooling::makeRule(
+ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
+   hasElse(stmt().bind(E))),
+change(statement(std::string(RewriteRule::RootID)),
+   cat("if(!(", node(std::string(C)), ")) ",
+   statement(std::string(E)), " else ",
+   statement(std::string(T,
+cat("negate condition and reverse `then` and `else` branches"));
+return Rule;
+  }
 };
 
 // Basic test of using a rewrite rule as a ClangTidy.
@@ -70,10 +71,12 @@
 class IntLitCheck : public TransformerClangTidyCheck {
 public:
   IntLitCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(tooling::makeRule(integerLiteral(),
-change(cat("LIT")),
-cat("no message")),
-  Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional buildRule() const override {
+return tooling::makeRule(integerLiteral(), change(cat("LIT")),
+ cat("no message"));
+  }
 };
 
 // Tests that two changes in a single macro expansion do not lead to conflicts
@@ -94,11 +97,13 @@
 class BinOpCheck : public TransformerClangTidyCheck {
 public:
   BinOpCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(
-tooling::makeRule(
-binaryOperator(hasOperatorName("+"), hasRHS(expr().bind("r"))),
-change(node("r"), cat("RIGHT")), cat("no message")),
-Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional buildRule() const override {
+return tooling::makeRule(
+binaryOperator(hasOperatorName("+"), hasRHS(expr().bind("r"))),
+change(node("r"), cat("RIGHT")), cat("no message"));
+  }
 };
 
 // Tests case where the rule's match spans both source from the macro and its
@@ -118,18 +123,20 @@
 }
 
 // A trivial rewrite-rule generator that requires Objective-C code.
-Optional needsObjC(const LangOptions &LangOpts,
-const ClangTidyCheck::OptionsView &Options) {
-  if (!LangOpts.ObjC)
-return None;
-  return tooling::makeRule(clang::ast_matchers::functionDecl(),
-   change(cat("void changed() {}")), cat("no message"));
-}
-
 class NeedsObjCCheck : public TransformerClangTidyCheck {
 public:
   NeedsObjCCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(needsObjC, Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  bool isLanguageVersionSupported(const La

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

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

It may be worth verifying that the fix-its are identical too, multiple versions 
of a check could be running with differing options resulting in different 
fix-its generated, in that case we should let clang-tidy disable any 
conflicting fixes for us.
Side note would it not be nicer to just group the diagnostics into one, 
thinking either of these ways

  CHECK-MESSAGES: warning: use emplace_back instead of push_back 
[hicpp-use-emplace, modernize-use-emplace]
  CHECK-MESSAGES: warning: use emplace_back instead of push_back 
[hicpp-use-emplace] [modernize-use-emplace]

This would result in cleaner diagnostics emitted and remove the need for that 
note.




Comment at: 
clang-tools-extra/test/clang-tidy/infrastructure/duplicate-fixes-of-alias-checkers.cpp:53
+}
\ No newline at end of file


Eugene.Zelenko wrote:
> Please add newline.
New line


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

https://reviews.llvm.org/D80753



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


[PATCH] D80697: [clang-tidy] Reworked TransformerClangTidyCheck to simplify usage of Options

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

There are a few reasons for using the virtual method:

- It keeps everything contained in the one class.
- In the case where options are needed it avoid extra work in the derived class.
- It's consistent with how all base class checks handle the specifics of 
derived checks.




Comment at: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h:62
-  // of the language or clang-tidy options.
-  TransformerClangTidyCheck(transformer::RewriteRule R, StringRef Name,
-ClangTidyContext *Context);

ymandel wrote:
> Why delete this? It is the most commonly used constructor and cleaner than 
> the OOP goop of the virtual method.
I'll add that back in, but I feel this constructor is no different in most 
cases to just placing the rule builder in the virtual method


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80697



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


[PATCH] D80697: [clang-tidy] Reworked TransformerClangTidyCheck to simplify usage of Options

2020-05-29 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 267161.
njames93 marked 3 inline comments as done.
njames93 added a comment.

- Add back old constructors, one being deprecated


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80697

Files:
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -10,6 +10,7 @@
 #include "ClangTidyTest.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Transformer/RangeSelector.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
 #include "clang/Tooling/Transformer/Stencil.h"
 #include "clang/Tooling/Transformer/Transformer.h"
 #include "gtest/gtest.h"
@@ -28,23 +29,23 @@
 using transformer::statement;
 
 // Invert the code of an if-statement, while maintaining its semantics.
-RewriteRule invertIf() {
-  StringRef C = "C", T = "T", E = "E";
-  RewriteRule Rule = tooling::makeRule(
-  ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
- hasElse(stmt().bind(E))),
-  change(statement(std::string(RewriteRule::RootID)),
- cat("if(!(", node(std::string(C)), ")) ",
- statement(std::string(E)), " else ",
- statement(std::string(T,
-  cat("negate condition and reverse `then` and `else` branches"));
-  return Rule;
-}
-
 class IfInverterCheck : public TransformerClangTidyCheck {
 public:
   IfInverterCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(invertIf(), Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional buildRule() const override {
+StringRef C = "C", T = "T", E = "E";
+RewriteRule Rule = tooling::makeRule(
+ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
+   hasElse(stmt().bind(E))),
+change(statement(std::string(RewriteRule::RootID)),
+   cat("if(!(", node(std::string(C)), ")) ",
+   statement(std::string(E)), " else ",
+   statement(std::string(T,
+cat("negate condition and reverse `then` and `else` branches"));
+return Rule;
+  }
 };
 
 // Basic test of using a rewrite rule as a ClangTidy.
@@ -70,10 +71,12 @@
 class IntLitCheck : public TransformerClangTidyCheck {
 public:
   IntLitCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(tooling::makeRule(integerLiteral(),
-change(cat("LIT")),
-cat("no message")),
-  Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional buildRule() const override {
+return tooling::makeRule(integerLiteral(), change(cat("LIT")),
+ cat("no message"));
+  }
 };
 
 // Tests that two changes in a single macro expansion do not lead to conflicts
@@ -94,11 +97,13 @@
 class BinOpCheck : public TransformerClangTidyCheck {
 public:
   BinOpCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(
-tooling::makeRule(
-binaryOperator(hasOperatorName("+"), hasRHS(expr().bind("r"))),
-change(node("r"), cat("RIGHT")), cat("no message")),
-Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  Optional buildRule() const override {
+return tooling::makeRule(
+binaryOperator(hasOperatorName("+"), hasRHS(expr().bind("r"))),
+change(node("r"), cat("RIGHT")), cat("no message"));
+  }
 };
 
 // Tests case where the rule's match spans both source from the macro and its
@@ -118,18 +123,20 @@
 }
 
 // A trivial rewrite-rule generator that requires Objective-C code.
-Optional needsObjC(const LangOptions &LangOpts,
-const ClangTidyCheck::OptionsView &Options) {
-  if (!LangOpts.ObjC)
-return None;
-  return tooling::makeRule(clang::ast_matchers::functionDecl(),
-   change(cat("void changed() {}")), cat("no message"));
-}
-
 class NeedsObjCCheck : public TransformerClangTidyCheck {
 public:
   NeedsObjCCheck(StringRef Name, ClangTidyContext *Context)
-  : TransformerClangTidyCheck(needsObjC, Name, Context) {}
+  : TransformerClangTidyCheck(Name, Context) {}
+
+  bool isLanguageVersio

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

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

In D80753#2064857 , @Daniel599 wrote:

> I have made the needed changes in order to detect a conflict in duplicated 
> fix-it of aliased checkers and also added a test for it.
>  Now I`ll try to work on combining aliased errors together,  any tips 
> regarding this feature?


Here is a quick draft I built up for this ClangTidyDiagnosticsConsumer.cpp 
 lmk what 
you think.
Some of the handling probably can be changed for conflicting fix its.


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

https://reviews.llvm.org/D80753



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


[PATCH] D77572: [clang-tidy] add new check readability-use-anyofallof

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

LGMT, just a few minor nits though.




Comment at: 
clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.cpp:15-16
+#include "clang/Frontend/CompilerInstance.h"
+#include 
+#include 
+

Fairly certain these headers aren't used



Comment at: clang-tools-extra/clang-tidy/readability/UseAnyOfAllOfCheck.h:30
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+return LangOpts.CPlusPlus;
+  }

`std::all_of`, `std::any_of` and `std::none_of` were only introduced in c++11, 
maybe `CPlusPlus11` should be the minimum requirement.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:202
 ---
-

This removed line in unrelated and should be added back


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77572



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


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

2020-05-30 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG44119626dedf: [clang-tidy] RenamerClangTidyChecks ignore 
builtin and command line macros (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80631

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -80,7 +80,7 @@
 // RUN: {key: readability-identifier-naming.LocalPointerPrefix, value: 
'l_'}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerCase, 
value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerPrefix, 
value: 'lc_'}, \
-// RUN:   ]}' -- -fno-delayed-template-parsing \
+// RUN:   ]}' -- -fno-delayed-template-parsing -Dbad_macro \
 // RUN:   -I%S/Inputs/readability-identifier-naming \
 // RUN:   -isystem %S/Inputs/readability-identifier-naming/system
 
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -73,6 +73,14 @@
   /// MacroDefined calls checkMacro for macros in the main file
   void MacroDefined(const Token &MacroNameTok,
 const MacroDirective *MD) override {
+if (MD->getMacroInfo()->isBuiltinMacro())
+  return;
+if (PP->getSourceManager().isWrittenInBuiltinFile(
+MacroNameTok.getLocation()))
+  return;
+if (PP->getSourceManager().isWrittenInCommandLineFile(
+MacroNameTok.getLocation()))
+  return;
 Check->checkMacro(PP->getSourceManager(), MacroNameTok, 
MD->getMacroInfo());
   }
 


Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -80,7 +80,7 @@
 // RUN: {key: readability-identifier-naming.LocalPointerPrefix, value: 'l_'}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerCase, value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.LocalConstantPointerPrefix, value: 'lc_'}, \
-// RUN:   ]}' -- -fno-delayed-template-parsing \
+// RUN:   ]}' -- -fno-delayed-template-parsing -Dbad_macro \
 // RUN:   -I%S/Inputs/readability-identifier-naming \
 // RUN:   -isystem %S/Inputs/readability-identifier-naming/system
 
Index: clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
@@ -73,6 +73,14 @@
   /// MacroDefined calls checkMacro for macros in the main file
   void MacroDefined(const Token &MacroNameTok,
 const MacroDirective *MD) override {
+if (MD->getMacroInfo()->isBuiltinMacro())
+  return;
+if (PP->getSourceManager().isWrittenInBuiltinFile(
+MacroNameTok.getLocation()))
+  return;
+if (PP->getSourceManager().isWrittenInCommandLineFile(
+MacroNameTok.getLocation()))
+  return;
 Check->checkMacro(PP->getSourceManager(), MacroNameTok, MD->getMacroInfo());
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

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

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80877

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


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


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


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

2020-05-30 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, alexfh.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Motivated by clang-tidy crashed for unknown command line argument. 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80879

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


Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
Index: clang-tools-extra/clang-query/tool/ClangQuery.cpp
===
--- clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,13 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +106,8 @@
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;


Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) 

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

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

In D80753#2065067 , @Daniel599 wrote:

> Thank you @njames93, I already started and took a bit different approach.
>  In case of a conflict, leaving it to clang-tidy itself didn't help as it 
> added both of the fix-its together resulting in `= 0{};`, so I thought it 
> will be better to disable both of them.


Fair enough, your solution looks a lot nicer than what I suggested anyway.

> Sadly I didn't find 3 aliased checkers which can be configured to produce 
> different code so I can't check this edge case.
>  Please let me know if another changes are needed for this patch

You could create a unit test for 3 aliased checks with different options, 
however if there isn't a check that users can use to reproduce that edge case 
there is no point in worrying about it.




Comment at: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp:765-778
+  (*Inserted.first)->Message.Fix;
+
+  if (!(CandidateFix == ExistingFix)) {
+std::string AliasedCheckerFixConflict =
+"cannot apply fix-it because an alias checker has "
+"suggested a different fix-it, please remove one of the checkers "
+"or make sure they are both configured the same. "

`s/(*Inserted.first)->/ExistingError.`



Comment at: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp:779
+(*Inserted.first)
+->Notes.emplace_back(std::move(AliasedCheckerFixConflict));
+  }

```
ExistingError.Notes.emplace_back(llvm::formatv(
"cannot apply fix-it because an alias checker has "
"suggested a different fix-it, please remove one of the checkers "
"or make sure they are both configured the same. "
"Aliased checkers: '{0}', '{1}'",
ExistingError.DiagnosticName, Error.DiagnosticName).str());```



Comment at: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h:51
   bool IsWarningAsError;
+  std::vector EnabledDiagnosticAliases;
 };

Just ignore this, but do you ever get so bored and feel the need to save 24 
bytes... https://gist.github.com/njames93/aac662ca52d345245e5e6f5dbc47d484 :)


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

https://reviews.llvm.org/D80753



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


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

2020-05-30 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 267483.
njames93 added a comment.

Fix compile error


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80879

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


Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
Index: clang-tools-extra/clang-query/tool/ClangQuery.cpp
===
--- clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,14 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
+  llvm::cl::OneOrMore);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +107,8 @@
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;


Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +4

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

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



Comment at: 
clang-tools-extra/test/clang-tidy/infrastructure/duplicate-fixes-of-alias-checkers.cpp:4-8
+template 
+class initializer_list {
+public:
+  initializer_list() noexcept {}
+};

This isn't needed for the test case and can safely be removed.



Comment at: 
clang-tools-extra/test/clang-tidy/infrastructure/duplicate-fixes-of-alias-checkers.cpp:13-21
+  vector() = default;
+  vector(initializer_list) {}
+
+  void push_back(const T &) {}
+  void push_back(T &&) {}
+
+  template 

The 2 constructors can be removed as well as the destructor.



Comment at: llvm/include/llvm/ADT/StringMap.h:251-268
+  /// equal - check whether both of the containers are equal
+  bool operator==(const StringMap &RHS) const {
+if (size() != RHS.size())
+  return false;
+
+for (const auto &KeyValue : *this) {
+  auto FindInRHS = RHS.find(KeyValue.getKey());

This needs unit tests `llvm/unittests/ADT/StringMapTest.cpp`, also a small nit 
but could you add the corresponding `operator!=`


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

https://reviews.llvm.org/D80753



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


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

2020-05-31 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: klimek, hokein, gribozavr, jvikstrom.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80884

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

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -950,10 +950,14 @@
   "template\n"
   "template\n"
   "int Struct::field = 123;\n";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T2";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U2";
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("T")), LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("T2")), LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("U")), LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("U2")), LanguageMode::Cxx14));
 }
 
 TEST(TemplateTypeParmDecl, ClassTemplatePartialSpecializationDecl) {
@@ -2061,113 +2065,146 @@
 
 )cpp";
 
-  EXPECT_TRUE(matches(
-  Code, traverse(TK_IgnoreUnlessSpelledInSource,
- returnStmt(forFunction(functionDecl(hasName("func1"))),
-hasReturnValue(integerLiteral(equals(42)));
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   returnStmt(forFunction(functionDecl(hasName("func1"))),
+  hasReturnValue(integerLiteral(equals(42),
+  LanguageMode::Cxx2a));
 
-  EXPECT_TRUE(matches(
-  Code, traverse(TK_IgnoreUnlessSpelledInSource,
- integerLiteral(equals(42),
-hasParent(returnStmt(forFunction(
-functionDecl(hasName("func1");
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   integerLiteral(equals(42),
+  hasParent(returnStmt(forFunction(
+  functionDecl(hasName("func1"))),
+  LanguageMode::Cxx2a));
 
   EXPECT_TRUE(matches(
   Code,
   traverse(TK_IgnoreUnlessSpelledInSource,
returnStmt(forFunction(functionDecl(hasName("func2"))),
   hasReturnValue(cxxTemporaryObjectExpr(
-  hasArgument(0, integerLiteral(equals(42);
+  hasArgument(0, integerLiteral(equals(42))),
+  LanguageMode::Cxx2a));
   EXPECT_TRUE(matches(
   Code,
-  traverse(TK_IgnoreUnlessSpelledInSource,
-   integerLiteral(
-   equals(42),
-   hasParent(cxxTemporaryObjectExpr(hasParent(returnStmt(
-   forFunction(functionDecl(hasName("func2")));
+  traverse(
+  TK_IgnoreUnlessSpelledInSource,
+  integerLiteral(equals(42),
+ hasParent(cxxTemporaryObjectExpr(hasParent(returnStmt(
+ forFunction(functionDecl(hasName("func2"),
+  LanguageMode::Cxx2a));
 
   EXPECT_TRUE(matches(
-  Code, traverse(TK_IgnoreUnlessSpelledInSource,
- returnStmt(forFunction(functionDecl(hasName("func3"))),
-hasReturnValue(
-cxxFunctionalCastExpr(hasSourceExpression(
-integerLiteral(equals(42);
+  Code,
+  traverse(
+  TK_IgnoreUnlessSpelledInSource,
+  returnStmt(forFunction(functionDecl(hasName("func3"))),
+ hasReturnValue(cxxFunctionalCastExpr(
+ hasSourceExpression(integerLiteral(equals(42))),
+  LanguageMode::Cxx2a));
 
   EXPECT_TRUE(matches(
   Code,
-  traverse(TK_IgnoreUnlessSpelledInSource,
-   integerLiteral(
-   equals(42),
-   hasParent(cxxFunctionalCastExpr(hasParent(returnStmt(
-   forFunction(functionDecl(hasName("func3")));
+  traverse(
+  TK_IgnoreUnlessSpelledInSource,
+  integerLiteral(equals(42),
+ hasParent(cxxFunctionalCastExpr(hasParent(returnStmt(
+ forFunction(functionDecl(hasName("func3"),
+  LanguageMode::Cxx2a));
 
-  EXPECT_TRUE(matc

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

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

Disables the check from warning on some built in vararg functions, Address 
Clang-tidy should not consider __builtin_constant_p a variadic function. 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80887

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -49,3 +49,11 @@
 }
 
 int my_vprintf(const char* format, va_list arg ); // OK to declare function 
taking va_list
+
+void ignoredBuiltinsTest() {
+  (void)__builtin_assume_aligned(0, 8);
+  (void)__builtin_constant_p(0);
+  (void)__builtin_fpclassify(0, 0, 0, 0, 0, 0.f);
+  (void)__builtin_isinf_sign(0.f);
+  (void)__builtin_prefetch(nullptr);
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -18,11 +18,20 @@
 
 const internal::VariadicDynCastAllOfMatcher vAArgExpr;
 
+// FIXME: Add any more builtin variadics that shouldn't trigger this
+static constexpr StringRef AllowedVariadics[] = {
+"__builtin_constant_p", "__builtin_isinf_sign", "__builtin_assume_aligned",
+"__builtin_prefetch",   "__builtin_fpclassify",
+};
+
 void ProTypeVarargCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(vAArgExpr().bind("va_use"), this);
 
   Finder->addMatcher(
-  callExpr(callee(functionDecl(isVariadic(.bind("callvararg"), this);
+  callExpr(callee(functionDecl(isVariadic(),
+   unless(hasAnyName(AllowedVariadics)
+  .bind("callvararg"),
+  this);
 }
 
 static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) {


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -49,3 +49,11 @@
 }
 
 int my_vprintf(const char* format, va_list arg ); // OK to declare function taking va_list
+
+void ignoredBuiltinsTest() {
+  (void)__builtin_assume_aligned(0, 8);
+  (void)__builtin_constant_p(0);
+  (void)__builtin_fpclassify(0, 0, 0, 0, 0, 0.f);
+  (void)__builtin_isinf_sign(0.f);
+  (void)__builtin_prefetch(nullptr);
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -18,11 +18,20 @@
 
 const internal::VariadicDynCastAllOfMatcher vAArgExpr;
 
+// FIXME: Add any more builtin variadics that shouldn't trigger this
+static constexpr StringRef AllowedVariadics[] = {
+"__builtin_constant_p", "__builtin_isinf_sign", "__builtin_assume_aligned",
+"__builtin_prefetch",   "__builtin_fpclassify",
+};
+
 void ProTypeVarargCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(vAArgExpr().bind("va_use"), this);
 
   Finder->addMatcher(
-  callExpr(callee(functionDecl(isVariadic(.bind("callvararg"), this);
+  callExpr(callee(functionDecl(isVariadic(),
+   unless(hasAnyName(AllowedVariadics)
+  .bind("callvararg"),
+  this);
 }
 
 static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

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

In D80884#2065270 , @gribozavr2 wrote:

> This is an interesting question. Since Clang accepts certain constructs in 
> older C++ standard versions as extensions, shouldn't we test AST matchers in 
> those modes as well? I think it could be argued either way.


Clang accepts a lot of stuff for better or worse, my fist try at this was using 
`-pedantic-errors`, but that was throwing errors with gnu and microsoft 
extensions which would be a much more invasive fix to sort out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80884



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


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

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



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp:21
 
+// FIXME: Add any more builtin variadics that shouldn't trigger this
+static constexpr StringRef AllowedVariadics[] = {

aaron.ballman wrote:
> How would we know which builtins should or should not trigger this? Can we 
> add that information to this comment (or, better yet, just fix the fixme up 
> front)?
Good point, its more a case that I don't know all the variadic builtins clang 
supports. Those ones I included are just the ones you find in the gcc 
documentation. Shall I just remove the Fixme completely, If there is another 
one that's been missed we can address that later


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887



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


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

2020-05-31 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 267497.
njames93 added a comment.

Remove unnecessary fixme.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -49,3 +49,11 @@
 }
 
 int my_vprintf(const char* format, va_list arg ); // OK to declare function 
taking va_list
+
+void ignoredBuiltinsTest() {
+  (void)__builtin_assume_aligned(0, 8);
+  (void)__builtin_constant_p(0);
+  (void)__builtin_fpclassify(0, 0, 0, 0, 0, 0.f);
+  (void)__builtin_isinf_sign(0.f);
+  (void)__builtin_prefetch(nullptr);
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -18,11 +18,19 @@
 
 const internal::VariadicDynCastAllOfMatcher vAArgExpr;
 
+static constexpr StringRef AllowedVariadics[] = {
+"__builtin_constant_p", "__builtin_isinf_sign", "__builtin_assume_aligned",
+"__builtin_prefetch",   "__builtin_fpclassify",
+};
+
 void ProTypeVarargCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(vAArgExpr().bind("va_use"), this);
 
   Finder->addMatcher(
-  callExpr(callee(functionDecl(isVariadic(.bind("callvararg"), this);
+  callExpr(callee(functionDecl(isVariadic(),
+   unless(hasAnyName(AllowedVariadics)
+  .bind("callvararg"),
+  this);
 }
 
 static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) {


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-pro-type-vararg.cpp
@@ -49,3 +49,11 @@
 }
 
 int my_vprintf(const char* format, va_list arg ); // OK to declare function taking va_list
+
+void ignoredBuiltinsTest() {
+  (void)__builtin_assume_aligned(0, 8);
+  (void)__builtin_constant_p(0);
+  (void)__builtin_fpclassify(0, 0, 0, 0, 0, 0.f);
+  (void)__builtin_isinf_sign(0.f);
+  (void)__builtin_prefetch(nullptr);
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -18,11 +18,19 @@
 
 const internal::VariadicDynCastAllOfMatcher vAArgExpr;
 
+static constexpr StringRef AllowedVariadics[] = {
+"__builtin_constant_p", "__builtin_isinf_sign", "__builtin_assume_aligned",
+"__builtin_prefetch",   "__builtin_fpclassify",
+};
+
 void ProTypeVarargCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(vAArgExpr().bind("va_use"), this);
 
   Finder->addMatcher(
-  callExpr(callee(functionDecl(isVariadic(.bind("callvararg"), this);
+  callExpr(callee(functionDecl(isVariadic(),
+   unless(hasAnyName(AllowedVariadics)
+  .bind("callvararg"),
+  this);
 }
 
 static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

2020-05-31 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 267501.
njames93 added a comment.

Added test coverage.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80879

Files:
  clang-tools-extra/clang-query/tool/ClangQuery.cpp
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-query/invalid-command-line.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-tidy --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-tidy: Unknown command line argument '--invalid-arg'.  Try: 'clang-tidy --help'
+// CHECK-NEXT: clang-tidy: Did you mean '--extra-arg'?
Index: clang-tools-extra/test/clang-query/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-query/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-query --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-query: Unknown command line argument '--invalid-arg'.  Try: 'clang-query --help'
+// CHECK-NEXT: clang-query: Did you mean '--extra-arg'?
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
Index: clang-tools-extra/clang-query/tool/ClangQuery.cpp
===
--- clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,14 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
+  llvm::cl::OneOrMore);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +107,8 @@
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

2020-05-31 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf23ddbe3c3ae: clang-tidy and clang-query wont crash with 
invalid command line options (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80879

Files:
  clang-tools-extra/clang-query/tool/ClangQuery.cpp
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-query/invalid-command-line.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-tidy --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-tidy: Unknown command line argument '--invalid-arg'.  Try: 'clang-tidy --help'
+// CHECK-NEXT: clang-tidy: Did you mean '--extra-arg'?
Index: clang-tools-extra/test/clang-query/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-query/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-query --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-query: Unknown command line argument '--invalid-arg'.  Try: 'clang-query --help'
+// CHECK-NEXT: clang-query: Did you mean '--extra-arg'?
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
Index: clang-tools-extra/clang-query/tool/ClangQuery.cpp
===
--- clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,14 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
+  llvm::cl::OneOrMore);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +107,8 @@
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

2020-05-31 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 267504.
njames93 added a comment.

Hopefully fix windows test cases


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80879

Files:
  clang-tools-extra/clang-query/tool/ClangQuery.cpp
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-query/invalid-command-line.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-tidy --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-tidy{{(\.exe)?}}: Unknown command line argument '--invalid-arg'.  Try: 'clang-tidy{{(\.exe)?}} --help'
+// CHECK-NEXT: clang-tidy: Did you mean '--extra-arg'?
Index: clang-tools-extra/test/clang-query/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-query/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-query --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-query{{(\.exe)?}}: Unknown command line argument '--invalid-arg'.  Try: 'clang-query{{(\.exe)?}} --help'
+// CHECK-NEXT: clang-query: Did you mean '--extra-arg'?
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
Index: clang-tools-extra/clang-query/tool/ClangQuery.cpp
===
--- clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,14 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
+  llvm::cl::OneOrMore);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +107,8 @@
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

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

In D80879#2065350 , @thakis wrote:

> This breaks check-clang-tools on windows: 
> http://45.33.8.238/win/16485/step_8.txt
>
> Looks like you need to optionally allow a .exe suffix in the test. Please 
> take a look, and revert if it takes a while until you can fix.
>
> (I'm on a phone, else I'd fix myself.)


Just seen the buildbot, I've reverted it for now. Don't have windows to test so 
didnt want to fire away more breaking commits


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80879



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


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

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

In D80879#2065364 , @thakis wrote:

> Test fix looks good as far as I can tell. Landing and seeing what the bot 
> says is ok. It's fine for some of the bots to be red for a short while as 
> long as it isn't hours. Thanks!


I'm unsure about one part(the `CHECK-NEXT` lines, just wanna see what the pre 
merge bot says.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80879



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


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

2020-05-31 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 267505.
njames93 added a comment.

Actually fix the windows builds


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80879

Files:
  clang-tools-extra/clang-query/tool/ClangQuery.cpp
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-query/invalid-command-line.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-tidy --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-tidy{{(\.exe)?}}: Unknown command line argument '--invalid-arg'.  Try: 'clang-tidy{{(\.exe)?}} --help'
+// CHECK-NEXT: clang-tidy{{(\.exe)?}}: Did you mean '--extra-arg'?
Index: clang-tools-extra/test/clang-query/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-query/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-query --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-query{{(\.exe)?}}: Unknown command line argument '--invalid-arg'.  Try: 'clang-query{{(\.exe)?}} --help'
+// CHECK-NEXT: clang-query{{(\.exe)?}}: Did you mean '--extra-arg'?
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
Index: clang-tools-extra/clang-query/tool/ClangQuery.cpp
===
--- clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,14 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
+  llvm::cl::OneOrMore);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +107,8 @@
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

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



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp:21
 
+// FIXME: Add any more builtin variadics that shouldn't trigger this
+static constexpr StringRef AllowedVariadics[] = {

aaron.ballman wrote:
> njames93 wrote:
> > aaron.ballman wrote:
> > > How would we know which builtins should or should not trigger this? Can 
> > > we add that information to this comment (or, better yet, just fix the 
> > > fixme up front)?
> > Good point, its more a case that I don't know all the variadic builtins 
> > clang supports. Those ones I included are just the ones you find in the gcc 
> > documentation. Shall I just remove the Fixme completely, If there is 
> > another one that's been missed we can address that later
> Taking a look at Builtins.def shows quite a few more that likely should be 
> added to the list. I think we should probably have the initial commit 
> covering anything that's a C standard library function/macro that ends with 
> "." in its builtin type signature where the C API isn't variadic. For 
> instance, `__builtin_isfinite`, `__builtin_isinf`, etc. I'm fine if we don't 
> vet every builtin we support (that's a large amount of work), but we should 
> be able to cover the most common cases where there's a specification to 
> compare against.
```
BUILTIN(__builtin_isgreater , "i.", "Fnct")
BUILTIN(__builtin_isgreaterequal, "i.", "Fnct")
BUILTIN(__builtin_isless, "i.", "Fnct")
BUILTIN(__builtin_islessequal   , "i.", "Fnct")
BUILTIN(__builtin_islessgreater , "i.", "Fnct")
BUILTIN(__builtin_isunordered   , "i.", "Fnct")
BUILTIN(__builtin_fpclassify, "ii.", "Fnct")
BUILTIN(__builtin_isfinite,   "i.", "Fnct")
BUILTIN(__builtin_isinf,  "i.", "Fnct")
BUILTIN(__builtin_isinf_sign, "i.", "Fnct")
BUILTIN(__builtin_isnan,  "i.", "Fnct")
BUILTIN(__builtin_isnormal,   "i.", "Fnct")
BUILTIN(__builtin_signbit, "i.", "Fnct")
BUILTIN(__builtin_constant_p, "i.", "nctu")
BUILTIN(__builtin_classify_type, "i.", "nctu")
BUILTIN(__builtin_va_start, "vA.", "nt")
BUILTIN(__builtin_stdarg_start, "vA.", "nt")
BUILTIN(__builtin_assume_aligned, "v*vC*z.", "nc")
BUILTIN(__builtin_fprintf, "iP*cC*.", "Fp:1:")
BUILTIN(__builtin_printf, "icC*.", "Fp:0:")
BUILTIN(__builtin_snprintf, "ic*zcC*.", "nFp:2:")
BUILTIN(__builtin___snprintf_chk, "ic*zizcC*.", "Fp:4:")
BUILTIN(__builtin___sprintf_chk, "ic*izcC*.", "Fp:3:")
BUILTIN(__builtin___fprintf_chk, "iP*icC*.", "Fp:2:")
BUILTIN(__builtin___printf_chk, "iicC*.", "Fp:1:")
BUILTIN(__builtin_prefetch, "vvC*.", "nc")
BUILTIN(__builtin_shufflevector, "v."   , "nct")
BUILTIN(__builtin_convertvector, "v."   , "nct")
BUILTIN(__builtin_call_with_static_chain, "v.", "nt")
BUILTIN(__builtin_annotation, "v.", "tn")
BUILTIN(__builtin_add_overflow, "b.", "nt")
BUILTIN(__builtin_sub_overflow, "b.", "nt")
BUILTIN(__builtin_mul_overflow, "b.", "nt")
BUILTIN(__builtin_preserve_access_index, "v.", "t")
BUILTIN(__builtin_nontemporal_store, "v.", "t")
BUILTIN(__builtin_nontemporal_load, "v.", "t")
BUILTIN(__builtin_os_log_format_buffer_size, "zcC*.", "p:0:nut")
BUILTIN(__builtin_os_log_format, "v*v*cC*.", "p:0:nt")
BUILTIN(__builtin_ms_va_start, "vc*&.", "nt")```
That's all the variadics inside `Builtin.def` that are called `__builtin...`.
Would you suggest including all those apart from the va, print or format 
related ones


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887



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


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

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

In D80631#2065168 , @MaskRay wrote:

> `arc` adds many unneeded tags from Phabricator. You can drop `Reviewers:` 
> `Subscribers:` `Tags:` and the text `Summary:` with the following script:
>
>   arcfilter () {
> arc amend
> git log -1 --pretty=%B | awk '/Reviewers:|Subscribers:/{p=1} /Reviewed 
> By:|Differential Revision:/{p=0} !p && !/^Summary:$/ {sub(/^Summary: 
> /,"");print}' | git commit --amend --date=now -F -
>   }
>   
>
> `Reviewed By: ` is considered important by some people 
> (https://lists.llvm.org/pipermail/llvm-dev/2020-January/137889.html). You 
> should keep the tag. (I started to use `--date=now` because some people find 
> author date != committer date annoying. The committer date is usually what 
> people care.))


Thanks for this, got it working nicely here 
https://github.com/llvm/llvm-project/commit/5952125691571de9bd817551fb1baabe270e73f9


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80631



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


[PATCH] D80879: clang-tidy and clang-query wont crash with invalid command line options

2020-05-31 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG595212569157: clang-tidy and clang-query wont crash with 
invalid command line options (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80879

Files:
  clang-tools-extra/clang-query/tool/ClangQuery.cpp
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/test/clang-query/invalid-command-line.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/infrastructure/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-tidy --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-tidy{{(\.exe)?}}: Unknown command line argument '--invalid-arg'.  Try: 'clang-tidy{{(\.exe)?}} --help'
+// CHECK-NEXT: clang-tidy{{(\.exe)?}}: Did you mean '--extra-arg'?
Index: clang-tools-extra/test/clang-query/invalid-command-line.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-query/invalid-command-line.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-query --invalid-arg 2>&1 | FileCheck %s
+
+// CHECK: error: [CommonOptionsParser]: clang-query{{(\.exe)?}}: Unknown command line argument '--invalid-arg'.  Try: 'clang-query{{(\.exe)?}} --help'
+// CHECK-NEXT: clang-query{{(\.exe)?}}: Did you mean '--extra-arg'?
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -23,6 +23,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/WithColor.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::driver;
@@ -333,8 +334,14 @@
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
-  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
-cl::ZeroOrMore);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangTidyCategory,
+  cl::ZeroOrMore);
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
+
   llvm::IntrusiveRefCntPtr BaseFS(
   new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
 
@@ -365,7 +372,7 @@
   SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
 
   StringRef FileName("dummy");
-  auto PathList = OptionsParser.getSourcePathList();
+  auto PathList = OptionsParser->getSourcePathList();
   if (!PathList.empty()) {
 FileName = PathList.front();
   }
@@ -433,7 +440,7 @@
   ClangTidyContext Context(std::move(OwningOptionsProvider),
AllowEnablingAnalyzerAlphaCheckers);
   std::vector Errors =
-  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
+  runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
EnableCheckProfile, ProfilePrefix);
   bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
Index: clang-tools-extra/clang-query/tool/ClangQuery.cpp
===
--- clang-tools-extra/clang-query/tool/ClangQuery.cpp
+++ clang-tools-extra/clang-query/tool/ClangQuery.cpp
@@ -35,6 +35,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 
@@ -86,7 +87,14 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
+  llvm::Expected OptionsParser =
+  CommonOptionsParser::create(argc, argv, ClangQueryCategory,
+  llvm::cl::OneOrMore);
+
+  if (!OptionsParser) {
+llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
+return 1;
+  }
 
   if (!Commands.empty() && !CommandFiles.empty()) {
 llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
@@ -99,8 +107,8 @@
 return 1;
   }
 
-  ClangTool Tool(OptionsParser.getCompilations(),
- OptionsParser.getSourcePathList());
+  ClangTool Tool(OptionsParser->getCompilations(),
+ OptionsParser->getSourcePathList());
   std::vector> ASTs;
   int Status = Tool.buildASTs(ASTs);
   int ASTStatus = 0;
___
cfe-commits mailing list
cfe-commits@lists.llvm.or

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

2020-05-31 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb6d23f2efc64: [ASTMatchers] Force c++ unittests to specify 
correct language standard (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80884

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

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -950,10 +950,14 @@
   "template\n"
   "template\n"
   "int Struct::field = 123;\n";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T2";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U";
-  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U2";
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("T")), LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("T2")), LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("U")), LanguageMode::Cxx14));
+  EXPECT_TRUE(
+  matches(input, templateTypeParmDecl(hasName("U2")), LanguageMode::Cxx14));
 }
 
 TEST(TemplateTypeParmDecl, ClassTemplatePartialSpecializationDecl) {
@@ -2061,113 +2065,146 @@
 
 )cpp";
 
-  EXPECT_TRUE(matches(
-  Code, traverse(TK_IgnoreUnlessSpelledInSource,
- returnStmt(forFunction(functionDecl(hasName("func1"))),
-hasReturnValue(integerLiteral(equals(42)));
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   returnStmt(forFunction(functionDecl(hasName("func1"))),
+  hasReturnValue(integerLiteral(equals(42),
+  LanguageMode::Cxx2a));
 
-  EXPECT_TRUE(matches(
-  Code, traverse(TK_IgnoreUnlessSpelledInSource,
- integerLiteral(equals(42),
-hasParent(returnStmt(forFunction(
-functionDecl(hasName("func1");
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   integerLiteral(equals(42),
+  hasParent(returnStmt(forFunction(
+  functionDecl(hasName("func1"))),
+  LanguageMode::Cxx2a));
 
   EXPECT_TRUE(matches(
   Code,
   traverse(TK_IgnoreUnlessSpelledInSource,
returnStmt(forFunction(functionDecl(hasName("func2"))),
   hasReturnValue(cxxTemporaryObjectExpr(
-  hasArgument(0, integerLiteral(equals(42);
+  hasArgument(0, integerLiteral(equals(42))),
+  LanguageMode::Cxx2a));
   EXPECT_TRUE(matches(
   Code,
-  traverse(TK_IgnoreUnlessSpelledInSource,
-   integerLiteral(
-   equals(42),
-   hasParent(cxxTemporaryObjectExpr(hasParent(returnStmt(
-   forFunction(functionDecl(hasName("func2")));
+  traverse(
+  TK_IgnoreUnlessSpelledInSource,
+  integerLiteral(equals(42),
+ hasParent(cxxTemporaryObjectExpr(hasParent(returnStmt(
+ forFunction(functionDecl(hasName("func2"),
+  LanguageMode::Cxx2a));
 
   EXPECT_TRUE(matches(
-  Code, traverse(TK_IgnoreUnlessSpelledInSource,
- returnStmt(forFunction(functionDecl(hasName("func3"))),
-hasReturnValue(
-cxxFunctionalCastExpr(hasSourceExpression(
-integerLiteral(equals(42);
+  Code,
+  traverse(
+  TK_IgnoreUnlessSpelledInSource,
+  returnStmt(forFunction(functionDecl(hasName("func3"))),
+ hasReturnValue(cxxFunctionalCastExpr(
+ hasSourceExpression(integerLiteral(equals(42))),
+  LanguageMode::Cxx2a));
 
   EXPECT_TRUE(matches(
   Code,
-  traverse(TK_IgnoreUnlessSpelledInSource,
-   integerLiteral(
-   equals(42),
-   hasParent(cxxFunctionalCastExpr(hasParent(returnStmt(
-   forFunction(functionDecl(hasName("func3")));
+  traverse(
+  TK_IgnoreUnlessSpelledInSource,
+  integerLiteral(equals(42),
+ hasParent(cxxFunctionalCastExpr(hasParent(returnStmt(
+ forFunction(functionDecl(hasName("func3"),
+  LanguageMode::Cxx2a));

[PATCH] D80896: [clang-tidy][misc-redundant-expression] Fix crash on CXXFoldExpr

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

This fix has expanded from preventing the crash to adding support for 
`CXXFoldExpr` to misc-redundant-expression. Maybe rename the revision to 
explain that better. 
If that is the case then you may as well add a test case showing a redundant 
fold expression




Comment at: clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp:75
   while (LeftIter != Left->child_end() && RightIter != Right->child_end()) {
-if (!areEquivalentExpr(dyn_cast(*LeftIter),
+if (*LeftIter && *RightIter &&
+!areEquivalentExpr(dyn_cast(*LeftIter),

What happens when `*LeftIter` is null, but `*RightIter` isn't or vice versa, 
That case should also return false.


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

https://reviews.llvm.org/D80896



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


[PATCH] D80531: [clang-tidy]: Added modernize-replace-disallow-copy-and-assign-macro

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

LGTM with 2 small nits, but I'd still give a few days see if anyone else wants 
to weight in.




Comment at: 
clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.h:52
+
+  const std::string getMacroName() const { return MacroName; }
+

Return by reference here.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize-replace-disallow-copy-and-assign-macro.rst:17
+
+When running this check on a code like this
+

Put a colon on the end of this line.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize-replace-disallow-copy-and-assign-macro.rst:26
+
+It will be transformed to this
+

Ditto here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80531



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


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

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

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


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

https://reviews.llvm.org/D79912



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


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

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

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80877

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


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


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


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

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

Included more builtins.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887

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


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


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

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

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

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81075

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

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

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

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

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80536



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


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

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

Fix clang-format error.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81075

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

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

[PATCH] D80514: [clang-tidy] modernize-use-trailing-return-type support for C++20 concepts and decltype

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

In D80514#2070843 , @bernhardmgruber 
wrote:

> Ping.
>
> Furthermore: how can I schedule another CI build with the newest version of 
> the diff? When I go to the failed build from Harbormaster and I click 
> restart, it rebuilds an older version of the diff. Thanks for the info!


The restart build feature is only really useful when something on trunk caused 
the failure and will restart the build with the diff it had when the build was 
first started. The CI should build each time you update the diff, not sure why 
it isn't, but I don't think there is a special way to fix that. As the failure 
was caused by the test cases you could try and run `ninja check-clang-tools` 
from your build directory to ensure things are working, Alternatively if you 
upload another diff it should force a new build.


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

https://reviews.llvm.org/D80514



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


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

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

Add va_start.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887

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


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


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

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

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



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp:40
+// "__builtin_va_start",
+// "__builtin_stdarg_start",
+"__builtin_assume_aligned", // Documented as variadic to support 
overloading

aaron.ballman wrote:
> Should remove commented-out code from the list.
Once we are happy I will remove it, more  a temporary step.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp:41
+// "__builtin_stdarg_start",
+"__builtin_assume_aligned", // Documented as variadic to support 
overloading
+// "__builtin_fprintf",

aaron.ballman wrote:
> If it's documented as being variadic, I think we want to remove it from the 
> list so we warn on its use, right?
> 
> From here on down look like things that are not part of any standard, also, 
> so we may want to remove them based on that, too.
This function should have this signature if default arguments were allowed.
```
extern void* __builtin_assume_aligned(const void* exp, size_t align, size_t 
misaligned = 0);```



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp:49
+// "__builtin___printf_chk",
+"__builtin_prefetch",  // Documented as variadic to support overloading
+"__builtin_shufflevector", // Documented as variadic but with a defined

aaron.ballman wrote:
> Same here.
Likewise this one should have this signature
```
extern void builtin_prefetch(const void* addr, bool rw = false, unsigned 
locality = 3);```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80887



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


[PATCH] D80514: [clang-tidy] modernize-use-trailing-return-type support for C++20 concepts and decltype

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

In D80514#2071056 , @bernhardmgruber 
wrote:

> Reuploaded diff in an attempt to trigger a CI build.


It's not working, Still no big issue, when its ready to land just the checks 
locally


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

https://reviews.llvm.org/D80514



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


[PATCH] D83717: [clang-tidy] Add check fo SEI CERT item ENV32-C

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

In D83717#2152762 , @gamesh411 wrote:

> In D83717#2150977 , @njames93 wrote:
>
> > Alternatively you could do something like this, though it would be a pain 
> > https://github.com/llvm/llvm-project/blob/master/clang-tools-extra/test/clang-tidy/checkers/bugprone-argument-comment-gmock.cpp#L86
>
>
> I have bitten the bullet, and have gone down this route. With relative 
> numbering, the sections themselves are at least translation-invariant. Not 
> the prettiest sight, tho.
>  Thanks!


I almost think it would be nice FileCheck supported some directive like:

  // LINE-NAME: 

And corresponding check lines:

  [[]]
  [[+N]] 
  [[-N]]

Would result in the ability to write checks like this:

  void longjmp_handler() {// LINE-NAME: LONGJMP
  longjmp(env, 255); 
  }
  
  ...
  
  void foo(){
atexit(longjmp_handler);
 // CHECK-NOTES: :[[@LINE-1]]:3: warning: exit-handler potentially calls a 
jump function. Handlers should terminate by returning [cert-env32-c]
// CHECK-NOTES: :[[LONGJMP]]:1: note: handler function declared here
// CHECK-NOTES: :[[LONGJMP+1]]:3: note: jump function called here
  }

Anyway that's a story for another day.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83717



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


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

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

Updated release notes for version bump.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82089

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

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

[PATCH] D83680: [clang-tidy] Refactor IncludeInserter

2020-07-17 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 278807.
njames93 marked 5 inline comments as done.
njames93 added a comment.

Address reviewer comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83680

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

Index: clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
@@ -33,9 +33,7 @@
 
   void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override {
-Inserter = std::make_unique(
-SM, getLangOpts(), utils::IncludeSorter::IS_Google);
-PP->addPPCallbacks(Inserter->CreatePPCallbacks());
+Inserter.registerPreprocessor(PP);
   }
 
   void registerMatchers(ast_matchers::MatchFinder *Finder) override {
@@ -46,15 +44,15 @@
 auto Diag = diag(Result.Nodes.getNodeAs("stmt")->getBeginLoc(),
  "foo, bar");
 for (StringRef Header : HeadersToInclude()) {
-  Diag << Inserter->CreateIncludeInsertion(
-  Result.SourceManager->getMainFileID(), Header, IsAngledInclude());
+  Diag << Inserter.createMainFileIncludeInsertion(Header,
+  IsAngledInclude());
 }
   }
 
   virtual std::vector HeadersToInclude() const = 0;
   virtual bool IsAngledInclude() const = 0;
 
-  std::unique_ptr Inserter;
+  utils::IncludeInserter Inserter{utils::IncludeSorter::IS_Google};
 };
 
 class NonSystemHeaderInserterCheck : public IncludeInserterCheckBase {
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
@@ -70,8 +70,7 @@
 
 private:
   Optional Rule;
-  const IncludeSorter::IncludeStyle IncludeStyle;
-  std::unique_ptr Inserter;
+  IncludeInserter Inserter;
 };
 
 } // namespace utils
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -32,8 +32,8 @@
 MakeRule,
 StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context), Rule(MakeRule(getLangOpts(), Options)),
-  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
-IncludeSorter::IS_LLVM)) {
+  Inserter(
+  Options.getLocalOrGlobal("IncludeStyle", IncludeSorter::IS_LLVM)) {
   if (Rule)
 assert(llvm::all_of(Rule->Cases, hasExplanation) &&
"clang-tidy checks must have an explanation by default;"
@@ -44,8 +44,8 @@
  StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context), Rule(std::move(R)),
-  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
-  

[PATCH] D83717: [clang-tidy] Add check fo SEI CERT item ENV32-C

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

In D83717#2155103 , @gamesh411 wrote:

> My thoughts exactly! I also thought about anchor-points as a feature in 
> file-check, as that would immensely increase the readability of the test-code 
> in such cases.


I've put in an RFC for that functionality, Think I CC'd you into it, if you 
have any comments about it I'd appreciate them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83717



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


[PATCH] D83759: [clangd] Port lit tests to Windows

2020-07-21 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D83759#2163622 , @ArcsinX wrote:

> What do you think of this patch? I'm not sure if Windows is important OS for 
> developers.


Windows is most certainly an important OS for developers and something the 
whole llvm project has been trying to catch up on where possible.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83759



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


[PATCH] D84453: [clang-tidy] Suppress one unittest under ASan.

2020-07-24 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I was having issues with this test case under macos in D82188 
.
It would fail for seemingly no apparent reason until I disable a test in a 
different translation unit.
This made me think there is a subtle bug in the linker used on macos. That 
could also explain why asan is having a hard time with this as well.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D84453



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


[PATCH] D83680: [clang-tidy] Refactor IncludeInserter

2020-07-27 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG13c9bbc28ef9: [clang-tidy] Refactor IncludeInserter 
(authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83680

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

Index: clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
@@ -33,9 +33,7 @@
 
   void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override {
-Inserter = std::make_unique(
-SM, getLangOpts(), utils::IncludeSorter::IS_Google);
-PP->addPPCallbacks(Inserter->CreatePPCallbacks());
+Inserter.registerPreprocessor(PP);
   }
 
   void registerMatchers(ast_matchers::MatchFinder *Finder) override {
@@ -46,15 +44,15 @@
 auto Diag = diag(Result.Nodes.getNodeAs("stmt")->getBeginLoc(),
  "foo, bar");
 for (StringRef Header : HeadersToInclude()) {
-  Diag << Inserter->CreateIncludeInsertion(
-  Result.SourceManager->getMainFileID(), Header, IsAngledInclude());
+  Diag << Inserter.createMainFileIncludeInsertion(Header,
+  IsAngledInclude());
 }
   }
 
   virtual std::vector HeadersToInclude() const = 0;
   virtual bool IsAngledInclude() const = 0;
 
-  std::unique_ptr Inserter;
+  utils::IncludeInserter Inserter{utils::IncludeSorter::IS_Google};
 };
 
 class NonSystemHeaderInserterCheck : public IncludeInserterCheckBase {
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
@@ -70,8 +70,7 @@
 
 private:
   Optional Rule;
-  const IncludeSorter::IncludeStyle IncludeStyle;
-  std::unique_ptr Inserter;
+  IncludeInserter Inserter;
 };
 
 } // namespace utils
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -32,8 +32,8 @@
 MakeRule,
 StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context), Rule(MakeRule(getLangOpts(), Options)),
-  IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
-IncludeSorter::IS_LLVM)) {
+  Inserter(
+  Options.getLocalOrGlobal("IncludeStyle", IncludeSorter::IS_LLVM)) {
   if (Rule)
 assert(llvm::all_of(Rule->Cases, hasExplanation) &&
"clang-tidy checks must have an explanation by default;"
@@ -44,8 +44,8 @@
  StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context), Rule(std::move(R)),
-  IncludeStyle(Options.getLocalOrGlobal("Incl

[PATCH] D84453: [clang-tidy] Suppress one unittest on macOS.

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

In D84453#2177665 , @NoQ wrote:

> In D84453#2171548 , @njames93 wrote:
>
>> I was having issues with this test case under macos in D82188 
>> .
>> It would fail for seemingly no apparent reason until I disable a test in a 
>> different translation unit.
>> This made me think there is a subtle bug in the linker used on macos. That 
>> could also explain why asan is having a hard time with this as well. 
>> I got as far as seeing that runCheckOnCode was called, the check was 
>> instantiated but its matchers never got registered effectively meaning it 
>> didn't run.
>
> Damn, i'm very glad you showed up. I can reproduce your problem as well, so 
> ASan is probably not at fault. I'll try to talk to linker folks to see if 
> they can fix this.
>
> I guess i'll still commit this patch so that to unbreak the buildbots but 
> i'll keep an eye on this issue.

If it is an issue with the linking and the issue lies within the system ld 
binary on mac os then we really can't do much here apart from raise an issue 
with apple folks.
Be interesting to see if this bug is present when using lld on mac os, however 
I don't have a mac so its kind of hard for me to test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84453

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


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

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

Fix new lines in test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82898

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
===
--- /dev/null
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s 
cppcoreguidelines-init-variables,readability-isolate-declaration %t
+
+void foo() {
+  int A, B, C;
+  // CHECK-MESSAGES-DAG: :[[@LINE-1]]:7: warning: variable 'A' is not 
initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-2]]:10: warning: variable 'B' is not 
initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-3]]:13: warning: variable 'C' is not 
initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-4]]:3: warning: multiple declarations in a 
single statement reduces readability
+
+  // Only the isolate declarations fix-it should be applied
+
+  //  CHECK-FIXES: int A;
+  // CHECK-FIXES-NEXT: int B;
+  // CHECK-FIXES-NEXT: int C;
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -590,6 +590,7 @@
 // An event can be either the begin or the end of an interval.
 enum EventType {
   ET_Begin = 1,
+  ET_Insert = 0,
   ET_End = -1,
 };
 
@@ -623,6 +624,8 @@
   //   disallowing the first one.
   if (Type == ET_Begin)
 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
+  else if (Type == ET_Insert)
+Priority = std::make_tuple(Begin, Type, -End, ErrorSize, ErrorId);
   else
 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
 }
@@ -662,19 +665,19 @@
   }
 
   // Build events from error intervals.
-  std::map> FileEvents;
+  llvm::StringMap> FileEvents;
   for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
 for (const auto &FileAndReplace : *ErrorFixes[I].second) {
   for (const auto &Replace : FileAndReplace.second) {
 unsigned Begin = Replace.getOffset();
 unsigned End = Begin + Replace.getLength();
-const std::string &FilePath = std::string(Replace.getFilePath());
-// FIXME: Handle empty intervals, such as those from insertions.
-if (Begin == End)
-  continue;
-auto &Events = FileEvents[FilePath];
-Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
-Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+auto &Events = FileEvents[Replace.getFilePath()];
+if (Begin == End) {
+  Events.emplace_back(Begin, End, Event::ET_Insert, I, Sizes[I]);
+} else {
+  Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
+  Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+}
   }
 }
   }
@@ -686,6 +689,11 @@
 llvm::sort(Events);
 int OpenIntervals = 0;
 for (const auto &Event : Events) {
+  if (Event.Type == Event::ET_Insert) {
+if (OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+continue;
+  }
   if (Event.Type == Event::ET_End)
 --OpenIntervals;
   // This has to be checked after removing the interval from the count if 
it


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables,readability-isolate-declaration %t
+
+void foo() {
+  int A, B, C;
+  // CHECK-MESSAGES-DAG: :[[@LINE-1]]:7: warning: variable 'A' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-2]]:10: warning: variable 'B' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-3]]:13: warning: variable 'C' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-4]]:3: warning: multiple declarations in a single statement reduces readability
+
+  // Only the isolate declarations fix-it should be applied
+
+  //  CHECK-FIXES: int A;
+  // CHECK-FIXES-NEXT: int B;
+  // CHECK-FIXES-NEXT: int C;
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -590,6 +590,7 @@
 // An event can be either the b

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

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

Replace if/else logic with switches


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82898

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

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables,readability-isolate-declaration %t
+
+void foo() {
+  int A, B, C;
+  // CHECK-MESSAGES-DAG: :[[@LINE-1]]:7: warning: variable 'A' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-2]]:10: warning: variable 'B' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-3]]:13: warning: variable 'C' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-4]]:3: warning: multiple declarations in a single statement reduces readability
+
+  // Only the isolate declarations fix-it should be applied
+
+  //  CHECK-FIXES: int A;
+  // CHECK-FIXES-NEXT: int B;
+  // CHECK-FIXES-NEXT: int C;
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -31,6 +31,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Regex.h"
 #include 
@@ -590,6 +591,7 @@
 // An event can be either the begin or the end of an interval.
 enum EventType {
   ET_Begin = 1,
+  ET_Insert = 0,
   ET_End = -1,
 };
 
@@ -621,10 +623,18 @@
   //   one will be processed before, disallowing the second one, and the
   //   end point of the first one will also be processed before,
   //   disallowing the first one.
-  if (Type == ET_Begin)
+  switch (Type) {
+  case ET_Begin:
 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
-  else
+return;
+  case ET_Insert:
+Priority = std::make_tuple(Begin, Type, -End, ErrorSize, ErrorId);
+return;
+  case ET_End:
 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
+return;
+  }
+  llvm_unreachable("Invalid EventType");
 }
 
 bool operator<(const Event &Other) const {
@@ -662,19 +672,19 @@
   }
 
   // Build events from error intervals.
-  std::map> FileEvents;
+  llvm::StringMap> FileEvents;
   for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
 for (const auto &FileAndReplace : *ErrorFixes[I].second) {
   for (const auto &Replace : FileAndReplace.second) {
 unsigned Begin = Replace.getOffset();
 unsigned End = Begin + Replace.getLength();
-const std::string &FilePath = std::string(Replace.getFilePath());
-// FIXME: Handle empty intervals, such as those from insertions.
-if (Begin == End)
-  continue;
-auto &Events = FileEvents[FilePath];
-Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
-Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+auto &Events = FileEvents[Replace.getFilePath()];
+if (Begin == End) {
+  Events.emplace_back(Begin, End, Event::ET_Insert, I, Sizes[I]);
+} else {
+  Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
+  Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+}
   }
 }
   }
@@ -686,14 +696,21 @@
 llvm::sort(Events);
 int OpenIntervals = 0;
 for (const auto &Event : Events) {
-  if (Event.Type == Event::ET_End)
---OpenIntervals;
-  // This has to be checked after removing the interval from the count if it
-  // is an end event, or before adding it if it is a begin event.
-  if (OpenIntervals != 0)
-Apply[Event.ErrorId] = false;
-  if (Event.Type == Event::ET_Begin)
-++OpenIntervals;
+  switch (Event.Type) {
+  case Event::ET_Begin:
+if (OpenIntervals++ != 0)
+  Apply[Event.ErrorId] = false;
+continue;
+  case Event::ET_Insert:
+if (OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+continue;
+  case Event::ET_End:
+if (--OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+continue;
+  }
+  llvm_unreachable("Invalid EventType");
 }
 assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
   }
___
cfe-

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

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



Comment at: clang-tools-extra/clang-tidy/ClangTidyOptions.cpp:116-121
+  unsigned Priority = 0;
   for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
  E = ClangTidyModuleRegistry::end();
I != E; ++I)
-Options = Options.mergeWith(I->instantiate()->getModuleOptions());
+Options =
+Options.mergeWith(I->instantiate()->getModuleOptions(), ++Priority);

Is there a reason for incrementing the priority on each successive iteration, 
Seems like a bug that will lead to the later registered modules having higher 
priority for their options.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75184

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


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

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

Remove unreachable after switch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82898

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

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables,readability-isolate-declaration %t
+
+void foo() {
+  int A, B, C;
+  // CHECK-MESSAGES-DAG: :[[@LINE-1]]:7: warning: variable 'A' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-2]]:10: warning: variable 'B' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-3]]:13: warning: variable 'C' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-4]]:3: warning: multiple declarations in a single statement reduces readability
+
+  // Only the isolate declarations fix-it should be applied
+
+  //  CHECK-FIXES: int A;
+  // CHECK-FIXES-NEXT: int B;
+  // CHECK-FIXES-NEXT: int C;
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -31,6 +31,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Regex.h"
 #include 
@@ -590,6 +591,7 @@
 // An event can be either the begin or the end of an interval.
 enum EventType {
   ET_Begin = 1,
+  ET_Insert = 0,
   ET_End = -1,
 };
 
@@ -621,10 +623,17 @@
   //   one will be processed before, disallowing the second one, and the
   //   end point of the first one will also be processed before,
   //   disallowing the first one.
-  if (Type == ET_Begin)
+  switch (Type) {
+  case ET_Begin:
 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
-  else
+break;
+  case ET_Insert:
+Priority = std::make_tuple(Begin, Type, -End, ErrorSize, ErrorId);
+break;
+  case ET_End:
 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
+break;
+  }
 }
 
 bool operator<(const Event &Other) const {
@@ -662,19 +671,19 @@
   }
 
   // Build events from error intervals.
-  std::map> FileEvents;
+  llvm::StringMap> FileEvents;
   for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
 for (const auto &FileAndReplace : *ErrorFixes[I].second) {
   for (const auto &Replace : FileAndReplace.second) {
 unsigned Begin = Replace.getOffset();
 unsigned End = Begin + Replace.getLength();
-const std::string &FilePath = std::string(Replace.getFilePath());
-// FIXME: Handle empty intervals, such as those from insertions.
-if (Begin == End)
-  continue;
-auto &Events = FileEvents[FilePath];
-Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
-Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+auto &Events = FileEvents[Replace.getFilePath()];
+if (Begin == End) {
+  Events.emplace_back(Begin, End, Event::ET_Insert, I, Sizes[I]);
+} else {
+  Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
+  Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+}
   }
 }
   }
@@ -686,14 +695,20 @@
 llvm::sort(Events);
 int OpenIntervals = 0;
 for (const auto &Event : Events) {
-  if (Event.Type == Event::ET_End)
---OpenIntervals;
-  // This has to be checked after removing the interval from the count if it
-  // is an end event, or before adding it if it is a begin event.
-  if (OpenIntervals != 0)
-Apply[Event.ErrorId] = false;
-  if (Event.Type == Event::ET_Begin)
-++OpenIntervals;
+  switch (Event.Type) {
+  case Event::ET_Begin:
+if (OpenIntervals++ != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  case Event::ET_Insert:
+if (OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  case Event::ET_End:
+if (--OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  }
 }
 assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llv

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

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



Comment at: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp:629
 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
-  else
+return;
+  case ET_Insert:

aaron.ballman wrote:
> I'd drop these `return` statements and the unreachable, below. The switch is 
> fully-covered, so we'll get a diagnostic if any new enumerations are added 
> and we forget to update this switch.
I'd still need a `break` anyway, but yes the unreachable probably isn't required



Comment at: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp:703
+  Apply[Event.ErrorId] = false;
+continue;
+  case Event::ET_Insert:

aaron.ballman wrote:
> Similar here with `continue` and the unreachable.
As this is in a loop, I'm torn whether using `break` makes it less readable. 
WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82898

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


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

2020-07-28 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, gribozavr2.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.
njames93 requested review of this revision.
Herald added a subscriber: aheejin.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84812

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/header.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
@@ -0,0 +1,34 @@
+// Setup header directory
+
+// RUN: rm -rf %theaders
+// RUN: mkdir %theaders
+// RUN: cp -R %S/Inputs/readability-identifier-naming/. %theaders
+
+// C++11 isnt explicitly required, but failing to specify a standard means the
+// check will run multiple times for different standards. This will cause the
+// second test to fail as the header file will be changed during the first run.
+
+// RUN: %check_clang_tidy -std=c++11 %s readability-identifier-naming %t -- \
+// RUN:   -config='{ InheritParentConfig: true, CheckOptions: [ \
+// RUN: {key: readability-identifier-naming.FunctionCase, value: camelBack} \
+// RUN:  ]}' -header-filter='.*' -- -I%theaders
+
+#include "global-style1/header.h"
+#include "global-style2/header.h"
+// CHECK-MESSAGES-DAG: global-style1/header.h:5:6: warning: invalid case style for global function 'style1Bad'
+// CHECK-MESSAGES-DAG: global-style2/header.h:5:6: warning: invalid case style for global function 'style2Bad'
+
+void goodStyle() {
+  style1_good();
+  STYLE2_GOOD();
+}
+// CHECK-MESSAGES-DAG: :[[@LINE+1]]:6: warning: invalid case style for function 'bad_style'
+void bad_style() {
+  style1Bad();
+  style2Bad();
+}
+
+//  CHECK-FIXES: void badStyle() {
+// CHECK-FIXES-NEXT:   style1_bad();
+// CHECK-FIXES-NEXT:   STYLE2_BAD();
+// CHECK-FIXES-NEXT: }
\ No newline at end of file
Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
@@ -5,11 +5,11 @@
 // RUN:   {key: readability-identifier-naming.ClassCase, value: UUPER_CASE}, \
 // RUN:   {key: readability-identifier-naming.StructCase, value: CAMEL}, \
 // RUN:   {key: readability-identifier-naming.EnumCase, value: AnY_cASe}, \
-// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not warning
+// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not error
 
-// CHECK-DAG: warning: invalid configuration value 'camelback' for option 'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?{{$}}
-// CHECK-DAG: warning: invalid configuration value 'UUPER_CASE' for option 'readability-identifier-naming.ClassCase'; did you mean 'UPPER_CASE'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'camelback' for option 'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'UUPER_CASE' for option 'readability-identifier-naming.ClassCase'; did you mean 'UPPER_CASE'?{{$}}
 // Don't try to suggest an alternative for 'CAMEL'
-// CHECK-DAG: warning: invalid configuration value 'CAMEL' for option 'readability-identifier-naming.StructCase'{{$}}
+// CHECK-DAG: error: invalid configuration value 'CAMEL' for option 'readability-identifier-naming.StructCase'{{$}}
 // This fails on the EditDistance, but as it matches ignoring case suggest the correct value
-// CHECK-DAG: warning: invalid configuration value 'AnY_cASe' for option 'readability-identifier-naming.EnumCase'; did you mean 'aNy_CasE'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'AnY_cASe' for option 'readability-identifier-naming.EnumCase'; did you mean 'aNy_CasE'?{{$}}
Index: clang-to

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

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

Fix wrong patch diff


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84812

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

Index: clang-tools-extra/clang-tidy/ClangTidyCheck.h
===
--- clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -268,7 +268,7 @@
   if (llvm::Expected ValueOr = get(LocalName))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -314,7 +314,7 @@
   if (llvm::Expected ValueOr = getLocalOrGlobal(LocalName))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -353,7 +353,7 @@
   if (auto ValueOr = get(LocalName, IgnoreCase))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -395,10 +395,35 @@
   if (auto ValueOr = getLocalOrGlobal(LocalName, IgnoreCase))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
+/// Returns the value for the option \p LocalName represented as a ``T``.
+/// If the option is missing returns None, if the option can't be parsed
+/// as a ``T``, log that to stderr and return None.
+template 
+llvm::Optional getOptional(StringRef LocalName) const {
+  if (auto ValueOr = get(LocalName))
+return *ValueOr;
+  else
+logOptionParsingError(ValueOr.takeError());
+  return llvm::None;
+}
+
+/// Returns the value for the local or global option \p LocalName
+/// represented as a ``T``.
+/// If the option is missing returns None, if the
+/// option can't be parsed as a ``T``, log that to stderr and return None.
+template 
+llvm::Optional getOptionalLocalOrGlobal(StringRef LocalName) const {
+  if (auto ValueOr = getLocalOrGlobal(LocalName))
+return *ValueOr;
+  else
+logOptionParsingError(ValueOr.takeError());
+  return llvm::None;
+}
+
 /// Stores an option with the check-local name \p LocalName with
 /// string value \p Value to \p Options.
 void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
@@ -456,7 +481,8 @@
 void storeInt(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
   int64_t Value) const;
 
-static void logErrToStdErr(llvm::Error &&Err);
+/// Logs an Error to stderr if a \p Err is not a MissingOptionError.
+static void logOptionParsingError(llvm::Error &&Err);
 
 std::string NamePrefix;
 const ClangTidyOptions::OptionMap &CheckOptions;
@@ -524,6 +550,19 @@
 ClangTidyOptions::OptionMap &Options, StringRef LocalName,
 bool Value) const;
 
+/// Returns the value for the option \p LocalName.
+/// If the option is missing returns None.
+template <>
+Optional ClangTidyCheck::OptionsView::getOptional(
+StringRef LocalName) const;
+
+/// Returns the value for the local or global option \p LocalName.
+/// If the option is missing returns None.
+template <>
+Optional
+ClangTidyCheck::OptionsView::getOptionalLocalOrGlobal(
+StringRef LocalName) const;
+
 } // namespace tidy
 } // namespace clang
 
Index: clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -10,6 +10,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
 namespace clang {
@@ -126,7 +127,7 @@
   llvm::Expected ValueOr = get(LocalName);
   if (ValueOr)
 return *ValueOr;
-  logErrToStdErr(ValueOr.takeError());
+  logOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -145,7 +146,7 @@
   llvm::Expected ValueOr = getLocalOrGlobal(LocalName);
   if (ValueOr)
 return *ValueOr;
-  logErrToStdErr(ValueOr.takeError());
+  logOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -204,13 +205,36 @@
   Iter->second.Value);
 }
 
-void ClangTidyCheck::OptionsView::logErrToStdErr(llvm::Error &&Err) {
-  llvm::logAllUnhandledErrors(
-  llvm::handleErrors(std::move(Err),
- [](const MissingOptionError &) -> llvm::Error {
-   return llvm::Error::success();
- }),
-

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

2020-07-28 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, gribozavr2, alexfh.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.
njames93 requested review of this revision.
Herald added a subscriber: aheejin.

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

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84814

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/header.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
@@ -0,0 +1,34 @@
+// Setup header directory
+
+// RUN: rm -rf %theaders
+// RUN: mkdir %theaders
+// RUN: cp -R %S/Inputs/readability-identifier-naming/. %theaders
+
+// C++11 isnt explicitly required, but failing to specify a standard means the
+// check will run multiple times for different standards. This will cause the
+// second test to fail as the header file will be changed during the first run.
+
+// RUN: %check_clang_tidy -std=c++11 %s readability-identifier-naming %t -- \
+// RUN:   -config='{ InheritParentConfig: true, CheckOptions: [ \
+// RUN: {key: readability-identifier-naming.FunctionCase, value: camelBack} \
+// RUN:  ]}' -header-filter='.*' -- -I%theaders
+
+#include "global-style1/header.h"
+#include "global-style2/header.h"
+// CHECK-MESSAGES-DAG: global-style1/header.h:5:6: warning: invalid case style for global function 'style1Bad'
+// CHECK-MESSAGES-DAG: global-style2/header.h:5:6: warning: invalid case style for global function 'style2Bad'
+
+void goodStyle() {
+  style1_good();
+  STYLE2_GOOD();
+}
+// CHECK-MESSAGES-DAG: :[[@LINE+1]]:6: warning: invalid case style for function 'bad_style'
+void bad_style() {
+  style1Bad();
+  style2Bad();
+}
+
+//  CHECK-FIXES: void badStyle() {
+// CHECK-FIXES-NEXT:   style1_bad();
+// CHECK-FIXES-NEXT:   STYLE2_BAD();
+// CHECK-FIXES-NEXT: }
\ No newline at end of file
Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
@@ -5,11 +5,11 @@
 // RUN:   {key: readability-identifier-naming.ClassCase, value: UUPER_CASE}, \
 // RUN:   {key: readability-identifier-naming.StructCase, value: CAMEL}, \
 // RUN:   {key: readability-identifier-naming.EnumCase, value: AnY_cASe}, \
-// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not warning
+// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not error
 
-// CHECK-DAG: warning: invalid configuration value 'camelback' for option 'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?{{$}}
-// CHECK-DAG: warning: invalid configuration value 'UUPER_CASE' for option 'readability-identifier-naming.ClassCase'; did you mean 'UPPER_CASE'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'camelback' for option 'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'UUPER_CASE' for option 'readability-identifier-naming.ClassCase'; did you mean 'UPPER_CASE'?{{$}}
 // Don't try to suggest an alternative for 'CAMEL'
-// CHECK-DAG: warning: invalid configuration value 'CAMEL' for option 'readability-identifier-naming.StructCase'{{$}}
+// CHECK-DAG: error: invalid configuration value 'CAMEL' for option 'readability-identifier-naming.StructCase'{{$}}
 // This fails on the EditDistance, but as it matches ignoring case suggest the correct value
-// CHECK-DAG: warning: invalid configuration value 'AnY_cASe' for option 'readability-identifier-naming.EnumCase'; did you mean 'aNy_CasE'?{{$}}
+// CHECK-DAG: error

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

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

Add missing new lines in test files.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84814

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/header.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
@@ -0,0 +1,34 @@
+// Setup header directory
+
+// RUN: rm -rf %theaders
+// RUN: mkdir %theaders
+// RUN: cp -R %S/Inputs/readability-identifier-naming/. %theaders
+
+// C++11 isnt explicitly required, but failing to specify a standard means the
+// check will run multiple times for different standards. This will cause the
+// second test to fail as the header file will be changed during the first run.
+
+// RUN: %check_clang_tidy -std=c++11 %s readability-identifier-naming %t -- \
+// RUN:   -config='{ InheritParentConfig: true, CheckOptions: [ \
+// RUN: {key: readability-identifier-naming.FunctionCase, value: camelBack} \
+// RUN:  ]}' -header-filter='.*' -- -I%theaders
+
+#include "global-style1/header.h"
+#include "global-style2/header.h"
+// CHECK-MESSAGES-DAG: global-style1/header.h:5:6: warning: invalid case style for global function 'style1Bad'
+// CHECK-MESSAGES-DAG: global-style2/header.h:5:6: warning: invalid case style for global function 'style2Bad'
+
+void goodStyle() {
+  style1_good();
+  STYLE2_GOOD();
+}
+// CHECK-MESSAGES-DAG: :[[@LINE+1]]:6: warning: invalid case style for function 'bad_style'
+void bad_style() {
+  style1Bad();
+  style2Bad();
+}
+
+//  CHECK-FIXES: void badStyle() {
+// CHECK-FIXES-NEXT:   style1_bad();
+// CHECK-FIXES-NEXT:   STYLE2_BAD();
+// CHECK-FIXES-NEXT: }
Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
@@ -5,11 +5,11 @@
 // RUN:   {key: readability-identifier-naming.ClassCase, value: UUPER_CASE}, \
 // RUN:   {key: readability-identifier-naming.StructCase, value: CAMEL}, \
 // RUN:   {key: readability-identifier-naming.EnumCase, value: AnY_cASe}, \
-// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not warning
+// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not error
 
-// CHECK-DAG: warning: invalid configuration value 'camelback' for option 'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?{{$}}
-// CHECK-DAG: warning: invalid configuration value 'UUPER_CASE' for option 'readability-identifier-naming.ClassCase'; did you mean 'UPPER_CASE'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'camelback' for option 'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'UUPER_CASE' for option 'readability-identifier-naming.ClassCase'; did you mean 'UPPER_CASE'?{{$}}
 // Don't try to suggest an alternative for 'CAMEL'
-// CHECK-DAG: warning: invalid configuration value 'CAMEL' for option 'readability-identifier-naming.StructCase'{{$}}
+// CHECK-DAG: error: invalid configuration value 'CAMEL' for option 'readability-identifier-naming.StructCase'{{$}}
 // This fails on the EditDistance, but as it matches ignoring case suggest the correct value
-// CHECK-DAG: warning: invalid configuration value 'AnY_cASe' for option 'readability-identifier-naming.EnumCase'; did you mean 'aNy_CasE'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'AnY_cASe' for option 'readability-identifier-naming.EnumCase'; did you mean 'aNy_CasE'?{{$}}
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
@@ -0,0 +1,5 @@
+
+
+void STYLE2_GOOD();
+
+void style2Bad()

[PATCH] D84831: [clang-tidy] Fix RedundantStringCStrCheck with r values

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

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

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84831

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
@@ -15,6 +15,8 @@
   basic_string();
   basic_string(const C *p, const A &a = A());
 
+  ~basic_string();
+
   const C *c_str() const;
   const C *data() const;
 
Index: clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
@@ -92,16 +92,18 @@
 callee(memberExpr().bind("member")),
 callee(cxxMethodDecl(hasAnyName("c_str", "data"
   .bind("call");
-
+  const auto HasRValueTempParent =
+  hasParent(materializeTemporaryExpr(unless(isBoundToLValue(;
   // Detect redundant 'c_str()' calls through a string constructor.
   // If CxxConstructExpr is the part of some CallExpr we need to
   // check that matched ParamDecl of the ancestor CallExpr is not rvalue.
   Finder->addMatcher(
-  traverse(ast_type_traits::TK_AsIs,
-   cxxConstructExpr(StringConstructorExpr,
-hasArgument(0, StringCStrCallExpr),
-unless(hasParent(materializeTemporaryExpr(
-unless(isBoundToLValue())),
+  traverse(
+  ast_type_traits::TK_AsIs,
+  cxxConstructExpr(
+  StringConstructorExpr, hasArgument(0, StringCStrCallExpr),
+  unless(anyOf(HasRValueTempParent, hasParent(cxxBindTemporaryExpr(
+HasRValueTempParent)),
   this);
 
   // Detect: 's == str.c_str()'  ->  's == str'


Index: clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
@@ -15,6 +15,8 @@
   basic_string();
   basic_string(const C *p, const A &a = A());
 
+  ~basic_string();
+
   const C *c_str() const;
   const C *data() const;
 
Index: clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
@@ -92,16 +92,18 @@
 callee(memberExpr().bind("member")),
 callee(cxxMethodDecl(hasAnyName("c_str", "data"
   .bind("call");
-
+  const auto HasRValueTempParent =
+  hasParent(materializeTemporaryExpr(unless(isBoundToLValue(;
   // Detect redundant 'c_str()' calls through a string constructor.
   // If CxxConstructExpr is the part of some CallExpr we need to
   // check that matched ParamDecl of the ancestor CallExpr is not rvalue.
   Finder->addMatcher(
-  traverse(ast_type_traits::TK_AsIs,
-   cxxConstructExpr(StringConstructorExpr,
-hasArgument(0, StringCStrCallExpr),
-unless(hasParent(materializeTemporaryExpr(
-unless(isBoundToLValue())),
+  traverse(
+  ast_type_traits::TK_AsIs,
+  cxxConstructExpr(
+  StringConstructorExpr, hasArgument(0, StringCStrCallExpr),
+  unless(anyOf(HasRValueTempParent, hasParent(cxxBindTemporaryExpr(
+HasRValueTempParent)),
   this);
 
   // Detect: 's == str.c_str()'  ->  's == str'
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

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



Comment at: clang-tools-extra/clang-tidy/ClangTidyCheck.cpp:224
+  else
+consumeError(ValueOr.takeError());
+  return llvm::None;

gribozavr2 wrote:
> Is this specialization defined only because parsing a string option can never 
> fail? I'd let this special case behavior fall out of the primary template if 
> possible.
It's because the call to get that returns a `std::string` isn't a template.
So in the actual template definition of `getOptional`, trying to call `get` 
when `T` is a `std::string` results in a compile time error.
Consuming the error makes sense knowing the it will always be a 
`MissingOptionError`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84812

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


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

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

Rename logOptionParsingError


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84812

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

Index: clang-tools-extra/clang-tidy/ClangTidyCheck.h
===
--- clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -268,7 +268,7 @@
   if (llvm::Expected ValueOr = get(LocalName))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -314,7 +314,7 @@
   if (llvm::Expected ValueOr = getLocalOrGlobal(LocalName))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -353,7 +353,7 @@
   if (auto ValueOr = get(LocalName, IgnoreCase))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -395,10 +395,35 @@
   if (auto ValueOr = getLocalOrGlobal(LocalName, IgnoreCase))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
+/// Returns the value for the option \p LocalName represented as a ``T``.
+/// If the option is missing returns None, if the option can't be parsed
+/// as a ``T``, log that to stderr and return None.
+template 
+llvm::Optional getOptional(StringRef LocalName) const {
+  if (auto ValueOr = get(LocalName))
+return *ValueOr;
+  else
+logIfOptionParsingError(ValueOr.takeError());
+  return llvm::None;
+}
+
+/// Returns the value for the local or global option \p LocalName
+/// represented as a ``T``.
+/// If the option is missing returns None, if the
+/// option can't be parsed as a ``T``, log that to stderr and return None.
+template 
+llvm::Optional getOptionalLocalOrGlobal(StringRef LocalName) const {
+  if (auto ValueOr = getLocalOrGlobal(LocalName))
+return *ValueOr;
+  else
+logIfOptionParsingError(ValueOr.takeError());
+  return llvm::None;
+}
+
 /// Stores an option with the check-local name \p LocalName with
 /// string value \p Value to \p Options.
 void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
@@ -456,7 +481,8 @@
 void storeInt(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
   int64_t Value) const;
 
-static void logErrToStdErr(llvm::Error &&Err);
+/// Logs an Error to stderr if a \p Err is not a MissingOptionError.
+static void logIfOptionParsingError(llvm::Error &&Err);
 
 std::string NamePrefix;
 const ClangTidyOptions::OptionMap &CheckOptions;
@@ -524,6 +550,19 @@
 ClangTidyOptions::OptionMap &Options, StringRef LocalName,
 bool Value) const;
 
+/// Returns the value for the option \p LocalName.
+/// If the option is missing returns None.
+template <>
+Optional ClangTidyCheck::OptionsView::getOptional(
+StringRef LocalName) const;
+
+/// Returns the value for the local or global option \p LocalName.
+/// If the option is missing returns None.
+template <>
+Optional
+ClangTidyCheck::OptionsView::getOptionalLocalOrGlobal(
+StringRef LocalName) const;
+
 } // namespace tidy
 } // namespace clang
 
Index: clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -10,6 +10,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
 namespace clang {
@@ -126,7 +127,7 @@
   llvm::Expected ValueOr = get(LocalName);
   if (ValueOr)
 return *ValueOr;
-  logErrToStdErr(ValueOr.takeError());
+  logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -145,7 +146,7 @@
   llvm::Expected ValueOr = getLocalOrGlobal(LocalName);
   if (ValueOr)
 return *ValueOr;
-  logErrToStdErr(ValueOr.takeError());
+  logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -204,13 +205,36 @@
   Iter->second.Value);
 }
 
-void ClangTidyCheck::OptionsView::logErrToStdErr(llvm::Error &&Err) {
-  llvm::logAllUnhandledErrors(
-  llvm::handleErrors(std::move(Err),
- [](const MissingOptionError &) -> llvm::Error {
-   return llvm::Error::success();
-

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

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

- Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84814

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/header.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
@@ -0,0 +1,34 @@
+// Setup header directory
+
+// RUN: rm -rf %theaders
+// RUN: mkdir %theaders
+// RUN: cp -R %S/Inputs/readability-identifier-naming/. %theaders
+
+// C++11 isnt explicitly required, but failing to specify a standard means the
+// check will run multiple times for different standards. This will cause the
+// second test to fail as the header file will be changed during the first run.
+
+// RUN: %check_clang_tidy -std=c++11 %s readability-identifier-naming %t -- \
+// RUN:   -config='{ InheritParentConfig: true, CheckOptions: [ \
+// RUN: {key: readability-identifier-naming.FunctionCase, value: camelBack} \
+// RUN:  ]}' -header-filter='.*' -- -I%theaders
+
+#include "global-style1/header.h"
+#include "global-style2/header.h"
+// CHECK-MESSAGES-DAG: global-style1/header.h:5:6: warning: invalid case style for global function 'style1Bad'
+// CHECK-MESSAGES-DAG: global-style2/header.h:5:6: warning: invalid case style for global function 'style2Bad'
+
+void goodStyle() {
+  style1_good();
+  STYLE2_GOOD();
+}
+// CHECK-MESSAGES-DAG: :[[@LINE+1]]:6: warning: invalid case style for function 'bad_style'
+void bad_style() {
+  style1Bad();
+  style2Bad();
+}
+
+//  CHECK-FIXES: void badStyle() {
+// CHECK-FIXES-NEXT:   style1_bad();
+// CHECK-FIXES-NEXT:   STYLE2_BAD();
+// CHECK-FIXES-NEXT: }
Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-case-violation.cpp
@@ -5,11 +5,11 @@
 // RUN:   {key: readability-identifier-naming.ClassCase, value: UUPER_CASE}, \
 // RUN:   {key: readability-identifier-naming.StructCase, value: CAMEL}, \
 // RUN:   {key: readability-identifier-naming.EnumCase, value: AnY_cASe}, \
-// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not warning
+// RUN:   ]}" 2>&1 | FileCheck %s --implicit-check-not error
 
-// CHECK-DAG: warning: invalid configuration value 'camelback' for option 'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?{{$}}
-// CHECK-DAG: warning: invalid configuration value 'UUPER_CASE' for option 'readability-identifier-naming.ClassCase'; did you mean 'UPPER_CASE'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'camelback' for option 'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'UUPER_CASE' for option 'readability-identifier-naming.ClassCase'; did you mean 'UPPER_CASE'?{{$}}
 // Don't try to suggest an alternative for 'CAMEL'
-// CHECK-DAG: warning: invalid configuration value 'CAMEL' for option 'readability-identifier-naming.StructCase'{{$}}
+// CHECK-DAG: error: invalid configuration value 'CAMEL' for option 'readability-identifier-naming.StructCase'{{$}}
 // This fails on the EditDistance, but as it matches ignoring case suggest the correct value
-// CHECK-DAG: warning: invalid configuration value 'AnY_cASe' for option 'readability-identifier-naming.EnumCase'; did you mean 'aNy_CasE'?{{$}}
+// CHECK-DAG: error: invalid configuration value 'AnY_cASe' for option 'readability-identifier-naming.EnumCase'; did you mean 'aNy_CasE'?{{$}}
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
@@ -0,0 +1,5 @@
+
+
+void STYLE2_GOOD();
+
+void style2Bad();
Index: clang-too

[PATCH] D84831: [clang-tidy] Fix RedundantStringCStrCheck with r values

2020-07-29 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb99630e43261: [clang-tidy] Fix RedundantStringCStrCheck with 
r values (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84831

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
@@ -15,6 +15,8 @@
   basic_string();
   basic_string(const C *p, const A &a = A());
 
+  ~basic_string();
+
   const C *c_str() const;
   const C *data() const;
 
Index: clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
@@ -92,16 +92,18 @@
 callee(memberExpr().bind("member")),
 callee(cxxMethodDecl(hasAnyName("c_str", "data"
   .bind("call");
-
+  const auto HasRValueTempParent =
+  hasParent(materializeTemporaryExpr(unless(isBoundToLValue(;
   // Detect redundant 'c_str()' calls through a string constructor.
   // If CxxConstructExpr is the part of some CallExpr we need to
   // check that matched ParamDecl of the ancestor CallExpr is not rvalue.
   Finder->addMatcher(
-  traverse(ast_type_traits::TK_AsIs,
-   cxxConstructExpr(StringConstructorExpr,
-hasArgument(0, StringCStrCallExpr),
-unless(hasParent(materializeTemporaryExpr(
-unless(isBoundToLValue())),
+  traverse(
+  ast_type_traits::TK_AsIs,
+  cxxConstructExpr(
+  StringConstructorExpr, hasArgument(0, StringCStrCallExpr),
+  unless(anyOf(HasRValueTempParent, hasParent(cxxBindTemporaryExpr(
+HasRValueTempParent)),
   this);
 
   // Detect: 's == str.c_str()'  ->  's == str'


Index: clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-cstr.cpp
@@ -15,6 +15,8 @@
   basic_string();
   basic_string(const C *p, const A &a = A());
 
+  ~basic_string();
+
   const C *c_str() const;
   const C *data() const;
 
Index: clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp
@@ -92,16 +92,18 @@
 callee(memberExpr().bind("member")),
 callee(cxxMethodDecl(hasAnyName("c_str", "data"
   .bind("call");
-
+  const auto HasRValueTempParent =
+  hasParent(materializeTemporaryExpr(unless(isBoundToLValue(;
   // Detect redundant 'c_str()' calls through a string constructor.
   // If CxxConstructExpr is the part of some CallExpr we need to
   // check that matched ParamDecl of the ancestor CallExpr is not rvalue.
   Finder->addMatcher(
-  traverse(ast_type_traits::TK_AsIs,
-   cxxConstructExpr(StringConstructorExpr,
-hasArgument(0, StringCStrCallExpr),
-unless(hasParent(materializeTemporaryExpr(
-unless(isBoundToLValue())),
+  traverse(
+  ast_type_traits::TK_AsIs,
+  cxxConstructExpr(
+  StringConstructorExpr, hasArgument(0, StringCStrCallExpr),
+  unless(anyOf(HasRValueTempParent, hasParent(cxxBindTemporaryExpr(
+HasRValueTempParent)),
   this);
 
   // Detect: 's == str.c_str()'  ->  's == str'
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2020-07-29 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added a reviewer: DmitryPolukhin.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.
njames93 requested review of this revision.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84850

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


Index: clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -114,11 +114,9 @@
   Options.SystemHeaders = false;
   Options.FormatStyle = "none";
   Options.User = llvm::None;
-  unsigned Priority = 0;
   for (const ClangTidyModuleRegistry::entry &Module :
ClangTidyModuleRegistry::entries())
-Options =
-Options.mergeWith(Module.instantiate()->getModuleOptions(), 
++Priority);
+Options = Options.mergeWith(Module.instantiate()->getModuleOptions(), 0);
   return Options;
 }
 


Index: clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -114,11 +114,9 @@
   Options.SystemHeaders = false;
   Options.FormatStyle = "none";
   Options.User = llvm::None;
-  unsigned Priority = 0;
   for (const ClangTidyModuleRegistry::entry &Module :
ClangTidyModuleRegistry::entries())
-Options =
-Options.mergeWith(Module.instantiate()->getModuleOptions(), ++Priority);
+Options = Options.mergeWith(Module.instantiate()->getModuleOptions(), 0);
   return Options;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84831: [clang-tidy] Fix RedundantStringCStrCheck with r values

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

In D84831#2181336 , @gribozavr2 wrote:

>> Passed test cases but failed in the real world as std::string has a non 
>> trivial destructor so creates a CXXBindTemporaryExpr.
>
> An idea for a future change: move the std::string mock from this test into a 
> header that is shared across all tests that need a std::string. That will 
> hopefully allow us to combine forces when curating the standard library mocks.

That does sound like a good plan, could also add maybe vector

Also a future change for this specific check would be to replace the call to 
`c_str()` when its being bound to an r value with an explicit copy constructor 
call

   void foo(std::string &&);
   void bar(const std::string& S) {
  -  foo(S.c_str());
  +  foo(std::string(S));
   }

This would be more of a performance change though, basically save a call to 
strlen.
Though arguably it is slightly more readable, as you are explicitly saying you 
want to pass a copy of the string


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84831

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


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

2020-07-29 Thread Nathan James via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG62beb7c6f4f2: [clang-tidy] Fix module options being 
registered with different priorities (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84850

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


Index: clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -114,11 +114,9 @@
   Options.SystemHeaders = false;
   Options.FormatStyle = "none";
   Options.User = llvm::None;
-  unsigned Priority = 0;
   for (const ClangTidyModuleRegistry::entry &Module :
ClangTidyModuleRegistry::entries())
-Options =
-Options.mergeWith(Module.instantiate()->getModuleOptions(), 
++Priority);
+Options = Options.mergeWith(Module.instantiate()->getModuleOptions(), 0);
   return Options;
 }
 


Index: clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyOptions.cpp
@@ -114,11 +114,9 @@
   Options.SystemHeaders = false;
   Options.FormatStyle = "none";
   Options.User = llvm::None;
-  unsigned Priority = 0;
   for (const ClangTidyModuleRegistry::entry &Module :
ClangTidyModuleRegistry::entries())
-Options =
-Options.mergeWith(Module.instantiate()->getModuleOptions(), ++Priority);
+Options = Options.mergeWith(Module.instantiate()->getModuleOptions(), 0);
   return Options;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2020-07-29 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbbc2ddecbd34: [clang-tidy] Handled insertion only fixits 
when determining conflicts. (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82898

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

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-init-variables-conflict.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables,readability-isolate-declaration %t
+
+void foo() {
+  int A, B, C;
+  // CHECK-MESSAGES-DAG: :[[@LINE-1]]:7: warning: variable 'A' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-2]]:10: warning: variable 'B' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-3]]:13: warning: variable 'C' is not initialized
+  // CHECK-MESSAGES-DAG: :[[@LINE-4]]:3: warning: multiple declarations in a single statement reduces readability
+
+  // Only the isolate declarations fix-it should be applied
+
+  //  CHECK-FIXES: int A;
+  // CHECK-FIXES-NEXT: int B;
+  // CHECK-FIXES-NEXT: int C;
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -31,6 +31,7 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Regex.h"
 #include 
@@ -590,6 +591,7 @@
 // An event can be either the begin or the end of an interval.
 enum EventType {
   ET_Begin = 1,
+  ET_Insert = 0,
   ET_End = -1,
 };
 
@@ -621,10 +623,17 @@
   //   one will be processed before, disallowing the second one, and the
   //   end point of the first one will also be processed before,
   //   disallowing the first one.
-  if (Type == ET_Begin)
+  switch (Type) {
+  case ET_Begin:
 Priority = std::make_tuple(Begin, Type, -End, -ErrorSize, ErrorId);
-  else
+break;
+  case ET_Insert:
+Priority = std::make_tuple(Begin, Type, -End, ErrorSize, ErrorId);
+break;
+  case ET_End:
 Priority = std::make_tuple(End, Type, -Begin, ErrorSize, ErrorId);
+break;
+  }
 }
 
 bool operator<(const Event &Other) const {
@@ -662,19 +671,19 @@
   }
 
   // Build events from error intervals.
-  std::map> FileEvents;
+  llvm::StringMap> FileEvents;
   for (unsigned I = 0; I < ErrorFixes.size(); ++I) {
 for (const auto &FileAndReplace : *ErrorFixes[I].second) {
   for (const auto &Replace : FileAndReplace.second) {
 unsigned Begin = Replace.getOffset();
 unsigned End = Begin + Replace.getLength();
-const std::string &FilePath = std::string(Replace.getFilePath());
-// FIXME: Handle empty intervals, such as those from insertions.
-if (Begin == End)
-  continue;
-auto &Events = FileEvents[FilePath];
-Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
-Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+auto &Events = FileEvents[Replace.getFilePath()];
+if (Begin == End) {
+  Events.emplace_back(Begin, End, Event::ET_Insert, I, Sizes[I]);
+} else {
+  Events.emplace_back(Begin, End, Event::ET_Begin, I, Sizes[I]);
+  Events.emplace_back(Begin, End, Event::ET_End, I, Sizes[I]);
+}
   }
 }
   }
@@ -686,14 +695,20 @@
 llvm::sort(Events);
 int OpenIntervals = 0;
 for (const auto &Event : Events) {
-  if (Event.Type == Event::ET_End)
---OpenIntervals;
-  // This has to be checked after removing the interval from the count if it
-  // is an end event, or before adding it if it is a begin event.
-  if (OpenIntervals != 0)
-Apply[Event.ErrorId] = false;
-  if (Event.Type == Event::ET_Begin)
-++OpenIntervals;
+  switch (Event.Type) {
+  case Event::ET_Begin:
+if (OpenIntervals++ != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  case Event::ET_Insert:
+if (OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  case Event::ET_End:
+if (--OpenIntervals != 0)
+  Apply[Event.ErrorId] = false;
+break;
+  }
 }
 assert(OpenIntervals == 0 && "Amount of begin/end points doesn't match");
   }
___
cfe-commits mail

[PATCH] D84868: [clang-tidy] Use StringMap for ClangTidyOptions::OptionsMap

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

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84868

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

Index: clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
@@ -17,14 +17,10 @@
 // For this test we have to use names of the real checks because otherwise values are ignored.
 // RUN: clang-tidy -dump-config %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD4
 // CHECK-CHILD4: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto
-// CHECK-CHILD4: - key: llvm-qualified-auto.AddConstToQualified
-// CHECK-CHILD4-NEXT: value: 'true'
-// CHECK-CHILD4: - key: modernize-loop-convert.MaxCopySize
-// CHECK-CHILD4-NEXT: value: '20'
-// CHECK-CHILD4: - key: modernize-loop-convert.MinConfidence
-// CHECK-CHILD4-NEXT: value: reasonable
-// CHECK-CHILD4: - key: modernize-use-using.IgnoreMacros
-// CHECK-CHILD4-NEXT: value: 'false'
+// CHECK-CHILD4-DAG: - key: llvm-qualified-auto.AddConstToQualified{{ *[[:space:]] *}}value: 'true'
+// CHECK-CHILD4-DAG: - key: modernize-loop-convert.MaxCopySize{{ *[[:space:]] *}}value: '20'
+// CHECK-CHILD4-DAG: - key: modernize-loop-convert.MinConfidence{{ *[[:space:]] *}}value: reasonable
+// CHECK-CHILD4-DAG: - key: modernize-use-using.IgnoreMacros{{ *[[:space:]] *}}value: 'false'
 
 // RUN: clang-tidy --explain-config %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-EXPLAIN
 // CHECK-EXPLAIN: 'llvm-qualified-auto' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}44{{[/\\]}}.clang-tidy.
@@ -37,16 +33,13 @@
 // RUN: CheckOptions: [{key: modernize-loop-convert.MaxCopySize, value: 21}]}' \
 // RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD5
 // CHECK-CHILD5: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto,-llvm-qualified-auto
-// CHECK-CHILD5: - key: modernize-loop-convert.MaxCopySize
-// CHECK-CHILD5-NEXT: value: '21'
-// CHECK-CHILD5: - key: modernize-loop-convert.MinConfidence
-// CHECK-CHILD5-NEXT: value: reasonable
-// CHECK-CHILD5: - key: modernize-use-using.IgnoreMacros
-// CHECK-CHILD5-NEXT: value: 'false'
+// CHECK-CHILD5-DAG: - key: modernize-loop-convert.MaxCopySize{{ *[[:space:]] *}}value: '21'
+// CHECK-CHILD5-DAG: - key: modernize-loop-convert.MinConfidence{{ *[[:space:]] *}}value: reasonable
+// CHECK-CHILD5-DAG: - key: modernize-use-using.IgnoreMacros{{ *[[:space:]] *}}value: 'false'
 
 // RUN: clang-tidy -dump-config \
 // RUN: --config='{InheritParentConfig: false, \
 // RUN: Checks: -llvm-qualified-auto}' \
 // RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD6
-// CHECK-CHILD6: Checks: {{.*}}-llvm-qualified-auto
+// CHECK-CHILD6: Checks: {{.*-llvm-qualified-auto'? *$}}
 // CHECK-CHILD6-NOT: - key: modernize-use-using.IgnoreMacros
Index: clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
@@ -1,10 +1,6 @@
 // RUN: clang-tidy -checks='-*,google*' -config='{}' -dump-config - -- | FileCheck %s
 // CHECK: CheckOptions:
-// CHECK: {{- key: *google-readability-braces-around-statements.ShortStatementLines}}
-// CHECK-NEXT: {{value: *'1'}}
-// CHECK: {{- key: *google-readability-function-size.StatementThreshold}}
-// CHECK-NEXT: {{value: *'800'}}
-// CHECK: {{- key: *google-readability-namespace-comments.ShortNamespaceLines}}
-// CHECK-NEXT: {{value: *'10'}}
-// CHECK: {{- key: *google-readability-namespace-comments.SpacesBeforeComments}}
-// CHECK-NEXT: {{value: *'2'}}
+// CHECK-DAG: {{- key: *google-readability-braces-around-statements.ShortStatementLines *[[:space:]] *value: *'1'}}
+// CHECK-DAG: {{- key: *google-readability-function-size.StatementThreshold *[[:space:]] *value: *'800'}}
+// CHECK-DAG: {{- key: *google-readability-namespace-comments.ShortNamespaceLines *[[:space:]] *value: *'10'}}
+// CHECK-DAG: {{- key: *google-readability-namespace-comments.SpacesBeforeComments *[[:space:]] *value: *'2'}}
Index: clang-tools-extra/clang-tidy/ClangTidyOptions.

[PATCH] D84868: [clang-tidy] Use StringMap for ClangTidyOptions::OptionsMap

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

Missing call to getValue()


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84868

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

Index: clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
@@ -17,14 +17,10 @@
 // For this test we have to use names of the real checks because otherwise values are ignored.
 // RUN: clang-tidy -dump-config %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD4
 // CHECK-CHILD4: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto
-// CHECK-CHILD4: - key: llvm-qualified-auto.AddConstToQualified
-// CHECK-CHILD4-NEXT: value: 'true'
-// CHECK-CHILD4: - key: modernize-loop-convert.MaxCopySize
-// CHECK-CHILD4-NEXT: value: '20'
-// CHECK-CHILD4: - key: modernize-loop-convert.MinConfidence
-// CHECK-CHILD4-NEXT: value: reasonable
-// CHECK-CHILD4: - key: modernize-use-using.IgnoreMacros
-// CHECK-CHILD4-NEXT: value: 'false'
+// CHECK-CHILD4-DAG: - key: llvm-qualified-auto.AddConstToQualified{{ *[[:space:]] *}}value: 'true'
+// CHECK-CHILD4-DAG: - key: modernize-loop-convert.MaxCopySize{{ *[[:space:]] *}}value: '20'
+// CHECK-CHILD4-DAG: - key: modernize-loop-convert.MinConfidence{{ *[[:space:]] *}}value: reasonable
+// CHECK-CHILD4-DAG: - key: modernize-use-using.IgnoreMacros{{ *[[:space:]] *}}value: 'false'
 
 // RUN: clang-tidy --explain-config %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-EXPLAIN
 // CHECK-EXPLAIN: 'llvm-qualified-auto' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}44{{[/\\]}}.clang-tidy.
@@ -37,16 +33,13 @@
 // RUN: CheckOptions: [{key: modernize-loop-convert.MaxCopySize, value: 21}]}' \
 // RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD5
 // CHECK-CHILD5: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto,-llvm-qualified-auto
-// CHECK-CHILD5: - key: modernize-loop-convert.MaxCopySize
-// CHECK-CHILD5-NEXT: value: '21'
-// CHECK-CHILD5: - key: modernize-loop-convert.MinConfidence
-// CHECK-CHILD5-NEXT: value: reasonable
-// CHECK-CHILD5: - key: modernize-use-using.IgnoreMacros
-// CHECK-CHILD5-NEXT: value: 'false'
+// CHECK-CHILD5-DAG: - key: modernize-loop-convert.MaxCopySize{{ *[[:space:]] *}}value: '21'
+// CHECK-CHILD5-DAG: - key: modernize-loop-convert.MinConfidence{{ *[[:space:]] *}}value: reasonable
+// CHECK-CHILD5-DAG: - key: modernize-use-using.IgnoreMacros{{ *[[:space:]] *}}value: 'false'
 
 // RUN: clang-tidy -dump-config \
 // RUN: --config='{InheritParentConfig: false, \
 // RUN: Checks: -llvm-qualified-auto}' \
 // RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD6
-// CHECK-CHILD6: Checks: {{.*}}-llvm-qualified-auto
+// CHECK-CHILD6: Checks: {{.*-llvm-qualified-auto'? *$}}
 // CHECK-CHILD6-NOT: - key: modernize-use-using.IgnoreMacros
Index: clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
@@ -1,10 +1,6 @@
 // RUN: clang-tidy -checks='-*,google*' -config='{}' -dump-config - -- | FileCheck %s
 // CHECK: CheckOptions:
-// CHECK: {{- key: *google-readability-braces-around-statements.ShortStatementLines}}
-// CHECK-NEXT: {{value: *'1'}}
-// CHECK: {{- key: *google-readability-function-size.StatementThreshold}}
-// CHECK-NEXT: {{value: *'800'}}
-// CHECK: {{- key: *google-readability-namespace-comments.ShortNamespaceLines}}
-// CHECK-NEXT: {{value: *'10'}}
-// CHECK: {{- key: *google-readability-namespace-comments.SpacesBeforeComments}}
-// CHECK-NEXT: {{value: *'2'}}
+// CHECK-DAG: {{- key: *google-readability-braces-around-statements.ShortStatementLines *[[:space:]] *value: *'1'}}
+// CHECK-DAG: {{- key: *google-readability-function-size.StatementThreshold *[[:space:]] *value: *'800'}}
+// CHECK-DAG: {{- key: *google-readability-namespace-comments.ShortNamespaceLines *[[:space:]] *value: *'10'}}
+// CHECK-DAG: {{- key: *google-readability-namespace-comments.SpacesBeforeComments *[[:space:]] *value: *'2'}}
Index: clang-tools-extra/clang-tidy/ClangTidyOptions.h
===
--- clang-tools-extra/clang-tidy/ClangTidyOptions.h
+++ clang-tools-extra/clang-

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

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

Revert to using warning for logging parsing errors


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84812

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

Index: clang-tools-extra/clang-tidy/ClangTidyCheck.h
===
--- clang-tools-extra/clang-tidy/ClangTidyCheck.h
+++ clang-tools-extra/clang-tidy/ClangTidyCheck.h
@@ -268,7 +268,7 @@
   if (llvm::Expected ValueOr = get(LocalName))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -314,7 +314,7 @@
   if (llvm::Expected ValueOr = getLocalOrGlobal(LocalName))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -353,7 +353,7 @@
   if (auto ValueOr = get(LocalName, IgnoreCase))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -395,10 +395,35 @@
   if (auto ValueOr = getLocalOrGlobal(LocalName, IgnoreCase))
 return *ValueOr;
   else
-logErrToStdErr(ValueOr.takeError());
+logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
+/// Returns the value for the option \p LocalName represented as a ``T``.
+/// If the option is missing returns None, if the option can't be parsed
+/// as a ``T``, log that to stderr and return None.
+template 
+llvm::Optional getOptional(StringRef LocalName) const {
+  if (auto ValueOr = get(LocalName))
+return *ValueOr;
+  else
+logIfOptionParsingError(ValueOr.takeError());
+  return llvm::None;
+}
+
+/// Returns the value for the local or global option \p LocalName
+/// represented as a ``T``.
+/// If the option is missing returns None, if the
+/// option can't be parsed as a ``T``, log that to stderr and return None.
+template 
+llvm::Optional getOptionalLocalOrGlobal(StringRef LocalName) const {
+  if (auto ValueOr = getLocalOrGlobal(LocalName))
+return *ValueOr;
+  else
+logIfOptionParsingError(ValueOr.takeError());
+  return llvm::None;
+}
+
 /// Stores an option with the check-local name \p LocalName with
 /// string value \p Value to \p Options.
 void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
@@ -456,7 +481,8 @@
 void storeInt(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
   int64_t Value) const;
 
-static void logErrToStdErr(llvm::Error &&Err);
+/// Logs an Error to stderr if a \p Err is not a MissingOptionError.
+static void logIfOptionParsingError(llvm::Error &&Err);
 
 std::string NamePrefix;
 const ClangTidyOptions::OptionMap &CheckOptions;
@@ -524,6 +550,19 @@
 ClangTidyOptions::OptionMap &Options, StringRef LocalName,
 bool Value) const;
 
+/// Returns the value for the option \p LocalName.
+/// If the option is missing returns None.
+template <>
+Optional ClangTidyCheck::OptionsView::getOptional(
+StringRef LocalName) const;
+
+/// Returns the value for the local or global option \p LocalName.
+/// If the option is missing returns None.
+template <>
+Optional
+ClangTidyCheck::OptionsView::getOptionalLocalOrGlobal(
+StringRef LocalName) const;
+
 } // namespace tidy
 } // namespace clang
 
Index: clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
@@ -10,6 +10,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
 namespace clang {
@@ -126,7 +127,7 @@
   llvm::Expected ValueOr = get(LocalName);
   if (ValueOr)
 return *ValueOr;
-  logErrToStdErr(ValueOr.takeError());
+  logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -145,7 +146,7 @@
   llvm::Expected ValueOr = getLocalOrGlobal(LocalName);
   if (ValueOr)
 return *ValueOr;
-  logErrToStdErr(ValueOr.takeError());
+  logIfOptionParsingError(ValueOr.takeError());
   return Default;
 }
 
@@ -204,13 +205,33 @@
   Iter->second.Value);
 }
 
-void ClangTidyCheck::OptionsView::logErrToStdErr(llvm::Error &&Err) {
-  llvm::logAllUnhandledErrors(
-  llvm::handleErrors(std::move(Err),
- [](const MissingOptionError &) -> llvm::Error {
-   return llvm::E

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

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

Rebase from parent and address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84814

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/header.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/.clang-tidy
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
@@ -0,0 +1,34 @@
+// Setup header directory
+
+// RUN: rm -rf %theaders
+// RUN: mkdir %theaders
+// RUN: cp -R %S/Inputs/readability-identifier-naming/. %theaders
+
+// C++11 isn't explicitly required, but failing to specify a standard means the
+// check will run multiple times for different standards. This will cause the
+// second test to fail as the header file will be changed during the first run.
+
+// RUN: %check_clang_tidy -std=c++11 %s readability-identifier-naming %t -- \
+// RUN:   -config='{ InheritParentConfig: true, CheckOptions: [ \
+// RUN: {key: readability-identifier-naming.FunctionCase, value: camelBack} \
+// RUN:  ]}' -header-filter='.*' -- -I%theaders
+
+#include "global-style1/header.h"
+#include "global-style2/header.h"
+// CHECK-MESSAGES-DAG: global-style1/header.h:5:6: warning: invalid case style for global function 'style1Bad'
+// CHECK-MESSAGES-DAG: global-style2/header.h:5:6: warning: invalid case style for global function 'style2Bad'
+
+void goodStyle() {
+  style1_good();
+  STYLE2_GOOD();
+}
+// CHECK-MESSAGES-DAG: :[[@LINE+1]]:6: warning: invalid case style for function 'bad_style'
+void bad_style() {
+  style1Bad();
+  style2Bad();
+}
+
+//  CHECK-FIXES: void badStyle() {
+// CHECK-FIXES-NEXT:   style1_bad();
+// CHECK-FIXES-NEXT:   STYLE2_BAD();
+// CHECK-FIXES-NEXT: }
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/header.h
@@ -0,0 +1,5 @@
+
+
+void STYLE2_GOOD();
+
+void style2Bad();
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/.clang-tidy
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style2/.clang-tidy
@@ -0,0 +1,4 @@
+CheckOptions:
+  - key: readability-identifier-naming.GlobalFunctionCase
+value:   UPPER_CASE
+
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/header.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/header.h
@@ -0,0 +1,5 @@
+
+
+void style1_good();
+
+void style1Bad();
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/.clang-tidy
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-identifier-naming/global-style1/.clang-tidy
@@ -0,0 +1,4 @@
+CheckOptions:
+  - key: readability-identifier-naming.GlobalFunctionCase
+value:   lower_case
+
Index: clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
===
--- clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
+++ clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
@@ -69,7 +69,16 @@
   DiagInfo GetDiagInfo(const NamingCheckId &ID,
const NamingCheckFailure &Failure) const override;
 
-  std::vector> NamingStyles;
+  ArrayRef>
+  getStyleForFile(StringRef FileName) const;
+
+  /// Stores the style options as a vector, indexed by the specified \ref
+  /// StyleKind, for a given directory.
+  mutable llvm::StringMap>>
+  NamingStylesCache;
+
+  ClangTidyContext *const Context;
+  const std::string CheckName;
   const bool IgnoreFailedSplit;
   const bool IgnoreMainLikeFunctions;
 };
Index: clang-tools-extra

[PATCH] D84898: [clang-tidy] Add new checker for complex conditions with no meaning

2020-07-30 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

For the record `X < Y < Z ` does have a mathematical meaning, Y is constrained 
between X and Z.
However in the context of `C` the expression isnt parsed like that.
If someone writes this they likely wanted `(X < Y) && (Y < Z)`
For this specific check as you pointed out we wouldn't want to make that 
assumption though there is a case for adding notes to silence the warning by 
wrapping one of the comparisons in parenthesis.

It appears that this check fire multiple times for the case of `W < X < Y < Z`
Once for `(W < X < Y) < Z` and another time for `(W < X) < Y`
This again likely wont be visible as the warning currently is emitted at the 
start of the expression




Comment at: clang-tools-extra/clang-tidy/misc/ComplexConditionsCheck.cpp:28-33
+  const auto *If = Result.Nodes.getNodeAs("complex_binop");
+  const auto *Statement = Result.Nodes.getNodeAs("complex_binop");
+  if (If) {
+diag(If->getBeginLoc(),
+ "comparisons like `X<=Y<=Z` have no mathematical meaning");
+  }

The `If` looks suspicious, as you match on a `BinaryOperator`, the `If` will 
always be nullptr and should likely be removed.
Likewise `Statement` will match but should likely be changed to BinOp as that's 
what it is.



Comment at: clang-tools-extra/clang-tidy/misc/ComplexConditionsCheck.cpp:34
+  }
+  if (Statement) {
+diag(Statement->getBeginLoc(),

Elide braces


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84898

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


[PATCH] D84902: [clang-tidy] Fix ODR violation in unittests.

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

LGTM, Thanks that bug was eating away at me for a good few days.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D84902

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


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

2020-07-30 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: alexfh, aaron.ballman, gribozavr2, Eugene.Zelenko, 
hokein.
Herald added subscribers: cfe-commits, arphaman, xazax.hun.
Herald added a project: clang.
njames93 requested review of this revision.

Added an option to control whether to apply the fixes found in notes attached 
to clang tidy errors or not.
Diagnostics may contain multiple notes each offering different ways to fix the 
issue, for that reason the default behaviour should be to not look at fixes 
found in notes.
Instead offer up all the available fix-its in the output but don't try to apply 
the first one unless `-fix-notes` is supplied.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84924

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidy.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
  
clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/index.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
  clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s "llvm-namespace-comment,clang-diagnostic-*" %t
+// RUN: %check_clang_tidy %s "llvm-namespace-comment,clang-diagnostic-*" %t -- -fix-notes
 void foo(int a) {
   if (a = 1) {
   // CHECK-NOTES: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
Index: clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
@@ -81,7 +81,6 @@
 // eol-comments aren't removed (yet)
 using n::A; // A
 // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'A' is unused
-// CHECK-MESSAGES: :[[@LINE-2]]:10: note: remove the using
 // CHECK-FIXES: {{^}}// A
 using n::B;
 using n::C;
Index: clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s misc-definitions-in-headers %t
+// RUN: %check_clang_tidy %s misc-definitions-in-headers %t -- -fix-notes
 
 int f() {
 // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: function 'f' defined in a header file; function definitions in header files can lead to ODR violations [misc-definitions-in-headers]
Index: clang-tools-extra/docs/clang-tidy/index.rst
===
--- clang-tools-extra/docs/clang-tidy/index.rst
+++ clang-tools-extra/docs/clang-tidy/index.rst
@@ -170,6 +170,11 @@
  errors were found. If compiler errors have
  attached fix-its, clang-tidy will apply them as
  well.
+--fix-notes- 
+ If a warning has no fix, but has notes attached
+ which contain fixes, apply the first fix found
+ in any notes.
+ Requires -fix to be specified.
 --format-style=-
  Style for formatting code around applied fixes:
- 'none' (default) turns off formatting
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -67,7 +67,8 @@
 Improvements to clang-tidy
 --
 
-The improvements are...
+ - Added command line option `-fix-notes` to apply fixes found in notes
+   attached to warnings.
 
 Improvements to include-fixer
 -
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tools-extra/clang-tidy/tool/

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

2020-07-30 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

This is very much a work in progress


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84924

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


[PATCH] D84868: [clang-tidy] Use StringMap for ClangTidyOptions::OptionsMap

2020-07-30 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG45a720a86432: [clang-tidy] Use StringMap for 
ClangTidyOptions::OptionsMap (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84868

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

Index: clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/config-files.cpp
@@ -17,14 +17,10 @@
 // For this test we have to use names of the real checks because otherwise values are ignored.
 // RUN: clang-tidy -dump-config %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD4
 // CHECK-CHILD4: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto
-// CHECK-CHILD4: - key: llvm-qualified-auto.AddConstToQualified
-// CHECK-CHILD4-NEXT: value: 'true'
-// CHECK-CHILD4: - key: modernize-loop-convert.MaxCopySize
-// CHECK-CHILD4-NEXT: value: '20'
-// CHECK-CHILD4: - key: modernize-loop-convert.MinConfidence
-// CHECK-CHILD4-NEXT: value: reasonable
-// CHECK-CHILD4: - key: modernize-use-using.IgnoreMacros
-// CHECK-CHILD4-NEXT: value: 'false'
+// CHECK-CHILD4-DAG: - key: llvm-qualified-auto.AddConstToQualified{{ *[[:space:]] *}}value: 'true'
+// CHECK-CHILD4-DAG: - key: modernize-loop-convert.MaxCopySize{{ *[[:space:]] *}}value: '20'
+// CHECK-CHILD4-DAG: - key: modernize-loop-convert.MinConfidence{{ *[[:space:]] *}}value: reasonable
+// CHECK-CHILD4-DAG: - key: modernize-use-using.IgnoreMacros{{ *[[:space:]] *}}value: 'false'
 
 // RUN: clang-tidy --explain-config %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-EXPLAIN
 // CHECK-EXPLAIN: 'llvm-qualified-auto' is enabled in the {{.*}}{{[/\\]}}Inputs{{[/\\]}}config-files{{[/\\]}}4{{[/\\]}}44{{[/\\]}}.clang-tidy.
@@ -37,16 +33,13 @@
 // RUN: CheckOptions: [{key: modernize-loop-convert.MaxCopySize, value: 21}]}' \
 // RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD5
 // CHECK-CHILD5: Checks: {{.*}}modernize-loop-convert,modernize-use-using,llvm-qualified-auto,-llvm-qualified-auto
-// CHECK-CHILD5: - key: modernize-loop-convert.MaxCopySize
-// CHECK-CHILD5-NEXT: value: '21'
-// CHECK-CHILD5: - key: modernize-loop-convert.MinConfidence
-// CHECK-CHILD5-NEXT: value: reasonable
-// CHECK-CHILD5: - key: modernize-use-using.IgnoreMacros
-// CHECK-CHILD5-NEXT: value: 'false'
+// CHECK-CHILD5-DAG: - key: modernize-loop-convert.MaxCopySize{{ *[[:space:]] *}}value: '21'
+// CHECK-CHILD5-DAG: - key: modernize-loop-convert.MinConfidence{{ *[[:space:]] *}}value: reasonable
+// CHECK-CHILD5-DAG: - key: modernize-use-using.IgnoreMacros{{ *[[:space:]] *}}value: 'false'
 
 // RUN: clang-tidy -dump-config \
 // RUN: --config='{InheritParentConfig: false, \
 // RUN: Checks: -llvm-qualified-auto}' \
 // RUN: %S/Inputs/config-files/4/44/- -- | FileCheck %s -check-prefix=CHECK-CHILD6
-// CHECK-CHILD6: Checks: {{.*}}-llvm-qualified-auto
+// CHECK-CHILD6: Checks: {{.*-llvm-qualified-auto'? *$}}
 // CHECK-CHILD6-NOT: - key: modernize-use-using.IgnoreMacros
Index: clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/google-module.cpp
@@ -1,10 +1,6 @@
 // RUN: clang-tidy -checks='-*,google*' -config='{}' -dump-config - -- | FileCheck %s
 // CHECK: CheckOptions:
-// CHECK: {{- key: *google-readability-braces-around-statements.ShortStatementLines}}
-// CHECK-NEXT: {{value: *'1'}}
-// CHECK: {{- key: *google-readability-function-size.StatementThreshold}}
-// CHECK-NEXT: {{value: *'800'}}
-// CHECK: {{- key: *google-readability-namespace-comments.ShortNamespaceLines}}
-// CHECK-NEXT: {{value: *'10'}}
-// CHECK: {{- key: *google-readability-namespace-comments.SpacesBeforeComments}}
-// CHECK-NEXT: {{value: *'2'}}
+// CHECK-DAG: {{- key: *google-readability-braces-around-statements.ShortStatementLines *[[:space:]] *value: *'1'}}
+// CHECK-DAG: {{- key: *google-readability-function-size.StatementThreshold *[[:space:]] *value: *'800'}}
+// CHECK-DAG: {{- key: *google-readability-namespace-comments.ShortNamespaceLines *[[:space:]] *value: *'10'}}
+// CHECK-DAG: {{- key: *google-readability-namespace-comments.SpacesBeforeComments *[[:space:]] *value: *'2'}}
Index: clang-tools-extra/clang-tidy/ClangTidyOptions.h
==

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

2020-07-30 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: aaron.ballman, gribozavr2.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.
njames93 requested review of this revision.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D84926

Files:
  clang-tools-extra/clang-tidy/ClangTidyModule.cpp
  clang-tools-extra/clang-tidy/ClangTidyModule.h


Index: clang-tools-extra/clang-tidy/ClangTidyModule.h
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.h
+++ clang-tools-extra/clang-tidy/ClangTidyModule.h
@@ -69,7 +69,7 @@
   std::vector>
   createChecks(ClangTidyContext *Context);
 
-  typedef std::map FactoryMap;
+  typedef llvm::StringMap FactoryMap;
   FactoryMap::const_iterator begin() const { return Factories.begin(); }
   FactoryMap::const_iterator end() const { return Factories.end(); }
   bool empty() const { return Factories.empty(); }
Index: clang-tools-extra/clang-tidy/ClangTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyModule.cpp
@@ -18,15 +18,15 @@
 
 void ClangTidyCheckFactories::registerCheckFactory(StringRef Name,
CheckFactory Factory) {
-  Factories[std::string(Name)] = std::move(Factory);
+  Factories.insert_or_assign(Name, std::move(Factory));
 }
 
 std::vector>
 ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) {
   std::vector> Checks;
   for (const auto &Factory : Factories) {
-if (Context->isCheckEnabled(Factory.first))
-  Checks.emplace_back(Factory.second(Factory.first, Context));
+if (Context->isCheckEnabled(Factory.getKey()))
+  Checks.emplace_back(Factory.getValue()(Factory.getKey(), Context));
   }
   return Checks;
 }


Index: clang-tools-extra/clang-tidy/ClangTidyModule.h
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.h
+++ clang-tools-extra/clang-tidy/ClangTidyModule.h
@@ -69,7 +69,7 @@
   std::vector>
   createChecks(ClangTidyContext *Context);
 
-  typedef std::map FactoryMap;
+  typedef llvm::StringMap FactoryMap;
   FactoryMap::const_iterator begin() const { return Factories.begin(); }
   FactoryMap::const_iterator end() const { return Factories.end(); }
   bool empty() const { return Factories.empty(); }
Index: clang-tools-extra/clang-tidy/ClangTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyModule.cpp
@@ -18,15 +18,15 @@
 
 void ClangTidyCheckFactories::registerCheckFactory(StringRef Name,
CheckFactory Factory) {
-  Factories[std::string(Name)] = std::move(Factory);
+  Factories.insert_or_assign(Name, std::move(Factory));
 }
 
 std::vector>
 ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) {
   std::vector> Checks;
   for (const auto &Factory : Factories) {
-if (Context->isCheckEnabled(Factory.first))
-  Checks.emplace_back(Factory.second(Factory.first, Context));
+if (Context->isCheckEnabled(Factory.getKey()))
+  Checks.emplace_back(Factory.getValue()(Factory.getKey(), Context));
   }
   return Checks;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

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

Fix build errors


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84926

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


Index: clang-tools-extra/clang-tidy/ClangTidyModule.h
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.h
+++ clang-tools-extra/clang-tidy/ClangTidyModule.h
@@ -69,7 +69,7 @@
   std::vector>
   createChecks(ClangTidyContext *Context);
 
-  typedef std::map FactoryMap;
+  typedef llvm::StringMap FactoryMap;
   FactoryMap::const_iterator begin() const { return Factories.begin(); }
   FactoryMap::const_iterator end() const { return Factories.end(); }
   bool empty() const { return Factories.empty(); }
Index: clang-tools-extra/clang-tidy/ClangTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyModule.cpp
@@ -18,15 +18,15 @@
 
 void ClangTidyCheckFactories::registerCheckFactory(StringRef Name,
CheckFactory Factory) {
-  Factories[std::string(Name)] = std::move(Factory);
+  Factories.insert_or_assign(Name, std::move(Factory));
 }
 
 std::vector>
 ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) {
   std::vector> Checks;
   for (const auto &Factory : Factories) {
-if (Context->isCheckEnabled(Factory.first))
-  Checks.emplace_back(Factory.second(Factory.first, Context));
+if (Context->isCheckEnabled(Factory.getKey()))
+  Checks.emplace_back(Factory.getValue()(Factory.getKey(), Context));
   }
   return Checks;
 }
Index: clang-tools-extra/clang-tidy/ClangTidy.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -450,8 +450,8 @@
 std::vector ClangTidyASTConsumerFactory::getCheckNames() {
   std::vector CheckNames;
   for (const auto &CheckFactory : *CheckFactories) {
-if (Context.isCheckEnabled(CheckFactory.first))
-  CheckNames.push_back(CheckFactory.first);
+if (Context.isCheckEnabled(CheckFactory.getKey()))
+  CheckNames.emplace_back(CheckFactory.getKey());
   }
 
 #if CLANG_ENABLE_STATIC_ANALYZER


Index: clang-tools-extra/clang-tidy/ClangTidyModule.h
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.h
+++ clang-tools-extra/clang-tidy/ClangTidyModule.h
@@ -69,7 +69,7 @@
   std::vector>
   createChecks(ClangTidyContext *Context);
 
-  typedef std::map FactoryMap;
+  typedef llvm::StringMap FactoryMap;
   FactoryMap::const_iterator begin() const { return Factories.begin(); }
   FactoryMap::const_iterator end() const { return Factories.end(); }
   bool empty() const { return Factories.empty(); }
Index: clang-tools-extra/clang-tidy/ClangTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyModule.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyModule.cpp
@@ -18,15 +18,15 @@
 
 void ClangTidyCheckFactories::registerCheckFactory(StringRef Name,
CheckFactory Factory) {
-  Factories[std::string(Name)] = std::move(Factory);
+  Factories.insert_or_assign(Name, std::move(Factory));
 }
 
 std::vector>
 ClangTidyCheckFactories::createChecks(ClangTidyContext *Context) {
   std::vector> Checks;
   for (const auto &Factory : Factories) {
-if (Context->isCheckEnabled(Factory.first))
-  Checks.emplace_back(Factory.second(Factory.first, Context));
+if (Context->isCheckEnabled(Factory.getKey()))
+  Checks.emplace_back(Factory.getValue()(Factory.getKey(), Context));
   }
   return Checks;
 }
Index: clang-tools-extra/clang-tidy/ClangTidy.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -450,8 +450,8 @@
 std::vector ClangTidyASTConsumerFactory::getCheckNames() {
   std::vector CheckNames;
   for (const auto &CheckFactory : *CheckFactories) {
-if (Context.isCheckEnabled(CheckFactory.first))
-  CheckNames.push_back(CheckFactory.first);
+if (Context.isCheckEnabled(CheckFactory.getKey()))
+  CheckNames.emplace_back(CheckFactory.getKey());
   }
 
 #if CLANG_ENABLE_STATIC_ANALYZER
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

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

- Added test case


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77199

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
@@ -432,3 +432,17 @@
   // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: use default member initializer 
for 'k' [modernize-use-default-member-init]
   // CHECK-FIXES: int i{5}, k{8};
 };
+
+struct PR45363 {
+  // Ensure no warning is emitted here
+  PR45363(int i = 0) : m_i{i} {}
+  int m_i;
+};
+
+struct EmptyBracedIntDefault {
+  EmptyBracedIntDefault() : m_i{} {}
+  int m_i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'm_i' [modernize-use-default-member-init]
+  // CHECK-FIXES:  {{^  }}EmptyBracedIntDefault()  {}
+  // CHECK-FIXES-NEXT: {{^  }}int m_i{};
+};
Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -17,6 +17,12 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER_P(InitListExpr, initCountIs, unsigned, N) {
+  return Node.getNumInits() == N;
+}
+} // namespace
+
 static StringRef getValueOfValueInit(const QualType InitType) {
   switch (InitType->getScalarTypeKind()) {
   case Type::STK_CPointer:
@@ -190,7 +196,7 @@
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
-  auto Init =
+  auto InitBase =
   anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(integerLiteral())),
@@ -198,7 +204,13 @@
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(floatLiteral())),
 cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-initListExpr(), declRefExpr(to(enumConstantDecl(;
+declRefExpr(to(enumConstantDecl(;
+
+  auto Init =
+  anyOf(initListExpr(anyOf(
+allOf(initCountIs(1), hasInit(0, ignoringImplicit(InitBase))),
+initCountIs(0))),
+InitBase);
 
   Finder->addMatcher(
   cxxConstructorDecl(


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
@@ -432,3 +432,17 @@
   // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: use default member initializer for 'k' [modernize-use-default-member-init]
   // CHECK-FIXES: int i{5}, k{8};
 };
+
+struct PR45363 {
+  // Ensure no warning is emitted here
+  PR45363(int i = 0) : m_i{i} {}
+  int m_i;
+};
+
+struct EmptyBracedIntDefault {
+  EmptyBracedIntDefault() : m_i{} {}
+  int m_i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'm_i' [modernize-use-default-member-init]
+  // CHECK-FIXES:  {{^  }}EmptyBracedIntDefault()  {}
+  // CHECK-FIXES-NEXT: {{^  }}int m_i{};
+};
Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -17,6 +17,12 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER_P(InitListExpr, initCountIs, unsigned, N) {
+  return Node.getNumInits() == N;
+}
+} // namespace
+
 static StringRef getValueOfValueInit(const QualType InitType) {
   switch (InitType->getScalarTypeKind()) {
   case Type::STK_CPointer:
@@ -190,7 +196,7 @@
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
-  auto Init =
+  auto InitBase =
   anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(integerLiteral())),
@@ -198,7 +204,13 @@
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(floatLiteral())),
 cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-initListExpr(), declRefExpr(to(enumConstantDecl())

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

2020-04-03 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2c7ea1c4c5f7: [clang-tidy] Address false positive in 
modernize-use-default-member-init (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77199

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


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
@@ -432,3 +432,17 @@
   // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: use default member initializer 
for 'k' [modernize-use-default-member-init]
   // CHECK-FIXES: int i{5}, k{8};
 };
+
+struct PR45363 {
+  // Ensure no warning is emitted here
+  PR45363(int i = 0) : m_i{i} {}
+  int m_i;
+};
+
+struct EmptyBracedIntDefault {
+  EmptyBracedIntDefault() : m_i{} {}
+  int m_i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'm_i' [modernize-use-default-member-init]
+  // CHECK-FIXES:  {{^  }}EmptyBracedIntDefault()  {}
+  // CHECK-FIXES-NEXT: {{^  }}int m_i{};
+};
Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -17,6 +17,12 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER_P(InitListExpr, initCountIs, unsigned, N) {
+  return Node.getNumInits() == N;
+}
+} // namespace
+
 static StringRef getValueOfValueInit(const QualType InitType) {
   switch (InitType->getScalarTypeKind()) {
   case Type::STK_CPointer:
@@ -190,7 +196,7 @@
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
-  auto Init =
+  auto InitBase =
   anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(integerLiteral())),
@@ -198,7 +204,13 @@
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(floatLiteral())),
 cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-initListExpr(), declRefExpr(to(enumConstantDecl(;
+declRefExpr(to(enumConstantDecl(;
+
+  auto Init =
+  anyOf(initListExpr(anyOf(
+allOf(initCountIs(1), hasInit(0, ignoringImplicit(InitBase))),
+initCountIs(0))),
+InitBase);
 
   Finder->addMatcher(
   cxxConstructorDecl(


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
@@ -432,3 +432,17 @@
   // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: use default member initializer for 'k' [modernize-use-default-member-init]
   // CHECK-FIXES: int i{5}, k{8};
 };
+
+struct PR45363 {
+  // Ensure no warning is emitted here
+  PR45363(int i = 0) : m_i{i} {}
+  int m_i;
+};
+
+struct EmptyBracedIntDefault {
+  EmptyBracedIntDefault() : m_i{} {}
+  int m_i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'm_i' [modernize-use-default-member-init]
+  // CHECK-FIXES:  {{^  }}EmptyBracedIntDefault()  {}
+  // CHECK-FIXES-NEXT: {{^  }}int m_i{};
+};
Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -17,6 +17,12 @@
 namespace tidy {
 namespace modernize {
 
+namespace {
+AST_MATCHER_P(InitListExpr, initCountIs, unsigned, N) {
+  return Node.getNumInits() == N;
+}
+} // namespace
+
 static StringRef getValueOfValueInit(const QualType InitType) {
   switch (InitType->getScalarTypeKind()) {
   case Type::STK_CPointer:
@@ -190,7 +196,7 @@
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
-  auto Init =
+  auto InitBase =
   anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(integerLiteral())),
@@ -198,7 +204,13 @@
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(floatLiteral())),
 cxxBoolLiteral(), c

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

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

- Address nits


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77085

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

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -1,6 +1,8 @@
 #include "ClangTidyOptions.h"
-#include "gtest/gtest.h"
+#include "ClangTidyCheck.h"
+#include "ClangTidyDiagnosticConsumer.h"
 #include "llvm/ADT/StringExtras.h"
+#include "gtest/gtest.h"
 
 namespace clang {
 namespace tidy {
@@ -97,6 +99,155 @@
 llvm::join(Options.ExtraArgsBefore->begin(),
Options.ExtraArgsBefore->end(), ","));
 }
+
+class TestCheck : public ClangTidyCheck {
+public:
+  TestCheck(ClangTidyContext *Context) : ClangTidyCheck("test", Context) {}
+
+  template  auto getLocal(Args &&... Arguments) {
+return Options.get(std::forward(Arguments)...);
+  }
+
+  template  auto getGlobal(Args &&... Arguments) {
+return Options.getLocalOrGlobal(std::forward(Arguments)...);
+  }
+
+  template 
+  auto getIntLocal(Args &&... Arguments) {
+return Options.get(std::forward(Arguments)...);
+  }
+
+  template 
+  auto getIntGlobal(Args &&... Arguments) {
+return Options.getLocalOrGlobal(std::forward(Arguments)...);
+  }
+};
+
+#define CHECK_VAL(Value, Expected) \
+  do { \
+auto Item = Value; \
+ASSERT_TRUE(!!Item);   \
+EXPECT_EQ(*Item, Expected);\
+  } while (false)
+
+#define CHECK_ERROR(Value, ErrorType, ExpectedMessage) \
+  do { \
+auto Item = Value; \
+ASSERT_FALSE(Item);\
+ASSERT_TRUE(Item.errorIsA());   \
+ASSERT_FALSE(llvm::handleErrors(   \
+Item.takeError(), [&](const ErrorType &Err) -> llvm::Error {   \
+  EXPECT_EQ(Err.message(), ExpectedMessage);   \
+  return llvm::Error::success();   \
+}));   \
+  } while (false)
+
+TEST(CheckOptionsValidation, MissingOptions) {
+  ClangTidyOptions Options;
+  ClangTidyContext Context(std::make_unique(
+  ClangTidyGlobalOptions(), Options));
+  TestCheck TestCheck(&Context);
+  CHECK_ERROR(TestCheck.getLocal("Opt"), MissingOptionError,
+  "option not found 'test.Opt'");
+  EXPECT_EQ(TestCheck.getLocal("Opt", "Unknown"), "Unknown");
+}
+
+TEST(CheckOptionsValidation, ValidIntOptions) {
+  ClangTidyOptions Options;
+  auto &CheckOptions = Options.CheckOptions;
+  CheckOptions["test.IntExpected1"] = "1";
+  CheckOptions["test.IntExpected2"] = "1WithMore";
+  CheckOptions["test.IntExpected3"] = "NoInt";
+  CheckOptions["GlobalIntExpected1"] = "1";
+  CheckOptions["GlobalIntExpected2"] = "NoInt";
+  CheckOptions["test.DefaultedIntInvalid"] = "NoInt";
+  CheckOptions["GlobalIntInvalid"] = "NoInt";
+
+  ClangTidyContext Context(std::make_unique(
+  ClangTidyGlobalOptions(), Options));
+  TestCheck TestCheck(&Context);
+
+#define CHECK_ERROR_INT(Name, Expected)\
+  CHECK_ERROR(Name, UnparseableIntegerOptionError, Expected)
+
+  CHECK_VAL(TestCheck.getIntLocal("IntExpected1"), 1);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalIntExpected1"), 1);
+  CHECK_ERROR_INT(TestCheck.getIntLocal("IntExpected2"),
+  "invalid configuration value '1WithMore' for option "
+  "'test.IntExpected2'; expected an integer value");
+  CHECK_ERROR_INT(TestCheck.getIntLocal("IntExpected3"),
+  "invalid configuration value 'NoInt' for option "
+  "'test.IntExpected3'; expected an integer value");
+  CHECK_ERROR_INT(TestCheck.getIntGlobal("GlobalIntExpected2"),
+  "invalid configuration value 'NoInt' for option "
+  "'GlobalIntExpected2'; expected an integer value");
+  ASSERT_EQ(TestCheck.getIntLocal("DefaultedIntInvalid", 1), 1);
+  ASSERT_EQ(TestCheck.getIntGlobal("GlobalIntInvalid", 1), 1);
+
+#undef CHECK_ERROR_INT
+}
+
+TEST(ValidConfiguration, ValidEnumOptions) {
+
+  en

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

2020-04-03 Thread Nathan James via Phabricator via cfe-commits
njames93 marked 8 inline comments as done.
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/ClangTidyCheck.cpp:25
+  llvm::raw_svector_ostream Output(Buffer);
+  Output << "warning: Option not found '" << OptionName << "'\n";
+  return std::string(Buffer);

aaron.ballman wrote:
> aaron.ballman wrote:
> > I think the diagnostic text should probably not start with a capital 
> > letter. Also, the name of the classes are confusing in that they say error 
> > but the diagnostic is a warning. When I hear "error", the class name makes 
> > me think this would stop compilation and give a nonzero result code from 
> > the program.
> Sorry, I was unclear with what I was looking for.
> 
> It looks to me like the behavior of `OptionError` is to act more like a 
> warning than an error in that a message is printed and execution of the tool 
> continues, correct? If so, then I'd prefer to rename it to `OptionWarning` 
> (unless you want to generalize it to be either a warning or an error with a 
> return code, then `OptionDiagnostic` would be good), and all the subclasses 
> to be `FooWarning`. Or did I misunderstand the design?
> 
> Also, I like having the `warning:` in the message (though we could bikeshed 
> if we want to make it look less like a check warning by doing something like 
> `warning [clang-tidy command line]:`), but maybe that's being added by 
> `OptionsView::logErrToStdErr()`?
`OptionError` is just there for convenience to avoid having to retype the `log` 
and `convertToErrorCode` function. Arguably, the `MissingOptionError` isn't 
really an error, but the `UnparseableEnumOptionError` and 
`UnparseableIntegerOptionError` should be classed as errors.

From what it seems with other errors, the message function shouldn't contain a 
`warning:` or `error:` prefix, instead that now gets added in 
`OptionsView::logErrToStdErr`. The output for enumerations looks like 
```
warning: invalid configuration value 'camelback' for option 
'readability-identifier-naming.FunctionCase'; did you mean 'camelBack'?```

I do think down the line this should be actually handled as a 
`ClangTidyDiagnostic` however that is a much larger change to implement given 
how diagnostics are currently handled.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77085



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


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

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

I added support for bools. The previous integer parsing behaviour is still 
there, however now it also responds to `true` or `false`.
This won't parse `True|TRUE|False|FALSE` etc as I wanted it to be in line with 
`.clang-format` configuration files for handling of bool.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77085



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


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

2020-04-04 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 255023.
njames93 added a comment.

- Extended support for boolean types


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D77085

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

Index: clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp
@@ -1,6 +1,8 @@
 #include "ClangTidyOptions.h"
-#include "gtest/gtest.h"
+#include "ClangTidyCheck.h"
+#include "ClangTidyDiagnosticConsumer.h"
 #include "llvm/ADT/StringExtras.h"
+#include "gtest/gtest.h"
 
 namespace clang {
 namespace tidy {
@@ -97,6 +99,172 @@
 llvm::join(Options.ExtraArgsBefore->begin(),
Options.ExtraArgsBefore->end(), ","));
 }
+
+class TestCheck : public ClangTidyCheck {
+public:
+  TestCheck(ClangTidyContext *Context) : ClangTidyCheck("test", Context) {}
+
+  template  auto getLocal(Args &&... Arguments) {
+return Options.get(std::forward(Arguments)...);
+  }
+
+  template  auto getGlobal(Args &&... Arguments) {
+return Options.getLocalOrGlobal(std::forward(Arguments)...);
+  }
+
+  template 
+  auto getIntLocal(Args &&... Arguments) {
+return Options.get(std::forward(Arguments)...);
+  }
+
+  template 
+  auto getIntGlobal(Args &&... Arguments) {
+return Options.getLocalOrGlobal(std::forward(Arguments)...);
+  }
+};
+
+#define CHECK_VAL(Value, Expected) \
+  do { \
+auto Item = Value; \
+ASSERT_TRUE(!!Item);   \
+EXPECT_EQ(*Item, Expected);\
+  } while (false)
+
+#define CHECK_ERROR(Value, ErrorType, ExpectedMessage) \
+  do { \
+auto Item = Value; \
+ASSERT_FALSE(Item);\
+ASSERT_TRUE(Item.errorIsA());   \
+ASSERT_FALSE(llvm::handleErrors(   \
+Item.takeError(), [&](const ErrorType &Err) -> llvm::Error {   \
+  EXPECT_EQ(Err.message(), ExpectedMessage);   \
+  return llvm::Error::success();   \
+}));   \
+  } while (false)
+
+TEST(CheckOptionsValidation, MissingOptions) {
+  ClangTidyOptions Options;
+  ClangTidyContext Context(std::make_unique(
+  ClangTidyGlobalOptions(), Options));
+  TestCheck TestCheck(&Context);
+  CHECK_ERROR(TestCheck.getLocal("Opt"), MissingOptionError,
+  "option not found 'test.Opt'");
+  EXPECT_EQ(TestCheck.getLocal("Opt", "Unknown"), "Unknown");
+}
+
+TEST(CheckOptionsValidation, ValidIntOptions) {
+  ClangTidyOptions Options;
+  auto &CheckOptions = Options.CheckOptions;
+  CheckOptions["test.IntExpected1"] = "1";
+  CheckOptions["test.IntExpected2"] = "1WithMore";
+  CheckOptions["test.IntExpected3"] = "NoInt";
+  CheckOptions["GlobalIntExpected1"] = "1";
+  CheckOptions["GlobalIntExpected2"] = "NoInt";
+  CheckOptions["test.DefaultedIntInvalid"] = "NoInt";
+  CheckOptions["GlobalIntInvalid"] = "NoInt";
+  CheckOptions["test.BoolITrueValue"] = "1";
+  CheckOptions["test.BoolIFalseValue"] = "0";
+  CheckOptions["test.BoolTrueValue"] = "true";
+  CheckOptions["test.BoolFalseValue"] = "false";
+  CheckOptions["test.BoolUnparseable"] = "Nothing";
+  CheckOptions["test.BoolCaseMismatch"] = "True";
+
+  ClangTidyContext Context(std::make_unique(
+  ClangTidyGlobalOptions(), Options));
+  TestCheck TestCheck(&Context);
+
+#define CHECK_ERROR_INT(Name, Expected)\
+  CHECK_ERROR(Name, UnparseableIntegerOptionError, Expected)
+
+  CHECK_VAL(TestCheck.getIntLocal("IntExpected1"), 1);
+  CHECK_VAL(TestCheck.getIntGlobal("GlobalIntExpected1"), 1);
+  CHECK_ERROR_INT(TestCheck.getIntLocal("IntExpected2"),
+  "invalid configuration value '1WithMore' for option "
+  "'test.IntExpected2'; expected an integer value");
+  CHECK_ERROR_INT(TestCheck.getIntLocal("IntExpected3"),
+  "invalid configuration value 'NoInt' for option "
+  "'test.IntExpected3'; expected an integer value");
+  CHECK_ERROR_INT(TestCheck.getIntGlobal("GlobalIntExpected2"),
+  "invalid configura

  1   2   3   4   5   6   7   8   9   10   >