[clang-tools-extra] [clangd] Use InitLLVM (PR #69119)

2023-11-12 Thread Aleksandr Platonov via cfe-commits

https://github.com/ArcsinX closed 
https://github.com/llvm/llvm-project/pull/69119
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Use InitLLVM (PR #69119)

2023-10-27 Thread Aleksandr Platonov via cfe-commits

ArcsinX wrote:

Friendly ping

https://github.com/llvm/llvm-project/pull/69119
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][index] Fix processing of CompoundAssignOperator at setting up reference roles (PR #69370)

2023-10-19 Thread Aleksandr Platonov via cfe-commits

https://github.com/ArcsinX closed 
https://github.com/llvm/llvm-project/pull/69370
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][index] Fix processing of CompoundAssignOperator at setting up reference roles (PR #69370)

2023-10-19 Thread Aleksandr Platonov via cfe-commits


@@ -77,9 +77,15 @@ class BodyIndexer : public RecursiveASTVisitor {
 const Stmt *Parent = *It;
 
 if (auto BO = dyn_cast(Parent)) {
-  if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == 
E)
-Roles |= (unsigned)SymbolRole::Write;
-
+  if (BO->getOpcode() == BO_Assign) {
+if (BO->getLHS()->IgnoreParenCasts() == E)

ArcsinX wrote:

I split this `if` to avoid this check `else if (auto CA = 
dyn_cast(Parent))`  if `BO->getOpcode() == BO_Assign && 
BO->getLHS()->IgnoreParenCasts() != E`

I.e. if `BO->getOpcode() == BO_Assign` then `Parent` is not a  
`CompoundAssignOperator` and we don't need to check this

https://github.com/llvm/llvm-project/pull/69370
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][index] Fix processing of CompoundAssignOperator at setting up reference roles (PR #69370)

2023-10-17 Thread Aleksandr Platonov via cfe-commits

https://github.com/ArcsinX created 
https://github.com/llvm/llvm-project/pull/69370

Without this patch in expressions like `foo += 1` reference `foo` has no read 
and write roles.

This happens because `CompoundAssignOperator` is also a `BinaryOperator`, thus 
handling `CompoindAssignOperator` in `else` branch is a dead code.

>From 849d366ae5824d7b072fcb28ecad0138dade6324 Mon Sep 17 00:00:00 2001
From: Aleksandr Platonov 
Date: Tue, 17 Oct 2023 21:44:10 +0300
Subject: [PATCH] [clang][index] Fix processing of CompoundAssignOperator at
 setting up reference roles

Without this patch in expressions like `foo += 1` reference `foo` has no read 
and write roles.

This happens because `CompoundAssignOperator` is also a `BinaryOperator`, thus 
handling `CompoindAssignOperator` in `else` branch is a dead code.
---
 clang/lib/Index/IndexBody.cpp| 18 +-
 clang/unittests/Index/IndexTests.cpp | 25 +
 2 files changed, 34 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Index/IndexBody.cpp b/clang/lib/Index/IndexBody.cpp
index e88f321f18a7129..08136baa5d408e9 100644
--- a/clang/lib/Index/IndexBody.cpp
+++ b/clang/lib/Index/IndexBody.cpp
@@ -77,9 +77,15 @@ class BodyIndexer : public RecursiveASTVisitor {
 const Stmt *Parent = *It;
 
 if (auto BO = dyn_cast(Parent)) {
-  if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == 
E)
-Roles |= (unsigned)SymbolRole::Write;
-
+  if (BO->getOpcode() == BO_Assign) {
+if (BO->getLHS()->IgnoreParenCasts() == E)
+  Roles |= (unsigned)SymbolRole::Write;
+  } else if (auto CA = dyn_cast(Parent)) {
+if (CA->getLHS()->IgnoreParenCasts() == E) {
+  Roles |= (unsigned)SymbolRole::Read;
+  Roles |= (unsigned)SymbolRole::Write;
+}
+  }
 } else if (auto UO = dyn_cast(Parent)) {
   if (UO->isIncrementDecrementOp()) {
 Roles |= (unsigned)SymbolRole::Read;
@@ -88,12 +94,6 @@ class BodyIndexer : public RecursiveASTVisitor {
 Roles |= (unsigned)SymbolRole::AddressOf;
   }
 
-} else if (auto CA = dyn_cast(Parent)) {
-  if (CA->getLHS()->IgnoreParenCasts() == E) {
-Roles |= (unsigned)SymbolRole::Read;
-Roles |= (unsigned)SymbolRole::Write;
-  }
-
 } else if (auto CE = dyn_cast(Parent)) {
   if (CE->getCallee()->IgnoreParenCasts() == E) {
 addCallRole(Roles, Relations);
diff --git a/clang/unittests/Index/IndexTests.cpp 
b/clang/unittests/Index/IndexTests.cpp
index 4d19f47283c2853..8e9a1c6bf88245c 100644
--- a/clang/unittests/Index/IndexTests.cpp
+++ b/clang/unittests/Index/IndexTests.cpp
@@ -428,6 +428,31 @@ TEST(IndexTest, NonTypeTemplateParameter) {
  WrittenAt(Position(3, 15);
 }
 
+TEST(IndexTest, ReadWriteRoles) {
+  std::string Code = R"cpp(
+int main() {
+  int foo = 0;
+  foo = 2;
+  foo += 1;
+  int bar = foo;
+  }
+  )cpp";
+  auto Index = std::make_shared();
+  IndexingOptions Opts;
+  Opts.IndexFunctionLocals = true;
+  tooling::runToolOnCode(std::make_unique(Index, Opts), Code);
+  EXPECT_THAT(
+  Index->Symbols,
+  AllOf(Contains(AllOf(QName("foo"), HasRole(SymbolRole::Write),
+   WrittenAt(Position(4, 7,
+Contains(AllOf(QName("foo"),
+   HasRole(static_cast(SymbolRole::Read) |
+   static_cast(SymbolRole::Write)),
+   WrittenAt(Position(5, 7,
+Contains(AllOf(QName("foo"), HasRole(SymbolRole::Read),
+   WrittenAt(Position(6, 17));
+}
+
 } // namespace
 } // namespace index
 } // namespace clang

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


[clang-tools-extra] [clangd] Use InitLLVM (PR #69119)

2023-10-15 Thread Aleksandr Platonov via cfe-commits

https://github.com/ArcsinX created 
https://github.com/llvm/llvm-project/pull/69119

This patch is similar to a7acba29c19ac67c77ed282ec9432602ae21268d but for 
clangd.

It allows to pass non-UTF8 encoded command line arguments (e.g. path where 
compile-commands.json file is located) on Windows.

>From e64a5fa3cc13aaba1ff7f8be503707cb52ac8356 Mon Sep 17 00:00:00 2001
From: Aleksandr Platonov 
Date: Sun, 15 Oct 2023 21:39:28 +0300
Subject: [PATCH] [clangd] Use InitLLVM

This patch is similar to a7acba29c19ac67c77ed282ec9432602ae21268d but for 
clangd.
It allows to pass non-UTF8 encoded command line arguments (e.g. path where 
compile-commands.json file is located) on Windows.
---
 clang-tools-extra/clangd/tool/ClangdMain.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp 
b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index f656a8c587c6533..9fd002d0eebba5f 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -35,6 +35,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
@@ -714,8 +715,8 @@ int clangdMain(int argc, char *argv[]) {
   // Clang could run on the main thread. e.g., when the flag '-check' or 
'-sync'
   // is enabled.
   clang::noteBottomOfStack();
+  llvm::InitLLVM X(argc, argv);
   llvm::InitializeAllTargetInfos();
-  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   llvm::sys::AddSignalHandler(
   [](void *) {
 ThreadCrashReporter::runCrashHandlers();

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


[clang] 5a42c90 - [clang] Make variables of undeduced types to have dependent alignment

2022-10-07 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-10-07T20:40:03+08:00
New Revision: 5a42c90b778c65238a54f0f1d8c8d6b35e2f6007

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

LOG: [clang] Make variables of undeduced types to have dependent alignment

Without this patch `VarDecl::hasDependent()` checks only undeduced auto types, 
so can give false negatives result for other undeduced types.
This lead to crashes in sequence `!VarDecl::hasDepentent()` => `getDeclAlign()`.

It seems this problem appeared since D105380

Reviewed By: mizvekov

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

Added: 


Modified: 
clang/lib/AST/Decl.cpp
clang/test/Sema/tls_alignment.cpp

Removed: 




diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 49ad2230e7ca0..b326933b1d7d1 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -2581,7 +2581,7 @@ bool VarDecl::isNonEscapingByref() const {
 
 bool VarDecl::hasDependentAlignment() const {
   QualType T = getType();
-  return T->isDependentType() || T->isUndeducedAutoType() ||
+  return T->isDependentType() || T->isUndeducedType() ||
  llvm::any_of(specific_attrs(), [](const AlignedAttr *AA) 
{
return AA->isAlignmentDependent();
  });

diff  --git a/clang/test/Sema/tls_alignment.cpp 
b/clang/test/Sema/tls_alignment.cpp
index 5a7bb2c463f37..18db565055d0e 100644
--- a/clang/test/Sema/tls_alignment.cpp
+++ b/clang/test/Sema/tls_alignment.cpp
@@ -1,6 +1,6 @@
 // TLS variable cannot be aligned to more than 32 bytes on PS4.
 
-// RUN: %clang_cc1 -triple x86_64-scei-ps4 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4 -std=c++17 -fsyntax-only -verify %s
 
 
 // A non-aligned type.
@@ -18,6 +18,12 @@ struct  struct_with_aligned_field {
 int some_aligned_data[12] __attribute__(( aligned(64) )); // 48 bytes of 
stuff, aligned to 64.
 };
 
+// A templated type
+template 
+struct templated_struct {};
+// expected-note@-1{{candidate template ignored: couldn't infer template 
argument ''}}
+// expected-note@-2{{candidate function template not viable: requires 1 
argument, but 0 were provided}}
+
 // A typedef of the aligned struct.
 typedef aligned_struct another_aligned_struct;
 
@@ -42,6 +48,9 @@ __thread another_aligned_structbar4; // 
expected-error{{alignment (6
 // Variable aligned because of typedef, second case.
 __thread yet_another_aligned_structbar5; // expected-error{{alignment 
(64) of thread-local variable}}
 
+// No crash for undeduced type.
+__thread templated_struct  bar6; // expected-error{{no viable 
constructor or deduction guide for deduction of template arguments of 
'templated_struct'}}
+
 int baz ()
 {
 return foo.some_data[0] + bar.some_data[1] + bar2.some_data[2] +



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


[clang] 3ce7d25 - [clang][RecoveryExpr] Don't perform alignment check if parameter type is dependent

2022-09-15 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-09-15T15:51:43+03:00
New Revision: 3ce7d256f2d7f64d57ccbfd7935d55eafc639314

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

LOG: [clang][RecoveryExpr] Don't perform alignment check if parameter type is 
dependent

This patch fixes a crash which appears because of getTypeAlignInChars() call 
with depentent type.

Reviewed By: hokein

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

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp
clang/test/SemaCXX/recovery-expr-type.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index bc9642d17d852..e419287014893 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -5690,9 +5690,9 @@ void Sema::CheckArgAlignment(SourceLocation Loc, 
NamedDecl *FDecl,
 
   // Find expected alignment, and the actual alignment of the passed object.
   // getTypeAlignInChars requires complete types
-  if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
-  ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
-  ArgTy->isUndeducedType())
+  if (ArgTy.isNull() || ParamTy->isDependentType() ||
+  ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
+  ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
 return;
 
   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);

diff  --git a/clang/test/SemaCXX/recovery-expr-type.cpp 
b/clang/test/SemaCXX/recovery-expr-type.cpp
index df6f4b69763c7..a5ba1ae2b8222 100644
--- a/clang/test/SemaCXX/recovery-expr-type.cpp
+++ b/clang/test/SemaCXX/recovery-expr-type.cpp
@@ -162,3 +162,12 @@ extern "C" void *memset(void *, int b, unsigned long) {
   b = __builtin_object_size(c, 0); // crash2
 }
 }
+
+namespace test15 {
+void f() {
+  struct {
+void m(int (&)[undefined()]) {} // expected-error {{undeclared identifier}}
+  } S;
+  S.m(1); // no crash
+}
+}



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


[clang-tools-extra] cc4b86c - [clangd] Fix tests for implicit C function declaration

2022-09-01 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-09-01T23:46:20+03:00
New Revision: cc4b86cfc01c3a923324c4bf1485ae9c8021e0a1

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

LOG: [clangd] Fix tests for implicit C function declaration

clangd code fixes at D122983 were not right.
We need to check that clangd provides IncludeFixer fixits for implicit function 
declaration even if this is not an error (e.g. implicit function declaration in 
C89).

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index cf4c57e6e871b..50923c862c583 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -493,6 +493,7 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs ,
 // We restore the original severity in the level adjuster.
 // FIXME: It would be better to have a real API for this, but what?
 for (auto ID : {diag::ext_implicit_function_decl_c99,
+diag::ext_implicit_lib_function_decl,
 diag::ext_implicit_lib_function_decl_c99,
 diag::warn_implicit_function_decl}) {
   OverriddenSeverity.try_emplace(

diff  --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp 
b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
index 306c8b1221093..0727fff464303 100644
--- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1465,11 +1465,12 @@ TEST(IncludeFixerTest, NoCrashOnTemplateInstantiations) 
{
 TEST(IncludeFixerTest, HeaderNamedInDiag) {
   Annotations Test(R"cpp(
 $insert[[]]int main() {
-  [[printf]](""); // error-ok
+  [[printf]]("");
 }
   )cpp");
   auto TU = TestTU::withCode(Test.code());
-  TU.ExtraArgs = {"-xc"};
+  TU.ExtraArgs = {"-xc", "-std=c99",
+  "-Wno-error=implicit-function-declaration"};
   auto Index = buildIndexWithSymbol({});
   TU.ExternalIndex = Index.get();
 
@@ -1482,13 +1483,22 @@ TEST(IncludeFixerTest, HeaderNamedInDiag) {
  "declarations"),
   withFix(Fix(Test.range("insert"), "#include \n",
   "Include  for symbol printf");
+
+  TU.ExtraArgs = {"-xc", "-std=c89"};
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(), "implicitly declaring library function 'printf' "
+ "with type 'int (const char *, ...)'"),
+  withFix(Fix(Test.range("insert"), "#include \n",
+  "Include  for symbol printf");
 }
 
 TEST(IncludeFixerTest, CImplicitFunctionDecl) {
-  Annotations Test("void x() { [[foo]](); /* error-ok */ }");
+  Annotations Test("void x() { [[foo]](); }");
   auto TU = TestTU::withCode(Test.code());
   TU.Filename = "test.c";
-  TU.ExtraArgs.push_back("-std=c99");
+  TU.ExtraArgs = {"-std=c99", "-Wno-error=implicit-function-declaration"};
 
   Symbol Sym = func("foo");
   Sym.Flags |= Symbol::IndexedForCodeCompletion;
@@ -1509,6 +1519,13 @@ TEST(IncludeFixerTest, CImplicitFunctionDecl) {
"support implicit function declarations"),
   withFix(Fix(Range{}, "#include \"foo.h\"\n",
   "Include \"foo.h\" for symbol foo");
+
+  TU.ExtraArgs = {"-std=c89", "-Wall"};
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(), "implicit declaration of function 'foo'"),
+  withFix(Fix(Range{}, "#include \"foo.h\"\n",
+  "Include \"foo.h\" for symbol foo");
 }
 
 TEST(DiagsInHeaders, DiagInsideHeader) {



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


[clang-tools-extra] ee648c0 - [clang][index] Index unresolved member expression as reference

2022-08-19 Thread Aleksandr Platonov via cfe-commits

Author: Denis Fatkulin
Date: 2022-08-19T19:02:42+03:00
New Revision: ee648c0ce09b1edcee65407041eab38228f4b042

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

LOG: [clang][index] Index unresolved member expression as reference

Unresolved member expressions aren't indexed as references.

Example code:

```
struct Foo {
  template  void bar(T t);
};
template  void test(Foo F, T t) {
  F.bar(t); // Not indexed
}
```

Reviewed By: hokein

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/XRefsTests.cpp
clang/lib/Index/IndexBody.cpp
clang/test/Index/Core/index-dependent-source.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 40650c36046cb..e9e6b6f79a2d5 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2090,6 +2090,14 @@ TEST(FindReferences, WithinAST) {
   [[f^oo]](s);
 }
   )cpp",
+  R"cpp(// unresolved member expression
+struct Foo {
+  template  void $decl[[b^ar]](T t); 
+};
+template  void test(Foo F, T t) {
+  F.[[bar]](t);
+}
+  )cpp",
 
   // Enum base
   R"cpp(

diff  --git a/clang/lib/Index/IndexBody.cpp b/clang/lib/Index/IndexBody.cpp
index eb8905a7459cd..8b8235c133023 100644
--- a/clang/lib/Index/IndexBody.cpp
+++ b/clang/lib/Index/IndexBody.cpp
@@ -468,7 +468,7 @@ class BodyIndexer : public RecursiveASTVisitor 
{
 return true;
   }
 
-  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+  bool VisitOverloadExpr(OverloadExpr *E) {
 SmallVector Relations;
 SymbolRoleSet Roles = getRolesForRef(E, Relations);
 for (auto *D : E->decls())

diff  --git a/clang/test/Index/Core/index-dependent-source.cpp 
b/clang/test/Index/Core/index-dependent-source.cpp
index 8832edefd5bf9..8fec9abd1e926 100644
--- a/clang/test/Index/Core/index-dependent-source.cpp
+++ b/clang/test/Index/Core/index-dependent-source.cpp
@@ -231,3 +231,12 @@ template  void bar() {
   foo();
 // CHECK: [[@LINE-1]]:3 | function/C | foo | c:@FT@>1#Tfoo#v# |  | 
Ref,Call,RelCall,RelCont | rel: 1
 }
+
+struct Foo {
+  template  void bar();
+  // CHECK: [[@LINE-1]]:30 | instance-method/C++ | bar | 
c:@S@Foo@FT@>1#Tbar#v# |  | Decl,RelChild | rel: 1
+};
+template  void baz(Foo f) {
+  f.bar();
+  // CHECK: [[@LINE-1]]:5 | instance-method/C++ | bar | c:@S@Foo@FT@>1#Tbar#v# 
|  | Ref,Call,RelCall,RelCont | rel: 1
+}



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


[clang-tools-extra] 42ee0d8 - [clangd][unittests][IncludeCleaner] Don't call findReferencedFiles() if the result is not used

2022-08-12 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-08-12T21:00:11+03:00
New Revision: 42ee0d8c16f7052c3bc8434325868f48a501baf2

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

LOG: [clangd][unittests][IncludeCleaner] Don't call findReferencedFiles() if 
the result is not used

IncludeCleaner.RecursiveInclusion and IncludeCleaner.IWYUPragmaExport tests 
don't check referenced files list, so we don't need to call 
findReferencedFiles() there.

Reviewed By: kbobyrev

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp 
b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
index 527db2a5d2193..d79f1219511f8 100644
--- a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -571,9 +571,6 @@ TEST(IncludeCleaner, RecursiveInclusion) {
   )cpp");
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles = findReferencedFiles(
-  findReferencedLocations(AST), AST.getIncludeStructure(),
-  AST.getCanonicalIncludes(), AST.getSourceManager());
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
   EXPECT_THAT(computeUnusedIncludes(AST), IsEmpty());
 }
@@ -596,9 +593,6 @@ TEST(IncludeCleaner, IWYUPragmaExport) {
   )cpp");
   ParsedAST AST = TU.build();
 
-  auto ReferencedFiles = findReferencedFiles(
-  findReferencedLocations(AST), AST.getIncludeStructure(),
-  AST.getCanonicalIncludes(), AST.getSourceManager());
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
   // FIXME: This is not correct: foo.h is unused but is not diagnosed as such
   // because we ignore headers with IWYU export pragmas for now.



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


[clang] 4977fd2 - [clang-format] Missing space between trailing return type 'auto' and left brace

2022-07-28 Thread Aleksandr Platonov via cfe-commits

Author: Denis Fatkulin
Date: 2022-07-29T00:30:22+03:00
New Revision: 4977fd2192fc13e17ea162da15ddbe17cd623757

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

LOG: [clang-format] Missing space between trailing return type 'auto' and left 
brace

There's no a space symbol between  trailing return type `auto` and left brace 
`{`.

The simpliest examles of code to reproduce the issue:

```
[]() -> auto {}
```

and

```
auto foo() -> auto {}
```

Depends on D130299

Reviewed By: HazardyKnusperkeks, curdeius, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5991cf23d5dc7..6b65b69caa09a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3310,6 +3310,11 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine ,
 }
   }
 
+  // trailing return type 'auto': []() -> auto {}, auto foo() -> auto {}
+  if (Left.is(tok::kw_auto) &&
+  Right.isOneOf(TT_LambdaLBrace, TT_FunctionLBrace))
+return true;
+
   // auto{x} auto(x)
   if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace))
 return false;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index e26cfb0ee88a0..d15c38f291ac2 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -23550,6 +23550,16 @@ TEST_F(FormatTest, AmbersandInLamda) {
   verifyFormat("auto lambda = [ = a]() { a = 2; };", AlignStyle);
 }
 
+TEST_F(FormatTest, TrailingReturnTypeAuto) {
+  FormatStyle Style = getLLVMStyle();
+  verifyFormat("[]() -> auto { return Val; }", Style);
+  verifyFormat("[]() -> auto * { return Val; }", Style);
+  verifyFormat("[]() -> auto & { return Val; }", Style);
+  verifyFormat("auto foo() -> auto { return Val; }", Style);
+  verifyFormat("auto foo() -> auto * { return Val; }", Style);
+  verifyFormat("auto foo() -> auto & { return Val; }", Style);
+}
+
 TEST_F(FormatTest, SpacesInConditionalStatement) {
   FormatStyle Spaces = getLLVMStyle();
   Spaces.IfMacros.clear();



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


[clang] 17fb879 - [clang-format] FIX: Misannotation 'auto' as trailing return type in lambdas

2022-07-27 Thread Aleksandr Platonov via cfe-commits

Author: Denis Fatkulin
Date: 2022-07-27T22:20:09+03:00
New Revision: 17fb879764dcaf1f5f6bc505c5c747067ba7c3cd

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

LOG: [clang-format] FIX: Misannotation 'auto' as trailing return type in lambdas

Lambdas with trailing return type 'auto' are annotated incorrectly. It causes a 
misformatting. The simpliest code to reproduce is:

```
auto list = {[]() -> auto { return 0; }};
```

Fixes https://github.com/llvm/llvm-project/issues/54798

Reviewed By: HazardyKnusperkeks, owenpan, curdeius

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 83b4f1e7991f8..b936f73d70fa7 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2108,6 +2108,7 @@ bool UnwrappedLineParser::tryToParseLambda() {
 case tok::l_square:
   parseSquare();
   break;
+case tok::kw_auto:
 case tok::kw_class:
 case tok::kw_template:
 case tok::kw_typename:

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 4b2622522e0f8..b2c50aaea6d79 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -747,6 +747,21 @@ TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   ASSERT_EQ(Tokens.size(), 8u) << Tokens;
   EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);
   EXPECT_TOKEN(Tokens[5], tok::l_brace, TT_LambdaLBrace);
+
+  Tokens = annotate("[]() -> auto {}");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_LambdaArrow);
+  EXPECT_TOKEN(Tokens[6], tok::l_brace, TT_LambdaLBrace);
+
+  Tokens = annotate("[]() -> auto & {}");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_LambdaArrow);
+  EXPECT_TOKEN(Tokens[7], tok::l_brace, TT_LambdaLBrace);
+
+  Tokens = annotate("[]() -> auto * {}");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_LambdaArrow);
+  EXPECT_TOKEN(Tokens[7], tok::l_brace, TT_LambdaLBrace);
 }
 
 } // namespace



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


[clang] b2c3ae0 - [Sema] Don't check bounds for function pointer

2022-04-13 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-04-13T20:39:38+03:00
New Revision: b2c3ae0b6f05fd0c2184aea82637685a13b8dc4f

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

LOG: [Sema] Don't check bounds for function pointer

Currently, clang crashes with i386 target on the following code:
```
void f() {
  f + 0xdeadUL;
}
```
This problem is similar to the problem fixed in D104424, but that fix can't 
handle function pointer case, because `getTypeSizeInCharsIfKnown()` says that 
size is known and equal to 0 for function type.

This patch prevents bounds checking for function pointer, thus fixes the crash.

Fixes https://github.com/llvm/llvm-project/issues/50463

Reviewed By: erichkeane

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

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/unbounded-array-bounds.c

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 9331d169f800f..03f9b692c0631 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -15495,6 +15495,8 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, const 
Expr *IndexExpr,
 ND = ME->getMemberDecl();
 
   if (IsUnboundedArray) {
+if (EffectiveType->isFunctionType())
+  return;
 if (index.isUnsigned() || !index.isNegative()) {
   const auto  = getASTContext();
   unsigned AddrBits =

diff  --git a/clang/test/Sema/unbounded-array-bounds.c 
b/clang/test/Sema/unbounded-array-bounds.c
index e7636c2a9249f..01463158418c6 100644
--- a/clang/test/Sema/unbounded-array-bounds.c
+++ b/clang/test/Sema/unbounded-array-bounds.c
@@ -80,3 +80,7 @@ void pr50741(void) {
   (void *)0 + 0xdeadUL;
   // no array-bounds warning, and no crash
 }
+
+void func() {
+  func + 0xdeadUL; // no crash
+}



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


[clang] 1bb13b3 - Fix sphinx build because of indentation

2022-03-15 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-03-16T00:11:56+03:00
New Revision: 1bb13b3f4956370afc01a8a9315dabed8c09a2cd

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

LOG: Fix sphinx build because of indentation

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ed79b647ed794..a0e3cabe89a9a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -95,6 +95,7 @@ Attribute Changes in Clang
   This fixes `Issue 53805 
`_.
 
 - Improved namespace attributes handling:
+
   - Handle GNU attributes before a namespace identifier and subsequent
 attributes of 
diff erent kinds.
   - Emit error on GNU attributes for a nested namespace definition.



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


[clang] 8bd0055 - [clang][parser] Allow GNU attributes before namespace identifier

2022-03-15 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-03-15T22:30:22+03:00
New Revision: 8bd00557e3f43b46a96cf0e357d5e65624c85a2b

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

LOG: [clang][parser] Allow GNU attributes before namespace identifier

GCC supports:
- `namespace  identifier`
- `namespace identifier `

But clang supports only `namespace identifier ` and diagnostics 
for `namespace  identifier` case looks unclear:
Code:
```
namespace __attribute__((visibility("hidden"))) A
{
}
```
Diags:
```
test.cpp:1:49: error: expected identifier or '{'
namespace __attribute__((visibility("hidden"))) A
^
test.cpp:1:49: error: C++ requires a type specifier for all declarations
test.cpp:3:2: error: expected ';' after top level declarator
}
```

This patch adds support for `namespace  identifier` and also 
forbids gnu attributes for nested namespaces (this already done for C++ 
attributes).

Reviewed By: aaron.ballman

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

Added: 
clang/test/Parser/namespace-attributes.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Parse/ParseDeclCXX.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2422c8f2cba7a..ed79b647ed794 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -94,6 +94,11 @@ Attribute Changes in Clang
   locations a declaration attribute may appear.
   This fixes `Issue 53805 
`_.
 
+- Improved namespace attributes handling:
+  - Handle GNU attributes before a namespace identifier and subsequent
+attributes of 
diff erent kinds.
+  - Emit error on GNU attributes for a nested namespace definition.
+
 Windows Support
 ---
 

diff  --git a/clang/lib/Parse/ParseDeclCXX.cpp 
b/clang/lib/Parse/ParseDeclCXX.cpp
index 4ac3baba0d689..77fc504ebe462 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -74,15 +74,27 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
   SourceLocation FirstNestedInlineLoc;
 
   ParsedAttributesWithRange attrs(AttrFactory);
-  SourceLocation attrLoc;
-  if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
-Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
-? diag::warn_cxx14_compat_ns_enum_attribute
-: diag::ext_ns_enum_attribute)
-  << 0 /*namespace*/;
-attrLoc = Tok.getLocation();
-ParseCXX11Attributes(attrs);
-  }
+
+  auto ReadAttributes = [&] {
+bool MoreToParse;
+do {
+  MoreToParse = false;
+  if (Tok.is(tok::kw___attribute)) {
+ParseGNUAttributes(attrs);
+MoreToParse = true;
+  }
+  if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
+Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
+? diag::warn_cxx14_compat_ns_enum_attribute
+: diag::ext_ns_enum_attribute)
+<< 0 /*namespace*/;
+ParseCXX11Attributes(attrs);
+MoreToParse = true;
+  }
+} while (MoreToParse);
+  };
+
+  ReadAttributes();
 
   if (Tok.is(tok::identifier)) {
 Ident = Tok.getIdentifierInfo();
@@ -108,16 +120,14 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
 }
   }
 
+  ReadAttributes();
+
+  SourceLocation attrLoc = attrs.Range.getBegin();
+
   // A nested namespace definition cannot have attributes.
   if (!ExtraNSs.empty() && attrLoc.isValid())
 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
 
-  // Read label attributes, if present.
-  if (Tok.is(tok::kw___attribute)) {
-attrLoc = Tok.getLocation();
-ParseGNUAttributes(attrs);
-  }
-
   if (Tok.is(tok::equal)) {
 if (!Ident) {
   Diag(Tok, diag::err_expected) << tok::identifier;

diff  --git a/clang/test/Parser/namespace-attributes.cpp 
b/clang/test/Parser/namespace-attributes.cpp
new file mode 100644
index 0..9f925b742dfeb
--- /dev/null
+++ b/clang/test/Parser/namespace-attributes.cpp
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -std=c++17 -verify %s
+
+namespace __attribute__(()) A
+{
+}
+
+namespace A __attribute__(())
+{
+}
+
+namespace __attribute__(()) [[]] A
+{
+}
+
+namespace [[]] __attribute__(()) A
+{
+}
+
+namespace A __attribute__(()) [[]]
+{
+}
+
+namespace A [[]] __attribute__(())
+{
+}
+
+namespace [[]] A __attribute__(())
+{
+}
+
+namespace __attribute__(()) A [[]]
+{
+}
+
+namespace A::B __attribute__(()) // expected-error{{attributes cannot be 
specified on a nested namespace definition}}
+{
+}
+
+namespace __attribute__(()) A::B // expected-error{{attributes cannot be 
specified on a nested 

[clang] 491c154 - [analyzer] Don't specify PLUGIN_TOOL for analyzer plugins

2022-01-25 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-01-25T23:05:00+03:00
New Revision: 491c154677bcf0fba3c91fdaa7897a48ab605327

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

LOG: [analyzer] Don't specify PLUGIN_TOOL for analyzer plugins

Analyzer plugins explicitly export clang_registerCheckers and 
clang_analyzerAPIVersionString symbols, so we don't need to specify a tool to 
link agains.

Also, without this patch MSVC build fails with cmake flags 
-DLLVM_ENABLE_PLUGINS=On -DCLANG_PLUGINS_SUPPORT=On 
-DLLVM_EXPORT_SYMBOLS_FOR_PLUGINS=On
```
[936/936] Linking CXX shared module bin\SampleAnalyzerPlugin.dll
FAILED: bin/SampleAnalyzerPlugin.dll
cmd.exe /C "cd . && "D:\Program Files\CMake\bin\cmake.exe" -E vs_link_dll 
--intdir=tools\clang\lib\Analysis\plugins\SampleAnalyzer\CMakeFiles\SampleAnalyzerPlugin.dir
 --rc=C:\PROGRA~2\WI3CF2~1\10\bin\100183~1.0\x64\rc.exe 
--mt=C:\PROGRA~2\WI3CF2~1\10\bin\100183~1.0\x64\mt.exe --manifests  -- 
C:\PROGRA~2\MICROS~4\2019\COMMUN~1\VC\Tools\MSVC\1428~1.299\bin\Hostx64\x64\link.exe
 /nologo 
tools\clang\lib\Analysis\plugins\SampleAnalyzer\CMakeFiles\SampleAnalyzerPlugin.dir\MainCallChecker.cpp.obj
  /out:bin\SampleAnalyzerPlugin.dll /implib:lib\SampleAnalyzerPlugin.lib 
/pdb:bin\SampleAnalyzerPlugin.pdb /dll /version:0.0 /machine:x64 
/INCREMENTAL:NO  
/DEF:"D:/work/llvm-project-original/build-plugins/tools/clang/lib/Analysis/plugins/SampleAnalyzer/SampleAnalyzerPlugin.def"
  lib\clang.lib  lib\clangAnalysis.lib  lib\clangAST.lib  
lib\clangStaticAnalyzerCore.lib  lib\clangStaticAnalyzerFrontend.lib  
lib\clangStaticAnalyzerCheckers.lib  lib\clangStaticAnalyzerCore.lib  
lib\clangCrossTU.lib  lib\clangIndex.lib  lib\clangFormat.lib  
lib\clangToolingInclusions.lib  lib\clangFrontend.lib  lib\clangDriver.lib  
version.lib  lib\clangParse.lib  lib\clangSerialization.lib  lib\clangSema.lib  
lib\clangAnalysis.lib  lib\clangEdit.lib  lib\LLVMOption.lib  
lib\clangToolingCore.lib  lib\clangRewrite.lib  lib\clangASTMatchers.lib  
lib\clangAST.lib  lib\clangLex.lib  lib\clangBasic.lib  
lib\LLVMFrontendOpenMP.lib  lib\LLVMScalarOpts.lib  
lib\LLVMAggressiveInstCombine.lib  lib\LLVMInstCombine.lib  
lib\LLVMTransformUtils.lib  lib\LLVMAnalysis.lib  lib\LLVMProfileData.lib  
lib\LLVMDebugInfoDWARF.lib  lib\LLVMObject.lib  lib\LLVMBitReader.lib  
lib\LLVMCore.lib  lib\LLVMRemarks.lib  lib\LLVMBitstreamReader.lib  
lib\LLVMMCParser.lib  lib\LLVMMC.lib  lib\LLVMDebugInfoCodeView.lib  
lib\LLVMTextAPI.lib  lib\LLVMBinaryFormat.lib  lib\LLVMSupport.lib  psapi.lib  
shell32.lib  ole32.lib  uuid.lib  advapi32.lib  delayimp.lib  
-delayload:shell32.dll  -delayload:ole32.dll  lib\LLVMDemangle.lib  
kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib 
oleaut32.lib uuid.lib comdlg32.lib advapi32.lib  && cd ."
LINK: command 
"C:\PROGRA~2\MICROS~4\2019\COMMUN~1\VC\Tools\MSVC\1428~1.299\bin\Hostx64\x64\link.exe
 /nologo 
tools\clang\lib\Analysis\plugins\SampleAnalyzer\CMakeFiles\SampleAnalyzerPlugin.dir\MainCallChecker.cpp.obj
 /out:bin\SampleAnalyzerPlugin.dll /implib:lib\SampleAnalyzerPlugin.lib 
/pdb:bin\SampleAnalyzerPlugin.pdb /dll /version:0.0 /machine:x64 
/INCREMENTAL:NO 
/DEF:D:/work/llvm-project-original/build-plugins/tools/clang/lib/Analysis/plugins/SampleAnalyzer/SampleAnalyzerPlugin.def
 lib\clang.lib lib\clangAnalysis.lib lib\clangAST.lib 
lib\clangStaticAnalyzerCore.lib lib\clangStaticAnalyzerFrontend.lib 
lib\clangStaticAnalyzerCheckers.lib lib\clangStaticAnalyzerCore.lib 
lib\clangCrossTU.lib lib\clangIndex.lib lib\clangFormat.lib 
lib\clangToolingInclusions.lib lib\clangFrontend.lib lib\clangDriver.lib 
version.lib lib\clangParse.lib lib\clangSerialization.lib lib\clangSema.lib 
lib\clangAnalysis.lib lib\clangEdit.lib lib\LLVMOption.lib 
lib\clangToolingCore.lib lib\clangRewrite.lib lib\clangASTMatchers.lib 
lib\clangAST.lib lib\clangLex.lib lib\clangBasic.lib lib\LLVMFrontendOpenMP.lib 
lib\LLVMScalarOpts.lib lib\LLVMAggressiveInstCombine.lib 
lib\LLVMInstCombine.lib lib\LLVMTransformUtils.lib lib\LLVMAnalysis.lib 
lib\LLVMProfileData.lib lib\LLVMDebugInfoDWARF.lib lib\LLVMObject.lib 
lib\LLVMBitReader.lib lib\LLVMCore.lib lib\LLVMRemarks.lib 
lib\LLVMBitstreamReader.lib lib\LLVMMCParser.lib lib\LLVMMC.lib 
lib\LLVMDebugInfoCodeView.lib lib\LLVMTextAPI.lib lib\LLVMBinaryFormat.lib 
lib\LLVMSupport.lib psapi.lib shell32.lib ole32.lib uuid.lib advapi32.lib 
delayimp.lib -delayload:shell32.dll -delayload:ole32.dll lib\LLVMDemangle.lib 
kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib 
oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST 
/MANIFESTFILE:bin\SampleAnalyzerPlugin.dll.manifest" failed (exit code 1169) 
with the following output:
clangStaticAnalyzerCore.lib(BugReporter.cpp.obj) : error LNK2005: "public: 
__cdecl clang::ento::PathSensitiveBugReport::PathSensitiveBugReport(class 

[clang-tools-extra] 555eacf - [clangd] Fix undefined behavior when generating error message at rename with an invalid name

2021-12-19 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2021-12-19T22:28:26+03:00
New Revision: 555eacf75f21cd1dfc6363d73ad187b730349543

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

LOG: [clangd] Fix undefined behavior when generating error message at rename 
with an invalid name

`Message()` lambda uses `Reason.Details` as an input parameter for 
`llvm::formatv()`, but `Reason` in `Message()` is a local object.
Return value of `llvm::formatv()` contains references to its input arguments, 
thus `Message()` returns an object which contains a reference to `Details` 
field of the local object `Reason`.
This patch fixes this behavior by passing `Reason` as a reference to 
`Message()` to ensure that return value of `Message()` contains references to 
alive object and also prevents copying of `InvalidName` structure at passing it 
to `makeError()`.

Provided test passes on Linux+GCC with or without this patch, but fails on 
Windows+VisualStudio without this patch.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/Rename.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index 76182375ea170..5e157db5900af 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -455,7 +455,7 @@ std::string toString(InvalidName::Kind K) {
 }
 
 llvm::Error makeError(InvalidName Reason) {
-  auto Message = [](InvalidName Reason) {
+  auto Message = [](const InvalidName ) {
 switch (Reason.K) {
 case InvalidName::Keywords:
   return llvm::formatv("the chosen name \"{0}\" is a keyword",
@@ -733,7 +733,7 @@ llvm::Expected rename(const RenameInputs 
) {
 return makeError(ReasonToReject::SameName);
   auto Invalid = checkName(RenameDecl, RInputs.NewName);
   if (Invalid)
-return makeError(*Invalid);
+return makeError(std::move(*Invalid));
 
   auto Reject = renameable(RenameDecl, RInputs.MainFilePath, RInputs.Index);
   if (Reject)

diff  --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index f062f91c94378..26b3d7ad1c6c0 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1060,6 +1060,11 @@ TEST(RenameTest, Renameable) {
   )cpp",
"conflict", !HeaderFile, "Conflict"},
 
+  {R"cpp(
+int V^ar;
+  )cpp",
+   "\"const\" is a keyword", !HeaderFile, "const"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;



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


[clang-tools-extra] a62579f - [clangd][nfc] Show more information in logs when compiler instance prepare fails

2021-06-30 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2021-06-30T21:58:33+01:00
New Revision: a62579fc008e22b6c9e1544788644f5fceef15ce

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

LOG: [clangd][nfc] Show more information in logs when compiler instance prepare 
fails

Without this patch clangd silently process compiler instance prepare failure 
and only LSP errors "Invalid AST" could be found in logs.
E.g. the reason of the problem https://github.com/clangd/clangd/issues/734 is 
impossible to understand without verbose logs or with disabled background index.
This patch adds more information into logs to help understand the reason of 
such failures.

Logs without this patch:
```
E[...] Could not build a preamble for file test.cpp version 1
```

Logs with this patch:
```
E[...] Could not build a preamble for file test.cpp version 1: 
CreateTargetInfo() return null
..
E[...] Failed to prepare a compiler instance: unknown target ABI 'lp64'
```

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/Preamble.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index 0d7e4631d660..cb8ad5a8fa9f 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -289,8 +289,15 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs ,
   std::move(CI), PreamblePCH,
   llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, Filename), VFS,
   ASTDiags);
-  if (!Clang)
+  if (!Clang) {
+// The last diagnostic contains information about the reason of this
+// failure.
+std::vector Diags(ASTDiags.take());
+elog("Failed to prepare a compiler instance: {0}",
+ !Diags.empty() ? static_cast(Diags.back()).Message
+: "unknown error");
 return None;
+  }
 
   auto Action = std::make_unique();
   const FrontendInputFile  = Clang->getFrontendOpts().Inputs[0];

diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index e003af6e0dfa..9173dcda513a 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -390,8 +390,8 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
 SerializedDeclsCollector.takeMacros(), std::move(StatCache),
 SerializedDeclsCollector.takeCanonicalIncludes());
   } else {
-elog("Could not build a preamble for file {0} version {1}", FileName,
- Inputs.Version);
+elog("Could not build a preamble for file {0} version {1}: {2}", FileName,
+ Inputs.Version, BuiltPreamble.getError().message());
 return nullptr;
   }
 }



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


[clang-tools-extra] c4efd04 - [clangd] Use URIs instead of paths in the index file list

2021-03-05 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2021-03-06T10:47:05+03:00
New Revision: c4efd04f18c7e10c11de4a790f4d0c42f694d49b

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

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

Without this patch the file list of the preamble index contains URIs, but other 
indexes file lists contain file paths.
This makes `indexedFiles()` always returns `IndexContents::None` for the 
preamble index, because current implementation expects file paths inside the 
file list of the index.

This patch fixes this problem and also helps to avoid a lot of URI to path 
conversions during indexes merge.

Reviewed By: kadircet

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Background.cpp
clang-tools-extra/clangd/index/FileIndex.cpp
clang-tools-extra/clangd/index/MemIndex.cpp
clang-tools-extra/clangd/index/dex/Dex.cpp
clang-tools-extra/clangd/test/memory_tree.test
clang-tools-extra/clangd/unittests/DexTests.cpp
clang-tools-extra/clangd/unittests/FileIndexTests.cpp
clang-tools-extra/clangd/unittests/IndexTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Background.cpp 
b/clang-tools-extra/clangd/index/Background.cpp
index f97f13d8dabe..ddfe962d3189 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -243,7 +243,7 @@ void BackgroundIndex::update(
   // this thread sees the older version but finishes later. This should be
   // rare in practice.
   IndexedSymbols.update(
-  Path, std::make_unique(std::move(*IF->Symbols)),
+  Uri, std::make_unique(std::move(*IF->Symbols)),
   std::make_unique(std::move(*IF->Refs)),
   std::make_unique(std::move(*IF->Relations)),
   Path == MainFile);
@@ -390,8 +390,9 @@ BackgroundIndex::loadProject(std::vector 
MainFiles) {
   SV.HadErrors = LS.HadErrors;
   ++LoadedShards;
 
-  IndexedSymbols.update(LS.AbsolutePath, std::move(SS), std::move(RS),
-std::move(RelS), LS.CountReferences);
+  IndexedSymbols.update(URI::create(LS.AbsolutePath).toString(),
+std::move(SS), std::move(RS), std::move(RelS),
+LS.CountReferences);
 }
   }
   Rebuilder.loadedShard(LoadedShards);

diff  --git a/clang-tools-extra/clangd/index/FileIndex.cpp 
b/clang-tools-extra/clangd/index/FileIndex.cpp
index 528630f9232a..b91c66b88770 100644
--- a/clang-tools-extra/clangd/index/FileIndex.cpp
+++ b/clang-tools-extra/clangd/index/FileIndex.cpp
@@ -463,7 +463,8 @@ void FileIndex::updatePreamble(PathRef Path, 
llvm::StringRef Version,
 void FileIndex::updateMain(PathRef Path, ParsedAST ) {
   auto Contents = indexMainDecls(AST);
   MainFileSymbols.update(
-  Path, std::make_unique(std::move(std::get<0>(Contents))),
+  URI::create(Path).toString(),
+  std::make_unique(std::move(std::get<0>(Contents))),
   std::make_unique(std::move(std::get<1>(Contents))),
   std::make_unique(std::move(std::get<2>(Contents))),
   /*CountReferences=*/true);

diff  --git a/clang-tools-extra/clangd/index/MemIndex.cpp 
b/clang-tools-extra/clangd/index/MemIndex.cpp
index e2a8eb7f8e3f..9dc8e0aec944 100644
--- a/clang-tools-extra/clangd/index/MemIndex.cpp
+++ b/clang-tools-extra/clangd/index/MemIndex.cpp
@@ -112,14 +112,7 @@ void MemIndex::relations(
 llvm::unique_function
 MemIndex::indexedFiles() const {
   return [this](llvm::StringRef FileURI) {
-if (Files.empty())
-  return IndexContents::None;
-auto Path = URI::resolve(FileURI, Files.begin()->first());
-if (!Path) {
-  vlog("Failed to resolve the URI {0} : {1}", FileURI, Path.takeError());
-  return IndexContents::None;
-}
-return Files.contains(*Path) ? IdxContents : IndexContents::None;
+return Files.contains(FileURI) ? IdxContents : IndexContents::None;
   };
 }
 

diff  --git a/clang-tools-extra/clangd/index/dex/Dex.cpp 
b/clang-tools-extra/clangd/index/dex/Dex.cpp
index a6a8f23cab4c..7ebd5f685685 100644
--- a/clang-tools-extra/clangd/index/dex/Dex.cpp
+++ b/clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -316,14 +316,7 @@ void Dex::relations(
 llvm::unique_function
 Dex::indexedFiles() const {
   return [this](llvm::StringRef FileURI) {
-if (Files.empty())
-  return IndexContents::None;
-auto Path = URI::resolve(FileURI, Files.begin()->first());
-if (!Path) {
-  vlog("Failed to resolve the URI {0} : {1}", FileURI, Path.takeError());
-  return IndexContents::None;
-}
-return Files.contains(*Path) ? IdxContents : IndexContents::None;
+return Files.contains(FileURI) ? IdxContents : IndexContents::None;
   };
 }
 


[clang-tools-extra] 91698fe - [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-02-05 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2021-02-05T13:35:07+03:00
New Revision: 91698fe45f6068c5a6f8284e5e8e19a8d89dfea8

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

LOG: [clangd] Take into account what is in the index (symbols, references, 
etc.) at indexes merge

Current indexes merge logic skip data from the static index if the file is in 
the dynamic index, but sometimes the dynamic index does not contain references 
(e.g. preamble (dynamic) index vs background (static) index).
This problem is masked with the fact, that the preamble index file list 
consists of file URI's and other indexes file lists consist of file paths.
This patch introduces the index contents (symbols, references, etc.), which 
makes indexes merge more flexible and makes it able to use URI's for the index 
file list.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Background.cpp
clang-tools-extra/clangd/index/FileIndex.cpp
clang-tools-extra/clangd/index/FileIndex.h
clang-tools-extra/clangd/index/Index.cpp
clang-tools-extra/clangd/index/Index.h
clang-tools-extra/clangd/index/MemIndex.cpp
clang-tools-extra/clangd/index/MemIndex.h
clang-tools-extra/clangd/index/Merge.cpp
clang-tools-extra/clangd/index/Merge.h
clang-tools-extra/clangd/index/ProjectAware.cpp
clang-tools-extra/clangd/index/dex/Dex.cpp
clang-tools-extra/clangd/index/dex/Dex.h
clang-tools-extra/clangd/index/remote/Client.cpp
clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
clang-tools-extra/clangd/unittests/DexTests.cpp
clang-tools-extra/clangd/unittests/FileIndexTests.cpp
clang-tools-extra/clangd/unittests/IndexTests.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Background.cpp 
b/clang-tools-extra/clangd/index/Background.cpp
index d122d8aa2776..f97f13d8dabe 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -97,6 +97,7 @@ BackgroundIndex::BackgroundIndex(
 BackgroundIndexStorage::Factory IndexStorageFactory, Options Opts)
 : SwapIndex(std::make_unique()), TFS(TFS), CDB(CDB),
   ContextProvider(std::move(Opts.ContextProvider)),
+  IndexedSymbols(IndexContents::All),
   Rebuilder(this, , Opts.ThreadPoolSize),
   IndexStorageFactory(std::move(IndexStorageFactory)),
   Queue(std::move(Opts.OnProgress)),

diff  --git a/clang-tools-extra/clangd/index/FileIndex.cpp 
b/clang-tools-extra/clangd/index/FileIndex.cpp
index 9f05968020b0..f497f845b42d 100644
--- a/clang-tools-extra/clangd/index/FileIndex.cpp
+++ b/clang-tools-extra/clangd/index/FileIndex.cpp
@@ -236,6 +236,9 @@ SlabTuple indexHeaderSymbols(llvm::StringRef Version, 
ASTContext ,
   /*CollectMainFileRefs=*/false);
 }
 
+FileSymbols::FileSymbols(IndexContents IdxContents)
+: IdxContents(IdxContents) {}
+
 void FileSymbols::update(llvm::StringRef Key,
  std::unique_ptr Symbols,
  std::unique_ptr Refs,
@@ -376,14 +379,14 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling 
DuplicateHandle,
   case IndexType::Light:
 return std::make_unique(
 llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
-std::move(AllRelations), std::move(Files),
+std::move(AllRelations), std::move(Files), IdxContents,
 std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
 std::move(RefsStorage), std::move(SymsStorage)),
 StorageSize);
   case IndexType::Heavy:
 return std::make_unique(
 llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
-std::move(AllRelations), std::move(Files),
+std::move(AllRelations), std::move(Files), IdxContents,
 std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
 std::move(RefsStorage), std::move(SymsStorage)),
 StorageSize);
@@ -412,7 +415,9 @@ void FileSymbols::profile(MemoryTree ) const {
 
 FileIndex::FileIndex()
 : MergedIndex(, ),
+  PreambleSymbols(IndexContents::Symbols | IndexContents::Relations),
   PreambleIndex(std::make_unique()),
+  MainFileSymbols(IndexContents::All),
   MainFileIndex(std::make_unique()) {}
 
 void FileIndex::updatePreamble(PathRef Path, llvm::StringRef Version,

diff  --git a/clang-tools-extra/clangd/index/FileIndex.h 
b/clang-tools-extra/clangd/index/FileIndex.h
index 29958ca30be2..d46a87464568 100644
--- a/clang-tools-extra/clangd/index/FileIndex.h
+++ b/clang-tools-extra/clangd/index/FileIndex.h
@@ -71,6 +71,7 @@ enum 

[clang-tools-extra] 7388c34 - [clangd][SwapIndex] ensure that the old index is alive while we are using it via the function returned by `SwapIndex::indexedFiles()` call

2021-01-22 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2021-01-22T16:26:39+03:00
New Revision: 7388c34685954862e5f1fa4734f42f7087e697a2

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

LOG: [clangd][SwapIndex] ensure that the old index is alive while we are using 
it via the function returned by `SwapIndex::indexedFiles()` call

Without this patch the old index could be freed, but there still could be tries 
to access it via the function returned by `SwapIndex::indexedFiles()` call.
This leads to hard to reproduce clangd crashes at code completion.
This patch keeps the old index alive until the function returned by 
`SwapIndex::indexedFiles()` call is alive.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Index.cpp
clang-tools-extra/clangd/index/Merge.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Index.cpp 
b/clang-tools-extra/clangd/index/Index.cpp
index 5da06f36ffe4..1b085140b4ff 100644
--- a/clang-tools-extra/clangd/index/Index.cpp
+++ b/clang-tools-extra/clangd/index/Index.cpp
@@ -78,7 +78,13 @@ void SwapIndex::relations(
 
 llvm::unique_function
 SwapIndex::indexedFiles() const {
-  return snapshot()->indexedFiles();
+  // The index snapshot should outlive this method return value.
+  auto SnapShot = snapshot();
+  auto IndexedFiles = SnapShot->indexedFiles();
+  return [KeepAlive{std::move(SnapShot)},
+  IndexContainsFile{std::move(IndexedFiles)}](llvm::StringRef File) {
+return IndexContainsFile(File);
+  };
 }
 
 size_t SwapIndex::estimateMemoryUsage() const {

diff  --git a/clang-tools-extra/clangd/index/Merge.cpp 
b/clang-tools-extra/clangd/index/Merge.cpp
index 0dd0d9e01518..6f369ed2edcf 100644
--- a/clang-tools-extra/clangd/index/Merge.cpp
+++ b/clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@ bool MergedIndex::fuzzyFind(
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol ) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Callback(S);
-++MergedCount;
-SeenDynamicSymbols.insert(S.ID);
-Callback(mergeSymbol(*DynS, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+More |= Static->fuzzyFind(Req, [&](const Symbol ) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  auto DynS = Dyn.find(S.ID);
+  ++StaticCount;
+  if (DynS == Dyn.end())
+return Callback(S);
+  ++MergedCount;
+  SeenDynamicSymbols.insert(S.ID);
+  Callback(mergeSymbol(*DynS, S));
+});
+  }
   SPAN_ATTACH(Tracer, "dynamic", DynamicCount);
   SPAN_ATTACH(Tracer, "static", StaticCount);
   SPAN_ATTACH(Tracer, "merged", MergedCount);
@@ -77,20 +79,22 @@ void MergedIndex::lookup(
   Dynamic->lookup(Req, [&](const Symbol ) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  Static->lookup(Req, [&](const Symbol ) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-const Symbol *Sym = B.find(S.ID);
-RemainingIDs.erase(S.ID);
-if (!Sym)
-  Callback(S);
-else
-  Callback(mergeSymbol(*Sym, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+Static->lookup(Req, [&](const Symbol ) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  const Symbol *Sym = B.find(S.ID);
+  RemainingIDs.erase(S.ID);
+  if (!Sym)
+Callback(S);
+  else
+Callback(mergeSymbol(*Sym, S));
+});
+  }
   for (const auto  : RemainingIDs)
 if (const Symbol *Sym = B.find(ID))
 

[clang-tools-extra] 2e25be0 - [clangd] Add main file macros into the main-file index.

2021-01-14 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2021-01-14T15:10:17+03:00
New Revision: 2e25be0b6134e9544f7cee7bb7b31a921ca37cc0

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

LOG: [clangd] Add main file macros into the main-file index.

This patch is a try to fix `WorkspaceSymbols.Macros` test after D93796.
If a macro definition is in the preamble section, then it appears to be in the 
preamble (static) index and not in the main-file (dynamic) index.
Thus, a such macro could not be found at a symbol search according to the logic 
that we skip symbols from the static index if the location of these symbols is 
inside the dynamic index files.
To fix this behavior this patch adds main file macros into the main-file 
(dynamic) index.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/CollectMacros.cpp
clang-tools-extra/clangd/CollectMacros.h
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/index/SymbolCollector.cpp
clang-tools-extra/clangd/unittests/CollectMacrosTests.cpp
clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
clang-tools-extra/clangd/unittests/ParsedASTTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CollectMacros.cpp 
b/clang-tools-extra/clangd/CollectMacros.cpp
index bd6165ef10ba..0e89b35d9d56 100644
--- a/clang-tools-extra/clangd/CollectMacros.cpp
+++ b/clang-tools-extra/clangd/CollectMacros.cpp
@@ -13,8 +13,8 @@
 namespace clang {
 namespace clangd {
 
-void CollectMainFileMacros::add(const Token ,
-const MacroInfo *MI) {
+void CollectMainFileMacros::add(const Token , const MacroInfo *MI,
+bool IsDefinition) {
   if (!InMainFile)
 return;
   auto Loc = MacroNameTok.getLocation();
@@ -26,9 +26,9 @@ void CollectMainFileMacros::add(const Token ,
   auto Range = halfOpenToRange(
   SM, CharSourceRange::getCharRange(Loc, MacroNameTok.getEndLoc()));
   if (auto SID = getSymbolID(Name, MI, SM))
-Out.MacroRefs[SID].push_back(Range);
+Out.MacroRefs[SID].push_back({Range, IsDefinition});
   else
-Out.UnknownMacros.push_back(Range);
+Out.UnknownMacros.push_back({Range, IsDefinition});
 }
 } // namespace clangd
 } // namespace clang

diff  --git a/clang-tools-extra/clangd/CollectMacros.h 
b/clang-tools-extra/clangd/CollectMacros.h
index eecea0455be2..3240111e5a33 100644
--- a/clang-tools-extra/clangd/CollectMacros.h
+++ b/clang-tools-extra/clangd/CollectMacros.h
@@ -21,15 +21,20 @@
 namespace clang {
 namespace clangd {
 
-struct MainFileMacros {
-  llvm::StringSet<> Names;
+struct MacroOccurrence {
   // Instead of storing SourceLocation, we have to store the token range 
because
   // SourceManager from preamble is not available when we build the AST.
-  llvm::DenseMap> MacroRefs;
+  Range Rng;
+  bool IsDefinition;
+};
+
+struct MainFileMacros {
+  llvm::StringSet<> Names;
+  llvm::DenseMap> MacroRefs;
   // Somtimes it is not possible to compute the SymbolID for the Macro, e.g. a
   // reference to an undefined macro. Store them separately, e.g. for semantic
   // highlighting.
-  std::vector UnknownMacros;
+  std::vector UnknownMacros;
   // Ranges skipped by the preprocessor due to being inactive.
   std::vector SkippedRanges;
 };
@@ -49,7 +54,7 @@ class CollectMainFileMacros : public PPCallbacks {
   }
 
   void MacroDefined(const Token , const MacroDirective *MD) override 
{
-add(MacroName, MD->getMacroInfo());
+add(MacroName, MD->getMacroInfo(), /*IsDefinition=*/true);
   }
 
   void MacroExpands(const Token , const MacroDefinition ,
@@ -87,7 +92,8 @@ class CollectMainFileMacros : public PPCallbacks {
   }
 
 private:
-  void add(const Token , const MacroInfo *MI);
+  void add(const Token , const MacroInfo *MI,
+   bool IsDefinition = false);
   const SourceManager 
   bool InMainFile = true;
   MainFileMacros 

diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index be0a5437cde6..5e70baf73310 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -397,10 +397,10 @@ std::vector 
getSemanticHighlightings(ParsedAST ) {
   // Add highlightings for macro references.
   for (const auto  : AST.getMacros().MacroRefs) {
 for (const auto  : SIDToRefs.second)
-  Builder.addToken({HighlightingKind::Macro, M});
+  Builder.addToken({HighlightingKind::Macro, M.Rng});
   }
   for (const auto  : AST.getMacros().UnknownMacros)
-Builder.addToken({HighlightingKind::Macro, M});
+Builder.addToken({HighlightingKind::Macro, M.Rng});
 
   return 

[clang-tools-extra] 979228f - [clangd][fuzzyFind] Do not show stale symbols in the result.

2021-01-06 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2021-01-06T11:17:12+03:00
New Revision: 979228f120f4aa1265648b1c06f65a84bcca1ed6

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

LOG: [clangd][fuzzyFind] Do not show stale symbols in the result.

This is follow up to D93393.
Without this patch `MergedIndex::fuzzyFind()` returns stale symbols from the 
static index even if these symbols were removed.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Merge.cpp
clang-tools-extra/clangd/index/Merge.h
clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
clang-tools-extra/clangd/unittests/IndexTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Merge.cpp 
b/clang-tools-extra/clangd/index/Merge.cpp
index f66f47499624..29174ff0d354 100644
--- a/clang-tools-extra/clangd/index/Merge.cpp
+++ b/clang-tools-extra/clangd/index/Merge.cpp
@@ -22,11 +22,6 @@
 namespace clang {
 namespace clangd {
 
-// FIXME: Deleted symbols in dirty files are still returned (from Static).
-//To identify these eliminate these, we should:
-//  - find the generating file from each Symbol which is Static-only
-//  - ask Dynamic if it has that file (needs new SymbolIndex method)
-//  - if so, drop the Symbol.
 bool MergedIndex::fuzzyFind(
 const FuzzyFindRequest ,
 llvm::function_ref Callback) const {
@@ -49,7 +44,13 @@ bool MergedIndex::fuzzyFind(
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
+  auto DynamicContainsFile = Dynamic->indexedFiles();
   More |= Static->fuzzyFind(Req, [&](const Symbol ) {
+// We expect the definition to see the canonical declaration, so it seems
+// to be enough to check only the definition if it exists.
+if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+ : S.CanonicalDeclaration.FileURI))
+  return;
 auto DynS = Dyn.find(S.ID);
 ++StaticCount;
 if (DynS == Dyn.end())

diff  --git a/clang-tools-extra/clangd/index/Merge.h 
b/clang-tools-extra/clangd/index/Merge.h
index 0cdff38f0678..f8696b460c90 100644
--- a/clang-tools-extra/clangd/index/Merge.h
+++ b/clang-tools-extra/clangd/index/Merge.h
@@ -23,10 +23,6 @@ Symbol mergeSymbol(const Symbol , const Symbol );
 //  - the Dynamic index covers few files, but is relatively up-to-date.
 //  - the Static index covers a bigger set of files, but is relatively stale.
 // The returned index attempts to combine results, and avoid duplicates.
-//
-// FIXME: We don't have a mechanism in Index to track deleted symbols and
-// refs in dirty files, so the merged index may return stale symbols
-// and refs from Static index.
 class MergedIndex : public SymbolIndex {
   const SymbolIndex *Dynamic, *Static;
 

diff  --git a/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp 
b/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
index 43658284937e..bdd3ddca1a61 100644
--- a/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -52,7 +52,17 @@ std::vector getSymbols(TestTU , 
llvm::StringRef Query,
   return *SymbolInfos;
 }
 
-TEST(WorkspaceSymbols, Macros) {
+// FIXME: We update two indexes during main file processing:
+//- preamble index (static)
+//- main-file index (dynamic)
+//The macro in this test appears to be in the preamble index and not
+//in the main-file index. According to our logic of indexes merging, we
+//do not take this macro from the static (preamble) index, because it
+//location within the file from the dynamic (main-file) index.
+//
+//Possible solution is to exclude main-file symbols from the preamble
+//index, after that we can enable this test again.
+TEST(WorkspaceSymbols, DISABLED_Macros) {
   TestTU TU;
   TU.Code = R"cpp(
#define MACRO X

diff  --git a/clang-tools-extra/clangd/unittests/IndexTests.cpp 
b/clang-tools-extra/clangd/unittests/IndexTests.cpp
index ce4845e3e144..33b0414275ca 100644
--- a/clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -335,6 +335,39 @@ TEST(MergeIndexTest, FuzzyFind) {
   UnorderedElementsAre("ns::A", "ns::B", "ns::C"));
 }
 
+TEST(MergeIndexTest, FuzzyFindRemovedSymbol) {
+  FileIndex DynamicIndex, StaticIndex;
+  MergedIndex Merge(, );
+
+  const char *HeaderCode = "class Foo;";
+  auto HeaderSymbols = TestTU::withHeaderCode(HeaderCode).headerSymbols();
+  auto Foo = findSymbol(HeaderSymbols, "Foo");
+
+  // Build static index for test.cc with Foo symbol
+  TestTU Test;
+  Test.HeaderCode = HeaderCode;
+  Test.Code = "class Foo 

[clang-tools-extra] 2522fa0 - [clangd] Do not take stale definition from the static index.

2020-12-23 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-12-23T18:21:38+03:00
New Revision: 2522fa053b62520ae48b4b27117ca003a2c878ab

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

LOG: [clangd] Do not take stale definition from the static index.

This is follow up to D93393.
Without this patch clangd takes the symbol definition from the static index if 
this definition was removed from the dynamic index.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Merge.cpp
clang-tools-extra/clangd/unittests/IndexTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Merge.cpp 
b/clang-tools-extra/clangd/index/Merge.cpp
index 97babacf2b38..f66f47499624 100644
--- a/clang-tools-extra/clangd/index/Merge.cpp
+++ b/clang-tools-extra/clangd/index/Merge.cpp
@@ -76,7 +76,13 @@ void MergedIndex::lookup(
   Dynamic->lookup(Req, [&](const Symbol ) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
+  auto DynamicContainsFile = Dynamic->indexedFiles();
   Static->lookup(Req, [&](const Symbol ) {
+// We expect the definition to see the canonical declaration, so it seems
+// to be enough to check only the definition if it exists.
+if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+ : S.CanonicalDeclaration.FileURI))
+  return;
 const Symbol *Sym = B.find(S.ID);
 RemainingIDs.erase(S.ID);
 if (!Sym)

diff  --git a/clang-tools-extra/clangd/unittests/IndexTests.cpp 
b/clang-tools-extra/clangd/unittests/IndexTests.cpp
index 8efc637d1250..ce4845e3e144 100644
--- a/clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -290,6 +290,40 @@ TEST(MergeIndexTest, Lookup) {
   EXPECT_THAT(lookup(M, {}), UnorderedElementsAre());
 }
 
+TEST(MergeIndexTest, LookupRemovedDefinition) {
+  FileIndex DynamicIndex, StaticIndex;
+  MergedIndex Merge(, );
+
+  const char *HeaderCode = "class Foo;";
+  auto HeaderSymbols = TestTU::withHeaderCode(HeaderCode).headerSymbols();
+  auto Foo = findSymbol(HeaderSymbols, "Foo");
+
+  // Build static index for test.cc with Foo definition
+  TestTU Test;
+  Test.HeaderCode = HeaderCode;
+  Test.Code = "class Foo {};";
+  Test.Filename = "test.cc";
+  auto AST = Test.build();
+  StaticIndex.updateMain(testPath(Test.Filename), AST);
+
+  // Remove Foo definition from test.cc, i.e. build dynamic index for test.cc
+  // without Foo definition.
+  Test.Code = "class Foo;";
+  AST = Test.build();
+  DynamicIndex.updateMain(testPath(Test.Filename), AST);
+
+  // Merged index should not return the symbol definition if this definition
+  // location is inside a file from the dynamic index.
+  LookupRequest LookupReq;
+  LookupReq.IDs = {Foo.ID};
+  unsigned SymbolCounter = 0;
+  Merge.lookup(LookupReq, [&](const Symbol ) {
+++SymbolCounter;
+EXPECT_FALSE(Sym.Definition);
+  });
+  EXPECT_EQ(SymbolCounter, 1u);
+}
+
 TEST(MergeIndexTest, FuzzyFind) {
   auto I = MemIndex::build(generateSymbols({"ns::A", "ns::B"}), RefSlab(),
RelationSlab()),



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


[clang-tools-extra] e35f922 - [clangd] Ignore the static index refs from the dynamic index files.

2020-12-18 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-12-18T15:36:30+03:00
New Revision: e35f9229dcb264be4a0a1ecf5cca2493f2c48878

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

LOG: [clangd] Ignore the static index refs from the dynamic index files.

This patch fixes the following problem:
- open a file with references to the symbol `Foo`
- remove all references to `Foo` (from the dynamic index).
- `MergedIndex::refs()` result will contain positions of removed references 
(from the static index).

The idea of this patch is to keep a set of files which were used during index 
build inside the index.
Thus at processing the static index references we can check if the file of 
processing reference is a part of the dynamic index or not.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/index/FileIndex.cpp
clang-tools-extra/clangd/index/Index.cpp
clang-tools-extra/clangd/index/Index.h
clang-tools-extra/clangd/index/MemIndex.cpp
clang-tools-extra/clangd/index/MemIndex.h
clang-tools-extra/clangd/index/Merge.cpp
clang-tools-extra/clangd/index/Merge.h
clang-tools-extra/clangd/index/ProjectAware.cpp
clang-tools-extra/clangd/index/dex/Dex.cpp
clang-tools-extra/clangd/index/dex/Dex.h
clang-tools-extra/clangd/index/remote/Client.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
clang-tools-extra/clangd/unittests/DexTests.cpp
clang-tools-extra/clangd/unittests/IndexTests.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp
clang-tools-extra/clangd/unittests/TestFS.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/FileIndex.cpp 
b/clang-tools-extra/clangd/index/FileIndex.cpp
index 1ccfb4485638..143e76863777 100644
--- a/clang-tools-extra/clangd/index/FileIndex.cpp
+++ b/clang-tools-extra/clangd/index/FileIndex.cpp
@@ -266,11 +266,14 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling 
DuplicateHandle,
   std::vector> SymbolSlabs;
   std::vector> RefSlabs;
   std::vector> RelationSlabs;
+  llvm::StringSet<> Files;
   std::vector MainFileRefs;
   {
 std::lock_guard Lock(Mutex);
-for (const auto  : SymbolsSnapshot)
+for (const auto  : SymbolsSnapshot) {
   SymbolSlabs.push_back(FileAndSymbols.second);
+  Files.insert(FileAndSymbols.first());
+}
 for (const auto  : RefsSnapshot) {
   RefSlabs.push_back(FileAndRefs.second.Slab);
   if (FileAndRefs.second.CountReferences)
@@ -372,14 +375,14 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling 
DuplicateHandle,
   case IndexType::Light:
 return std::make_unique(
 llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
-std::move(AllRelations),
+std::move(AllRelations), std::move(Files),
 std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
 std::move(RefsStorage), std::move(SymsStorage)),
 StorageSize);
   case IndexType::Heavy:
 return std::make_unique(
 llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
-std::move(AllRelations),
+std::move(AllRelations), std::move(Files),
 std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
 std::move(RefsStorage), std::move(SymsStorage)),
 StorageSize);

diff  --git a/clang-tools-extra/clangd/index/Index.cpp 
b/clang-tools-extra/clangd/index/Index.cpp
index b309053972eb..5da06f36ffe4 100644
--- a/clang-tools-extra/clangd/index/Index.cpp
+++ b/clang-tools-extra/clangd/index/Index.cpp
@@ -76,6 +76,11 @@ void SwapIndex::relations(
   return snapshot()->relations(R, CB);
 }
 
+llvm::unique_function
+SwapIndex::indexedFiles() const {
+  return snapshot()->indexedFiles();
+}
+
 size_t SwapIndex::estimateMemoryUsage() const {
   return snapshot()->estimateMemoryUsage();
 }

diff  --git a/clang-tools-extra/clangd/index/Index.h 
b/clang-tools-extra/clangd/index/Index.h
index f0959e71d50f..c961aa9d8bd9 100644
--- a/clang-tools-extra/clangd/index/Index.h
+++ b/clang-tools-extra/clangd/index/Index.h
@@ -14,6 +14,7 @@
 #include "Symbol.h"
 #include "SymbolID.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/FunctionExtras.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/JSON.h"
@@ -121,6 +122,11 @@ class SymbolIndex {
   llvm::function_ref
   Callback) const = 0;
 
+  /// Returns function which checks if the specified file was used to build 
this
+  /// index or not. The function must only be called while the index is alive.
+  virtual llvm::unique_function
+  indexedFiles() const = 0;
+
   /// Returns estimated size of index (in bytes).
   virtual size_t estimateMemoryUsage() const = 0;
 };
@@ -145,6 

[clang-tools-extra] 1ca174b - [clangd][query-driver] Extract target

2020-11-26 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-11-26T15:08:26+03:00
New Revision: 1ca174b6420a49bcd3331d6f86e237b627163597

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

LOG: [clangd][query-driver] Extract target

In some cases system includes extractions is not enough, we also need target 
specific defines.
The problems appears when clang default target is not the same as toolchain's 
one (GCC cross-compiler, MinGW on Windows).
After this patch `query-driver` also extracts target and adds 
`--target=` compile option.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/QueryDriverDatabase.cpp
clang-tools-extra/clangd/test/system-include-extractor.test

Removed: 




diff  --git a/clang-tools-extra/clangd/QueryDriverDatabase.cpp 
b/clang-tools-extra/clangd/QueryDriverDatabase.cpp
index 9d731f5563cf..d59263e73994 100644
--- a/clang-tools-extra/clangd/QueryDriverDatabase.cpp
+++ b/clang-tools-extra/clangd/QueryDriverDatabase.cpp
@@ -33,6 +33,9 @@
 #include "support/Logger.h"
 #include "support/Path.h"
 #include "support/Trace.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/TargetInfo.h"
+#include "clang/Basic/TargetOptions.h"
 #include "clang/Driver/Types.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/ADT/DenseMap.h"
@@ -56,55 +59,102 @@ namespace clang {
 namespace clangd {
 namespace {
 
-std::vector parseDriverOutput(llvm::StringRef Output) {
+struct DriverInfo {
   std::vector SystemIncludes;
+  std::string Target;
+};
+
+bool isValidTarget(llvm::StringRef Triple) {
+  std::shared_ptr TargetOpts(new TargetOptions);
+  TargetOpts->Triple = Triple.str();
+  DiagnosticsEngine Diags(new DiagnosticIDs, new DiagnosticOptions,
+  new IgnoringDiagConsumer);
+  IntrusiveRefCntPtr Target =
+  TargetInfo::CreateTargetInfo(Diags, TargetOpts);
+  return bool(Target);
+}
+
+llvm::Optional parseDriverOutput(llvm::StringRef Output) {
+  DriverInfo Info;
   const char SIS[] = "#include <...> search starts here:";
   const char SIE[] = "End of search list.";
+  const char TS[] = "Target: ";
   llvm::SmallVector Lines;
   Output.split(Lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
 
-  auto StartIt = llvm::find_if(
-  Lines, [SIS](llvm::StringRef Line) { return Line.trim() == SIS; });
-  if (StartIt == Lines.end()) {
+  enum {
+Initial,// Initial state: searching for target or includes 
list.
+IncludesExtracting, // Includes extracting.
+Done// Includes and target extraction done.
+  } State = Initial;
+  bool SeenIncludes = false;
+  bool SeenTarget = false;
+  for (auto *It = Lines.begin(); State != Done && It != Lines.end(); ++It) {
+auto Line = *It;
+switch (State) {
+case Initial:
+  if (!SeenIncludes && Line.trim() == SIS) {
+SeenIncludes = true;
+State = IncludesExtracting;
+  } else if (!SeenTarget && Line.trim().startswith(TS)) {
+SeenTarget = true;
+llvm::StringRef TargetLine = Line.trim();
+TargetLine.consume_front(TS);
+// Only detect targets that clang understands
+if (!isValidTarget(TargetLine)) {
+  elog("System include extraction: invalid target \"{0}\", ignoring",
+   TargetLine);
+} else {
+  Info.Target = TargetLine.str();
+  vlog("System include extraction: target extracted: \"{0}\"",
+   TargetLine);
+}
+  }
+  break;
+case IncludesExtracting:
+  if (Line.trim() == SIE) {
+State = SeenTarget ? Done : Initial;
+  } else {
+Info.SystemIncludes.push_back(Line.trim().str());
+vlog("System include extraction: adding {0}", Line);
+  }
+  break;
+default:
+  llvm_unreachable("Impossible state of the driver output parser");
+  break;
+}
+  }
+  if (!SeenIncludes) {
 elog("System include extraction: start marker not found: {0}", Output);
-return {};
+return llvm::None;
   }
-  ++StartIt;
-  const auto EndIt =
-  llvm::find_if(llvm::make_range(StartIt, Lines.end()),
-[SIE](llvm::StringRef Line) { return Line.trim() == SIE; 
});
-  if (EndIt == Lines.end()) {
+  if (State == IncludesExtracting) {
 elog("System include extraction: end marker missing: {0}", Output);
-return {};
+return llvm::None;
   }
-
-  for (llvm::StringRef Line : llvm::make_range(StartIt, EndIt)) {
-SystemIncludes.push_back(Line.trim().str());
-vlog("System include extraction: adding {0}", Line);
-  }
-  return SystemIncludes;
+  return std::move(Info);
 }
 
-std::vector
-extractSystemIncludes(PathRef Driver, llvm::StringRef Lang,
-  llvm::ArrayRef 

[clang-tools-extra] dad804a - [clangd] Improve clangd-indexer performance

2020-11-11 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-11-11T14:38:06+03:00
New Revision: dad804a193edf092322d80bb404fabb2f6f2c888

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

LOG: [clangd] Improve clangd-indexer performance

This is a try to improve clangd-indexer tool performance:
- avoid processing already processed files.
- use different mutexes for different entities (e.g. do not block insertion of 
references while symbols are inserted)

Results for LLVM project indexing:
- before: ~30 minutes
- after: ~10 minutes

Reviewed By: kadircet

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

Added: 


Modified: 
clang-tools-extra/clangd/indexer/IndexerMain.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/indexer/IndexerMain.cpp 
b/clang-tools-extra/clangd/indexer/IndexerMain.cpp
index 46224238c3fc..fd8404be677a 100644
--- a/clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ b/clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -43,6 +43,16 @@ class IndexActionFactory : public 
tooling::FrontendActionFactory {
   std::unique_ptr create() override {
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
+Opts.FileFilter = [&](const SourceManager , FileID FID) {
+  const auto *F = SM.getFileEntryForID(FID);
+  if (!F)
+return false; // Skip invalid files.
+  auto AbsPath = getCanonicalPath(F, SM);
+  if (!AbsPath)
+return false; // Skip files without absolute path.
+  std::lock_guard Lock(FilesMu);
+  return Files.insert(*AbsPath).second; // Skip already processed files.
+};
 return createStaticIndexingAction(
 Opts,
 [&](SymbolSlab S) {
@@ -56,7 +66,7 @@ class IndexActionFactory : public 
tooling::FrontendActionFactory {
   }
 },
 [&](RefSlab S) {
-  std::lock_guard Lock(SymbolsMu);
+  std::lock_guard Lock(RefsMu);
   for (const auto  : S) {
 // Deduplication happens during insertion.
 for (const auto  : Sym.second)
@@ -64,7 +74,7 @@ class IndexActionFactory : public 
tooling::FrontendActionFactory {
   }
 },
 [&](RelationSlab S) {
-  std::lock_guard Lock(SymbolsMu);
+  std::lock_guard Lock(RelsMu);
   for (const auto  : S) {
 Relations.insert(R);
   }
@@ -82,9 +92,13 @@ class IndexActionFactory : public 
tooling::FrontendActionFactory {
 
 private:
   IndexFileIn 
+  std::mutex FilesMu;
+  llvm::StringSet<> Files;
   std::mutex SymbolsMu;
   SymbolSlab::Builder Symbols;
+  std::mutex RefsMu;
   RefSlab::Builder Refs;
+  std::mutex RelsMu;
   RelationSlab::Builder Relations;
 };
 



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


[clang-tools-extra] 1bbf87e - [clangd][remote] Check an index file correctly

2020-11-09 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-11-09T21:40:45+03:00
New Revision: 1bbf87e22a73011fdea411baf8fe768f854d497c

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

LOG: [clangd][remote] Check an index file correctly

There is not reason to check `std::make_unique<...>(..)` return value,
but `clangd::clang::loadIndex()` returns `nullptr` if an index file could not 
be loaded (e.g. incorrect version).

Reviewed By: kadircet

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

Added: 


Modified: 
clang-tools-extra/clangd/index/remote/server/Server.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/remote/server/Server.cpp 
b/clang-tools-extra/clangd/index/remote/server/Server.cpp
index 4a479eece50f..fac1bd98ad5f 100644
--- a/clang-tools-extra/clangd/index/remote/server/Server.cpp
+++ b/clang-tools-extra/clangd/index/remote/server/Server.cpp
@@ -357,24 +357,23 @@ int main(int argc, char *argv[]) {
 return Status.getError().value();
   }
 
-  auto Index = std::make_unique(
-  clang::clangd::loadIndex(IndexPath));
-
-  if (!Index) {
+  auto SymIndex = clang::clangd::loadIndex(IndexPath);
+  if (!SymIndex) {
 llvm::errs() << "Failed to open the index.\n";
 return -1;
   }
+  clang::clangd::SwapIndex Index(std::move(SymIndex));
 
   std::thread HotReloadThread([, , ]() {
 llvm::vfs::Status LastStatus = *Status;
 static constexpr auto RefreshFrequency = std::chrono::seconds(30);
 while (!clang::clangd::shutdownRequested()) {
-  hotReload(*Index, llvm::StringRef(IndexPath), LastStatus, FS);
+  hotReload(Index, llvm::StringRef(IndexPath), LastStatus, FS);
   std::this_thread::sleep_for(RefreshFrequency);
 }
   });
 
-  runServerAndWait(*Index, ServerAddress, IndexPath);
+  runServerAndWait(Index, ServerAddress, IndexPath);
 
   HotReloadThread.join();
 }



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


[clang-tools-extra] d99b2a9 - [clangd][remote] Add Windows paths support

2020-10-20 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-10-20T13:04:20+03:00
New Revision: d99b2a976a37f5a63117086d464df40c124f5777

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

LOG: [clangd][remote] Add Windows paths support

Without this patch 6 marshalling tests fail on Windows.
This patch contains the following changes:
- Allow paths with Windows slashes (convert to the POSIX style instead of 
assertion)
- Add support for URI with Windows path.
- Change the value of the second parameter of several 
`llvm::sys::path::convert_to_slash()` calls: we should use `windows` instead of 
`posix` to ensure UNIX slashes in the path.
- Port `RemoteMarshallingTest::IncludeHeaderURI` test to Windows.

Reviewed By: kbobyrev

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

Added: 


Modified: 
clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp 
b/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
index d61848f295a3..6285022fc0a8 100644
--- a/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
+++ b/clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
@@ -50,20 +50,23 @@ llvm::Expected> getIDs(IDRange 
IDs) {
 Marshaller::Marshaller(llvm::StringRef RemoteIndexRoot,
llvm::StringRef LocalIndexRoot)
 : Strings(Arena) {
+  llvm::StringRef PosixSeparator =
+  llvm::sys::path::get_separator(llvm::sys::path::Style::posix);
   if (!RemoteIndexRoot.empty()) {
 assert(llvm::sys::path::is_absolute(RemoteIndexRoot));
-assert(RemoteIndexRoot ==
-   llvm::sys::path::convert_to_slash(RemoteIndexRoot));
-this->RemoteIndexRoot = RemoteIndexRoot.str();
-if (!RemoteIndexRoot.endswith(llvm::sys::path::get_separator()))
-  *this->RemoteIndexRoot += llvm::sys::path::get_separator();
+this->RemoteIndexRoot = llvm::sys::path::convert_to_slash(
+RemoteIndexRoot, llvm::sys::path::Style::windows);
+llvm::StringRef Path(*this->RemoteIndexRoot);
+if (!Path.endswith(PosixSeparator))
+  *this->RemoteIndexRoot += PosixSeparator;
   }
   if (!LocalIndexRoot.empty()) {
 assert(llvm::sys::path::is_absolute(LocalIndexRoot));
-assert(LocalIndexRoot == 
llvm::sys::path::convert_to_slash(LocalIndexRoot));
-this->LocalIndexRoot = LocalIndexRoot.str();
-if (!LocalIndexRoot.endswith(llvm::sys::path::get_separator()))
-  *this->LocalIndexRoot += llvm::sys::path::get_separator();
+this->LocalIndexRoot = llvm::sys::path::convert_to_slash(
+LocalIndexRoot, llvm::sys::path::Style::windows);
+llvm::StringRef Path(*this->LocalIndexRoot);
+if (!Path.endswith(PosixSeparator))
+  *this->LocalIndexRoot += PosixSeparator;
   }
   assert(!RemoteIndexRoot.empty() || !LocalIndexRoot.empty());
 }
@@ -92,6 +95,9 @@ Marshaller::fromProtobuf(const FuzzyFindRequest *Message) {
   for (const auto  : Message->proximity_paths()) {
 llvm::SmallString<256> LocalPath = llvm::StringRef(*RemoteIndexRoot);
 llvm::sys::path::append(LocalPath, Path);
+// FuzzyFindRequest requires proximity paths to have platform-native format
+// in order for SymbolIndex to process the query correctly.
+llvm::sys::path::native(LocalPath);
 Result.ProximityPaths.push_back(std::string(LocalPath));
   }
   for (const auto  : Message->preferred_types())
@@ -209,7 +215,7 @@ FuzzyFindRequest Marshaller::toProtobuf(const 
clangd::FuzzyFindRequest ) {
 llvm::SmallString<256> RelativePath = llvm::StringRef(Path);
 if (llvm::sys::path::replace_path_prefix(RelativePath, *LocalIndexRoot, 
""))
   RPCRequest.add_proximity_paths(llvm::sys::path::convert_to_slash(
-  RelativePath, llvm::sys::path::Style::posix));
+  RelativePath, llvm::sys::path::Style::windows));
   }
   for (const auto  : From.PreferredTypes)
 RPCRequest.add_preferred_types(Type);
@@ -315,12 +321,17 @@ llvm::Expected 
Marshaller::uriToRelativePath(llvm::StringRef URI) {
   if (ParsedURI->scheme() != "file")
 return error("Can not use URI schemes other than file, given: '{0}'.", 
URI);
   llvm::SmallString<256> Result = ParsedURI->body();
+  llvm::StringRef Path(Result);
+  // Check for Windows paths (URI=file:///X:/path => Body=/X:/path)
+  if (llvm::sys::path::is_absolute(Path.substr(1),
+   llvm::sys::path::Style::windows))
+Result = Path.drop_front();
   if (!llvm::sys::path::replace_path_prefix(Result, *RemoteIndexRoot, ""))
 return error("File path '{0}' doesn't start with '{1}'.", Result.str(),
  *RemoteIndexRoot);
-  // Make sure the result has UNIX slashes.
-  return 

[clang-tools-extra] d8ba6b4 - [clangd] findNearbyIdentifier(): guaranteed to give up after 2^N lines

2020-09-29 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-09-29T19:54:55+03:00
New Revision: d8ba6b4ab3eceb6bbcdf4371d4ffaab9d1a5cebe

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

LOG: [clangd] findNearbyIdentifier(): guaranteed to give up after 2^N lines

As @kadircet mentions in D84912#2184144, `findNearbyIdentifier()` traverses the 
whole file if there is no identifier for the word.
This patch ensures give up after 2^N lines in any case.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/unittests/XRefsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index 9e8791c2a765..9532e1418cca 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -562,19 +562,34 @@ const syntax::Token *findNearbyIdentifier(const 
SpelledWord ,
   auto Cost = [&](SourceLocation Loc) -> unsigned {
 assert(SM.getFileID(Loc) == File && "spelled token in wrong file?");
 unsigned Line = SM.getSpellingLineNumber(Loc);
-if (Line > WordLine)
-  return 1 + llvm::Log2_64(Line - WordLine);
-if (Line < WordLine)
-  return 2 + llvm::Log2_64(WordLine - Line);
-return 0;
+return Line >= WordLine ? Line - WordLine : 2 * (WordLine - Line);
   };
   const syntax::Token *BestTok = nullptr;
-  // Search bounds are based on word length: 2^N lines forward.
-  unsigned BestCost = Word.Text.size() + 1;
+  unsigned BestCost = -1;
+  // Search bounds are based on word length:
+  // - forward: 2^N lines
+  // - backward: 2^(N-1) lines.
+  unsigned MaxDistance =
+  1U << std::min(Word.Text.size(),
+   std::numeric_limits::digits - 1);
+  // Line number for SM.translateLineCol() should be one-based, also
+  // SM.translateLineCol() can handle line number greater than
+  // number of lines in the file.
+  // - LineMin = max(1, WordLine + 1 - 2^(N-1))
+  // - LineMax = WordLine + 1 + 2^N
+  unsigned LineMin =
+  WordLine + 1 <= MaxDistance / 2 ? 1 : WordLine + 1 - MaxDistance / 2;
+  unsigned LineMax = WordLine + 1 + MaxDistance;
+  SourceLocation LocMin = SM.translateLineCol(File, LineMin, 1);
+  assert(LocMin.isValid());
+  SourceLocation LocMax = SM.translateLineCol(File, LineMax, 1);
+  assert(LocMax.isValid());
 
   // Updates BestTok and BestCost if Tok is a good candidate.
   // May return true if the cost is too high for this token.
   auto Consider = [&](const syntax::Token ) {
+if (Tok.location() < LocMin || Tok.location() > LocMax)
+  return true; // we are too far from the word, break the outer loop.
 if (!(Tok.kind() == tok::identifier && Tok.text(SM) == Word.Text))
   return false;
 // No point guessing the same location we started with.

diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index a48bb9c8c182..40637b5fa758 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -1428,6 +1428,11 @@ TEST(LocateSymbol, NearbyIdentifier) {
 
 
   // h^i
+
+
+
+
+  int x = hi;
 )cpp",
   R"cpp(
   // prefer nearest occurrence even if several matched tokens



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


[clang-tools-extra] d427df6 - [clangd] Don't use zlib when it's unavailable.

2020-09-16 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-09-16T11:05:18+03:00
New Revision: d427df6369f1d229a9f498b4dc621433ada380d2

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

LOG: [clangd] Don't use zlib when it's unavailable.

Without this patch `clangd` crashes at try to load compressed string table when 
`zlib` is not available.
Example:
- Build `clangd` with MinGW (`zlib` found)
- Build index
- Build `clangd` with Visual Studio compiler (`zlib` not found)
- Try to load index

Reviewed By: sammccall, adamcz

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Serialization.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Serialization.cpp 
b/clang-tools-extra/clangd/index/Serialization.cpp
index c099a30c4d34..e7f65f087b1c 100644
--- a/clang-tools-extra/clangd/index/Serialization.cpp
+++ b/clang-tools-extra/clangd/index/Serialization.cpp
@@ -201,12 +201,13 @@ llvm::Expected 
readStringTable(llvm::StringRef Data) {
   llvm::SmallString<1> UncompressedStorage;
   if (UncompressedSize == 0) // No compression
 Uncompressed = R.rest();
-  else {
+  else if (llvm::zlib::isAvailable()) {
 if (llvm::Error E = llvm::zlib::uncompress(R.rest(), UncompressedStorage,
UncompressedSize))
   return std::move(E);
 Uncompressed = UncompressedStorage;
-  }
+  } else
+return error("Compressed string table, but zlib is unavailable");
 
   StringTableIn Table;
   llvm::StringSaver Saver(Table.Arena);



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


[clang-tools-extra] 4457398 - [clangd] Don't crash on `#pragma clang __debug parser_crash`

2020-08-20 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-08-20T15:53:21+03:00
New Revision: 445739826567e5402b558f2c130d76dc916c82ec

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

LOG: [clangd] Don't crash on `#pragma clang __debug parser_crash`

Currently, clangd crashes when opening a file with `#pragma clang __debug 
parser_crash` (e.g. clang/test/Modules/Inputs/crash.h).
This patch disables these crashes.

Reviewed By: kadircet

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

Added: 


Modified: 
clang-tools-extra/clangd/Compiler.cpp
clang-tools-extra/clangd/unittests/CompilerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Compiler.cpp 
b/clang-tools-extra/clangd/Compiler.cpp
index 2c7ef471d382..f5875e2a7971 100644
--- a/clang-tools-extra/clangd/Compiler.cpp
+++ b/clang-tools-extra/clangd/Compiler.cpp
@@ -78,6 +78,8 @@ buildCompilerInvocation(const ParseInputs , 
clang::DiagnosticConsumer ,
   CI->getPreprocessorOpts().PCHThroughHeader.clear();
   CI->getPreprocessorOpts().PCHWithHdrStop = false;
   CI->getPreprocessorOpts().PCHWithHdrStopCreate = false;
+  // Don't crash on `#pragma clang __debug parser_crash`
+  CI->getPreprocessorOpts().DisablePragmaDebugCrash = true;
 
   // Recovery expression currently only works for C++.
   if (CI->getLangOpts()->CPlusPlus) {

diff  --git a/clang-tools-extra/clangd/unittests/CompilerTests.cpp 
b/clang-tools-extra/clangd/unittests/CompilerTests.cpp
index 59feb9312d23..45e9bcd9d534 100644
--- a/clang-tools-extra/clangd/unittests/CompilerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CompilerTests.cpp
@@ -51,6 +51,11 @@ TEST(BuildCompilerInvocation, DropsPCH) {
   IsEmpty());
 }
 
+TEST(BuildCompilerInvocation, PragmaDebugCrash) {
+  TestTU TU = TestTU::withCode("#pragma clang __debug parser_crash");
+  TU.build(); // no-crash
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang



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


[clang] 3fa0a03 - [clang] Check `expr` inside `InitListChecker::UpdateStructuredListElement()`

2020-08-12 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-08-12T22:12:43+03:00
New Revision: 3fa0a039ab6f856e39dab973df56831b63ed51c5

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

LOG: [clang] Check `expr` inside 
`InitListChecker::UpdateStructuredListElement()`

- Prevent nullptr-deference at try to emit warning for invalid `expr`
- Simplify `InitListChecker::UpdateStructuredListElement()` usages. We do not 
need to check `expr` and increment `StructuredIndex` (for invalid `expr`) 
before the call anymore.

Reviewed By: aaron.ballman

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

Added: 
clang/test/Sema/init-invalid-struct-array.c

Modified: 
clang/lib/Sema/SemaInit.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index f4cfae0f7d85..f63d600032ce 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -1585,10 +1585,7 @@ void InitListChecker::CheckScalarType(const 
InitializedEntity ,
   IList->setInit(Index, ResultExpr);
 }
   }
-  if (hadError)
-++StructuredIndex;
-  else
-UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
+  UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
   ++Index;
 }
 
@@ -1643,10 +1640,7 @@ void InitListChecker::CheckReferenceType(const 
InitializedEntity ,
   if (!VerifyOnly && expr)
 IList->setInit(Index, expr);
 
-  if (hadError)
-++StructuredIndex;
-  else
-UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
+  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
   ++Index;
 }
 
@@ -1697,11 +1691,7 @@ void InitListChecker::CheckVectorType(const 
InitializedEntity ,
   IList->setInit(Index, ResultExpr);
 }
   }
-  if (hadError)
-++StructuredIndex;
-  else
-UpdateStructuredListElement(StructuredList, StructuredIndex,
-ResultExpr);
+  UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
   ++Index;
   return;
 }
@@ -3100,8 +3090,12 @@ void 
InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
 
   if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
   StructuredIndex, expr)) {
-// This initializer overwrites a previous initializer. Warn.
-diagnoseInitOverride(PrevInit, expr->getSourceRange());
+// This initializer overwrites a previous initializer.
+// No need to diagnose when `expr` is nullptr because a more relevant
+// diagnostic has already been issued and this diagnostic is potentially
+// noise.
+if (expr)
+  diagnoseInitOverride(PrevInit, expr->getSourceRange());
   }
 
   ++StructuredIndex;

diff  --git a/clang/test/Sema/init-invalid-struct-array.c 
b/clang/test/Sema/init-invalid-struct-array.c
new file mode 100644
index ..e234d68039c0
--- /dev/null
+++ b/clang/test/Sema/init-invalid-struct-array.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+struct S {
+  Unknown u; // expected-error {{unknown type name 'Unknown'}}
+  int i;
+};
+// Should not crash
+struct S s[] = {[0].i = 0, [1].i = 1, {}};



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


[clang-tools-extra] dcb8d3b - [clang-tidy] Fix a crash in bugprone-not-null-terminated-result check when `__STDC_WANT_LIB_EXT1__` is not a literal.

2020-08-10 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-08-10T15:12:03+03:00
New Revision: dcb8d3b72234ea557df2af1141ad30bf1670a03a

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

LOG: [clang-tidy] Fix a crash in bugprone-not-null-terminated-result check when 
`__STDC_WANT_LIB_EXT1__` is not a literal.

If `__STDC_WANT_LIB_EXT1__` is not a literal (e.g. `#define 
__STDC_WANT_LIB_EXT1__ ((unsigned)1)`) bugprone-not-null-terminated-result 
check crashes.
Stack dump:
```
 #0 0x02185e6a llvm::sys::PrintStackTrace(llvm::raw_ostream&) 
(/llvm-project/build/bin/clang-tidy+0x2185e6a)
 #1 0x02183e8c llvm::sys::RunSignalHandlers() 
(/llvm-project/build/bin/clang-tidy+0x2183e8c)
 #2 0x02183ff3 SignalHandler(int) 
(/llvm-project/build/bin/clang-tidy+0x2183ff3)
 #3 0x7f08d91b1390 __restore_rt 
(/lib/x86_64-linux-gnu/libpthread.so.0+0x11390)
 #4 0x021338bb llvm::StringRef::getAsInteger(unsigned int, 
llvm::APInt&) const (/llvm-project/build/bin/clang-tidy+0x21338bb)
 #5 0x0052051c 
clang::tidy::bugprone::NotNullTerminatedResultCheck::check(clang::ast_matchers::MatchFinder::MatchResult
 const&) (/llvm-project/build/bin/clang-tidy+0x52051c)
```

Reviewed By: hokein

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/bugprone-not-null-terminated-result-stdc-want-lib-ext1-not-a-literal.c

Modified: 
clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index 7d484d777165..9a44ba2f58a5 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -805,10 +805,12 @@ void NotNullTerminatedResultCheck::check(
 // PP->getMacroInfo() returns nullptr if macro has no definition.
 if (MI) {
   const auto  = MI->tokens().back();
-  StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
-  llvm::APInt IntValue;
-  ValueStr.getAsInteger(10, IntValue);
-  AreSafeFunctionsWanted = IntValue.getZExtValue();
+  if (T.isLiteral() && T.getLiteralData()) {
+StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
+llvm::APInt IntValue;
+ValueStr.getAsInteger(10, IntValue);
+AreSafeFunctionsWanted = IntValue.getZExtValue();
+  }
 }
   }
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-not-null-terminated-result-stdc-want-lib-ext1-not-a-literal.c
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-not-null-terminated-result-stdc-want-lib-ext1-not-a-literal.c
new file mode 100644
index ..bba807fb6e09
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-not-null-terminated-result-stdc-want-lib-ext1-not-a-literal.c
@@ -0,0 +1,16 @@
+// RUN: %check_clang_tidy %s bugprone-not-null-terminated-result %t -- \
+// RUN: -- -std=c11 -I %S/Inputs/bugprone-not-null-terminated-result
+
+#include "not-null-terminated-result-c.h"
+
+#define __STDC_LIB_EXT1__ 1
+#define __STDC_WANT_LIB_EXT1__ ((unsigned)1)
+
+void f(const char *src) {
+  char dest[13];
+  memcpy_s(dest, 13, src, strlen(src) - 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 
'memcpy_s' is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: char dest[14];
+  // CHECK-FIXES-NEXT: strncpy_s(dest, 14, src, strlen(src) - 1);
+}
+



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


[clang-tools-extra] 5965fbf - [clang-tidy] Fix a crash in bugprone-not-null-terminated-result check when `__STDC_WANT_LIB_EXT1__` was undefined after definition.

2020-08-10 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-08-10T10:24:38+03:00
New Revision: 5965fbf81b25217c40b09b48bd808a8f4a5d4e89

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

LOG: [clang-tidy] Fix a crash in bugprone-not-null-terminated-result check when 
`__STDC_WANT_LIB_EXT1__` was undefined after definition.

PP->getMacroInfo() returns nullptr for undefined macro, so we need to check 
this return value before dereference.
Stack dump:
```
 #0 0x02185e6a llvm::sys::PrintStackTrace(llvm::raw_ostream&) 
(/llvm-project/build/bin/clang-tidy+0x2185e6a)
 #1 0x02183e8c llvm::sys::RunSignalHandlers() 
(/llvm-project/build/bin/clang-tidy+0x2183e8c)
 #2 0x02183ff3 SignalHandler(int) 
(/llvm-project/build/bin/clang-tidy+0x2183ff3)
 #3 0x7f37df9b1390 __restore_rt 
(/lib/x86_64-linux-gnu/libpthread.so.0+0x11390)
 #4 0x0052054e 
clang::tidy::bugprone::NotNullTerminatedResultCheck::check(clang::ast_matchers::MatchFinder::MatchResult
 const&) (/llvm-project/build/bin/clang-tidy+0x52054e)
```

Reviewed By: hokein

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/bugprone-not-null-terminated-result-undef-stdc-want-lib-ext1.c

Modified: 
clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index 269d69c1c124..7d484d777165 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -802,11 +802,14 @@ void NotNullTerminatedResultCheck::check(
 while (It != PP->macro_end() && !AreSafeFunctionsWanted.hasValue()) {
   if (It->first->getName() == "__STDC_WANT_LIB_EXT1__") {
 const auto *MI = PP->getMacroInfo(It->first);
-const auto  = MI->tokens().back();
-StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
-llvm::APInt IntValue;
-ValueStr.getAsInteger(10, IntValue);
-AreSafeFunctionsWanted = IntValue.getZExtValue();
+// PP->getMacroInfo() returns nullptr if macro has no definition.
+if (MI) {
+  const auto  = MI->tokens().back();
+  StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
+  llvm::APInt IntValue;
+  ValueStr.getAsInteger(10, IntValue);
+  AreSafeFunctionsWanted = IntValue.getZExtValue();
+}
   }
 
   ++It;

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-not-null-terminated-result-undef-stdc-want-lib-ext1.c
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-not-null-terminated-result-undef-stdc-want-lib-ext1.c
new file mode 100644
index ..25e38800d28b
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-not-null-terminated-result-undef-stdc-want-lib-ext1.c
@@ -0,0 +1,17 @@
+// RUN: %check_clang_tidy %s bugprone-not-null-terminated-result %t -- \
+// RUN: -- -std=c11 -I %S/Inputs/bugprone-not-null-terminated-result
+
+#include "not-null-terminated-result-c.h"
+
+#define __STDC_LIB_EXT1__ 1
+#define __STDC_WANT_LIB_EXT1__ 1
+#undef __STDC_WANT_LIB_EXT1__
+
+void f(const char *src) {
+  char dest[13];
+  memcpy_s(dest, 13, src, strlen(src) - 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 
'memcpy_s' is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: char dest[14];
+  // CHECK-FIXES-NEXT: strncpy_s(dest, 14, src, strlen(src) - 1);
+}
+



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


[clang-tools-extra] 9f24148 - [clangd] Fix crash in bugprone-bad-signal-to-kill-thread clang-tidy check.

2020-08-06 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-08-06T21:45:21+03:00
New Revision: 9f24148b212698aca220ac923d215c2073e443ce

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

LOG: [clangd] Fix crash in bugprone-bad-signal-to-kill-thread clang-tidy check.

Inside clangd, clang-tidy checks don't see preprocessor events in the preamble.
This leads to `Token::PtrData == nullptr` for tokens that the macro is defined 
to.
E.g. `#define SIGTERM 15`:
- Token::Kind == tok::numeric_constant (Token::isLiteral() == true)
- Token::UintData == 2
- Token::PtrData == nullptr

As the result of this, bugprone-bad-signal-to-kill-thread check crashes at 
null-dereference inside clangd.

Reviewed By: hokein

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
index 0720c7e689a1..3833640b3de3 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
@@ -39,7 +39,7 @@ void BadSignalToKillThreadCheck::check(const 
MatchFinder::MatchResult ) {
   return llvm::None;
 const MacroInfo *MI = PP->getMacroInfo(It->first);
 const Token  = MI->tokens().back();
-if (!T.isLiteral())
+if (!T.isLiteral() || !T.getLiteralData())
   return llvm::None;
 StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
 

diff  --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp 
b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
index fcc6d40a988a..e8757079c675 100644
--- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -438,6 +438,21 @@ TEST(DiagnosticTest, 
ClangTidySuppressionCommentTrumpsWarningAsError) {
   EXPECT_THAT(TU.build().getDiagnostics(), UnorderedElementsAre());
 }
 
+TEST(DiagnosticTest, ClangTidyNoLiteralDataInMacroToken) {
+  Annotations Main(R"cpp(
+#define SIGTERM 15
+using pthread_t = int;
+int pthread_kill(pthread_t thread, int sig);
+int func() {
+  pthread_t thread;
+  return pthread_kill(thread, 0);
+}
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.ClangTidyChecks = "-*,bugprone-bad-signal-to-kill-thread";
+  EXPECT_THAT(TU.build().getDiagnostics(), UnorderedElementsAre()); // no-crash
+}
+
 TEST(DiagnosticsTest, Preprocessor) {
   // This looks like a preamble, but there's an #else in the middle!
   // Check that:



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


[clang-tools-extra] 216ad2d - [clang-tidy] Fix bugprone-bad-signal-to-kill-thread crash when `SIGTERM` is not a literal.

2020-08-06 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-08-06T10:32:03+03:00
New Revision: 216ad2da74f0e952af8f1c8ac84e19146d739ff2

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

LOG: [clang-tidy] Fix bugprone-bad-signal-to-kill-thread crash when `SIGTERM` 
is not a literal.

If `SIGTERM` is not a literal (e.g. `#define SIGTERM ((unsigned)15)`) 
bugprone-bad-signal-to-kill-thread check crashes.
Stack dump:
```
 #0 0x0217d15a llvm::sys::PrintStackTrace(llvm::raw_ostream&) 
(/llvm-project/build/bin/clang-tidy+0x217d15a)
 #1 0x0217b17c llvm::sys::RunSignalHandlers() 
(/llvm-project/build/bin/clang-tidy+0x217b17c)
 #2 0x0217b2e3 SignalHandler(int) 
(/llvm-project/build/bin/clang-tidy+0x217b2e3)
 #3 0x7f6a7efb1390 __restore_rt 
(/lib/x86_64-linux-gnu/libpthread.so.0+0x11390)
 #4 0x0212ac9b llvm::StringRef::getAsInteger(unsigned int, 
llvm::APInt&) const (/llvm-project/build/bin/clang-tidy+0x212ac9b)
 #5 0x00593501 
clang::tidy::bugprone::BadSignalToKillThreadCheck::check(clang::ast_matchers::MatchFinder::MatchResult
 const&) (/llvm-project/build/bin/clang-tidy+0x593501)
```

Reviewed By: hokein

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/bugprone-bad-signal-to-kill-thread-sigterm-not-a-literal.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
index 2c7b7b9faa9b..0720c7e689a1 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
@@ -39,6 +39,8 @@ void BadSignalToKillThreadCheck::check(const 
MatchFinder::MatchResult ) {
   return llvm::None;
 const MacroInfo *MI = PP->getMacroInfo(It->first);
 const Token  = MI->tokens().back();
+if (!T.isLiteral())
+  return llvm::None;
 StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
 
 llvm::APInt IntValue;

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-bad-signal-to-kill-thread-sigterm-not-a-literal.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-bad-signal-to-kill-thread-sigterm-not-a-literal.cpp
new file mode 100644
index ..f96f270dbf29
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-bad-signal-to-kill-thread-sigterm-not-a-literal.cpp
@@ -0,0 +1,10 @@
+// RUN: clang-tidy %s --checks=-*,bugprone-bad-signal-to-kill-thread -- | 
count 0
+
+#define SIGTERM ((unsigned)15) // no-crash
+using pthread_t = int;
+int pthread_kill(pthread_t thread, int sig);
+
+int func() {
+  pthread_t thread;
+  return pthread_kill(thread, 0);
+}



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


[clang-tools-extra] 8671166 - [clang-tidy] Fix bugprone-bad-signal-to-kill-thread crash when `SIGTERM` was undefined after definition.

2020-08-06 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-08-06T10:28:20+03:00
New Revision: 86711668330cf48325a5e960f30d33f6a7364db2

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

LOG: [clang-tidy] Fix bugprone-bad-signal-to-kill-thread crash when `SIGTERM` 
was undefined after definition.

`PP->getMacroInfo()` returns nullptr for undefined macro, which leads to 
null-dereference at `MI->tockens().back()`.
Stack dump:
```
 #0 0x0217d15a llvm::sys::PrintStackTrace(llvm::raw_ostream&) 
(/llvm-project/build/bin/clang-tidy+0x217d15a)
 #1 0x0217b17c llvm::sys::RunSignalHandlers() 
(/llvm-project/build/bin/clang-tidy+0x217b17c)
 #2 0x0217b2e3 SignalHandler(int) 
(/llvm-project/build/bin/clang-tidy+0x217b2e3)
 #3 0x7f39be5b1390 __restore_rt 
(/lib/x86_64-linux-gnu/libpthread.so.0+0x11390)
 #4 0x00593532 
clang::tidy::bugprone::BadSignalToKillThreadCheck::check(clang::ast_matchers::MatchFinder::MatchResult
 const&) (/llvm-project/build/bin/clang-tidy+0x593532)
```

Reviewed By: hokein

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/bugprone-bad-signal-to-kill-thread-undef-sigterm.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
index 3591a7da8eb7..2c7b7b9faa9b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
@@ -30,7 +30,8 @@ static Preprocessor *PP;
 
 void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult ) 
{
   const auto IsSigterm = [](const auto ) -> bool {
-return KeyValue.first->getName() == "SIGTERM";
+return KeyValue.first->getName() == "SIGTERM" &&
+   KeyValue.first->hasMacroDefinition();
   };
   const auto TryExpandAsInteger =
   [](Preprocessor::macro_iterator It) -> Optional {

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-bad-signal-to-kill-thread-undef-sigterm.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-bad-signal-to-kill-thread-undef-sigterm.cpp
new file mode 100644
index ..7c2ae16a08e8
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-bad-signal-to-kill-thread-undef-sigterm.cpp
@@ -0,0 +1,11 @@
+// RUN: clang-tidy %s --checks=-*,bugprone-bad-signal-to-kill-thread -- | 
count 0
+
+#define SIGTERM 15
+#undef SIGTERM // no-crash
+using pthread_t = int;
+int pthread_kill(pthread_t thread, int sig);
+
+int func() {
+  pthread_t thread;
+  return pthread_kill(thread, 0);
+}



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


[clang-tools-extra] 05b1734 - [clangd] findNearbyIdentifier(): fix the word search in the token stream.

2020-07-30 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-07-30T12:45:58+03:00
New Revision: 05b173466142596b3297ab02e423574cb74b3799

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

LOG: [clangd] findNearbyIdentifier(): fix the word search in the token stream.

Without this patch the word occurrence search always returns the first token of 
the file.
Despite of that, `findNeardyIdentifier()` returns the correct result (but 
inefficently) until there are several matched tokens with the same value 
`floor(log2( - ))` (e.g. several matched tokens on the 
same line).

Reviewed By: kadircet

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/unittests/XRefsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index aeff7ebc32a2..cf747b607f4a 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -518,7 +518,7 @@ const syntax::Token *findNearbyIdentifier(const SpelledWord 
,
   // Find where the word occurred in the token stream, to search forward & 
back.
   auto *I = llvm::partition_point(SpelledTokens, [&](const syntax::Token ) {
 assert(SM.getFileID(T.location()) == SM.getFileID(Word.Location));
-return T.location() >= Word.Location; // Comparison OK: same file.
+return T.location() < Word.Location; // Comparison OK: same file.
   });
   // Search for matches after the cursor.
   for (const syntax::Token  : llvm::makeArrayRef(I, SpelledTokens.end()))

diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 0428303f5b0a..0a8f85ed5317 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -1197,7 +1197,14 @@ TEST(LocateSymbol, NearbyIdentifier) {
 
   // h^i
 )cpp",
-  };
+  R"cpp(
+  // prefer nearest occurrence even if several matched tokens
+  // have the same value of `floor(log2( - ))`.
+  int hello;
+  int x = hello, y = hello;
+  int z = [[hello]];
+  // h^ello
+)cpp"};
   for (const char *Test : Tests) {
 Annotations T(Test);
 auto AST = TestTU::withCode(T.code()).build();



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


[clang-tools-extra] 90684d1 - [clangd] Collect references for externally visible main-file symbols

2020-07-27 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-07-27T15:35:53+03:00
New Revision: 90684d1545167ee4e0c93d8eaf6ba4a3c7ab710e

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

LOG: [clangd] Collect references for externally visible main-file symbols

Summary:
Without this patch clangd does not collect references for main-file symbols if 
there is no public declaration in preamble.
Example:
`test1.c`
```
void f1() {}
```

`test2.c`
```
extern void f1();
void f2() {
  f^1();
}
```
`Find all references` does not show definition of f1() in the result, but GTD 
works OK.

Reviewers: sammccall, kadircet

Reviewed By: kadircet

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/index/SymbolCollector.cpp
clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index 6c11399c87b6..c163951aff9b 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -314,7 +314,8 @@ bool SymbolCollector::handleDeclOccurrence(
   // file locations for references (as it aligns the behavior of clangd's
   // AST-based xref).
   // FIXME: we should try to use the file locations for other fields.
-  if (CollectRef && !IsMainFileOnly && !isa(ND) &&
+  if (CollectRef && (!IsMainFileOnly || ND->isExternallyVisible()) &&
+  !isa(ND) &&
   (Opts.RefsInHeaders ||
SM.getFileID(SM.getFileLoc(Loc)) == SM.getMainFileID()))
 DeclRefs[ND].emplace_back(SM.getFileLoc(Loc), Roles);

diff  --git a/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp 
b/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
index 70d5156b1072..f1c582ef1abe 100644
--- a/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
+++ b/clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
@@ -171,7 +171,7 @@ TEST_F(BackgroundIndexTest, IndexTwoFiles) {
   #endif
   )cpp";
   FS.Files[testPath("root/A.cc")] =
-  "#include \"A.h\"\nvoid g() { (void)common; }";
+  "#include \"A.h\"\nstatic void g() { (void)common; }";
   FS.Files[testPath("root/B.cc")] =
   R"cpp(
   #define A 0

diff  --git a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp 
b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
index 9e4f75b5cca3..3614ab2c5cb9 100644
--- a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -624,11 +624,13 @@ TEST_F(SymbolCollectorTest, Refs) {
   EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(Symbols, "NS").ID, _;
   EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "MACRO").ID,
   HaveRanges(Main.ranges("macro");
-  // Symbols *only* in the main file (a, b, c, FUNC) had no refs collected.
+  // Symbols *only* in the main file:
+  // - (a, b) externally visible and should have refs.
+  // - (c, FUNC) externally invisible and had no refs collected.
   auto MainSymbols =
   TestTU::withHeaderCode(SymbolsOnlyInMainCode.code()).headerSymbols();
-  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "a").ID, _;
-  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "b").ID, _;
+  EXPECT_THAT(Refs, Contains(Pair(findSymbol(MainSymbols, "a").ID, _)));
+  EXPECT_THAT(Refs, Contains(Pair(findSymbol(MainSymbols, "b").ID, _)));
   EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "c").ID, _;
   EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "FUNC").ID, 
_;
 }
@@ -816,11 +818,15 @@ TEST_F(SymbolCollectorTest, HeaderAsMainFile) {
 $Foo[[Foo]] fo;
   }
   )");
-  // The main file is normal .cpp file, we shouldn't collect any refs of 
symbols
-  // which are not declared in the preamble.
+  // The main file is normal .cpp file, we should collect the refs
+  // for externally visible symbols.
   TestFileName = testPath("foo.cpp");
   runSymbolCollector("", Header.code());
-  EXPECT_THAT(Refs, UnorderedElementsAre());
+  EXPECT_THAT(Refs,
+  UnorderedElementsAre(Pair(findSymbol(Symbols, "Foo").ID,
+HaveRanges(Header.ranges("Foo"))),
+   Pair(findSymbol(Symbols, "Func").ID,
+HaveRanges(Header.ranges("Func");
 
   // Run the .h file as main file, we should collect the refs.
   TestFileName = testPath("foo.h");




[clang-tools-extra] 98b56c0 - [clangd] Fixes in lit tests

2020-07-22 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-07-22T16:00:34+03:00
New Revision: 98b56c09be002855df18dada7debdb1322aad7d9

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

LOG: [clangd] Fixes in lit tests

Summary:
Changes:
- `background-index.test` Add Windows support, don't create redundant `*-e` 
files on macOS
- `did-change-configuration-params.test` Replace `cat | FileCheck` with 
`FileCheck --input-file`
- `test-uri-windows.test` This test did not run on Windows displite `REQUIRES: 
windows-gnu || windows-msvc` (replacement: `UNSUPPORTED: !(windows-gnu || 
windows-msvc)`).

Reviewers: sammccall, kadircet

Reviewed By: kadircet

Subscribers: thakis, njames93, ormris, ilya-biryukov, MaskRay, jkorous, 
arphaman, kadircet, usaxena95, cfe-commits

Tags: #clang

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

Added: 

clang-tools-extra/clangd/test/Inputs/background-index/compile_commands.json.tmpl

clang-tools-extra/clangd/test/Inputs/background-index/definition.jsonrpc.tmpl

Modified: 
clang-tools-extra/clangd/test/background-index.test
clang-tools-extra/clangd/test/did-change-configuration-params.test
clang-tools-extra/clangd/test/test-uri-windows.test

Removed: 
clang-tools-extra/clangd/test/Inputs/background-index/compile_commands.json
clang-tools-extra/clangd/test/Inputs/background-index/definition.jsonrpc



diff  --git 
a/clang-tools-extra/clangd/test/Inputs/background-index/compile_commands.json 
b/clang-tools-extra/clangd/test/Inputs/background-index/compile_commands.json.tmpl
similarity index 100%
rename from 
clang-tools-extra/clangd/test/Inputs/background-index/compile_commands.json
rename to 
clang-tools-extra/clangd/test/Inputs/background-index/compile_commands.json.tmpl

diff  --git 
a/clang-tools-extra/clangd/test/Inputs/background-index/definition.jsonrpc 
b/clang-tools-extra/clangd/test/Inputs/background-index/definition.jsonrpc.tmpl
similarity index 100%
rename from 
clang-tools-extra/clangd/test/Inputs/background-index/definition.jsonrpc
rename to 
clang-tools-extra/clangd/test/Inputs/background-index/definition.jsonrpc.tmpl

diff  --git a/clang-tools-extra/clangd/test/background-index.test 
b/clang-tools-extra/clangd/test/background-index.test
index 41184443e947..1983f0957dcc 100644
--- a/clang-tools-extra/clangd/test/background-index.test
+++ b/clang-tools-extra/clangd/test/background-index.test
@@ -1,23 +1,23 @@
-# We need to splice paths into file:// URIs for this test.
-# UNSUPPORTED: windows-msvc
-
 # Use a copy of inputs, as we'll mutate it (as will the background index).
-# RUN: rm -rf %t
-# RUN: cp -r %S/Inputs/background-index %t
+# RUN: rm -rf %/t
+# RUN: cp -r %/S/Inputs/background-index %/t
 # Need to embed the correct temp path in the actual JSON-RPC requests.
-# RUN: sed -i -e "s|DIRECTORY|%t|" %t/definition.jsonrpc
-# RUN: sed -i -e "s|DIRECTORY|%t|" %t/compile_commands.json
+# RUN: sed -e "s|DIRECTORY|%/t|" %/t/definition.jsonrpc.tmpl > 
%/t/definition.jsonrpc.1
+# RUN: sed -e "s|DIRECTORY|%/t|" %/t/compile_commands.json.tmpl > 
%/t/compile_commands.json
+# On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
+# (with the extra slash in the front), so we add it here.
+# RUN: sed -E -e 's|"file://([A-Z]):/|"file:///\1:/|g' 
%/t/definition.jsonrpc.1 > %/t/definition.jsonrpc
 
 # We're editing bar.cpp, which includes foo.h.
 # foo() is declared in foo.h and defined in foo.cpp.
 # The background index should allow us to go-to-definition on foo().
 # We should also see indexing progress notifications.
-# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc --check-prefixes=CHECK,BUILD
+# RUN: clangd -background-index -lit-test < %/t/definition.jsonrpc | FileCheck 
%/t/definition.jsonrpc --check-prefixes=CHECK,BUILD
 
 # Test that the index is writing files in the expected location.
-# RUN: ls %t/.cache/clangd/index/foo.cpp.*.idx
-# RUN: ls %t/sub_dir/.cache/clangd/index/foo.h.*.idx
+# RUN: ls %/t/.cache/clangd/index/foo.cpp.*.idx
+# RUN: ls %/t/sub_dir/.cache/clangd/index/foo.h.*.idx
 
 # Test the index is read from disk: delete code and restart clangd.
-# RUN: rm %t/foo.cpp
-# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc --check-prefixes=CHECK,USE
+# RUN: rm %/t/foo.cpp
+# RUN: clangd -background-index -lit-test < %/t/definition.jsonrpc | FileCheck 
%/t/definition.jsonrpc --check-prefixes=CHECK,USE

diff  --git 
a/clang-tools-extra/clangd/test/did-change-configuration-params.test 
b/clang-tools-extra/clangd/test/did-change-configuration-params.test
index 4aef1011b370..19d41d0812e2 100644
--- a/clang-tools-extra/clangd/test/did-change-configuration-params.test
+++ 

[clang-tools-extra] 23ff4e4 - Revert "[clangd] Fixes in lit tests"

2020-07-21 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-07-21T23:32:47+03:00
New Revision: 23ff4e4f5d651b4a75aede51defc8e903dfd694d

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

LOG: Revert "[clangd] Fixes in lit tests"

This reverts commit ff63d6be93dc5958bf35d92919ce6fafcc611e89.

Added: 


Modified: 
clang-tools-extra/clangd/test/background-index.test
clang-tools-extra/clangd/test/did-change-configuration-params.test
clang-tools-extra/clangd/test/test-uri-windows.test

Removed: 




diff  --git a/clang-tools-extra/clangd/test/background-index.test 
b/clang-tools-extra/clangd/test/background-index.test
index c17abb43376f..41184443e947 100644
--- a/clang-tools-extra/clangd/test/background-index.test
+++ b/clang-tools-extra/clangd/test/background-index.test
@@ -1,23 +1,23 @@
+# We need to splice paths into file:// URIs for this test.
+# UNSUPPORTED: windows-msvc
+
 # Use a copy of inputs, as we'll mutate it (as will the background index).
-# RUN: rm -rf %/t
-# RUN: cp -r %/S/Inputs/background-index %/t
+# RUN: rm -rf %t
+# RUN: cp -r %S/Inputs/background-index %t
 # Need to embed the correct temp path in the actual JSON-RPC requests.
-# RUN: sed -i -e "s|DIRECTORY|%/t|" %/t/definition.jsonrpc
-# RUN: sed -i -e "s|DIRECTORY|%/t|" %/t/compile_commands.json
-# On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
-# (with the extra slash in the front), so we add it here.
-# RUN: sed -i -E -e 's|"file://([A-Z]):/|"file:///\1:/|g' 
%/t/definition.jsonrpc
+# RUN: sed -i -e "s|DIRECTORY|%t|" %t/definition.jsonrpc
+# RUN: sed -i -e "s|DIRECTORY|%t|" %t/compile_commands.json
 
 # We're editing bar.cpp, which includes foo.h.
 # foo() is declared in foo.h and defined in foo.cpp.
 # The background index should allow us to go-to-definition on foo().
 # We should also see indexing progress notifications.
-# RUN: clangd -background-index -lit-test < %/t/definition.jsonrpc | FileCheck 
%/t/definition.jsonrpc --check-prefixes=CHECK,BUILD
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc --check-prefixes=CHECK,BUILD
 
 # Test that the index is writing files in the expected location.
-# RUN: ls %/t/.cache/clangd/index/foo.cpp.*.idx
-# RUN: ls %/t/sub_dir/.cache/clangd/index/foo.h.*.idx
+# RUN: ls %t/.cache/clangd/index/foo.cpp.*.idx
+# RUN: ls %t/sub_dir/.cache/clangd/index/foo.h.*.idx
 
 # Test the index is read from disk: delete code and restart clangd.
-# RUN: rm %/t/foo.cpp
-# RUN: clangd -background-index -lit-test < %/t/definition.jsonrpc | FileCheck 
%/t/definition.jsonrpc --check-prefixes=CHECK,USE
+# RUN: rm %t/foo.cpp
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc --check-prefixes=CHECK,USE

diff  --git 
a/clang-tools-extra/clangd/test/did-change-configuration-params.test 
b/clang-tools-extra/clangd/test/did-change-configuration-params.test
index 19d41d0812e2..4aef1011b370 100644
--- a/clang-tools-extra/clangd/test/did-change-configuration-params.test
+++ b/clang-tools-extra/clangd/test/did-change-configuration-params.test
@@ -1,5 +1,5 @@
 # RUN: clangd -compile_args_from=lsp -lit-test < %s 2> %t | FileCheck 
-strict-whitespace %s
-# RUN: FileCheck --check-prefix=ERR --input-file=%t %s
+# RUN: cat %t | FileCheck --check-prefix=ERR %s
 # UNSUPPORTED: windows-gnu,windows-msvc
 
{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
 ---

diff  --git a/clang-tools-extra/clangd/test/test-uri-windows.test 
b/clang-tools-extra/clangd/test/test-uri-windows.test
index 3f03b2985a70..381c48fafc03 100644
--- a/clang-tools-extra/clangd/test/test-uri-windows.test
+++ b/clang-tools-extra/clangd/test/test-uri-windows.test
@@ -1,5 +1,5 @@
 # RUN: clangd -lit-test < %s | FileCheck -strict-whitespace %s
-# UNSUPPORTED: !(windows-gnu || windows-msvc)
+# REQUIRES: windows-gnu || windows-msvc
 # Test authority-less URI
 
{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
 ---



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


[clang-tools-extra] ff63d6b - [clangd] Fixes in lit tests

2020-07-21 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-07-21T21:21:40+03:00
New Revision: ff63d6be93dc5958bf35d92919ce6fafcc611e89

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

LOG: [clangd] Fixes in lit tests

Summary:
Changes:
- `background-index.test` Add Windows support.
- `did-change-configuration-params.test` Replace `cat | FileCheck` with 
`FileCheck --input-file`
- `test-uri-windows.test` This test did not run on Windows displite `REQUIRES: 
windows-gnu || windows-msvc` (replacement: `UNSUPPORTED: !(windows-gnu || 
windows-msvc)`).

Reviewers: sammccall, kadircet

Reviewed By: kadircet

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/test/background-index.test
clang-tools-extra/clangd/test/did-change-configuration-params.test
clang-tools-extra/clangd/test/test-uri-windows.test

Removed: 




diff  --git a/clang-tools-extra/clangd/test/background-index.test 
b/clang-tools-extra/clangd/test/background-index.test
index 41184443e947..c17abb43376f 100644
--- a/clang-tools-extra/clangd/test/background-index.test
+++ b/clang-tools-extra/clangd/test/background-index.test
@@ -1,23 +1,23 @@
-# We need to splice paths into file:// URIs for this test.
-# UNSUPPORTED: windows-msvc
-
 # Use a copy of inputs, as we'll mutate it (as will the background index).
-# RUN: rm -rf %t
-# RUN: cp -r %S/Inputs/background-index %t
+# RUN: rm -rf %/t
+# RUN: cp -r %/S/Inputs/background-index %/t
 # Need to embed the correct temp path in the actual JSON-RPC requests.
-# RUN: sed -i -e "s|DIRECTORY|%t|" %t/definition.jsonrpc
-# RUN: sed -i -e "s|DIRECTORY|%t|" %t/compile_commands.json
+# RUN: sed -i -e "s|DIRECTORY|%/t|" %/t/definition.jsonrpc
+# RUN: sed -i -e "s|DIRECTORY|%/t|" %/t/compile_commands.json
+# On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
+# (with the extra slash in the front), so we add it here.
+# RUN: sed -i -E -e 's|"file://([A-Z]):/|"file:///\1:/|g' 
%/t/definition.jsonrpc
 
 # We're editing bar.cpp, which includes foo.h.
 # foo() is declared in foo.h and defined in foo.cpp.
 # The background index should allow us to go-to-definition on foo().
 # We should also see indexing progress notifications.
-# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc --check-prefixes=CHECK,BUILD
+# RUN: clangd -background-index -lit-test < %/t/definition.jsonrpc | FileCheck 
%/t/definition.jsonrpc --check-prefixes=CHECK,BUILD
 
 # Test that the index is writing files in the expected location.
-# RUN: ls %t/.cache/clangd/index/foo.cpp.*.idx
-# RUN: ls %t/sub_dir/.cache/clangd/index/foo.h.*.idx
+# RUN: ls %/t/.cache/clangd/index/foo.cpp.*.idx
+# RUN: ls %/t/sub_dir/.cache/clangd/index/foo.h.*.idx
 
 # Test the index is read from disk: delete code and restart clangd.
-# RUN: rm %t/foo.cpp
-# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc --check-prefixes=CHECK,USE
+# RUN: rm %/t/foo.cpp
+# RUN: clangd -background-index -lit-test < %/t/definition.jsonrpc | FileCheck 
%/t/definition.jsonrpc --check-prefixes=CHECK,USE

diff  --git 
a/clang-tools-extra/clangd/test/did-change-configuration-params.test 
b/clang-tools-extra/clangd/test/did-change-configuration-params.test
index 4aef1011b370..19d41d0812e2 100644
--- a/clang-tools-extra/clangd/test/did-change-configuration-params.test
+++ b/clang-tools-extra/clangd/test/did-change-configuration-params.test
@@ -1,5 +1,5 @@
 # RUN: clangd -compile_args_from=lsp -lit-test < %s 2> %t | FileCheck 
-strict-whitespace %s
-# RUN: cat %t | FileCheck --check-prefix=ERR %s
+# RUN: FileCheck --check-prefix=ERR --input-file=%t %s
 # UNSUPPORTED: windows-gnu,windows-msvc
 
{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
 ---

diff  --git a/clang-tools-extra/clangd/test/test-uri-windows.test 
b/clang-tools-extra/clangd/test/test-uri-windows.test
index 381c48fafc03..3f03b2985a70 100644
--- a/clang-tools-extra/clangd/test/test-uri-windows.test
+++ b/clang-tools-extra/clangd/test/test-uri-windows.test
@@ -1,5 +1,5 @@
 # RUN: clangd -lit-test < %s | FileCheck -strict-whitespace %s
-# REQUIRES: windows-gnu || windows-msvc
+# UNSUPPORTED: !(windows-gnu || windows-msvc)
 # Test authority-less URI
 
{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
 ---



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