[clang-tools-extra] r362176 - [clangd] clang-format SymbolCollector.cpp

2019-06-01 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Thu May 30 16:54:43 2019
New Revision: 362176

URL: http://llvm.org/viewvc/llvm-project?rev=362176&view=rev
Log:
[clangd] clang-format SymbolCollector.cpp

Modified:
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=362176&r1=362175&r2=362176&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Thu May 30 
16:54:43 2019
@@ -416,8 +416,7 @@ bool SymbolCollector::handleMacroOccuren
   return true;
 }
 
-void SymbolCollector::setIncludeLocation(const Symbol &S,
- SourceLocation Loc) {
+void SymbolCollector::setIncludeLocation(const Symbol &S, SourceLocation Loc) {
   if (Opts.CollectIncludePath)
 if (shouldCollectIncludePath(S.SymInfo.Kind))
   // Use the expansion location to get the #include header since this is
@@ -681,7 +680,7 @@ static bool isErrorAboutInclude(llvm::St
   if (!Line.consume_front("#"))
 return false;
   Line = Line.ltrim();
-  if (! Line.startswith("error"))
+  if (!Line.startswith("error"))
 return false;
   return Line.contains_lower("includ"); // Matches "include" or "including".
 }
@@ -689,7 +688,7 @@ static bool isErrorAboutInclude(llvm::St
 bool SymbolCollector::isDontIncludeMeHeader(llvm::StringRef Content) {
   llvm::StringRef Line;
   // Only sniff up to 100 lines or 10KB.
-  Content = Content.take_front(100*100);
+  Content = Content.take_front(100 * 100);
   for (unsigned I = 0; I < 100 && !Content.empty(); ++I) {
 std::tie(Line, Content) = Content.split('\n');
 if (isIf(Line) && isErrorAboutInclude(Content.split('\n').first))


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


[clang-tools-extra] r362352 - [clangd] Add RelationSlab

2019-06-04 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Sun Jun  2 21:55:46 2019
New Revision: 362352

URL: http://llvm.org/viewvc/llvm-project?rev=362352&view=rev
Log:
[clangd] Add RelationSlab

Summary:
RelationSlab is a new index data structure that stores relations between
symbols.

Reviewers: kadircet

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

Tags: #clang

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

Added:
clang-tools-extra/trunk/clangd/index/Relation.cpp
clang-tools-extra/trunk/clangd/index/Relation.h
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/index/Index.h
clang-tools-extra/trunk/clangd/unittests/IndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=362352&r1=362351&r2=362352&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Sun Jun  2 21:55:46 2019
@@ -77,6 +77,7 @@ add_clang_library(clangDaemon
   index/MemIndex.cpp
   index/Merge.cpp
   index/Ref.cpp
+  index/Relation.cpp
   index/Serialization.cpp
   index/Symbol.cpp
   index/SymbolCollector.cpp

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=362352&r1=362351&r2=362352&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Sun Jun  2 21:55:46 2019
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
 #include "Ref.h"
+#include "Relation.h"
 #include "Symbol.h"
 #include "SymbolID.h"
 #include "llvm/ADT/DenseSet.h"

Added: clang-tools-extra/trunk/clangd/index/Relation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Relation.cpp?rev=362352&view=auto
==
--- clang-tools-extra/trunk/clangd/index/Relation.cpp (added)
+++ clang-tools-extra/trunk/clangd/index/Relation.cpp Sun Jun  2 21:55:46 2019
@@ -0,0 +1,40 @@
+//===--- Relation.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "Relation.h"
+
+#include 
+
+namespace clang {
+namespace clangd {
+
+llvm::iterator_range
+RelationSlab::lookup(const SymbolID &Subject,
+ index::SymbolRole Predicate) const {
+  auto IterPair = std::equal_range(Relations.begin(), Relations.end(),
+   Relation{Subject, Predicate, SymbolID{}},
+   [](const Relation &A, const Relation &B) {
+ return std::tie(A.Subject, A.Predicate) <
+std::tie(B.Subject, B.Predicate);
+   });
+  return {IterPair.first, IterPair.second};
+}
+
+RelationSlab RelationSlab::Builder::build() && {
+  // Sort in SPO order.
+  std::sort(Relations.begin(), Relations.end());
+
+  // Remove duplicates.
+  Relations.erase(std::unique(Relations.begin(), Relations.end()),
+  Relations.end());
+
+  return RelationSlab{std::move(Relations)};
+}
+
+} // namespace clangd
+} // namespace clang

Added: clang-tools-extra/trunk/clangd/index/Relation.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Relation.h?rev=362352&view=auto
==
--- clang-tools-extra/trunk/clangd/index/Relation.h (added)
+++ clang-tools-extra/trunk/clangd/index/Relation.h Sun Jun  2 21:55:46 2019
@@ -0,0 +1,88 @@
+//===--- Relation.h --*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_RELATION_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_RELATION_H
+
+#include "SymbolID.h"
+#include "SymbolLocation.h"
+#include "clang/Index/IndexSymbol.h"
+#include "llvm/ADT/iterator_range.h"
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+/// Represents a relation between two symbols.
+/// For an example "A is a base class of B" may be represented
+/// as { Subject = A, Predicate = RelationBaseOf, Object = B }.
+struct Rela

[clang-tools-extra] r362353 - [clangd] Serialization support for RelationSlab

2019-06-04 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Sun Jun  2 22:07:52 2019
New Revision: 362353

URL: http://llvm.org/viewvc/llvm-project?rev=362353&view=rev
Log:
[clangd] Serialization support for RelationSlab

Summary: This builds on D59407 to provide YAML and RIFF serialization support.

Reviewers: kadircet

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/index/Serialization.cpp
clang-tools-extra/trunk/clangd/index/Serialization.h
clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
clang-tools-extra/trunk/clangd/unittests/SerializationTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/Serialization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Serialization.cpp?rev=362353&r1=362352&r2=362353&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp Sun Jun  2 22:07:52 
2019
@@ -24,6 +24,29 @@ llvm::Error makeError(const llvm::Twine
   return llvm::make_error(Msg,
  llvm::inconvertibleErrorCode());
 }
+} // namespace
+
+RelationKind symbolRoleToRelationKind(index::SymbolRole Role) {
+  // SymbolRole is used to record relations in the index.
+  // Only handle the relations we actually store currently.
+  // If we start storing more relations, this list can be expanded.
+  switch (Role) {
+  case index::SymbolRole::RelationBaseOf:
+return RelationKind::BaseOf;
+  default:
+llvm_unreachable("Unsupported symbol role");
+  }
+}
+
+index::SymbolRole relationKindToSymbolRole(RelationKind Kind) {
+  switch (Kind) {
+  case RelationKind::BaseOf:
+return index::SymbolRole::RelationBaseOf;
+  }
+  llvm_unreachable("Invalid relation kind");
+}
+
+namespace {
 
 // IO PRIMITIVES
 // We use little-endian 32 bit ints, sometimes with variable-length encoding.
@@ -358,6 +381,28 @@ readRefs(Reader &Data, llvm::ArrayRef(Kind));
+  OS << R.Object.raw();
+}
+
+Relation readRelation(Reader &Data) {
+  SymbolID Subject = Data.consumeID();
+  index::SymbolRole Predicate =
+  relationKindToSymbolRole(static_cast(Data.consume8()));
+  SymbolID Object = Data.consumeID();
+  return {Subject, Predicate, Object};
+}
+
 // FILE ENCODING
 // A file is a RIFF chunk with type 'CdIx'.
 // It contains the sections:
@@ -434,6 +479,17 @@ llvm::Expected readRIFF(llv
   return makeError("malformed or truncated refs");
 Result.Refs = std::move(Refs).build();
   }
+  if (Chunks.count("rela")) {
+Reader RelationsReader(Chunks.lookup("rela"));
+RelationSlab::Builder Relations;
+while (!RelationsReader.eof()) {
+  auto Relation = readRelation(RelationsReader);
+  Relations.insert(Relation);
+}
+if (RelationsReader.err())
+  return makeError("malformed or truncated relations");
+Result.Relations = std::move(Relations).build();
+  }
   return std::move(Result);
 }
 
@@ -483,6 +539,14 @@ void writeRIFF(const IndexFileOut &Data,
 }
   }
 
+  std::vector Relations;
+  if (Data.Relations) {
+for (const auto &Relation : *Data.Relations) {
+  Relations.emplace_back(Relation);
+  // No strings to be interned in relations.
+}
+  }
+
   std::string StringSection;
   {
 llvm::raw_string_ostream StringOS(StringSection);
@@ -508,6 +572,16 @@ void writeRIFF(const IndexFileOut &Data,
 RIFF.Chunks.push_back({riff::fourCC("refs"), RefsSection});
   }
 
+  std::string RelationSection;
+  if (Data.Relations) {
+{
+  llvm::raw_string_ostream RelationOS{RelationSection};
+  for (const auto &Relation : Relations)
+writeRelation(Relation, RelationOS);
+}
+RIFF.Chunks.push_back({riff::fourCC("rela"), RelationSection});
+  }
+
   std::string SrcsSection;
   {
 {
@@ -561,6 +635,7 @@ std::unique_ptr loadIndex(l
 
   SymbolSlab Symbols;
   RefSlab Refs;
+  RelationSlab Relations;
   {
 trace::Span Tracer("ParseIndex");
 if (auto I = readIndexFile(Buffer->get()->getBuffer())) {
@@ -568,6 +643,8 @@ std::unique_ptr loadIndex(l
 Symbols = std::move(*I->Symbols);
   if (I->Refs)
 Refs = std::move(*I->Refs);
+  if (I->Relations)
+Relations = std::move(*I->Relations);
 } else {
   llvm::errs() << "Bad Index: " << llvm::toString(I.takeError()) << "\n";
   return nullptr;
@@ -576,15 +653,17 @@ std::unique_ptr loadIndex(l
 
   size_t NumSym = Symbols.size();
   size_t NumRefs = Refs.numRefs();
+  size_t NumRelations = Relations.size();
 
   trace::Span Tracer("BuildIndex");
   auto Index = UseDex ? dex::Dex::build(std::move(Symbols), std::move(Refs))
   : MemIndex::build(std::move(Symbols), std::move(Refs));
   vlog("Loaded {0} from {1} with estimated memory usage {2} bytes\n"
"  - number of symbols: {3}\n"
-   "  - num

[clang-tools-extra] r362467 - [clangd] SymbolCollector support for relations

2019-06-04 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Mon Jun  3 21:25:44 2019
New Revision: 362467

URL: http://llvm.org/viewvc/llvm-project?rev=362467&view=rev
Log:
[clangd] SymbolCollector support for relations

Summary:
The only relation currently collected is RelationBaseOf, because this is
all we need for type hierarchy subtypes. Additional relations can be
collected in the future as the need arises.

This patch builds on D59407 and D62459.

Reviewers: kadircet

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

Tags: #clang

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

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

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=362467&r1=362466&r2=362467&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Jun  3 
21:25:44 2019
@@ -193,6 +193,11 @@ RefKind toRefKind(index::SymbolRoleSet R
   return static_cast(static_cast(RefKind::All) & Roles);
 }
 
+bool shouldIndexRelation(const index::SymbolRelation &R) {
+  // We currently only index BaseOf relations, for type hierarchy subtypes.
+  return R.Roles & static_cast(index::SymbolRole::RelationBaseOf);
+}
+
 } // namespace
 
 SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
@@ -291,6 +296,16 @@ bool SymbolCollector::handleDeclOccurenc
   SM.getFileID(SpellingLoc) == SM.getMainFileID())
 ReferencedDecls.insert(ND);
 
+  auto ID = getSymbolID(ND);
+  if (!ID)
+return true;
+
+  // Note: we need to process relations for all decl occurrences, including
+  // refs, because the indexing code only populates relations for specific
+  // occurrences. For example, RelationBaseOf is only populated for the
+  // occurrence inside the base-specifier.
+  processRelations(*ND, *ID, Relations);
+
   bool CollectRef = static_cast(Opts.RefFilter) & Roles;
   bool IsOnlyRef =
   !(Roles & (static_cast(index::SymbolRole::Declaration) |
@@ -315,10 +330,6 @@ bool SymbolCollector::handleDeclOccurenc
   if (IsOnlyRef)
 return true;
 
-  auto ID = getSymbolID(ND);
-  if (!ID)
-return true;
-
   // FIXME: ObjCPropertyDecl are not properly indexed here:
   // - ObjCPropertyDecl may have an OrigD of ObjCPropertyImplDecl, which is
   // not a NamedDecl.
@@ -338,6 +349,7 @@ bool SymbolCollector::handleDeclOccurenc
 
   if (Roles & static_cast(index::SymbolRole::Definition))
 addDefinition(*OriginalDecl, *BasicSymbol);
+
   return true;
 }
 
@@ -416,6 +428,37 @@ bool SymbolCollector::handleMacroOccuren
   return true;
 }
 
+void SymbolCollector::processRelations(
+const NamedDecl &ND, const SymbolID &ID,
+ArrayRef Relations) {
+  // Store subtype relations.
+  if (!dyn_cast(&ND))
+return;
+
+  for (const auto &R : Relations) {
+if (!shouldIndexRelation(R))
+  continue;
+
+const Decl *Object = R.RelatedSymbol;
+
+auto ObjectID = getSymbolID(Object);
+if (!ObjectID)
+  continue;
+
+// Record the relation.
+// TODO: There may be cases where the object decl is not indexed for some
+// reason. Those cases should probably be removed in due course, but for
+// now there are two possible ways to handle it:
+//   (A) Avoid storing the relation in such cases.
+//   (B) Store it anyways. Clients will likely lookup() the SymbolID
+//   in the index and find nothing, but that's a situation they
+//   probably need to handle for other reasons anyways.
+// We currently do (B) because it's simpler.
+this->Relations.insert(
+Relation{ID, index::SymbolRole::RelationBaseOf, *ObjectID});
+  }
+}
+
 void SymbolCollector::setIncludeLocation(const Symbol &S, SourceLocation Loc) {
   if (Opts.CollectIncludePath)
 if (shouldCollectIncludePath(S.SymInfo.Kind))

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.h?rev=362467&r1=362466&r2=362467&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.h (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.h Mon Jun  3 21:25:44 
2019
@@ -110,6 +110,7 @@ public:
 
   SymbolSlab takeSymbols() { return std::move(Symbols).build(); }
   RefSlab takeRefs() { return std::move(Refs).build(); }
+  RelationSlab takeRelations() { return std::move(Relations).build(); }
 
   void finish() override;
 
@@ -117,6 +118,8 @@ private:
   const Symbol *addDeclaration(const NamedDecl &, SymbolID,
bool IsMainFileSymbol);
  

[clang-tools-extra] r363481 - [clangd] Index API and implementations for relations

2019-06-14 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Fri Jun 14 19:26:47 2019
New Revision: 363481

URL: http://llvm.org/viewvc/llvm-project?rev=363481&view=rev
Log:
[clangd] Index API and implementations for relations

Summary:
This builds on the relations support added in D59407, D62459,
and D62471 to expose relations in SymbolIndex and its
implementations.

Reviewers: kadircet

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/index/FileIndex.cpp
clang-tools-extra/trunk/clangd/index/FileIndex.h
clang-tools-extra/trunk/clangd/index/Index.cpp
clang-tools-extra/trunk/clangd/index/Index.h
clang-tools-extra/trunk/clangd/index/IndexAction.cpp
clang-tools-extra/trunk/clangd/index/IndexAction.h
clang-tools-extra/trunk/clangd/index/MemIndex.cpp
clang-tools-extra/trunk/clangd/index/MemIndex.h
clang-tools-extra/trunk/clangd/index/Merge.cpp
clang-tools-extra/trunk/clangd/index/Merge.h
clang-tools-extra/trunk/clangd/index/Relation.h
clang-tools-extra/trunk/clangd/index/Serialization.cpp
clang-tools-extra/trunk/clangd/index/dex/Dex.cpp
clang-tools-extra/trunk/clangd/index/dex/Dex.h
clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp
clang-tools-extra/trunk/clangd/unittests/BackgroundIndexTests.cpp
clang-tools-extra/trunk/clangd/unittests/CodeCompleteTests.cpp
clang-tools-extra/trunk/clangd/unittests/DexTests.cpp
clang-tools-extra/trunk/clangd/unittests/DiagnosticsTests.cpp
clang-tools-extra/trunk/clangd/unittests/FileIndexTests.cpp
clang-tools-extra/trunk/clangd/unittests/IndexActionTests.cpp
clang-tools-extra/trunk/clangd/unittests/IndexTests.cpp
clang-tools-extra/trunk/clangd/unittests/TestTU.cpp

Modified: clang-tools-extra/trunk/clangd/index/Background.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Background.cpp?rev=363481&r1=363480&r2=363481&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Background.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Background.cpp Fri Jun 14 19:26:47 2019
@@ -276,6 +276,7 @@ void BackgroundIndex::update(llvm::Strin
   struct File {
 llvm::DenseSet Symbols;
 llvm::DenseSet Refs;
+llvm::DenseSet Relations;
 FileDigest Digest;
   };
   llvm::StringMap Files;
@@ -288,12 +289,16 @@ void BackgroundIndex::update(llvm::Strin
 if (DigestIt == DigestsSnapshot.end() || DigestIt->getValue() != 
IGN.Digest)
   Files.try_emplace(AbsPath).first->getValue().Digest = IGN.Digest;
   }
+  // This map is used to figure out where to store relations.
+  llvm::DenseMap SymbolIDToFile;
   for (const auto &Sym : *Index.Symbols) {
 if (Sym.CanonicalDeclaration) {
   auto DeclPath = URICache.resolve(Sym.CanonicalDeclaration.FileURI);
   const auto FileIt = Files.find(DeclPath);
-  if (FileIt != Files.end())
+  if (FileIt != Files.end()) {
 FileIt->second.Symbols.insert(&Sym);
+SymbolIDToFile[Sym.ID] = &FileIt->second;
+  }
 }
 // For symbols with different declaration and definition locations, we 
store
 // the full symbol in both the header file and the implementation file, so
@@ -319,18 +324,27 @@ void BackgroundIndex::update(llvm::Strin
   }
 }
   }
+  for (const auto &Rel : *Index.Relations) {
+const auto FileIt = SymbolIDToFile.find(Rel.Subject);
+if (FileIt != SymbolIDToFile.end())
+  FileIt->second->Relations.insert(&Rel);
+  }
 
   // Build and store new slabs for each updated file.
   for (const auto &FileIt : Files) {
 llvm::StringRef Path = FileIt.getKey();
 SymbolSlab::Builder Syms;
 RefSlab::Builder Refs;
+RelationSlab::Builder Relations;
 for (const auto *S : FileIt.second.Symbols)
   Syms.insert(*S);
 for (const auto *R : FileIt.second.Refs)
   Refs.insert(RefToIDs[R], *R);
+for (const auto *Rel : FileIt.second.Relations)
+  Relations.insert(*Rel);
 auto SS = llvm::make_unique(std::move(Syms).build());
 auto RS = llvm::make_unique(std::move(Refs).build());
+auto RelS = llvm::make_unique(std::move(Relations).build());
 auto IG = llvm::make_unique(
 getSubGraph(URI::create(Path), Index.Sources.getValue()));
 // We need to store shards before updating the index, since the latter
@@ -339,6 +353,7 @@ void BackgroundIndex::update(llvm::Strin
   IndexFileOut Shard;
   Shard.Symbols = SS.get();
   Shard.Refs = RS.get();
+  Shard.Relations = RelS.get();
   Shard.Sources = IG.get();
 
   if (auto Error = IndexStorage->storeShard(Path, Shard))
@@ -356,7 +371,7 @@ void BackgroundIndex::update(llvm::Strin
   // This can override a newer version that is added in another thread, if
   // this thread sees the older version but finishes later. This 

[clang-tools-extra] r363506 - [clangd] Type hierarchy subtypes

2019-06-15 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Sat Jun 15 19:31:37 2019
New Revision: 363506

URL: http://llvm.org/viewvc/llvm-project?rev=363506&view=rev
Log:
[clangd] Type hierarchy subtypes

Summary:
This builds on the relations support added in D59407, D62459, D62471,
and D62839 to implement type hierarchy subtypes.

Reviewers: kadircet

Subscribers: ilya-biryukov, ioeric, MaskRay, jkorous, mgrang, arphaman,
jdoerfert, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/FindSymbols.cpp
clang-tools-extra/trunk/clangd/FindSymbols.h
clang-tools-extra/trunk/clangd/XRefs.cpp
clang-tools-extra/trunk/clangd/XRefs.h
clang-tools-extra/trunk/clangd/test/type-hierarchy.test
clang-tools-extra/trunk/clangd/unittests/TypeHierarchyTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=363506&r1=363505&r2=363506&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Sat Jun 15 19:31:37 2019
@@ -339,8 +339,7 @@ void ClangdServer::applyTweak(PathRef Fi
 // out a way to cache the format style.
 auto Style = getFormatStyleForFile(File, InpAST->Inputs.Contents,
InpAST->Inputs.FS.get());
-auto Formatted =
-cleanupAndFormat(InpAST->Inputs.Contents, *Raw, Style);
+auto Formatted = cleanupAndFormat(InpAST->Inputs.Contents, *Raw, Style);
 if (!Formatted)
   return CB(Formatted.takeError());
 return CB(replacementsToEdits(InpAST->Inputs.Contents, *Formatted));
@@ -487,11 +486,13 @@ void ClangdServer::findHover(PathRef Fil
 void ClangdServer::typeHierarchy(PathRef File, Position Pos, int Resolve,
  TypeHierarchyDirection Direction,
  Callback> CB) {
-  auto Action = [Pos, Resolve, Direction](decltype(CB) CB,
-  Expected InpAST) {
+  std::string FileCopy = File; // copy will be captured by the lambda
+  auto Action = [FileCopy, Pos, Resolve, Direction,
+ this](decltype(CB) CB, Expected InpAST) {
 if (!InpAST)
   return CB(InpAST.takeError());
-CB(clangd::getTypeHierarchy(InpAST->AST, Pos, Resolve, Direction));
+CB(clangd::getTypeHierarchy(InpAST->AST, Pos, Resolve, Direction, Index,
+FileCopy));
   };
 
   WorkScheduler.runWithAST("Type Hierarchy", File, Bind(Action, 
std::move(CB)));

Modified: clang-tools-extra/trunk/clangd/FindSymbols.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindSymbols.cpp?rev=363506&r1=363505&r2=363506&view=diff
==
--- clang-tools-extra/trunk/clangd/FindSymbols.cpp (original)
+++ clang-tools-extra/trunk/clangd/FindSymbols.cpp Sat Jun 15 19:31:37 2019
@@ -39,6 +39,37 @@ struct ScoredSymbolGreater {
 
 } // namespace
 
+llvm::Expected symbolToLocation(const Symbol &Sym,
+  llvm::StringRef HintPath) {
+  // Prefer the definition over e.g. a function declaration in a header
+  auto &CD = Sym.Definition ? Sym.Definition : Sym.CanonicalDeclaration;
+  auto Uri = URI::parse(CD.FileURI);
+  if (!Uri) {
+return llvm::make_error(
+formatv("Could not parse URI '{0}' for symbol '{1}'.", CD.FileURI,
+Sym.Name),
+llvm::inconvertibleErrorCode());
+  }
+  auto Path = URI::resolve(*Uri, HintPath);
+  if (!Path) {
+return llvm::make_error(
+formatv("Could not resolve path for URI '{0}' for symbol '{1}'.",
+Uri->toString(), Sym.Name),
+llvm::inconvertibleErrorCode());
+  }
+  Location L;
+  // Use HintPath as TUPath since there is no TU associated with this
+  // request.
+  L.uri = URIForFile::canonicalize(*Path, HintPath);
+  Position Start, End;
+  Start.line = CD.Start.line();
+  Start.character = CD.Start.column();
+  End.line = CD.End.line();
+  End.character = CD.End.column();
+  L.range = {Start, End};
+  return L;
+}
+
 llvm::Expected>
 getWorkspaceSymbols(llvm::StringRef Query, int Limit,
 const SymbolIndex *const Index, llvm::StringRef HintPath) {
@@ -65,37 +96,18 @@ getWorkspaceSymbols(llvm::StringRef Quer
   Req.Limit ? *Req.Limit : std::numeric_limits::max());
   FuzzyMatcher Filter(Req.Query);
   Index->fuzzyFind(Req, [HintPath, &Top, &Filter](const Symbol &Sym) {
-// Prefer the definition over e.g. a function declaration in a header
-auto &CD = Sym.Definition ? Sym.Definition : Sym.CanonicalDeclaration;
-auto Uri = URI::parse(CD.FileURI);
-if (!Uri) {
-  log("Workspace symbol: Could not parse URI '{0}' for symbol '{1}'.",
-  CD.Fi

[clang-tools-extra] r363889 - [clangd] Include the diagnostics's code when comparing diagnostics

2019-06-19 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Wed Jun 19 16:11:02 2019
New Revision: 363889

URL: http://llvm.org/viewvc/llvm-project?rev=363889&view=rev
Log:
[clangd] Include the diagnostics's code when comparing diagnostics

Summary: This fixes https://github.com/clangd/clangd/issues/60

Reviewers: kadircet

Reviewed By: kadircet

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

Tags: #clang

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

Added:
clang-tools-extra/trunk/clangd/test/fixits-duplication.test
Modified:
clang-tools-extra/trunk/clangd/Protocol.h

Modified: clang-tools-extra/trunk/clangd/Protocol.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.h?rev=363889&r1=363888&r2=363889&view=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.h (original)
+++ clang-tools-extra/trunk/clangd/Protocol.h Wed Jun 19 16:11:02 2019
@@ -616,7 +616,6 @@ struct DocumentSymbolParams {
 };
 bool fromJSON(const llvm::json::Value &, DocumentSymbolParams &);
 
-
 /// Represents a related message and source code location for a diagnostic.
 /// This should be used to point to code locations that cause or related to a
 /// diagnostics, e.g when duplicating a symbol in a scope.
@@ -666,11 +665,17 @@ llvm::json::Value toJSON(const Diagnosti
 
 /// A LSP-specific comparator used to find diagnostic in a container like
 /// std:map.
-/// We only use the required fields of Diagnostic to do the comparsion to avoid
-/// any regression issues from LSP clients (e.g. VScode), see
-/// https://git.io/vbr29
+/// We only use as many fields of Diagnostic as is needed to make distinct
+/// diagnostics unique in practice, to avoid  regression issues from LSP 
clients
+/// (e.g. VScode), see https://git.io/vbr29
 struct LSPDiagnosticCompare {
   bool operator()(const Diagnostic &LHS, const Diagnostic &RHS) const {
+if (!LHS.code.empty() && !RHS.code.empty()) {
+  // If the code is known for both, use the code to diambiguate, as e.g.
+  // two checkers could produce diagnostics with the same range and 
message.
+  return std::tie(LHS.range, LHS.message, LHS.code) <
+ std::tie(RHS.range, RHS.message, RHS.code);
+}
 return std::tie(LHS.range, LHS.message) < std::tie(RHS.range, RHS.message);
   }
 };

Added: clang-tools-extra/trunk/clangd/test/fixits-duplication.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/test/fixits-duplication.test?rev=363889&view=auto
==
--- clang-tools-extra/trunk/clangd/test/fixits-duplication.test (added)
+++ clang-tools-extra/trunk/clangd/test/fixits-duplication.test Wed Jun 19 
16:11:02 2019
@@ -0,0 +1,221 @@
+# RUN: clangd -lit-test 
-clang-tidy-checks=modernize-use-nullptr,hicpp-use-nullptr < %s | FileCheck 
-strict-whitespace %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{"textDocument":{"codeAction":{"codeActionLiteralSupport":{,"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.cpp","languageId":"cpp","version":1,"text":"void
 foo() { char* p = 0; }"}}}
+#  CHECK:"method": "textDocument/publishDiagnostics",
+# CHECK-NEXT:  "params": {
+# CHECK-NEXT:"diagnostics": [
+# CHECK-NEXT:  {
+# CHECK-NEXT:"code": "hicpp-use-nullptr",
+# CHECK-NEXT:"message": "Use nullptr (fix available)",
+# CHECK-NEXT:"range": {
+# CHECK-NEXT:  "end": {
+# CHECK-NEXT:"character": 24,
+# CHECK-NEXT:"line": 0
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "start": {
+# CHECK-NEXT:"character": 23,
+# CHECK-NEXT:"line": 0
+# CHECK-NEXT:  }
+# CHECK-NEXT:},
+# CHECK-NEXT:"severity": 2,
+# CHECK-NEXT:"source": "clang-tidy"
+# CHECK-NEXT:  },
+# CHECK-NEXT:  {
+# CHECK-NEXT:"code": "modernize-use-nullptr",
+# CHECK-NEXT:"message": "Use nullptr (fix available)",
+# CHECK-NEXT:"range": {
+# CHECK-NEXT:  "end": {
+# CHECK-NEXT:"character": 24,
+# CHECK-NEXT:"line": 0
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "start": {
+# CHECK-NEXT:"character": 23,
+# CHECK-NEXT:"line": 0
+# CHECK-NEXT:  }
+# CHECK-NEXT:},
+# CHECK-NEXT:"severity": 2,
+# CHECK-NEXT:"source": "clang-tidy"
+# CHECK-NEXT:  }
+# CHECK-NEXT:],
+# CHECK-NEXT:"uri": "file:///{{.*}}/foo.cpp"
+# CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{"textDocument":{"uri":"test:///foo.cpp"},"range":{"start":{"line":0,"character":23},"end":{"line":0,"character":24}},"context":{"diagnostics":[{"range":{"start":
 {"line": 0, "character": 23}, "end": {"line": 0, "character": 
24}},"severity":2,"mes

[clang-tools-extra] r365849 - [clangd] Add a missing early return in getTypeHierarchy()

2019-07-11 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Thu Jul 11 17:24:45 2019
New Revision: 365849

URL: http://llvm.org/viewvc/llvm-project?rev=365849&view=rev
Log:
[clangd] Add a missing early return in getTypeHierarchy()

Reviewers: sammccall

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/XRefs.cpp

Modified: clang-tools-extra/trunk/clangd/XRefs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/XRefs.cpp?rev=365849&r1=365848&r2=365849&view=diff
==
--- clang-tools-extra/trunk/clangd/XRefs.cpp (original)
+++ clang-tools-extra/trunk/clangd/XRefs.cpp Thu Jul 11 17:24:45 2019
@@ -1230,6 +1230,8 @@ getTypeHierarchy(ParsedAST &AST, Positio
   RecursionProtectionSet RPSet;
   Optional Result =
   getTypeAncestors(*CXXRD, AST.getASTContext(), RPSet);
+  if (!Result)
+return Result;
 
   if ((Direction == TypeHierarchyDirection::Children ||
Direction == TypeHierarchyDirection::Both) &&


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


[clang-tools-extra] r365867 - [clangd] Implement typeHierarchy/resolve for subtypes

2019-07-11 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Thu Jul 11 20:26:32 2019
New Revision: 365867

URL: http://llvm.org/viewvc/llvm-project?rev=365867&view=rev
Log:
[clangd] Implement typeHierarchy/resolve for subtypes

Summary:
This allows the client to resolve subtypes one level at a time.

For supertypes, this is not necessary, because we eagerly compute
supertypes and return all levels.

Reviewers: sammccall

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/clangd/XRefs.cpp
clang-tools-extra/trunk/clangd/XRefs.h
clang-tools-extra/trunk/clangd/test/type-hierarchy.test
clang-tools-extra/trunk/clangd/unittests/TypeHierarchyTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=365867&r1=365866&r2=365867&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Thu Jul 11 20:26:32 2019
@@ -926,6 +926,13 @@ void ClangdLSPServer::onTypeHierarchy(
 Params.resolve, Params.direction, std::move(Reply));
 }
 
+void ClangdLSPServer::onResolveTypeHierarchy(
+const ResolveTypeHierarchyItemParams &Params,
+Callback> Reply) {
+  Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
+   std::move(Reply));
+}
+
 void ClangdLSPServer::applyConfiguration(
 const ConfigurationSettings &Settings) {
   // Per-file update to the compilation database.
@@ -1021,6 +1028,7 @@ ClangdLSPServer::ClangdLSPServer(
   MsgHandler->bind("workspace/didChangeConfiguration", 
&ClangdLSPServer::onChangeConfiguration);
   MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
   MsgHandler->bind("textDocument/typeHierarchy", 
&ClangdLSPServer::onTypeHierarchy);
+  MsgHandler->bind("typeHierarchy/resolve", 
&ClangdLSPServer::onResolveTypeHierarchy);
   // clang-format on
 }
 

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.h?rev=365867&r1=365866&r2=365867&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.h Thu Jul 11 20:26:32 2019
@@ -100,6 +100,8 @@ private:
Callback>);
   void onTypeHierarchy(const TypeHierarchyParams &,
Callback>);
+  void onResolveTypeHierarchy(const ResolveTypeHierarchyItemParams &,
+  Callback>);
   void onChangeConfiguration(const DidChangeConfigurationParams &);
   void onSymbolInfo(const TextDocumentPositionParams &,
 Callback>);

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=365867&r1=365866&r2=365867&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Thu Jul 11 20:26:32 2019
@@ -101,8 +101,7 @@ ClangdServer::ClangdServer(const GlobalC
  : nullptr),
   GetClangTidyOptions(Opts.GetClangTidyOptions),
   SuggestMissingIncludes(Opts.SuggestMissingIncludes),
-  EnableHiddenFeatures(Opts.HiddenFeatures),
-  TweakFilter(Opts.TweakFilter),
+  EnableHiddenFeatures(Opts.HiddenFeatures), TweakFilter(Opts.TweakFilter),
   WorkspaceRoot(Opts.WorkspaceRoot),
   // Pass a callback into `WorkScheduler` to extract symbols from a newly
   // parsed file and rebuild the file index synchronously each time an AST
@@ -528,6 +527,13 @@ void ClangdServer::typeHierarchy(PathRef
   WorkScheduler.runWithAST("Type Hierarchy", File, Bind(Action, 
std::move(CB)));
 }
 
+void ClangdServer::resolveTypeHierarchy(
+TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction,
+Callback> CB) {
+  clangd::resolveTypeHierarchy(Item, Resolve, Direction, Index);
+  CB(Item);
+}
+
 void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
   // FIXME: Do nothing for now. This will be used for indexing and potentially
   // invalidating other caches.

Modified: clang-tools-extra/trunk/clangd/ClangdServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.h?rev=365

Re: [clang-tools-extra] r365867 - [clangd] Implement typeHierarchy/resolve for subtypes

2019-07-12 Thread Nathan Ridge via cfe-commits
Thanks. Is there a way to trigger a run of the bots on a patch prior to 
comitting it?

Nate


From: Russell Gallop 
Sent: July 12, 2019 2:46 PM
To: Nathan Ridge
Cc: cfe-commits
Subject: Re: [clang-tools-extra] r365867 - [clangd] Implement 
typeHierarchy/resolve for subtypes

Hi Nathan,

I've reverted this to get the bot green(er).

Regards
Russ

On Fri, 12 Jul 2019 at 13:32, Russell Gallop 
mailto:russell.gal...@gmail.com>> wrote:
Hi Nathan,
This is causing a test failure on Windows: 
http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast/builds/26909

Please can you take a look?

Thanks
Russ

[ RUN  ] Subtypes.LazyResolution
Preamble for file C:\clangd-test\TestTU.cpp cannot be reused. Attempting to 
rebuild it.
Built preamble of size 210988 for file C:\clangd-test\TestTU.cpp
Preamble for file C:\clangd-test\TestTU.cpp cannot be reused. Attempting to 
rebuild it.
Built preamble of size 210988 for file C:\clangd-test\TestTU.cpp
index AST for C:\clangd-test\TestTU.cpp (main=false):
  symbol slab: 4 symbols, 5152 bytes
  ref slab: 0 symbols, 0 refs, 136 bytes
  relations slab: 3 relations, 84 bytes
index AST for C:\clangd-test\TestTU.cpp (main=true):
  symbol slab: 4 symbols, 5152 bytes
  ref slab: 0 symbols, 0 refs, 136 bytes
  relations slab: 3 relations, 84 bytes
Expected must be checked before access or destruction.
Unchecked Expected contained error:
Hint path doesn't start with test root: /clangd-test/TestTU.cpp
0x7FF7486D1B25 (0x0016 0x7FF7486D1B20 0x7FF70006 
0x7FF748680AF4)
0x7FFF3F0EE19D (0x01CDE35AA701 0x01CD 0x01CDE35AA7B0 
0x01CDE35AB111), raise() + 0x1DD bytes(s)
0x7FFF3F0EF071 (0x0003 0x00290003 0x01CDE35AB111 
0x00294FD8E330), abort() + 0x31 bytes(s)
...

On Fri, 12 Jul 2019 at 04:26, Nathan Ridge via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:
Author: nridge
Date: Thu Jul 11 20:26:32 2019
New Revision: 365867

URL: http://llvm.org/viewvc/llvm-project?rev=365867&view=rev
Log:
[clangd] Implement typeHierarchy/resolve for subtypes

Summary:
This allows the client to resolve subtypes one level at a time.

For supertypes, this is not necessary, because we eagerly compute
supertypes and return all levels.

Reviewers: sammccall

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/clangd/XRefs.cpp
clang-tools-extra/trunk/clangd/XRefs.h
clang-tools-extra/trunk/clangd/test/type-hierarchy.test
clang-tools-extra/trunk/clangd/unittests/TypeHierarchyTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=365867&r1=365866&r2=365867&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Thu Jul 11 20:26:32 2019
@@ -926,6 +926,13 @@ void ClangdLSPServer::onTypeHierarchy(
 Params.resolve, Params.direction, std::move(Reply));
 }

+void ClangdLSPServer::onResolveTypeHierarchy(
+const ResolveTypeHierarchyItemParams &Params,
+Callback> Reply) {
+  Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
+   std::move(Reply));
+}
+
 void ClangdLSPServer::applyConfiguration(
 const ConfigurationSettings &Settings) {
   // Per-file update to the compilation database.
@@ -1021,6 +1028,7 @@ ClangdLSPServer::ClangdLSPServer(
   MsgHandler->bind("workspace/didChangeConfiguration", 
&ClangdLSPServer::onChangeConfiguration);
   MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
   MsgHandler->bind("textDocument/typeHierarchy", 
&ClangdLSPServer::onTypeHierarchy);
+  MsgHandler->bind("typeHierarchy/resolve", 
&ClangdLSPServer::onResolveTypeHierarchy);
   // clang-format on
 }


Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.h?rev=365867&r1=365866&r2=365867&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.h Thu Jul 11 20:26:32 2019
@@ -100,6 +100,8 @@ p

[clang-tools-extra] r365987 - [clangd] Mark type hierarchy as a supported feature in the docs

2019-07-12 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Fri Jul 12 20:24:54 2019
New Revision: 365987

URL: http://llvm.org/viewvc/llvm-project?rev=365987&view=rev
Log:
[clangd] Mark type hierarchy as a supported feature in the docs

Reviewers: sammccall

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/docs/clangd/Features.rst

Modified: clang-tools-extra/trunk/docs/clangd/Features.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clangd/Features.rst?rev=365987&r1=365986&r2=365987&view=diff
==
--- clang-tools-extra/trunk/docs/clangd/Features.rst (original)
+++ clang-tools-extra/trunk/docs/clangd/Features.rst Fri Jul 12 20:24:54 2019
@@ -261,7 +261,7 @@ developed outside clangd or become clang
 +-++--+
 | Call hierarchy  | No |   No |
 +-++--+
-| Type hierarchy  | No |   No |
+| Type hierarchy  | No |   Yes|
 +-++--+
 | Organize Includes   | No |   No |
 +-++--+


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


[clang-tools-extra] r365986 - [clangd] Implement typeHierarchy/resolve for subtypes

2019-07-12 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Fri Jul 12 20:24:48 2019
New Revision: 365986

URL: http://llvm.org/viewvc/llvm-project?rev=365986&view=rev
Log:
[clangd] Implement typeHierarchy/resolve for subtypes

Summary:
This allows the client to resolve subtypes one level at a time.

For supertypes, this is not necessary, because we eagerly compute
supertypes and return all levels.

Reviewers: sammccall

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/clangd/XRefs.cpp
clang-tools-extra/trunk/clangd/XRefs.h
clang-tools-extra/trunk/clangd/test/type-hierarchy.test
clang-tools-extra/trunk/clangd/unittests/TypeHierarchyTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=365986&r1=365985&r2=365986&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Fri Jul 12 20:24:48 2019
@@ -926,6 +926,13 @@ void ClangdLSPServer::onTypeHierarchy(
 Params.resolve, Params.direction, std::move(Reply));
 }
 
+void ClangdLSPServer::onResolveTypeHierarchy(
+const ResolveTypeHierarchyItemParams &Params,
+Callback> Reply) {
+  Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
+   std::move(Reply));
+}
+
 void ClangdLSPServer::applyConfiguration(
 const ConfigurationSettings &Settings) {
   // Per-file update to the compilation database.
@@ -1021,6 +1028,7 @@ ClangdLSPServer::ClangdLSPServer(
   MsgHandler->bind("workspace/didChangeConfiguration", 
&ClangdLSPServer::onChangeConfiguration);
   MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
   MsgHandler->bind("textDocument/typeHierarchy", 
&ClangdLSPServer::onTypeHierarchy);
+  MsgHandler->bind("typeHierarchy/resolve", 
&ClangdLSPServer::onResolveTypeHierarchy);
   // clang-format on
 }
 

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.h?rev=365986&r1=365985&r2=365986&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.h Fri Jul 12 20:24:48 2019
@@ -100,6 +100,8 @@ private:
Callback>);
   void onTypeHierarchy(const TypeHierarchyParams &,
Callback>);
+  void onResolveTypeHierarchy(const ResolveTypeHierarchyItemParams &,
+  Callback>);
   void onChangeConfiguration(const DidChangeConfigurationParams &);
   void onSymbolInfo(const TextDocumentPositionParams &,
 Callback>);

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=365986&r1=365985&r2=365986&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Fri Jul 12 20:24:48 2019
@@ -528,6 +528,13 @@ void ClangdServer::typeHierarchy(PathRef
   WorkScheduler.runWithAST("Type Hierarchy", File, Bind(Action, 
std::move(CB)));
 }
 
+void ClangdServer::resolveTypeHierarchy(
+TypeHierarchyItem Item, int Resolve, TypeHierarchyDirection Direction,
+Callback> CB) {
+  clangd::resolveTypeHierarchy(Item, Resolve, Direction, Index);
+  CB(Item);
+}
+
 void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
   // FIXME: Do nothing for now. This will be used for indexing and potentially
   // invalidating other caches.

Modified: clang-tools-extra/trunk/clangd/ClangdServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.h?rev=365986&r1=365985&r2=365986&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.h Fri Jul 12 20:24:48 2019
@@ -210,6 +210,11 @@ public:
  TypeHierarchyDirection Direction,
  Callback> CB);
 
+  /// Resolve type hierarchy item in the given direction.
+  void resolveTypeHierarchy(TypeHierarchyItem Item, int Resolve,
+TypeHierarchyDirection Direction,
+ 

[clang-tools-extra] r366338 - [clangd] Type hierarchy: don't resolve parents if the client only asked for children

2019-07-17 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Wed Jul 17 08:26:49 2019
New Revision: 366338

URL: http://llvm.org/viewvc/llvm-project?rev=366338&view=rev
Log:
[clangd] Type hierarchy: don't resolve parents if the client only asked for 
children

Summary: Also reorganize the code for computing supertypes to make it more 
symmetric to subtypes.

Reviewers: kadircet

Reviewed By: kadircet

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

Tags: #clang

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

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

Modified: clang-tools-extra/trunk/clangd/XRefs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/XRefs.cpp?rev=366338&r1=366337&r2=366338&view=diff
==
--- clang-tools-extra/trunk/clangd/XRefs.cpp (original)
+++ clang-tools-extra/trunk/clangd/XRefs.cpp Wed Jul 17 08:26:49 2019
@@ -1132,15 +1132,9 @@ static void fillSubTypes(const SymbolID
 
 using RecursionProtectionSet = llvm::SmallSet;
 
-static Optional
-getTypeAncestors(const CXXRecordDecl &CXXRD, ASTContext &ASTCtx,
- RecursionProtectionSet &RPSet) {
-  Optional Result = declToTypeHierarchyItem(ASTCtx, CXXRD);
-  if (!Result)
-return Result;
-
-  Result->parents.emplace();
-
+static void fillSuperTypes(const CXXRecordDecl &CXXRD, ASTContext &ASTCtx,
+   std::vector &SuperTypes,
+   RecursionProtectionSet &RPSet) {
   // typeParents() will replace dependent template specializations
   // with their class template, so to avoid infinite recursion for
   // certain types of hierarchies, keep the templates encountered
@@ -1149,22 +1143,22 @@ getTypeAncestors(const CXXRecordDecl &CX
   auto *Pattern = CXXRD.getDescribedTemplate() ? &CXXRD : nullptr;
   if (Pattern) {
 if (!RPSet.insert(Pattern).second) {
-  return Result;
+  return;
 }
   }
 
   for (const CXXRecordDecl *ParentDecl : typeParents(&CXXRD)) {
 if (Optional ParentSym =
-getTypeAncestors(*ParentDecl, ASTCtx, RPSet)) {
-  Result->parents->emplace_back(std::move(*ParentSym));
+declToTypeHierarchyItem(ASTCtx, *ParentDecl)) {
+  ParentSym->parents.emplace();
+  fillSuperTypes(*ParentDecl, ASTCtx, *ParentSym->parents, RPSet);
+  SuperTypes.emplace_back(std::move(*ParentSym));
 }
   }
 
   if (Pattern) {
 RPSet.erase(Pattern);
   }
-
-  return Result;
 }
 
 const CXXRecordDecl *findRecordTypeAt(ParsedAST &AST, Position Pos) {
@@ -1231,12 +1225,19 @@ getTypeHierarchy(ParsedAST &AST, Positio
   if (!CXXRD)
 return llvm::None;
 
-  RecursionProtectionSet RPSet;
   Optional Result =
-  getTypeAncestors(*CXXRD, AST.getASTContext(), RPSet);
+  declToTypeHierarchyItem(AST.getASTContext(), *CXXRD);
   if (!Result)
 return Result;
 
+  if (Direction == TypeHierarchyDirection::Parents ||
+  Direction == TypeHierarchyDirection::Both) {
+Result->parents.emplace();
+
+RecursionProtectionSet RPSet;
+fillSuperTypes(*CXXRD, AST.getASTContext(), *Result->parents, RPSet);
+  }
+
   if ((Direction == TypeHierarchyDirection::Children ||
Direction == TypeHierarchyDirection::Both) &&
   ResolveLevels > 0) {

Modified: clang-tools-extra/trunk/clangd/unittests/TypeHierarchyTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/TypeHierarchyTests.cpp?rev=366338&r1=366337&r2=366338&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/TypeHierarchyTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/TypeHierarchyTests.cpp Wed Jul 17 
08:26:49 2019
@@ -630,7 +630,8 @@ struct Child2b : Child1 {};
   ASSERT_TRUE(bool(Result));
   EXPECT_THAT(
   *Result,
-  AllOf(WithName("Parent"), WithKind(SymbolKind::Struct), Parents(),
+  AllOf(WithName("Parent"), WithKind(SymbolKind::Struct),
+ParentsNotResolved(),
 Children(AllOf(WithName("Child1"), WithKind(SymbolKind::Struct),
ParentsNotResolved(), ChildrenNotResolved();
 


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


[clang-tools-extra] r369229 - [clangd] Update features table in the docs with links to LSP extension proposals

2019-08-18 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Sun Aug 18 22:11:15 2019
New Revision: 369229

URL: http://llvm.org/viewvc/llvm-project?rev=369229&view=rev
Log:
[clangd] Update features table in the docs with links to LSP extension proposals

Also update the semantic coloring entry to reflect it being supported in
clangd now.

Reviewers: sammccall

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/docs/clangd/Features.rst

Modified: clang-tools-extra/trunk/docs/clangd/Features.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clangd/Features.rst?rev=369229&r1=369228&r2=369229&view=diff
==
--- clang-tools-extra/trunk/docs/clangd/Features.rst (original)
+++ clang-tools-extra/trunk/docs/clangd/Features.rst Sun Aug 18 22:11:15 2019
@@ -214,54 +214,58 @@ It is not clear whether or not some of t
 part of the Language Server Protocol; those features might be eventually
 developed outside clangd or become clangd extensions to LSP.
 
-+-++--+
-| C/C++ Editor feature|  LSP   |  Clangd  |
-+=++==+
-| Formatting  | Yes|   Yes|
-+-++--+
-| Completion  | Yes|   Yes|
-+-++--+
-| Diagnostics | Yes|   Yes|
-+-++--+
-| Fix-its | Yes|   Yes|
-+-++--+
-| Go to Definition| Yes|   Yes|
-+-++--+
-| Signature Help  | Yes|   Yes|
-+-++--+
-| Document Highlights | Yes|   Yes|
-+-++--+
-| Rename  | Yes|   Yes|
-+-++--+
-| Source hover| Yes|   Yes|
-+-++--+
-| Find References | Yes|   Yes|
-+-++--+
-| Document Symbols| Yes|   Yes|
-+-++--+
-| Workspace Symbols   | Yes|   Yes|
-+-++--+
-| Code Lens   | Yes|   No |
-+-++--+
-| Code folding| Yes|   No |
-+-++--+
-| Extract Local Variable  | Yes|   No |
-+-++--+
-| Extract Function/Method | Yes|   No |
-+-++--+
-| Quick Assist| Yes|   No |
-+-++--+
-| Hide Method | Yes|   No |
-+-++--+
-| Implement Method| Yes|   No |
-+-++--+
-| Gen. Getters/Setters| Yes|   No |
-+-++--+
-| Syntax and Semantic Coloring| No |   No |
-+-++--+
-| Call hierarchy  | No |   No |
-+-++--+
-| Type hierarchy  | No |   Yes|
-+-++--+
-| Organize Includes   | No |   No |
-+-++--+
++-+-+--+
+| C/C++ Editor feature|  LSP|  Clangd  |
++=+=+==+
+| Formatting  | Yes |   Yes|
++-+-+--+
+| Completion  | Yes |   Yes|
++-+-+--+
+| Diagnostics | Yes |   Yes|
++

[clang-tools-extra] r374799 - [clangd] Improve semantic highlighting in dependent contexts (fixes #154)

2019-10-14 Thread Nathan Ridge via cfe-commits
Author: nridge
Date: Mon Oct 14 11:26:13 2019
New Revision: 374799

URL: http://llvm.org/viewvc/llvm-project?rev=374799&view=rev
Log:
[clangd] Improve semantic highlighting in dependent contexts (fixes #154)

Reviewers: hokein

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
clang-tools-extra/trunk/clangd/SemanticHighlighting.h
clang-tools-extra/trunk/clangd/test/semantic-highlighting.test
clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp

Modified: clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp?rev=374799&r1=374798&r2=374799&view=diff
==
--- clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp (original)
+++ clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp Mon Oct 14 11:26:13 
2019
@@ -37,6 +37,10 @@ bool canHighlightName(DeclarationName Na
 
 llvm::Optional kindForType(const Type *TP);
 llvm::Optional kindForDecl(const NamedDecl *D) {
+  if (auto *TD = dyn_cast(D)) {
+if (auto *Templated = TD->getTemplatedDecl())
+  D = Templated;
+  }
   if (auto *TD = dyn_cast(D)) {
 // We try to highlight typedefs as their underlying type.
 if (auto K = kindForType(TD->getUnderlyingType().getTypePtrOrNull()))
@@ -95,6 +99,20 @@ llvm::Optional kindFor
 return kindForDecl(TD);
   return llvm::None;
 }
+// Given a set of candidate declarations for an unresolved name,
+// if the declarations all have the same highlighting kind, return
+// that highlighting kind, otherwise return None.
+llvm::Optional
+kindForCandidateDecls(llvm::iterator_range Decls) {
+  llvm::Optional Result;
+  for (NamedDecl *Decl : Decls) {
+auto Kind = kindForDecl(Decl);
+if (!Kind || (Result && Kind != Result))
+  return llvm::None;
+Result = Kind;
+  }
+  return Result;
+}
 
 // Collects all semantic tokens in an ASTContext.
 class HighlightingTokenCollector
@@ -152,6 +170,26 @@ public:
 return true;
   }
 
+  bool VisitOverloadExpr(OverloadExpr *E) {
+if (canHighlightName(E->getName()))
+  addToken(E->getNameLoc(),
+   kindForCandidateDecls(E->decls())
+   .getValueOr(HighlightingKind::DependentName));
+return true;
+  }
+
+  bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
+if (canHighlightName(E->getDeclName()))
+  addToken(E->getLocation(), HighlightingKind::DependentName);
+return true;
+  }
+
+  bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
+if (canHighlightName(E->getMember()))
+  addToken(E->getMemberLoc(), HighlightingKind::DependentName);
+return true;
+  }
+
   bool VisitNamedDecl(NamedDecl *ND) {
 if (canHighlightName(ND->getDeclName()))
   addToken(ND->getLocation(), ND);
@@ -187,6 +225,11 @@ public:
 return true;
   }
 
+  bool WalkUpFromDependentNameTypeLoc(DependentNameTypeLoc L) {
+addToken(L.getNameLoc(), HighlightingKind::DependentType);
+return true;
+  }
+
   bool VisitTypeLoc(TypeLoc TL) {
 if (auto K = kindForType(TL.getTypePtr()))
   addToken(TL.getBeginLoc(), *K);
@@ -339,6 +382,10 @@ llvm::raw_ostream &operator<<(llvm::raw_
 return OS << "EnumConstant";
   case HighlightingKind::Typedef:
 return OS << "Typedef";
+  case HighlightingKind::DependentType:
+return OS << "DependentType";
+  case HighlightingKind::DependentName:
+return OS << "DependentName";
   case HighlightingKind::Namespace:
 return OS << "Namespace";
   case HighlightingKind::TemplateParameter:
@@ -468,6 +515,10 @@ llvm::StringRef toTextMateScope(Highligh
 return "variable.other.enummember.cpp";
   case HighlightingKind::Typedef:
 return "entity.name.type.typedef.cpp";
+  case HighlightingKind::DependentType:
+return "entity.name.type.dependent.cpp";
+  case HighlightingKind::DependentName:
+return "entity.name.other.dependent.cpp";
   case HighlightingKind::Namespace:
 return "entity.name.namespace.cpp";
   case HighlightingKind::TemplateParameter:

Modified: clang-tools-extra/trunk/clangd/SemanticHighlighting.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SemanticHighlighting.h?rev=374799&r1=374798&r2=374799&view=diff
==
--- clang-tools-extra/trunk/clangd/SemanticHighlighting.h (original)
+++ clang-tools-extra/trunk/clangd/SemanticHighlighting.h Mon Oct 14 11:26:13 
2019
@@ -37,6 +37,8 @@ enum class HighlightingKind {
   Enum,
   EnumConstant,
   Typedef,
+  DependentType,
+  DependentName,
   Namespace,
   TemplateParameter,
   Primitive,

Modified: clang-tools-extra/trunk/clangd/test/semantic-highlighting.test
URL: 
http://llvm.org/view

[clang-tools-extra] 100dbd1 - [clangd] Handle deduction guides in TargetFinder and ExplicitReferenceCollector

2020-07-20 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-07-21T01:44:48-04:00
New Revision: 100dbd15624c1ac8d1210e7748462e20fed9a9d9

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

LOG: [clangd] Handle deduction guides in TargetFinder and 
ExplicitReferenceCollector

Summary: Fixes https://github.com/clangd/clangd/issues/463.

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/FindTarget.cpp
clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index 627f40c85436..c2887f3306fa 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -302,6 +302,8 @@ struct TargetFinder {
   // Record the underlying decl instead, if allowed.
   D = USD->getTargetDecl();
   Flags |= Rel::Underlying; // continue with the underlying decl.
+} else if (const auto *DG = dyn_cast(D)) {
+  D = DG->getDeducedTemplate();
 }
 
 if (const Decl *Pat = getTemplatePattern(D)) {
@@ -659,6 +661,15 @@ llvm::SmallVector refInDecl(const Decl 
*D) {
   /*IsDecl=*/true,
   {ND}});
 }
+
+void VisitCXXDeductionGuideDecl(const CXXDeductionGuideDecl *DG) {
+  // The class template name in a deduction guide targets the class
+  // template.
+  Refs.push_back(ReferenceLoc{DG->getQualifierLoc(),
+  DG->getNameInfo().getLoc(),
+  /*IsDecl=*/false,
+  {DG->getDeducedTemplate()}});
+}
   };
 
   Visitor V;

diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index bf5cc62411b7..fa8f4935b1d9 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -376,6 +376,8 @@ TEST_F(TargetDeclTest, ClassTemplate) {
{"template<> class Foo", Rel::TemplateInstantiation},
{"template  class Foo", Rel::TemplatePattern});
 
+  Flags.push_back("-std=c++17"); // for CTAD tests
+
   Code = R"cpp(
 // Class template argument deduction
 template 
@@ -386,9 +388,20 @@ TEST_F(TargetDeclTest, ClassTemplate) {
   [[Test]] a(5);
 }
   )cpp";
-  Flags.push_back("-std=c++17");
   EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
{"struct Test", Rel::TemplatePattern});
+
+  Code = R"cpp(
+// Deduction guide
+template 
+struct Test {
+  template 
+  Test(I, I);
+};
+template 
+[[Test]](I, I) -> Test;
+  )cpp";
+  EXPECT_DECLS("CXXDeductionGuideDecl", {"template  struct Test"});
 }
 
 TEST_F(TargetDeclTest, Concept) {
@@ -792,8 +805,8 @@ TEST_F(FindExplicitReferencesTest, All) {
goto $1^ten;
  }
)cpp",
-   "0: targets = {ten}, decl\n"
-   "1: targets = {ten}\n"},
+"0: targets = {ten}, decl\n"
+"1: targets = {ten}\n"},
// Simple templates.
{R"cpp(
   template  struct vector { using value_type = T; };
@@ -1295,7 +1308,7 @@ TEST_F(FindExplicitReferencesTest, All) {
 "6: targets = {bar}, decl\n"
 "7: targets = {foo()::Bar::Foo}\n"
 "8: targets = {foo()::Baz::Field}\n"},
-  {R"cpp(
+   {R"cpp(
template
void crash(T);
template
@@ -1305,10 +1318,9 @@ TEST_F(FindExplicitReferencesTest, All) {
 )cpp",
 "0: targets = {crash}\n"
 "1: targets = {}\n"
-"2: targets = {T}\n"
-  },
-  // unknown template name should not crash.
-  {R"cpp(
+"2: targets = {T}\n"},
+   // unknown template name should not crash.
+   {R"cpp(
 template  typename T>
 struct Base {};
 namespace foo {
@@ -1316,12 +1328,34 @@ TEST_F(FindExplicitReferencesTest, All) {
 struct $1^Derive : $2^Base<$3^T::template $4^Unknown> {};
 }
   )cpp",
-  "0: targets = {foo::Derive::T}, decl\n"
-  "1: targets = {foo::Derive}, decl\n"
-  "2: targets = {Base}\n"
-  "3: targets = {foo::Derive::T}\n"
-  "4: targets = {}, qualifier = 'T::'\n"},
-};
+"0: targets = {foo::Derive::T}, decl\n"
+"1: targets = {foo::Derive}, decl\n"
+"2: targets = {Base}\n"
+"3: targets = {foo::Derive::T}\n"
+"4: targets = {}, qualifier = 'T::'\n"},
+   // deduction guide
+   {R"cpp(
+  namespace foo {
+template 
+struct $1^Test {
+  template 
+

[clang-tools-extra] 9946dcd - [clangd] Improve heuristic resolution of dependent types in TargetFinder

2020-07-20 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-07-21T02:03:06-04:00
New Revision: 9946dcd3e9c7e8c7383265b82cc250c72a444f24

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

LOG: [clangd] Improve heuristic resolution of dependent types in TargetFinder

 * Try to apply heuristic resolution recursively to the base
   expression of a CXXDependentScopeMemberExpr.

 * Try to apply heuristic resolution recursively to the callee
   expression in a call expression.

Fixes https://github.com/clangd/clangd/issues/441

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/FindTarget.cpp
clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index c2887f3306fa..bc4002c42623 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -59,24 +59,32 @@ nodeToString(const ast_type_traits::DynTypedNode &N) {
 }
 
 // Helper function for getMembersReferencedViaDependentName()
-// which takes a dependent type `T` and heuristically
+// which takes a possibly-dependent type `T` and heuristically
 // resolves it to a CXXRecordDecl in which we can try name lookup.
 CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) {
   assert(T);
-  if (const auto *ICNT = T->getAs()) {
+
+  if (const auto *RT = T->getAs())
+return dyn_cast(RT->getDecl());
+
+  if (const auto *ICNT = T->getAs())
 T = ICNT->getInjectedSpecializationType().getTypePtrOrNull();
-  }
+  if (!T)
+return nullptr;
+
   const auto *TST = T->getAs();
   if (!TST)
 return nullptr;
+
   const ClassTemplateDecl *TD = dyn_cast_or_null(
   TST->getTemplateName().getAsTemplateDecl());
   if (!TD)
 return nullptr;
+
   return TD->getTemplatedDecl();
 }
 
-// Given a dependent type and a member name, heuristically resolve the
+// Given a tag-decl type and a member name, heuristically resolve the
 // name to one or more declarations.
 // The current heuristic is simply to look up the name in the primary
 // template. This is a heuristic because the template could potentially
@@ -154,6 +162,10 @@ const Type *getPointeeType(const Type *T) {
   return FirstArg.getAsType().getTypePtrOrNull();
 }
 
+// Forward declaration, needed as this function is mutually recursive
+// with resolveDependentExprToDecls.
+const Type *resolveDependentExprToType(const Expr *E);
+
 // Try to heuristically resolve a dependent expression `E` to one
 // or more declarations that it likely references.
 std::vector resolveDependentExprToDecls(const Expr *E) {
@@ -163,6 +175,15 @@ std::vector 
resolveDependentExprToDecls(const Expr *E) {
 if (ME->isArrow()) {
   BaseType = getPointeeType(BaseType);
 }
+if (const auto *BT = BaseType->getAs()) {
+  // If BaseType is the type of a dependent expression, it's just
+  // represented as BultinType::Dependent which gives us no information. We
+  // can get further by analyzing the depedent expression.
+  Expr *Base = ME->isImplicitAccess() ? nullptr : ME->getBase();
+  if (Base && BT->getKind() == BuiltinType::Dependent) {
+BaseType = resolveDependentExprToType(Base);
+  }
+}
 return getMembersReferencedViaDependentName(
 BaseType, [ME](ASTContext &) { return ME->getMember(); },
 /*IsNonstaticMember=*/true);
@@ -173,9 +194,38 @@ std::vector 
resolveDependentExprToDecls(const Expr *E) {
 [RE](ASTContext &) { return RE->getDeclName(); },
 /*IsNonstaticMember=*/false);
   }
+  if (const auto *CE = dyn_cast(E)) {
+const auto *CalleeType = resolveDependentExprToType(CE->getCallee());
+if (!CalleeType)
+  return {};
+if (const auto *FnTypePtr = CalleeType->getAs())
+  CalleeType = FnTypePtr->getPointeeType().getTypePtr();
+if (const FunctionType *FnType = CalleeType->getAs()) {
+  if (const auto *D =
+  resolveTypeToRecordDecl(FnType->getReturnType().getTypePtr())) {
+return {D};
+  }
+}
+  }
+  if (const auto *ME = dyn_cast(E)) {
+return {ME->getMemberDecl()};
+  }
   return {};
 }
 
+// Try to heuristically resolve the type of a dependent expression `E`.
+const Type *resolveDependentExprToType(const Expr *E) {
+  std::vector Decls = resolveDependentExprToDecls(E);
+  if (Decls.size() != 1) // Names an overload set -- just bail.
+return nullptr;
+  if (const auto *TD = dyn_cast(Decls[0])) {
+return TD->getTypeForDecl();
+  } else if (const auto *VD = dyn_cast(Decls[0])) {
+return VD->getType().getTypePtrOrNull();
+  }
+  return nullptr;
+}
+
 const NamedDecl *getTemplatePattern(con

[Differential] D82739: [clangd] Improve heuristic resolution of dependent types in TargetFinder

2020-07-20 Thread Nathan Ridge via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9946dcd3e9c7: [clangd] Improve heuristic resolution of 
dependent types in TargetFinder (authored by nridge).

Changed prior to commit:
  https://reviews.llvm.org/D82739?vs=276916&id=279037#toc

Repository:
  rG LLVM Github Monorepo

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


  https://reviews.llvm.org/D82739

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -561,6 +561,74 @@
   EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char *)");
 }
 
+TEST_F(TargetDeclTest, DependentExprs) {
+  Flags = {"-fno-delayed-template-parsing"};
+
+  // Heuristic resolution of method of dependent field
+  Code = R"cpp(
+struct A { void foo() {} };
+template 
+struct B {
+  A a;
+  void bar() {
+this->a.[[foo]]();
+  }
+};
+  )cpp";
+  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");
+
+  // Similar to above but base expression involves a function call.
+  Code = R"cpp(
+struct A {
+  void foo() {}
+};
+struct B {
+  A getA();
+};
+template 
+struct C {
+  B c;
+  void bar() {
+this->c.getA().[[foo]]();
+  }
+};
+  )cpp";
+  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");
+
+  // Similar to above but uses a function pointer.
+  Code = R"cpp(
+struct A {
+  void foo() {}
+};
+struct B {
+  using FPtr = A(*)();
+  FPtr fptr;
+};
+template 
+struct C {
+  B c;
+  void bar() {
+this->c.fptr().[[foo]]();
+  }
+};
+  )cpp";
+  EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");
+
+  // Base expression involves a member access into this.
+  Code = R"cpp(
+struct Bar {
+  int ;
+};
+template  struct Foo {
+  Bar func(int);
+  void test() {
+func(1).[[]];
+  }
+};
+  )cpp";
+  EXPECT_DECLS("CXXDependentScopeMemberExpr", "int ");
+}
+
 TEST_F(TargetDeclTest, ObjC) {
   Flags = {"-xobjective-c"};
   Code = R"cpp(
@@ -718,36 +786,37 @@
 
 TEST_F(FindExplicitReferencesTest, All) {
   std::pair Cases[] =
-  {// Simple expressions.
-   {R"cpp(
+  {
+  // Simple expressions.
+  {R"cpp(
 int global;
 int func();
 void foo(int param) {
   $0^global = $1^param + $2^func();
 }
 )cpp",
-"0: targets = {global}\n"
-"1: targets = {param}\n"
-"2: targets = {func}\n"},
-   {R"cpp(
+   "0: targets = {global}\n"
+   "1: targets = {param}\n"
+   "2: targets = {func}\n"},
+  {R"cpp(
 struct X { int a; };
 void foo(X x) {
   $0^x.$1^a = 10;
 }
 )cpp",
-"0: targets = {x}\n"
-"1: targets = {X::a}\n"},
-   {R"cpp(
+   "0: targets = {x}\n"
+   "1: targets = {X::a}\n"},
+  {R"cpp(
 // error-ok: testing with broken code
 int bar();
 int foo() {
   return $0^bar() + $1^bar(42);
 }
 )cpp",
-"0: targets = {bar}\n"
-"1: targets = {bar}\n"},
-   // Namespaces and aliases.
-   {R"cpp(
+   "0: targets = {bar}\n"
+   "1: targets = {bar}\n"},
+  // Namespaces and aliases.
+  {R"cpp(
   namespace ns {}
   namespace alias = ns;
   void foo() {
@@ -755,19 +824,19 @@
 using namespace $1^alias;
   }
 )cpp",
-"0: targets = {ns}\n"
-"1: targets = {alias}\n"},
-   // Using declarations.
-   {R"cpp(
+   "0: targets = {ns}\n"
+   "1: targets = {alias}\n"},
+  // Using declarations.
+  {R"cpp(
   namespace ns { int global; }
   void foo() {
 using $0^ns::$1^global;
   }
 )cpp",
-"0: targets = {ns}\n"
-"1: targets = {ns::global}, qualifier = 'ns::'\n"},
-   // Simple types.
-   {R"cpp(
+   "0: targets = {ns}\n"
+   "1: targets = {ns::global}, qualifier = 'ns::'\n"},
+  // Simple types.
+  {R"cpp(
  struct Struct { int a; };
  using Typedef = int;
  void foo() {
@@ -776,13 +845,13 @@
static_cast<$4^Struct*>(0);
  }
)cpp"

[clang] 8924779 - [clang] Fix ConceptSpecializationExpr::getEndLoc()

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

Author: Nathan Ridge
Date: 2020-07-29T02:44:26-04:00
New Revision: 89247792c5bdd58500b0e6c5e56532424c2e2ca1

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

LOG: [clang] Fix ConceptSpecializationExpr::getEndLoc()

Summary:
It returned an invalid location in case of a constrained-parameter
with no explicit arguments.

Reviewers: hokein

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/AST/ExprConcepts.h
clang/test/AST/ast-dump-concepts.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ExprConcepts.h 
b/clang/include/clang/AST/ExprConcepts.h
index 2a88ed5175d2..1544c498ef66 100644
--- a/clang/include/clang/AST/ExprConcepts.h
+++ b/clang/include/clang/AST/ExprConcepts.h
@@ -126,7 +126,11 @@ class ConceptSpecializationExpr final : public Expr, 
public ConceptReference,
   }
 
   SourceLocation getEndLoc() const LLVM_READONLY {
-return ArgsAsWritten->RAngleLoc;
+// If the ConceptSpecializationExpr is the ImmediatelyDeclaredConstraint
+// of a TypeConstraint written syntactically as a constrained-parameter,
+// there may not be a template argument list.
+return ArgsAsWritten->RAngleLoc.isValid() ? ArgsAsWritten->RAngleLoc
+  : ConceptName.getEndLoc();
   }
 
   // Iterators

diff  --git a/clang/test/AST/ast-dump-concepts.cpp 
b/clang/test/AST/ast-dump-concepts.cpp
index 530c1baeffa7..3429fa6b46be 100644
--- a/clang/test/AST/ast-dump-concepts.cpp
+++ b/clang/test/AST/ast-dump-concepts.cpp
@@ -6,14 +6,22 @@
 // RUN: -ast-dump-all -ast-dump-filter Foo /dev/null \
 // RUN: | FileCheck --strict-whitespace %s
 
+template 
+concept unary_concept = true;
+
 template 
 concept binary_concept = true;
 
 template 
 struct Foo {
   // CHECK:  TemplateTypeParmDecl {{.*}} referenced Concept {{.*}} 
'binary_concept'
-  // CHECK-NEXT: |-ConceptSpecializationExpr {{.*}} 'bool'
+  // CHECK-NEXT: |-ConceptSpecializationExpr {{.*}}  'bool'
   // CHECK-NEXT: `-TemplateArgument {{.*}} type 'int'
   template  R>
   Foo(R);
+
+  // CHECK:  TemplateTypeParmDecl {{.*}} referenced Concept {{.*}} 
'unary_concept'
+  // CHECK-NEXT: `-ConceptSpecializationExpr {{.*}}  'bool'
+  template 
+  Foo(R);
 };



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


[clang] 8b3b755 - [clang] Persist Attr::IsPackExpansion into the PCH

2020-04-05 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-04-05T23:32:03-04:00
New Revision: 8b3b7556e9ab6084e9fd337d64dac1c165867d32

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

LOG: [clang] Persist Attr::IsPackExpansion into the PCH

Summary: Fixes https://github.com/clangd/clangd/issues/309

Subscribers: ilya-biryukov, kadircet, usaxena95, cfe-commits

Tags: #clang

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

Added: 
clang/test/PCH/cxx-attrs-packexpansion.cpp

Modified: 
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/test/PCH/cxx-attrs-packexpansion.cpp 
b/clang/test/PCH/cxx-attrs-packexpansion.cpp
new file mode 100644
index ..6d292ec1e3e0
--- /dev/null
+++ b/clang/test/PCH/cxx-attrs-packexpansion.cpp
@@ -0,0 +1,25 @@
+// Test this without pch.
+// RUN: %clang_cc1 -include %s -emit-llvm -o - %s
+
+// Test with pch.
+// RUN: %clang_cc1 -emit-pch -o %t %s
+// RUN: %clang_cc1 -include-pch %t -emit-llvm -o - %s
+
+#ifndef HEADER
+#define HEADER
+
+template
+struct static_variant {
+alignas(Types...) T storage[10];
+};
+
+#else
+
+struct A {
+static_variant a;
+};
+struct B {
+static_variant _b;
+};
+
+#endif

diff  --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index e9f91c685ee4..486799eb81ba 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2911,6 +2911,7 @@ void EmitClangAttrPCHRead(RecordKeeper &Records, 
raw_ostream &OS) {
 if (R.isSubClassOf(InhClass))
   OS << "bool isInherited = Record.readInt();\n";
 OS << "bool isImplicit = Record.readInt();\n";
+OS << "bool isPackExpansion = Record.readInt();\n";
 ArgRecords = R.getValueAsListOfDefs("Args");
 Args.clear();
 for (const auto *Arg : ArgRecords) {
@@ -2926,6 +2927,7 @@ void EmitClangAttrPCHRead(RecordKeeper &Records, 
raw_ostream &OS) {
 if (R.isSubClassOf(InhClass))
   OS << "cast(New)->setInherited(isInherited);\n";
 OS << "New->setImplicit(isImplicit);\n";
+OS << "New->setPackExpansion(isPackExpansion);\n";
 OS << "break;\n";
 OS << "  }\n";
   }
@@ -2952,6 +2954,7 @@ void EmitClangAttrPCHWrite(RecordKeeper &Records, 
raw_ostream &OS) {
 if (R.isSubClassOf(InhClass))
   OS << "Record.push_back(SA->isInherited());\n";
 OS << "Record.push_back(A->isImplicit());\n";
+OS << "Record.push_back(A->isPackExpansion());\n";
 
 for (const auto *Arg : Args)
   createArgument(*Arg, R.getName())->writePCHWrite(OS);



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


[clang-tools-extra] d83541d - [clangd] Color dependent names based on their heuristic target if they have one

2020-04-14 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-04-15T00:57:08-04:00
New Revision: d83541d1b8f75ff44083c8ba1dba1ca7bac330cf

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

LOG: [clangd] Color dependent names based on their heuristic target if they 
have one

Summary: Fixes https://github.com/clangd/clangd/issues/297

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/FindTarget.cpp
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index ff50323980a7..27f6532bf5ac 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -654,6 +654,7 @@ llvm::SmallVector refInExpr(const Expr *E) 
{
   /*IsDecl=*/false,
   {E->getNamedConcept()}});
 }
+
 void VisitDeclRefExpr(const DeclRefExpr *E) {
   Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
   E->getNameInfo().getLoc(),
@@ -661,6 +662,12 @@ llvm::SmallVector refInExpr(const Expr 
*E) {
   {E->getFoundDecl()}});
 }
 
+void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
+  Refs.push_back(ReferenceLoc{
+  E->getQualifierLoc(), E->getNameInfo().getLoc(), /*IsDecl=*/false,
+  explicitReferenceTargets(DynTypedNode::create(*E), {})});
+}
+
 void VisitMemberExpr(const MemberExpr *E) {
   // Skip destructor calls to avoid duplication: TypeLoc within will be
   // visited separately.
@@ -672,6 +679,14 @@ llvm::SmallVector refInExpr(const Expr 
*E) {
   {E->getFoundDecl()}});
 }
 
+void
+VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
+  Refs.push_back(
+  ReferenceLoc{E->getQualifierLoc(), E->getMemberNameInfo().getLoc(),
+   /*IsDecl=*/false,
+   explicitReferenceTargets(DynTypedNode::create(*E), 
{})});
+}
+
 void VisitOverloadExpr(const OverloadExpr *E) {
   Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
   E->getNameInfo().getLoc(),

diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 35eabfe00dd2..baf13755ecf7 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -143,6 +143,36 @@ SourceLocation 
getHighlightableSpellingToken(SourceLocation L,
   return getHighlightableSpellingToken(SM.getImmediateSpellingLoc(L), SM);
 }
 
+unsigned evaluateHighlightPriority(HighlightingKind Kind) {
+  enum HighlightPriority { Dependent = 0, Resolved = 1 };
+  return Kind == HighlightingKind::DependentType ||
+ Kind == HighlightingKind::DependentName
+ ? Dependent
+ : Resolved;
+}
+
+// Sometimes we get conflicts between findExplicitReferences() returning
+// a heuristic result for a dependent name (e.g. Method) and
+// CollectExtraHighlighting returning a fallback dependent highlighting (e.g.
+// DependentName). In such cases, resolve the conflict in favour of the
+// resolved (non-dependent) highlighting.
+// With macros we can get other conflicts (if a spelled token has multiple
+// expansions with 
diff erent token types) which we can't usefully resolve.
+llvm::Optional
+resolveConflict(ArrayRef Tokens) {
+  if (Tokens.size() == 1)
+return Tokens[0];
+
+  if (Tokens.size() != 2)
+return llvm::None;
+
+  unsigned Priority1 = evaluateHighlightPriority(Tokens[0].Kind);
+  unsigned Priority2 = evaluateHighlightPriority(Tokens[1].Kind);
+  if (Priority1 == Priority2)
+return llvm::None;
+  return Priority1 > Priority2 ? Tokens[0] : Tokens[1];
+}
+
 /// Consumes source locations and maps them to text ranges for highlightings.
 class HighlightingsBuilder {
 public:
@@ -183,10 +213,8 @@ class HighlightingsBuilder {
 // this predicate would never fire.
 return T.R == TokRef.front().R;
   });
-  // If there is exactly one token with this range it's non conflicting and
-  // should be in the highlightings.
-  if (Conflicting.size() == 1)
-NonConflicting.push_back(TokRef.front());
+  if (auto Resolved = resolveConflict(Conflicting))
+NonConflicting.push_back(*Resolved);
   // TokRef[Conflicting.size()] is the next token with a 
dif

[clang-tools-extra] 7759f70 - [clangd] Support typeHierarchy/resolve for children of parents as well

2020-06-15 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-06-15T11:59:23-04:00
New Revision: 7759f70fb0ee2cd6752d9188bd2578cc3d9a7a2e

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

LOG: [clangd] Support typeHierarchy/resolve for children of parents as well

Summary:
The initial implementation of typeHierarchy/resolve only supported
cases where an initial request was made for children, and then
typeHierarchy/resolve was used to get additional levels of children.

However, a client may also want to make an initial request for
parents, and then show other children of those parents, so support
typeHierarchy/resolve for items returned in response to a request
for parents as well.

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

Tags: #clang

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

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index df2c7a7c7228..6aa031541846 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -1225,6 +1225,14 @@ declToTypeHierarchyItem(ASTContext &Ctx, const NamedDecl 
&ND,
 
   THI.uri = URIForFile::canonicalize(*FilePath, *TUPath);
 
+  // Compute the SymbolID and store it in the 'data' field.
+  // This allows typeHierarchy/resolve to be used to
+  // resolve children of items returned in a previous request
+  // for parents.
+  if (auto ID = getSymbolID(&ND)) {
+THI.data = ID->str();
+  }
+
   return THI;
 }
 



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


[clang-tools-extra] d150523 - [clangd] Follow-up to fix lit-test bustage in type-hierarchy.test

2020-06-15 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-06-15T12:18:21-04:00
New Revision: d1505233c85360bf3d9ab07af803b2bb478547a6

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

LOG: [clangd] Follow-up to fix lit-test bustage in type-hierarchy.test

This is a follow-up to D81845.

Added: 


Modified: 
clang-tools-extra/clangd/test/type-hierarchy.test

Removed: 




diff  --git a/clang-tools-extra/clangd/test/type-hierarchy.test 
b/clang-tools-extra/clangd/test/type-hierarchy.test
index 69014fab4ab1..cb38e49cf61e 100644
--- a/clang-tools-extra/clangd/test/type-hierarchy.test
+++ b/clang-tools-extra/clangd/test/type-hierarchy.test
@@ -35,14 +35,17 @@
 # CHECK-NEXT:"uri": "file://{{.*}}/clangd-test/main.cpp"
 # CHECK-NEXT:  }
 # CHECK-NEXT:],
+# CHECK-NEXT:"data": "8A991335E4E67D08",
 # CHECK-NEXT:"kind": 23,
 # CHECK-NEXT:"name": "Child2",
 # CHECK-NEXT:"parents": [
 # CHECK-NEXT:  {
+# CHECK-NEXT:"data": "ECDC0C46D75120F4",
 # CHECK-NEXT:"kind": 23,
 # CHECK-NEXT:"name": "Child1",
 # CHECK-NEXT:"parents": [
 # CHECK-NEXT:  {
+# CHECK-NEXT:"data": "FE546E7B648D69A7",
 # CHECK-NEXT:"kind": 23,
 # CHECK-NEXT:"name": "Parent",
 # CHECK-NEXT:"parents": [],



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


[clang-tools-extra] 98d763a - [clangd] Factor out some helper functions related to heuristic resolution in TargetFinder

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

Author: Nathan Ridge
Date: 2020-07-10T01:58:34-04:00
New Revision: 98d763ad051f5eab89fa46167516fc8a84f471d0

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

LOG: [clangd] Factor out some helper functions related to heuristic resolution 
in TargetFinder

Summary:
Two helpers are introduced:

 * Some of the logic previously in TargetFinder::Visit*() methods is
   factored out into resolveDependentExprToDecls().

 * Some of the logic in getMembersReferencedViaDependentName() is
   factored out into resolveTypeToRecordDecl().

D82739 will build on this and use these functions in new ways.

Reviewers: hokein

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/FindTarget.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index 1d09e8408c83..627f40c85436 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -58,6 +58,24 @@ nodeToString(const ast_type_traits::DynTypedNode &N) {
   return S;
 }
 
+// Helper function for getMembersReferencedViaDependentName()
+// which takes a dependent type `T` and heuristically
+// resolves it to a CXXRecordDecl in which we can try name lookup.
+CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) {
+  assert(T);
+  if (const auto *ICNT = T->getAs()) {
+T = ICNT->getInjectedSpecializationType().getTypePtrOrNull();
+  }
+  const auto *TST = T->getAs();
+  if (!TST)
+return nullptr;
+  const ClassTemplateDecl *TD = dyn_cast_or_null(
+  TST->getTemplateName().getAsTemplateDecl());
+  if (!TD)
+return nullptr;
+  return TD->getTemplatedDecl();
+}
+
 // Given a dependent type and a member name, heuristically resolve the
 // name to one or more declarations.
 // The current heuristic is simply to look up the name in the primary
@@ -82,25 +100,17 @@ std::vector 
getMembersReferencedViaDependentName(
 ET->getDecl()->lookup(NameFactory(ET->getDecl()->getASTContext()));
 return {Result.begin(), Result.end()};
   }
-  if (auto *ICNT = T->getAs()) {
-T = ICNT->getInjectedSpecializationType().getTypePtrOrNull();
+  if (auto *RD = resolveTypeToRecordDecl(T)) {
+if (!RD->hasDefinition())
+  return {};
+RD = RD->getDefinition();
+DeclarationName Name = NameFactory(RD->getASTContext());
+return RD->lookupDependentName(Name, [=](const NamedDecl *D) {
+  return IsNonstaticMember ? D->isCXXInstanceMember()
+   : !D->isCXXInstanceMember();
+});
   }
-  auto *TST = T->getAs();
-  if (!TST)
-return {};
-  const ClassTemplateDecl *TD = dyn_cast_or_null(
-  TST->getTemplateName().getAsTemplateDecl());
-  if (!TD)
-return {};
-  CXXRecordDecl *RD = TD->getTemplatedDecl();
-  if (!RD->hasDefinition())
-return {};
-  RD = RD->getDefinition();
-  DeclarationName Name = NameFactory(RD->getASTContext());
-  return RD->lookupDependentName(Name, [=](const NamedDecl *D) {
-return IsNonstaticMember ? D->isCXXInstanceMember()
- : !D->isCXXInstanceMember();
-  });
+  return {};
 }
 
 // Given the type T of a dependent expression that appears of the LHS of a 
"->",
@@ -144,6 +154,28 @@ const Type *getPointeeType(const Type *T) {
   return FirstArg.getAsType().getTypePtrOrNull();
 }
 
+// Try to heuristically resolve a dependent expression `E` to one
+// or more declarations that it likely references.
+std::vector resolveDependentExprToDecls(const Expr *E) {
+  assert(E->isTypeDependent());
+  if (const auto *ME = dyn_cast(E)) {
+const Type *BaseType = ME->getBaseType().getTypePtrOrNull();
+if (ME->isArrow()) {
+  BaseType = getPointeeType(BaseType);
+}
+return getMembersReferencedViaDependentName(
+BaseType, [ME](ASTContext &) { return ME->getMember(); },
+/*IsNonstaticMember=*/true);
+  }
+  if (const auto *RE = dyn_cast(E)) {
+return getMembersReferencedViaDependentName(
+RE->getQualifier()->getAsType(),
+[RE](ASTContext &) { return RE->getDeclName(); },
+/*IsNonstaticMember=*/false);
+  }
+  return {};
+}
+
 const NamedDecl *getTemplatePattern(const NamedDecl *D) {
   if (const CXXRecordDecl *CRD = dyn_cast(D)) {
 if (const auto *Result = CRD->getTemplateInstantiationPattern())
@@ -341,21 +373,12 @@ struct TargetFinder {
   }
   void
   VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
-const Type *BaseType = E->getBaseType().getTypePtrOrNull();
-if (E->isArrow()) {
-  BaseType = getPointeeType(BaseType);
-}
-for (const NamedDecl *D : getMembersRe

[clang-tools-extra] 230cae8 - [clangd] Enable textual fallback for go-to-definition on dependent names

2020-04-25 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-04-26T00:38:38-04:00
New Revision: 230cae89db3f8619e2b5383ae797462434f69d50

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

LOG: [clangd] Enable textual fallback for go-to-definition on dependent names

Reviewers: sammccall

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/XRefs.h
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 d17fa52bd82c..7eb3c4fcc7a3 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -22,6 +22,7 @@
 #include "index/Relation.h"
 #include "index/SymbolLocation.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/Attrs.inc"
 #include "clang/AST/Decl.h"
@@ -139,17 +140,20 @@ SymbolLocation getPreferredLocation(const Location 
&ASTLoc,
   return Merged.CanonicalDeclaration;
 }
 
-std::vector getDeclAtPosition(ParsedAST &AST,
- SourceLocation Pos,
- DeclRelationSet Relations) {
+std::vector
+getDeclAtPosition(ParsedAST &AST, SourceLocation Pos, DeclRelationSet 
Relations,
+  ASTNodeKind *NodeKind = nullptr) {
   unsigned Offset = 
AST.getSourceManager().getDecomposedSpellingLoc(Pos).second;
   std::vector Result;
   SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Offset,
 Offset, [&](SelectionTree ST) {
   if (const SelectionTree::Node *N =
-  ST.commonAncestor())
+  ST.commonAncestor()) {
+if (NodeKind)
+  *NodeKind = N->ASTNode.getNodeKind();
 llvm::copy(targetDecl(N->ASTNode, Relations),
std::back_inserter(Result));
+  }
   return !Result.empty();
 });
   return Result;
@@ -221,7 +225,7 @@ locateMacroReferent(const syntax::Token &TouchedIdentifier, 
ParsedAST &AST,
 std::vector
 locateASTReferent(SourceLocation CurLoc, const syntax::Token 
*TouchedIdentifier,
   ParsedAST &AST, llvm::StringRef MainFilePath,
-  const SymbolIndex *Index) {
+  const SymbolIndex *Index, ASTNodeKind *NodeKind) {
   const SourceManager &SM = AST.getSourceManager();
   // Results follow the order of Symbols.Decls.
   std::vector Result;
@@ -250,7 +254,8 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
   // Emit all symbol locations (declaration or definition) from AST.
   DeclRelationSet Relations =
   DeclRelation::TemplatePattern | DeclRelation::Alias;
-  for (const NamedDecl *D : getDeclAtPosition(AST, CurLoc, Relations)) {
+  for (const NamedDecl *D :
+   getDeclAtPosition(AST, CurLoc, Relations, NodeKind)) {
 // Special case: void foo() ^override: jump to the overridden method.
 if (const auto *CMD = llvm::dyn_cast(D)) {
   const InheritableAttr *Attr = D->getAttr();
@@ -332,14 +337,26 @@ llvm::StringRef sourcePrefix(SourceLocation Loc, const 
SourceManager &SM) {
   return Buf.substr(0, D.second);
 }
 
+bool isDependentName(ASTNodeKind NodeKind) {
+  return NodeKind.isSame(ASTNodeKind::getFromNodeKind()) ||
+ NodeKind.isSame(
+ ASTNodeKind::getFromNodeKind()) ||
+ NodeKind.isSame(
+ ASTNodeKind::getFromNodeKind());
+}
+
 } // namespace
 
 std::vector
 locateSymbolTextually(const SpelledWord &Word, ParsedAST &AST,
-  const SymbolIndex *Index,
-  const std::string &MainFilePath) {
-  // Don't use heuristics if this is a real identifier, or not an identifier.
-  if (Word.ExpandedToken || !Word.LikelyIdentifier || !Index)
+  const SymbolIndex *Index, const std::string 
&MainFilePath,
+  ASTNodeKind NodeKind) {
+  // Don't use heuristics if this is a real identifier, or not an
+  // identifier.
+  // Exception: dependent names, because those may have useful textual
+  // matches that AST-based heuristics cannot find.
+  if ((Word.ExpandedToken && !isDependentName(NodeKind)) ||
+  !Word.LikelyIdentifier || !Index)
 return {};
   // We don't want to handle words in string literals. It'd be nice to 
whitelist
   // comments instead, but

[clang-tools-extra] 4ede396 - [clang] Include trailing-requires-clause in FunctionDecl's source range

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

Author: Nathan Ridge
Date: 2020-08-04T02:52:01-04:00
New Revision: 4ede3968498174f35f8456cd4bf95d14811d40d1

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

LOG: [clang] Include trailing-requires-clause in FunctionDecl's source range

Fixes https://github.com/clangd/clangd/issues/476

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang/include/clang/Sema/DeclSpec.h
clang/test/AST/ast-dump-concepts.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 8b872d6314d4..3421b9cec2d3 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -405,6 +405,11 @@ TEST_F(TargetDeclTest, ClassTemplate) {
 }
 
 TEST_F(TargetDeclTest, Concept) {
+  Flags.push_back("-std=c++20");
+
+  // FIXME: Should we truncate the pretty-printed form of a concept decl
+  // somewhere?
+
   Code = R"cpp(
 template 
 concept Fooable = requires (T t) { t.foo(); };
@@ -414,12 +419,20 @@ TEST_F(TargetDeclTest, Concept) {
   t.foo();
 }
   )cpp";
-  Flags.push_back("-std=c++20");
   EXPECT_DECLS(
   "ConceptSpecializationExpr",
-  // FIXME: Should we truncate the pretty-printed form of a concept decl
-  // somewhere?
   {"template  concept Fooable = requires (T t) { t.foo(); 
};"});
+
+  // trailing requires clause
+  Code = R"cpp(
+  template 
+  concept Fooable = true;
+
+  template 
+  void foo() requires [[Fooable]];
+  )cpp";
+  EXPECT_DECLS("ConceptSpecializationExpr",
+   {"template  concept Fooable = true;"});
 }
 
 TEST_F(TargetDeclTest, FunctionTemplate) {

diff  --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 0a22b5af7c64..93a912609655 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -2448,6 +2448,8 @@ class Declarator {
   /// \brief Sets a trailing requires clause for this declarator.
   void setTrailingRequiresClause(Expr *TRC) {
 TrailingRequiresClause = TRC;
+
+SetRangeEnd(TRC->getEndLoc());
   }
 
   /// \brief Sets a trailing requires clause for this declarator.

diff  --git a/clang/test/AST/ast-dump-concepts.cpp 
b/clang/test/AST/ast-dump-concepts.cpp
index 3429fa6b46be..7050ee0fb449 100644
--- a/clang/test/AST/ast-dump-concepts.cpp
+++ b/clang/test/AST/ast-dump-concepts.cpp
@@ -24,4 +24,13 @@ struct Foo {
   // CHECK-NEXT: `-ConceptSpecializationExpr {{.*}}  'bool'
   template 
   Foo(R);
+
+  // CHECK:  FunctionTemplateDecl {{.*}}  {{.*}} 
Foo
+  template 
+  Foo(R, int) requires unary_concept;
+
+  // CHECK:  FunctionTemplateDecl {{.*}}  {{.*}} 
Foo
+  template 
+  Foo(R, char) requires unary_concept {
+  }
 };



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


[clang-tools-extra] f4ba7a1 - [clangd] Semantic highlighting for dependent template name in template argument

2020-08-06 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-08-06T21:23:49-04:00
New Revision: f4ba7a100a56b63f9b3eac709ecea9f514d90c00

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

LOG: [clangd] Semantic highlighting for dependent template name in template 
argument

Fixes https://github.com/clangd/clangd/issues/484

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

Added: 


Modified: 
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index ed75ce80999c..4bedea457e5c 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -296,6 +296,18 @@ class CollectExtraHighlightings
 return true;
   }
 
+  bool TraverseTemplateArgumentLoc(TemplateArgumentLoc L) {
+switch (L.getArgument().getKind()) {
+case TemplateArgument::Template:
+case TemplateArgument::TemplateExpansion:
+  H.addToken(L.getTemplateNameLoc(), HighlightingKind::DependentType);
+  break;
+default:
+  break;
+}
+return RecursiveASTVisitor::TraverseTemplateArgumentLoc(L);
+  }
+
   // findExplicitReferences will walk nested-name-specifiers and
   // find anything that can be resolved to a Decl. However, non-leaf
   // components of nested-name-specifiers which are dependent names

diff  --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
index 453986552ac5..1b90b21b2c58 100644
--- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -686,6 +686,14 @@ sizeof...($TemplateParameter[[Elements]]);
   void $Function[[bar]]($TemplateParameter[[T]] $Parameter[[F]]) {
 $Parameter[[F]].$DependentName[[foo]]();
   }
+)cpp",
+  // Dependent template name
+  R"cpp(
+  template  class> struct $Class[[A]] {};
+  template 
+  using $Typedef[[W]] = $Class[[A]]<
+$TemplateParameter[[T]]::template $DependentType[[Waldo]]
+  >;
 )cpp"};
   for (const auto &TestCase : TestCases) {
 checkHighlightings(TestCase);



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


[clang-tools-extra] 57f9518 - [clangd] Highlight structured bindings at local scope as LocalVariable

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

Author: Nathan Ridge
Date: 2020-08-07T03:23:10-04:00
New Revision: 57f9518bf032d773c35c86ec99983a47849fd322

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

LOG: [clangd] Highlight structured bindings at local scope as LocalVariable

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

Added: 


Modified: 
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 4bedea457e5c..fb1ef1e326b4 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -90,8 +90,10 @@ llvm::Optional kindForDecl(const NamedDecl 
*D) {
? HighlightingKind::StaticField
: VD->isLocalVarDecl() ? HighlightingKind::LocalVariable
   : HighlightingKind::Variable;
-  if (isa(D))
-return HighlightingKind::Variable;
+  if (const auto *BD = dyn_cast(D))
+return BD->getDeclContext()->isFunctionOrMethod()
+   ? HighlightingKind::LocalVariable
+   : HighlightingKind::Variable;
   if (isa(D))
 return HighlightingKind::Function;
   if (isa(D) || isa(D) ||

diff  --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
index 1b90b21b2c58..f9c2e7433cc4 100644
--- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -515,13 +515,14 @@ TEST(SemanticHighlighting, GetsCorrectTokens) {
 $Class[[S]] *$Field[[Next]];
   };
   $Class[[S]] $Variable[[Global]][2] = {$Class[[S]](), $Class[[S]]()};
+  auto [$Variable[[G1]], $Variable[[G2]]] = $Variable[[Global]];
   void $Function[[f]]($Class[[S]] $Parameter[[P]]) {
 int $LocalVariable[[A]][2] = {1,2};
-auto [$Variable[[B1]], $Variable[[B2]]] = $LocalVariable[[A]];
-auto [$Variable[[G1]], $Variable[[G2]]] = $Variable[[Global]];
-$Class[[auto]] [$Variable[[P1]], $Variable[[P2]]] = $Parameter[[P]];
+auto [$LocalVariable[[B1]], $LocalVariable[[B2]]] = 
$LocalVariable[[A]];
+auto [$LocalVariable[[G1]], $LocalVariable[[G2]]] = 
$Variable[[Global]];
+$Class[[auto]] [$LocalVariable[[P1]], $LocalVariable[[P2]]] = 
$Parameter[[P]];
 // Highlights references to BindingDecls.
-$Variable[[B1]]++;
+$LocalVariable[[B1]]++;
   }
 )cpp",
   R"cpp(



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


[clang] b1c7f84 - [clang] Allow DynTypedNode to store a TemplateArgumentLoc

2020-08-10 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-08-10T03:09:18-04:00
New Revision: b1c7f84643ffa63e72733b7089cea89723b82afc

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

LOG: [clang] Allow DynTypedNode to store a TemplateArgumentLoc

The patch also adds a templateArgumentLoc() AST matcher.

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

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/include/clang/AST/ASTTypeTraits.h
clang/include/clang/ASTMatchers/ASTMatchFinder.h
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/include/clang/ASTMatchers/ASTMatchersInternal.h
clang/lib/AST/ASTTypeTraits.cpp
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/lib/ASTMatchers/ASTMatchersInternal.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 60ff6ffe6056..eb85e420e7e4 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -679,7 +679,8 @@ Node Matchers
   #pragma omp parallel default(firstprivate)
   #pragma omp parallel
 
-``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``, and 
``default(firstprivate)``.
+``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``, and
+``default(firstprivate)``
 
 
 
@@ -1625,6 +1626,17 @@ Node Matchers
 
 
 
+MatcherTemplateArgumentLoc>templateArgumentLocMatcherTemplateArgumentLoc>...
+Matches 
template arguments (with location info).
+
+Given
+  template  struct C {};
+  C c;
+templateArgumentLoc()
+  matches 'int' in C.
+
+
+
 MatcherTemplateArgument>templateArgumentMatcherTemplateArgument>...
 Matches template 
arguments.
 
@@ -3776,8 +3788,9 @@ Narrowing Matchers
 
 
 
-MatcherOMPDefaultClause>isNoneKind
-Matches if the OpenMP 
``default`` clause has ``none`` kind specified.
+MatcherOMPDefaultClause>isFirstPrivateKind
+Matches if the 
OpenMP ``default`` clause has ``firstprivate`` kind
+specified.
 
 Given
 
@@ -3786,12 +3799,13 @@ Narrowing Matchers
   #pragma omp parallel default(shared)
   #pragma omp parallel default(firstprivate)
 
-``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
+``ompDefaultClause(isFirstPrivateKind())`` matches only
+``default(firstprivate)``.
 
 
 
-MatcherOMPDefaultClause>isSharedKind
-Matches if the OpenMP 
``default`` clause has ``shared`` kind specified.
+MatcherOMPDefaultClause>isNoneKind
+Matches if the OpenMP 
``default`` clause has ``none`` kind specified.
 
 Given
 
@@ -3800,12 +3814,12 @@ Narrowing Matchers
   #pragma omp parallel default(shared)
   #pragma omp parallel default(firstprivate)
 
-``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
+``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
 
 
 
-MatcherOMPDefaultClause>isSharedKind
-Matches if the 
OpenMP ``default`` clause has ``firstprivate`` kind specified.
+MatcherOMPDefaultClause>isSharedKind
+Matches if the OpenMP 
``default`` clause has ``shared`` kind specified.
 
 Given
 
@@ -3814,7 +3828,7 @@ Narrowing Matchers
   #pragma omp parallel default(shared)
   #pragma omp parallel default(firstprivate)
 
-``ompDefaultClause(isFirstPrivateKind())`` matches only 
``default(firstprivate)``.
+``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
 
 
 

diff  --git a/clang/include/clang/AST/ASTTypeTraits.h 
b/clang/include/clang/AST/ASTTypeTraits.h
index 328b7bce6ba5..bd817b75bb84 100644
--- a/clang/include/clang/AST/ASTTypeTraits.h
+++ b/clang/include/clang/AST/ASTTypeTraits.h
@@ -132,6 +132,7 @@ class ASTNodeKind {
   enum NodeKindId {
 NKI_None,
 NKI_TemplateArgument,
+NKI_TemplateArgumentLoc,
 NKI_TemplateName,
 NKI_NestedNameSpecifierLoc,
 NKI_QualType,
@@ -191,6 +192,7 @@ class ASTNodeKind {
   };
 KIND_TO_KIND_ID(CXXCtorInitializer)
 KIND_TO_KIND_ID(TemplateArgument)
+KIND_TO_KIND_ID(TemplateArgumentLoc)
 KIND_TO_KIND_ID(TemplateName)
 KIND_TO_KIND_ID(NestedNameSpecifier)
 KIND_TO_KIND_ID(NestedNameS

[clang-tools-extra] 70d583a - [clangd] Have template template arguments target their referenced template decl

2020-08-10 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-08-10T13:27:23-04:00
New Revision: 70d583ad12872ef8714b15f1d1e982f1db6d9a15

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

LOG: [clangd] Have template template arguments target their referenced template 
decl

Fixes https://github.com/clangd/clangd/issues/473

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

Added: 


Modified: 
clang-tools-extra/clangd/FindTarget.cpp
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index e4d2dddb4b5d..734b8432c838 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -596,6 +596,19 @@ struct TargetFinder {
   add(CCI->getAnyMember(), Flags);
 // Constructor calls contain a TypeLoc node, so we don't handle them here.
   }
+
+  void add(const TemplateArgument &Arg, RelSet Flags) {
+// Only used for template template arguments.
+// For type and non-type template arguments, SelectionTree
+// will hit a more specific node (e.g. a TypeLoc or a
+// DeclRefExpr).
+if (Arg.getKind() == TemplateArgument::Template ||
+Arg.getKind() == TemplateArgument::TemplateExpansion) {
+  if (TemplateDecl *TD = Arg.getAsTemplate().getAsTemplateDecl()) {
+report(TD, Flags);
+  }
+}
+  }
 };
 
 } // namespace
@@ -619,6 +632,8 @@ allTargetDecls(const ast_type_traits::DynTypedNode &N) {
 Finder.add(*QT, Flags);
   else if (const CXXCtorInitializer *CCI = N.get())
 Finder.add(CCI, Flags);
+  else if (const TemplateArgumentLoc *TAL = N.get())
+Finder.add(TAL->getArgument(), Flags);
 
   return Finder.takeDecls();
 }

diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index 2e3c491d561e..5c08485d8b92 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -479,6 +479,10 @@ class SelectionVisitor : public 
RecursiveASTVisitor {
   bool TraverseTypeLoc(TypeLoc X) {
 return traverseNode(&X, [&] { return Base::TraverseTypeLoc(X); });
   }
+  bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &X) {
+return traverseNode(&X,
+[&] { return Base::TraverseTemplateArgumentLoc(X); });
+  }
   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc X) {
 return traverseNode(
 &X, [&] { return Base::TraverseNestedNameSpecifierLoc(X); });

diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 3421b9cec2d3..838150815f5e 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -376,6 +376,15 @@ TEST_F(TargetDeclTest, ClassTemplate) {
{"template<> class Foo", Rel::TemplateInstantiation},
{"template  class Foo", Rel::TemplatePattern});
 
+  Code = R"cpp(
+// Template template argument.
+template struct Vector {};
+template  class Container>
+struct A {};
+A<[[Vector]]> a;
+  )cpp";
+  EXPECT_DECLS("TemplateArgumentLoc", {"template  struct Vector"});
+
   Flags.push_back("-std=c++17"); // for CTAD tests
 
   Code = R"cpp(

diff  --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 6a9f587a7768..2026292bc6f3 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -407,8 +407,16 @@ TEST(SelectionTest, CommonAncestor) {
   s2[[-^>]]f();
 }
   )cpp",
-   "DeclRefExpr"} // DeclRefExpr to the "operator->" method.
-  };
+   "DeclRefExpr"}, // DeclRefExpr to the "operator->" method.
+
+  // Template template argument.
+  {R"cpp(
+template  class Vector {};
+template  class Container> class A {};
+A<[[V^ector]]> a;
+  )cpp",
+   "TemplateArgumentLoc"}};
+
   for (const Case &C : Cases) {
 trace::TestTracer Tracer;
 Annotations Test(C.Code);



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


[clang-tools-extra] 15673d7 - [clangd] Index refs to main-file symbols as well

2020-08-17 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-08-18T00:30:07-04:00
New Revision: 15673d748acd8f26bdeee18c0aa18f44c775d738

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

LOG: [clangd] Index refs to main-file symbols as well

Summary: This will be needed to support call hierarchy

Reviewers: kadircet

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/ClangdServer.cpp
clang-tools-extra/clangd/ClangdServer.h
clang-tools-extra/clangd/index/Background.cpp
clang-tools-extra/clangd/index/Background.h
clang-tools-extra/clangd/index/FileIndex.cpp
clang-tools-extra/clangd/index/FileIndex.h
clang-tools-extra/clangd/index/SymbolCollector.cpp
clang-tools-extra/clangd/index/SymbolCollector.h
clang-tools-extra/clangd/tool/ClangdMain.cpp
clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 74ab21a5f778..d204e87c143b 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -173,7 +173,8 @@ ClangdServer::ClangdServer(const GlobalCompilationDatabase 
&CDB,
Callbacks *Callbacks)
 : ConfigProvider(Opts.ConfigProvider), TFS(TFS),
   DynamicIdx(Opts.BuildDynamicSymbolIndex
- ? new FileIndex(Opts.HeavyweightDynamicSymbolIndex)
+ ? new FileIndex(Opts.HeavyweightDynamicSymbolIndex,
+ Opts.CollectMainFileRefs)
  : nullptr),
   GetClangTidyOptions(Opts.GetClangTidyOptions),
   SuggestMissingIncludes(Opts.SuggestMissingIncludes),

diff  --git a/clang-tools-extra/clangd/ClangdServer.h 
b/clang-tools-extra/clangd/ClangdServer.h
index 1bc7d70eebad..7068cd5eb421 100644
--- a/clang-tools-extra/clangd/ClangdServer.h
+++ b/clang-tools-extra/clangd/ClangdServer.h
@@ -111,6 +111,9 @@ class ClangdServer {
 /// on background threads. The index is stored in the project root.
 bool BackgroundIndex = false;
 
+/// Store refs to main-file symbols in the index.
+bool CollectMainFileRefs = false;
+
 /// If set, use this index to augment code completion results.
 SymbolIndex *StaticIndex = nullptr;
 

diff  --git a/clang-tools-extra/clangd/index/Background.cpp 
b/clang-tools-extra/clangd/index/Background.cpp
index 18037d694c11..2bac6ec39d30 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -95,6 +95,7 @@ BackgroundIndex::BackgroundIndex(
 BackgroundIndexStorage::Factory IndexStorageFactory, Options Opts)
 : SwapIndex(std::make_unique()), TFS(TFS), CDB(CDB),
   ContextProvider(std::move(Opts.ContextProvider)),
+  CollectMainFileRefs(Opts.CollectMainFileRefs),
   Rebuilder(this, &IndexedSymbols, Opts.ThreadPoolSize),
   IndexStorageFactory(std::move(IndexStorageFactory)),
   Queue(std::move(Opts.OnProgress)),
@@ -301,6 +302,7 @@ llvm::Error BackgroundIndex::index(tooling::CompileCommand 
Cmd) {
   return false; // Skip files that haven't changed, without errors.
 return true;
   };
+  IndexOpts.CollectMainFileRefs = CollectMainFileRefs;
 
   IndexFileIn Index;
   auto Action = createStaticIndexingAction(

diff  --git a/clang-tools-extra/clangd/index/Background.h 
b/clang-tools-extra/clangd/index/Background.h
index 72fe84466959..472603013a53 100644
--- a/clang-tools-extra/clangd/index/Background.h
+++ b/clang-tools-extra/clangd/index/Background.h
@@ -137,6 +137,8 @@ class BackgroundIndex : public SwapIndex {
 // file. Called with the empty string for other tasks.
 // (When called, the context from BackgroundIndex construction is active).
 std::function ContextProvider = nullptr;
+// Whether to collect references to main-file-only symbols.
+bool CollectMainFileRefs = false;
   };
 
   /// Creates a new background index and starts its threads.
@@ -188,6 +190,7 @@ class BackgroundIndex : public SwapIndex {
   const ThreadsafeFS &TFS;
   const GlobalCompilationDatabase &CDB;
   std::function ContextProvider;
+  bool CollectMainFileRefs;
 
   llvm::Error index(tooling::CompileCommand);
 

diff  --git a/clang-tools-extra/clangd/index/FileIndex.cpp 
b/clang-tools-extra/clangd/index/FileIndex.cpp
index 5f84545d7c73..dafec6742c2c 100644
--- a/clang-tools-extra/clangd/index/FileIndex.cpp
+++ b/clang-tools-extra/clangd/index/FileIndex.cpp
@@ -47,12 +47,13 @@ SlabTuple indexSymbols(ASTContext &AST, 
std::shared_ptr PP,
llvm::ArrayRe

[clang] 00d7b7d - [clang] Fix visitation of ConceptSpecializationExpr in constrained-parameter

2020-08-17 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-08-18T00:32:34-04:00
New Revision: 00d7b7d014f90caef6f9c778614b09356bf0

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

LOG: [clang] Fix visitation of ConceptSpecializationExpr in 
constrained-parameter

Summary: RecursiveASTVisitor needs to traverse 
TypeConstraint::ImmediatelyDeclaredConstraint

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

Tags: #clang

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

Added: 
clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp

Modified: 
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang/include/clang/AST/RecursiveASTVisitor.h
clang/unittests/Tooling/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 4c655c3338d2..2507932c5cda 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -442,6 +442,28 @@ TEST_F(TargetDeclTest, Concept) {
   )cpp";
   EXPECT_DECLS("ConceptSpecializationExpr",
{"template  concept Fooable = true;"});
+
+  // constrained-parameter
+  Code = R"cpp(
+template 
+concept Fooable = true;
+
+template <[[Fooable]] T>
+void bar(T t);
+  )cpp";
+  EXPECT_DECLS("ConceptSpecializationExpr",
+   {"template  concept Fooable = true;"});
+
+  // partial-concept-id
+  Code = R"cpp(
+template 
+concept Fooable = true;
+
+template <[[Fooable]] T>
+void bar(T t);
+  )cpp";
+  EXPECT_DECLS("ConceptSpecializationExpr",
+   {"template  concept Fooable = true;"});
 }
 
 TEST_F(TargetDeclTest, FunctionTemplate) {

diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 3dcfc9fee629..6f07b92f2532 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -1777,8 +1777,17 @@ DEF_TRAVERSE_DECL(TemplateTypeParmDecl, {
   // D is the "T" in something like "template class vector;"
   if (D->getTypeForDecl())
 TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
-  if (const auto *TC = D->getTypeConstraint())
-TRY_TO(TraverseConceptReference(*TC));
+  if (const auto *TC = D->getTypeConstraint()) {
+if (Expr *IDC = TC->getImmediatelyDeclaredConstraint()) {
+  TRY_TO(TraverseStmt(IDC));
+} else {
+  // Avoid traversing the ConceptReference in the TypeCosntraint
+  // if we have an immediately-declared-constraint, otherwise
+  // we'll end up visiting the concept and the arguments in
+  // the TC twice.
+  TRY_TO(TraverseConceptReference(*TC));
+}
+  }
   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
 TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc()));
 })

diff  --git a/clang/unittests/Tooling/CMakeLists.txt 
b/clang/unittests/Tooling/CMakeLists.txt
index f290c3d2bede..9de330ab73d4 100644
--- a/clang/unittests/Tooling/CMakeLists.txt
+++ b/clang/unittests/Tooling/CMakeLists.txt
@@ -22,6 +22,7 @@ add_clang_unittest(ToolingTests
   RecursiveASTVisitorTests/Attr.cpp
   RecursiveASTVisitorTests/Callbacks.cpp
   RecursiveASTVisitorTests/Class.cpp
+  RecursiveASTVisitorTests/Concept.cpp
   RecursiveASTVisitorTests/ConstructExpr.cpp
   RecursiveASTVisitorTests/CXXBoolLiteralExpr.cpp
   RecursiveASTVisitorTests/CXXMemberCall.cpp

diff  --git a/clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp 
b/clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp
new file mode 100644
index ..f0f700204dd5
--- /dev/null
+++ b/clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp
@@ -0,0 +1,45 @@
+//===- 
unittest/Tooling/RecursiveASTVisitorTests/Concept.cpp==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+#include "clang/AST/ExprConcepts.h"
+
+using namespace clang;
+
+namespace {
+
+struct ConceptVisitor : ExpectedLocationVisitor {
+  bool VisitConceptSpecializationExpr(ConceptSpecializationExpr *E) {
+++ConceptSpecializationExprsVisited;
+return true;
+  }
+  bool TraverseConceptReference(const ConceptReference &R) {
+++ConceptReferencesTraversed;
+return true;
+  }
+
+  int ConceptSpecializationExprsVisited = 0;
+  int ConceptReferencesTraversed = 0;
+};
+
+TEST(RecursiveASTVisitor, ConstrainedParameter) {
+  ConceptVisitor Visitor;
+  EXPECT_TRUE(Visitor.runOver

[clang-tools-extra] e33ec9d - [clangd] Target member of dependent base made visible via a using-decl

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

Author: Nathan Ridge
Date: 2020-08-18T03:03:49-04:00
New Revision: e33ec9d90400a906314ccbd5821dbe05d070108a

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

LOG: [clangd] Target member of dependent base made visible via a using-decl

Fixes https://github.com/clangd/clangd/issues/307

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

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index f73a6e584972..9db814368a02 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -100,7 +100,7 @@ CXXRecordDecl *resolveTypeToRecordDecl(const Type *T) {
 std::vector getMembersReferencedViaDependentName(
 const Type *T,
 llvm::function_ref NameFactory,
-bool IsNonstaticMember) {
+llvm::function_ref Filter) {
   if (!T)
 return {};
   if (auto *ET = T->getAs()) {
@@ -113,17 +113,22 @@ std::vector 
getMembersReferencedViaDependentName(
   return {};
 RD = RD->getDefinition();
 DeclarationName Name = NameFactory(RD->getASTContext());
-return RD->lookupDependentName(Name, [=](const NamedDecl *D) {
-  return IsNonstaticMember ? D->isCXXInstanceMember()
-   : !D->isCXXInstanceMember();
-});
+return RD->lookupDependentName(Name, Filter);
   }
   return {};
 }
 
-// Given the type T of a dependent expression that appears of the LHS of a 
"->",
-// heuristically find a corresponding pointee type in whose scope we could look
-// up the name appearing on the RHS.
+const auto NonStaticFilter = [](const NamedDecl *D) {
+  return D->isCXXInstanceMember();
+};
+const auto StaticFilter = [](const NamedDecl *D) {
+  return !D->isCXXInstanceMember();
+};
+const auto ValueFilter = [](const NamedDecl *D) { return isa(D); };
+
+// Given the type T of a dependent expression that appears of the LHS of a
+// "->", heuristically find a corresponding pointee type in whose scope we
+// could look up the name appearing on the RHS.
 const Type *getPointeeType(const Type *T) {
   if (!T)
 return nullptr;
@@ -141,7 +146,7 @@ const Type *getPointeeType(const Type *T) {
   [](ASTContext &Ctx) {
 return Ctx.DeclarationNames.getCXXOperatorName(OO_Arrow);
   },
-  /*IsNonStaticMember=*/true);
+  NonStaticFilter);
   if (ArrowOps.empty())
 return nullptr;
 
@@ -187,13 +192,12 @@ std::vector resolveExprToDecls(const 
Expr *E) {
 }
 return getMembersReferencedViaDependentName(
 BaseType, [ME](ASTContext &) { return ME->getMember(); },
-/*IsNonstaticMember=*/true);
+NonStaticFilter);
   }
   if (const auto *RE = dyn_cast(E)) {
 return getMembersReferencedViaDependentName(
 RE->getQualifier()->getAsType(),
-[RE](ASTContext &) { return RE->getDeclName(); },
-/*IsNonstaticMember=*/false);
+[RE](ASTContext &) { return RE->getDeclName(); }, StaticFilter);
   }
   if (const auto *CE = dyn_cast(E)) {
 const auto *CalleeType = resolveExprToType(CE->getCallee());
@@ -291,7 +295,6 @@ const NamedDecl *getTemplatePattern(const NamedDecl *D) {
 // CXXDependentScopeMemberExpr, but some other constructs remain to be handled:
 //  - DependentTemplateSpecializationType,
 //  - DependentNameType
-//  - UnresolvedUsingValueDecl
 //  - UnresolvedUsingTypenameDecl
 struct TargetFinder {
   using RelSet = DeclRelationSet;
@@ -345,6 +348,15 @@ struct TargetFinder {
 } else if (const auto *NAD = dyn_cast(D)) {
   add(NAD->getUnderlyingDecl(), Flags | Rel::Underlying);
   Flags |= Rel::Alias; // continue with the alias
+} else if (const UnresolvedUsingValueDecl *UUVD =
+   dyn_cast(D)) {
+  for (const NamedDecl *Target : getMembersReferencedViaDependentName(
+   UUVD->getQualifier()->getAsType(),
+   [UUVD](ASTContext &) { return UUVD->getNameInfo().getName(); },
+   ValueFilter)) {
+add(Target, Flags | Rel::Underlying);
+  }
+  Flags |= Rel::Alias; // continue with the alias
 } else if (const UsingShadowDecl *USD = dyn_cast(D)) {
   // Include the using decl, but don't traverse it. This may end up
   // including *all* shadows, which we don't want.

diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index 9936c67cb6e5..031a9c7bf5da 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -345,7 +345,7 @@ locateASTReferent(SourceLocation CurLoc, const 
syntax::Token *TouchedIdentifier,
 
 

[clang-tools-extra] 5a7276b - [clangd] Have suppression comments take precedence over warning-as-error

2020-05-11 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2020-05-12T02:29:03-04:00
New Revision: 5a7276b3548589590b81975d5c3e487dd91ac097

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

LOG: [clangd] Have suppression comments take precedence over warning-as-error

Summary: This matches the clang-tidy behaviour.

Fixes https://github.com/clangd/clangd/issues/375

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

Tags: #clang

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

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 61221aaa1491..e63f105b1b6c 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -314,18 +314,12 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs &Inputs,
 std::string CheckName = CTContext->getCheckName(Info.getID());
 bool IsClangTidyDiag = !CheckName.empty();
 if (IsClangTidyDiag) {
-  // Check for warning-as-error.
-  // We deliberately let this take precedence over suppression comments
-  // to match clang-tidy's behaviour.
-  if (DiagLevel == DiagnosticsEngine::Warning &&
-  CTContext->treatAsError(CheckName)) {
-return DiagnosticsEngine::Error;
-  }
-
   // Check for suppression comment. Skip the check for diagnostics not
   // in the main file, because we don't want that function to query the
   // source buffer for preamble files. For the same reason, we ask
   // shouldSuppressDiagnostic to avoid I/O.
+  // We let suppression comments take precedence over warning-as-error
+  // to match clang-tidy's behaviour.
   bool IsInsideMainFile =
   Info.hasSourceManager() &&
   isInsideMainFile(Info.getLocation(), Info.getSourceManager());
@@ -334,6 +328,12 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs &Inputs,
  /*AllowIO=*/false)) {
 return DiagnosticsEngine::Ignored;
   }
+
+  // Check for warning-as-error.
+  if (DiagLevel == DiagnosticsEngine::Warning &&
+  CTContext->treatAsError(CheckName)) {
+return DiagnosticsEngine::Error;
+  }
 }
   }
   return DiagLevel;

diff  --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp 
b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
index b94de7412ce3..3d838c78a3c5 100644
--- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -374,23 +374,17 @@ n]] = 10; // error-ok
   Fix(Source.range(), "ident", "change 'ide\\…' to 
'ident'";
 }
 
-TEST(DiagnosticTest, ClangTidyWarningAsErrorTrumpsSuppressionComment) {
+TEST(DiagnosticTest, ClangTidySuppressionCommentTrumpsWarningAsError) {
   Annotations Main(R"cpp(
 int main() {
   int i = 3;
-  double f = [[8]] / i;  // NOLINT // error-ok
+  double f = [[8]] / i;  // NOLINT
 }
   )cpp");
   TestTU TU = TestTU::withCode(Main.code());
   TU.ClangTidyChecks = "bugprone-integer-division";
   TU.ClangTidyWarningsAsErrors = "bugprone-integer-division";
-  EXPECT_THAT(
-  TU.build().getDiagnostics(),
-  UnorderedElementsAre(::testing::AllOf(
-  Diag(Main.range(), "result of integer division used in a floating "
- "point context; possible loss of precision"),
-  DiagSource(Diag::ClangTidy), DiagName("bugprone-integer-division"),
-  DiagSeverity(DiagnosticsEngine::Error;
+  EXPECT_THAT(TU.build().getDiagnostics(), UnorderedElementsAre());
 }
 
 TEST(DiagnosticsTest, Preprocessor) {



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


[clang-tools-extra] 9af0a14 - [clangd] Fail more gracefully if QueryDriverDatabase cannot determine file type

2022-08-29 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2022-08-29T12:59:05-04:00
New Revision: 9af0a142e43625cb8478b83692510a5abd39f808

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

LOG: [clangd] Fail more gracefully if QueryDriverDatabase cannot determine file 
type

Currently, QueryDriverDatabase returns an empty compile command
if it could not determine the file type.

This failure mode is unnecessarily destructive; it's better to
just return the incoming compiler command, which is still more
likely to be useful than an empty command.

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

Added: 


Modified: 
clang-tools-extra/clangd/QueryDriverDatabase.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/QueryDriverDatabase.cpp 
b/clang-tools-extra/clangd/QueryDriverDatabase.cpp
index 3fdacf397028e..c36fb4f042a9f 100644
--- a/clang-tools-extra/clangd/QueryDriverDatabase.cpp
+++ b/clang-tools-extra/clangd/QueryDriverDatabase.cpp
@@ -341,7 +341,7 @@ class QueryDriverDatabase : public DelegatingCDB {
   auto Type = driver::types::lookupTypeForExtension(Ext);
   if (Type == driver::types::TY_INVALID) {
 elog("System include extraction: invalid file type for {0}", Ext);
-return {};
+return Cmd;
   }
   Lang = driver::types::getTypeName(Type);
 }



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


[clang] 898c421 - [clangd] Avoid crash when printing call to string literal operator template

2022-09-05 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2022-09-05T03:42:08-04:00
New Revision: 898c421975ed36b99ec2047589384539bd29a40b

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

LOG: [clangd] Avoid crash when printing call to string literal operator template

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

Added: 


Modified: 
clang/lib/AST/StmtPrinter.cpp
clang/unittests/AST/StmtPrinterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp
index 9cb72ee6b1964..03b71a7ec9416 100644
--- a/clang/lib/AST/StmtPrinter.cpp
+++ b/clang/lib/AST/StmtPrinter.cpp
@@ -1993,7 +1993,7 @@ void 
StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
   cast(DRE->getDecl())->getTemplateSpecializationArgs();
 assert(Args);
 
-if (Args->size() != 1) {
+if (Args->size() != 1 || Args->get(0).getKind() != TemplateArgument::Pack) 
{
   const TemplateParameterList *TPL = nullptr;
   if (!DRE->hadMultipleCandidates())
 if (const auto *TD = dyn_cast(DRE->getDecl()))

diff  --git a/clang/unittests/AST/StmtPrinterTest.cpp 
b/clang/unittests/AST/StmtPrinterTest.cpp
index f3ea74d65696f..b6f340507164f 100644
--- a/clang/unittests/AST/StmtPrinterTest.cpp
+++ b/clang/unittests/AST/StmtPrinterTest.cpp
@@ -31,7 +31,7 @@ using namespace tooling;
 
 namespace {
 
-enum class StdVer { CXX98, CXX11, CXX14, CXX17, CXX2a };
+enum class StdVer { CXX98, CXX11, CXX14, CXX17, CXX20 };
 
 DeclarationMatcher FunctionBodyMatcher(StringRef ContainingFunction) {
   return functionDecl(hasName(ContainingFunction),
@@ -67,7 +67,9 @@ PrintedStmtCXXMatches(StdVer Standard, StringRef Code, const 
T &NodeMatch,
   case StdVer::CXX11: StdOpt = "-std=c++11"; break;
   case StdVer::CXX14: StdOpt = "-std=c++14"; break;
   case StdVer::CXX17: StdOpt = "-std=c++17"; break;
-  case StdVer::CXX2a: StdOpt = "-std=c++2a"; break;
+  case StdVer::CXX20:
+StdOpt = "-std=c++20";
+break;
   }
 
   std::vector Args = {
@@ -146,6 +148,35 @@ TEST(StmtPrinter, TestFloatingPointLiteral) {
 // Should be: with semicolon
 }
 
+TEST(StmtPrinter, TestStringLiteralOperatorTemplate_Pack) {
+  ASSERT_TRUE(PrintedStmtCXXMatches(StdVer::CXX11,
+R"cpp(
+template  constexpr double operator""_c() { return 42; }
+void A() {
+  constexpr auto waldo = 42_c;
+}
+)cpp",
+FunctionBodyMatcher("A"),
+"constexpr auto waldo = 42_c;\n"));
+}
+
+TEST(StmtPrinter, TestStringLiteralOperatorTemplate_Class) {
+  ASSERT_TRUE(
+  PrintedStmtCXXMatches(StdVer::CXX20,
+R"cpp(
+struct C {
+  template  constexpr C(const char (&)[N]) : n(N) {}
+  unsigned n;
+};
+template  constexpr auto operator""_c() { return c.n; }
+void A() {
+  constexpr auto waldo = "abc"_c;
+}
+)cpp",
+FunctionBodyMatcher("A"),
+"constexpr auto waldo = 
operator\"\"_c<{4}>();\n"));
+}
+
 TEST(StmtPrinter, TestCXXConversionDeclImplicit) {
   ASSERT_TRUE(PrintedStmtCXXMatches(
   StdVer::CXX98,



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


[clang] c933453 - Fix build error in StmtPrinterTest.cpp

2022-09-05 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2022-09-05T03:48:46-04:00
New Revision: c933453858307d060a1b79e257feb99c9ac828d7

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

LOG: Fix build error in StmtPrinterTest.cpp

Added: 


Modified: 
clang/unittests/AST/StmtPrinterTest.cpp

Removed: 




diff  --git a/clang/unittests/AST/StmtPrinterTest.cpp 
b/clang/unittests/AST/StmtPrinterTest.cpp
index b6f340507164..ef80812886ae 100644
--- a/clang/unittests/AST/StmtPrinterTest.cpp
+++ b/clang/unittests/AST/StmtPrinterTest.cpp
@@ -232,15 +232,17 @@ TEST(StmtPrinter, TestCXXLamda) {
 "[](auto a, int b, auto c, int, auto) {\n"
 "}"));
 
-  ASSERT_TRUE(PrintedStmtCXXMatches(StdVer::CXX2a,
-"void A() {"
-"  auto l = [] class T3>"
-"   (int a, auto, int, auto d) { };"
-"}",
-lambdaExpr(anything()).bind("id"),
-"[] class T3>(int 
a, auto, int, auto d) {\n"
-"}"));
+  ASSERT_TRUE(
+  PrintedStmtCXXMatches(StdVer::CXX20,
+"void A() {"
+"  auto l = [] class T3>"
+"   (int a, auto, int, auto d) { };"
+"}",
+lambdaExpr(anything()).bind("id"),
+"[] class T3>(int a, auto, int, auto d) {\n"
+"}"));
 }
 
 TEST(StmtPrinter, TestNoImplicitBases) {



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


[clang-tools-extra] [clangd][RFC] Add container field to remote index Refs grpc method (PR #71605)

2023-11-08 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

This sounds like it might be the culprit behind 
https://github.com/clangd/clangd/issues/1358

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 requested changes to this pull request.

Thank you for the patch!

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits


@@ -0,0 +1,11 @@
+// RUN: cp %s %t.c

HighCommander4 wrote:

I think it would be more consistent with the rest of the clangd subproject if 
this was expressed as a unit test.

It can take the form of a new section added to [this existing 
test](https://searchfox.org/llvm/rev/6a91b7051df7e108c8ffd79c084859f90559962d/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp#19),
 similar to [this 
section](https://searchfox.org/llvm/rev/6a91b7051df7e108c8ffd79c084859f90559962d/clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp#61-66)
 but using `EXPECT_UNAVAILABLE` (since the refactoring does not end up being 
available on this test case, even though it passes this particular check). The 
`[[ ]]` in the input source code annotates the source range on which the 
refactoring is invoked.

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits


@@ -176,7 +176,8 @@ bool ExtractionContext::exprIsValidOutside(const 
clang::Stmt *Scope) const {
   SourceLocation ScopeBegin = Scope->getBeginLoc();
   SourceLocation ScopeEnd = Scope->getEndLoc();
   for (const Decl *ReferencedDecl : ReferencedDecls) {
-if (SM.isPointWithin(ReferencedDecl->getBeginLoc(), ScopeBegin, ScopeEnd) 
&&
+if (ReferencedDecl->getBeginLoc().isValid() &&

HighCommander4 wrote:

(I wondered whether there might be other cases where a `Decl` has an invalid 
location where we'd want this function to return `false`, but I couldn't think 
of a specific case, so I think this is fine for the time being.)

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

Thanks!

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


[clang-tools-extra] [clangd] Check for valid location in ExtractionContext::exprIsValidOutside (PR #71162)

2023-11-10 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Correctly identify the next token after the completion point (PR #69153)

2023-11-11 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/69153

>From 26861317e73e0e1a1d118688472ad0f0fc9af134 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Mon, 16 Oct 2023 03:51:48 -0400
Subject: [PATCH] [clangd] Correctly identify the next token after the
 completion point

The code was previously using Lexer::findNextToken() which does not
handle being passed the completion point as input.

Fixes https://github.com/clangd/clangd/issues/1785
---
 clang-tools-extra/clangd/CodeComplete.cpp | 42 ++-
 .../clangd/unittests/CodeCompleteTests.cpp| 23 ++
 2 files changed, 64 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index c5586eac606a668..5eef43e93cb519f 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -1491,6 +1491,46 @@ FuzzyFindRequest 
speculativeFuzzyFindRequestForCompletion(
   return CachedReq;
 }
 
+// This function is similar to Lexer::findNextToken(), but assumes
+// that the input SourceLocation is the completion point (which is
+// a case findNextToken() does not handle).
+std::optional
+findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
+  const SourceManager &SM,
+  const LangOptions &LangOpts) {
+  SourceLocation Loc = CompletionPoint;
+  if (Loc.isMacroID()) {
+if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
+  return std::nullopt;
+  }
+
+  // Advance to the next SourceLocation after the completion point.
+  // Lexer::findNextToken() would call MeasureTokenLength() here,
+  // which does not handle the completion point (and can't, because
+  // the Lexer instance it constructs internally doesn't have a
+  // Preprocessor and so doesn't know about the completion point).
+  Loc = Loc.getLocWithOffset(1);
+
+  // Break down the source location.
+  std::pair LocInfo = SM.getDecomposedLoc(Loc);
+
+  // Try to load the file buffer.
+  bool InvalidTemp = false;
+  StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
+  if (InvalidTemp)
+return std::nullopt;
+
+  const char *TokenBegin = File.data() + LocInfo.second;
+
+  // Lex from the start of the given location.
+  Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, 
File.begin(),
+ TokenBegin, File.end());
+  // Find the token.
+  Token Tok;
+  TheLexer.LexFromRawLexer(Tok);
+  return Tok;
+}
+
 // Runs Sema-based (AST) and Index-based completion, returns merged results.
 //
 // There are a few tricky considerations:
@@ -1589,7 +1629,7 @@ class CodeCompleteFlow {
   auto Style = getFormatStyleForFile(SemaCCInput.FileName,
  SemaCCInput.ParseInput.Contents,
  *SemaCCInput.ParseInput.TFS);
-  const auto NextToken = Lexer::findNextToken(
+  const auto NextToken = findTokenAfterCompletionPoint(
   Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
   Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
   if (NextToken)
diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 766998eb4f3c719..692c6db3c51bedf 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -3892,6 +3892,29 @@ TEST(CompletionTest, FunctionArgsExist) {
  kind(CompletionItemKind::Function;
 }
 
+TEST(CompletionTest, FunctionArgsExist_Issue1785) {
+  // This is a scenario where the implementation of our check for
+  // "is there a function argument list right after the cursor"
+  // gave a bogus result.
+  clangd::CodeCompleteOptions Opts;
+  Opts.EnableSnippets = true;
+  // The whitespace in this testcase is important!
+  std::string Code = R"cpp(
+void waldo(int);
+
+int main()
+{
+  wal^
+
+
+  // ()
+}
+  )cpp";
+  EXPECT_THAT(
+  completions(Code, {}, Opts).Completions,
+  Contains(AllOf(labeled("waldo(int)"), snippetSuffix("(${1:int})";
+}
+
 TEST(CompletionTest, NoCrashDueToMacroOrdering) {
   EXPECT_THAT(completions(R"cpp(
 #define ECHO(X) X

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


[clang-tools-extra] [clangd] Correctly identify the next token after the completion point (PR #69153)

2023-11-11 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

Rebased

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


[clang-tools-extra] [clangd] Correctly identify the next token after the completion point (PR #69153)

2023-11-11 Thread Nathan Ridge via cfe-commits


@@ -1491,6 +1491,46 @@ FuzzyFindRequest 
speculativeFuzzyFindRequestForCompletion(
   return CachedReq;
 }
 
+// This function is similar to Lexer::findNextToken(), but assumes
+// that the input SourceLocation is the completion point (which is
+// a case findNextToken() does not handle).
+std::optional
+findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
+  const SourceManager &SM,
+  const LangOptions &LangOpts) {
+  SourceLocation Loc = CompletionPoint;

HighCommander4 wrote:

> do you think it's possible to make this function a static member of `Lexer` 
> like `Lexer::findNextToken`? That way we might need a slight refactor to 
> reuse some common logics.

I think this would be a good improvement, but I'd like to leave it to a 
follow-up patch, because it involves adding new public API to 
`clang/Lex/Lexer.h`, so it should probably be approved by a code owner of the 
Lexer component.

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


[clang-tools-extra] [clangd] Correctly identify the next token after the completion point (PR #69153)

2023-11-11 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

Thank you @zyn0217 for the review!

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


[clang-tools-extra] [clangd] Correctly identify the next token after the completion point (PR #69153)

2023-11-11 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-12 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 commented:

Thanks very much for looking at this!

I'm wondering if it's possible to achieve the same results (and also solve your 
`CXXUnresolvedConstructExpr` issue) with a more targeted change that may also 
be simpler.

While I haven't experimented with this approach to verify that it's feasible, 
here's what I had in mind:

 * In a suitable place where we simplify dependent types (I'm thinking around 
[here](https://searchfox.org/mozilla-central/rev/fe8b30e982c86d26ccf1f14d825c0de870b91f27/build/clang-plugin/mozsearch-plugin/from-clangd/HeuristicResolver.cpp#59)),
 check if the type is a `TemplateTypeParmType`.
 * If so, get its `TemplateTypeParmDecl`, find the template whose parameter it 
is, and see if the template has a `getOnlyInstantiation`. If so, find the 
argument type substituted for this template parameter, and replace the template 
parameter with this type.

As a bonus, the "default argument heuristic" discussed 
[here](https://github.com/clangd/clangd/discussions/1056) could be implemented 
in the same place. (Even if the template doesn't have exactly one 
instantiation, if the template parameter has a default argument, replace the 
template parameter with the default argument.)

I _think_ this should handle the cases in this testcase without the need for 
any Visitor, though it's definitely possible I'm overlooking something.

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-12 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 commented:

Is it not possible to tell based on the `CallExpr` only (rather than checking 
an ancestor of it during traversal of the tree) that "this `CallExpr` is not 
explicitly written in the source"?

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-13 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

I see; it's a bit unfortunate that such an "invented" call expression gets an 
ordinary `SourceLocation`. I would have hoped it gets a source location in some 
sort of virtual buffer like the [rewritten form of 
`>>`](https://github.com/clangd/clangd/issues/871#issuecomment-933178468), or 
macro expansions.

---

What do you think about the following idea: override the traversal of 
`PseudoObjectExpr`, but rather than traversing [both the `getSyntacticForm()` 
and the semantic 
expressions](https://searchfox.org/llvm/rev/40671bbdefb6ff83e2685576a3cb041b62f25bbe/clang/include/clang/AST/RecursiveASTVisitor.h#2573-2584),
 only traverse the `getSyntacticForm()`?

That leave the door open to a future enhancement where the arguments in the 
syntactic form (the `__builtin_dump_struct`) could get parameter hints, which 
might be useful for a reader to understand what the builtin does.

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


[clang-tools-extra] [clangd] Initialize HighlightingsBuilder::Resolver (PR #74971)

2023-12-09 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/74971

None

>From ed2ccbab5bc9641cc857dd6e6d152449aab76431 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 10 Dec 2023 00:50:54 -0500
Subject: [PATCH] [clangd] Initialize HighlightingsBuilder::Resolver

---
 clang-tools-extra/clangd/SemanticHighlighting.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 49e479abf45621..abc3d1f58a776e 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -418,7 +418,8 @@ class HighlightingsBuilder {
 public:
   HighlightingsBuilder(const ParsedAST &AST, const HighlightingFilter &Filter)
   : TB(AST.getTokens()), SourceMgr(AST.getSourceManager()),
-LangOpts(AST.getLangOpts()), Filter(Filter) {}
+LangOpts(AST.getLangOpts()), Filter(Filter),
+Resolver(AST.getHeuristicResolver()) {}
 
   HighlightingToken &addToken(SourceLocation Loc, HighlightingKind Kind) {
 auto Range = getRangeForSourceLocation(Loc);

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


[clang-tools-extra] [clangd] Initialize HighlightingsBuilder::Resolver (PR #74971)

2023-12-09 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

Fixing issue spotted in 
https://github.com/llvm/llvm-project/pull/71279#issuecomment-1848347945.

I tried to construct a testcase that the previous code would fail but couldn't: 
`kindForDecl` only does something interesting with the resolver for 
`UnresolvedUsingValueDecl`, but the call sites in `HighlightingsBuilder` only 
use `kindForType`, which only calls into `kindForDecl` in the case of a 
`TemplateTypeParmType` or `TagType`, and I don't think those can ever have an 
`UnresolvedUsingValueDecl` as their associated decl.

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


[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-12-09 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> @HighCommander4 While at the `HeuristicResolver`, I think we may have a bug 
> inside `HighlightingsBuilder` defined in `SemanticHighlighting.cpp`.
> 
> https://github.com/llvm/llvm-project/blob/6ed9a81f7ebd23f125867dd270785dd0e63043c6/clang-tools-extra/clangd/SemanticHighlighting.cpp#L592
> 
> I didn't see any other lines initializing this member. so we're always 
> yielding `nullptr` from `H.getResolver` calls?

Thanks for spotting that. Posted 
https://github.com/llvm/llvm-project/pull/74971 to fix.

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


[clang-tools-extra] [clangd] Initialize HighlightingsBuilder::Resolver (PR #74971)

2023-12-10 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/74971

>From 86d99f7b29a131b949b32f18ff15eb1d1f5e4d3a Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 10 Dec 2023 00:50:54 -0500
Subject: [PATCH] [clangd] Initialize HighlightingsBuilder::Resolver

---
 clang-tools-extra/clangd/SemanticHighlighting.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 49e479abf45621..37939d36425a97 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -418,7 +418,8 @@ class HighlightingsBuilder {
 public:
   HighlightingsBuilder(const ParsedAST &AST, const HighlightingFilter &Filter)
   : TB(AST.getTokens()), SourceMgr(AST.getSourceManager()),
-LangOpts(AST.getLangOpts()), Filter(Filter) {}
+LangOpts(AST.getLangOpts()), Filter(Filter),
+Resolver(AST.getHeuristicResolver()) {}
 
   HighlightingToken &addToken(SourceLocation Loc, HighlightingKind Kind) {
 auto Range = getRangeForSourceLocation(Loc);
@@ -589,7 +590,7 @@ class HighlightingsBuilder {
   HighlightingFilter Filter;
   std::vector Tokens;
   std::map> ExtraModifiers;
-  const HeuristicResolver *Resolver = nullptr;
+  const HeuristicResolver *Resolver;
   // returned from addToken(InvalidLoc)
   HighlightingToken InvalidHighlightingToken;
 };

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


[clang-tools-extra] [clangd] Initialize HighlightingsBuilder::Resolver (PR #74971)

2023-12-10 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-17 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> I see; it's a bit unfortunate that such an "invented" call expression gets an 
> ordinary `SourceLocation`.

Out of curiosity, I dialled into today's LLVM [office 
hours](https://llvm.org/docs/GettingInvolved.html#office-hours) and asked Aaron 
Ballman about this. He also did not see an obvious way to tell apart the 
invented `CallExpr`s from regular `CallExpr`s, but suggested that it could be 
reasonable to just change the code for building the invented `CallExpr`s to 
give them an invalid SourceLocation (and then our inlay hints code should 
filter them out without further changes).

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


[clang-tools-extra] [clangd] Add includes from source to non-self-contained headers (PR #72479)

2023-11-17 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

@sr-tream just so you know, every time you force-push a PR, github sends every 
subscriber an email notification

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


[clang] [clang-tools-extra] [clang] Turn invented Exprs' source locations in __builtin_dump_struct to empty (PR #72750)

2023-11-18 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

The CI run shows the test 
[Sema/builtin-dump-struct.c](https://searchfox.org/llvm/source/clang/test/Sema/builtin-dump-struct.c)
 is failing.

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


[clang-tools-extra] [clang] [clang] Turn invented Exprs' source locations in __builtin_dump_struct to empty (PR #72750)

2023-11-18 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

It looks like the issue is, if the invented CallExpr is ill-formed and the 
compiler needs to issue a diagnostic about it, with the invalid SourceLocation 
it doesn't have a source location to attach to the diagnostic.

I guess this means the approach of using an invalid SourceLocation doesn't work 
after all?

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-19 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-19 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 requested changes to this pull request.


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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-19 Thread Nathan Ridge via cfe-commits


@@ -589,6 +589,24 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 return true;
   }
 
+  bool TraversePseudoObjectExpr(PseudoObjectExpr *E) {
+// Do not show inlay hints for the __builtin_dump_struct, which would
+// expand to a PseudoObjectExpr that includes a couple of calls to a
+// printf function. Printing parameter names for that anyway would end up
+// with duplicate parameter names (which, however, got de-duplicated after
+// visiting) for the printf function.
+if (auto *CE = dyn_cast(E->getSyntacticForm());
+CE && CE->getBuiltinCallee() == Builtin::BI__builtin_dump_struct)
+  // Only traverse the syntactic forms. This leaves the door open in case
+  // the arguments in the syntactic form for __builtin_dump_struct could
+  // possibly get parameter names.
+  return RecursiveASTVisitor::TraverseStmt(
+  E->getSyntacticForm());
+// FIXME: Shall we ignore semantic forms for other pseudo object

HighCommander4 wrote:

Maybe all PseudoObjectExprs where the syntactic form is a CallExpr with a 
builtin callee would be reasonable?

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-19 Thread Nathan Ridge via cfe-commits


@@ -1724,6 +1724,33 @@ TEST(InlayHints, RestrictRange) {
   ElementsAre(labelIs(": int"), labelIs(": char")));
 }
 
+TEST(ParameterHints, PseudoObjectExpr) {
+  Annotations Code(R"cpp(
+struct S {
+  __declspec(property(get=GetX, put=PutX)) int x[];
+  int GetX(int y, int z) { return 42 + y; }
+  void PutX(int y) { x = $one[[y]]; } // FIXME: Undesired `x = y: y` for 
this ill-formed expression.
+};
+
+int printf(const char *Format, ...);
+
+int main() {
+  S s;
+  __builtin_dump_struct(&s, printf); // Not `Format: 
__builtin_dump_struct()`
+  printf($Param[["Hello, %d"]], 42); // Normal calls are not affected.
+  return s.x[ $two[[1]] ][ $three[[2]] ]; // `x[y: 1][z: 2]`

HighCommander4 wrote:

Thanks, this is an interesting use case for not just skipping the semantic 
forms of all PseudoObjectExprs (which was my initial thought)

Since it's not obvious that this builds a PseudoObjectExpr, can you please add 
a comment:

```
// This builds a PseudoObjectExpr, but here it's useful for show the
// arguments from the semantic form.
```

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-19 Thread Nathan Ridge via cfe-commits


@@ -1724,6 +1724,33 @@ TEST(InlayHints, RestrictRange) {
   ElementsAre(labelIs(": int"), labelIs(": char")));
 }
 
+TEST(ParameterHints, PseudoObjectExpr) {
+  Annotations Code(R"cpp(
+struct S {
+  __declspec(property(get=GetX, put=PutX)) int x[];
+  int GetX(int y, int z) { return 42 + y; }
+  void PutX(int y) { x = $one[[y]]; } // FIXME: Undesired `x = y: y` for 
this ill-formed expression.

HighCommander4 wrote:

This is a bit confusing, since the fact that the expression is ill-formed is 
not related to the FIXME.

I would suggest moving the `x = y;` to some other function (where it's not 
ill-formed).

(Also mention in a comment that this builds a PseudoObjectExpr here too.)

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


[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-20 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> I suspect it won't work with the present `TemplateTypeParm{Type,Decl}` 
> models. `TemplateTypeParmDecl` per se is not tied to any `CXXRecordDecl` nor 
> `FunctionDecl` that the template parameter is declaring with. (For the most 
> seemingly-relevant part, i.e. the `DeclContext` it records, is the scope that 
> the template defines.)

I've done some local experimentation, and what I'm seeing is that 
`TemplateTypeParmDecl::getDeclContext()` does return the `FunctionDecl` or 
`CXXRecordDecl` which owns the template parameter.

One tricky thing I found is that when starting from a template parameter 
**type**, it's important to use `dyn_cast(T)` rather than 
`T->getAs()`; the latter does more than just cast, it 
returns the canonical type whose associated Decl is null.

I also discovered some complications related to nested templates, and I have 
some thoughts on how to resolve them, but I'm going to suggest that we start 
with getting a simple case (e.g. just one level of templates, no nested 
templates) to work, and then tackle nested templates as a next step.

> > If so, find the argument type substituted for this template parameter, and 
> > replace the template parameter with this type.
> 
> I was thinking this way before getting into the details :-). Soon I realized 
> that we had to tackle synthesized types e.g.
> 
> ```c++
> template  typename C, typename D, int E>
> void work() {
>   C complicated_type;
>   // ^ Shall we perform the type substitution once again? ;)
> }
> ```

I'm not too concerned about this. The idea behind `HeuristicResolver` is to 
perform name lookups in the primary template as a heuristic.

So, to give an example:

```c++
template 
void work() {
  std::vector a;
  a.pop_back();
}
```

here, `pop_back` is looked up in the primary template scope of `std::vector`; 
information from the argument list `` is not used.

Now, applying this to your example:

```c++
template  class A, typename T>
void work() {
  A a;
  a.pop_back();
}

// work() has one instantiation, with [A = std::vector, T = bar] 
```

applying the "only instantiation" heuristic will tell us that `A = 
std::vector`, and then we can look up `pop_back` in the primary template scope 
of `std::vector`; we still don't use information from the argument list ``.

We could potentially envision future enhancements to make use of information 
from the "only instantiation" to make lookup inside template specialization 
types more accurate than just "use the primary template" (which could then 
apply to the `std::vector` case as well, and e.g. return a more accurate 
result if the "only instantiation" is `T = bool`), but that seems like more of 
an edge case and I'd rather leave it to a future change.

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


[clang-tools-extra] [clangd] Add includes from source to non-self-contained headers (PR #72479)

2023-11-22 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

A somewhat narrow use case where this approach might be workable is unity 
builds (groups of source files batched together to be compiled as a single 
translation unit for build performance).

That's a situation where the non-self-contained files of interest (the 
individual source files that are included in such a batch) have precisely one 
includer, their incoming preprocessor state can be replicated precisely using 
`-include` flags, and the intervention can be limited to them (it wouldn't 
apply to header files).

Of course, the including file is not likely to be open in this case, so we'd 
want something like an include graph stored in the index (as proposed in #123) 
to consult.

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


[clang-tools-extra] [clangd] Support `-specs` arguments when querying the driver. (PR #70285)

2023-11-03 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

Thanks!

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


[clang-tools-extra] [clangd] Support `-specs` arguments when querying the driver. (PR #70285)

2023-11-03 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Allow specifying what headers are always included via "" or <> (PR #67749)

2023-12-12 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

What is the relationship between this patch, and clangd 17's ["missing include" 
warning](https://clangd.llvm.org/guides/include-cleaner#missing-include-warning)?
 Does the quick-fix for the "missing include" warning also respect these config 
options?

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


[clang-tools-extra] [clangd] don't lower severity of clang-tidy modernize-* checks to remarks (PR #75706)

2023-12-16 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> Explicitly pinging @kadircet and @sam-mccall for your involvement in the 
> mentioned commit. What are your thoughts on this? I looked into this because 
> someone on discord asked about this difference.

Added Sam and Kadir as reviewers.

This patch seems to contradict the explicit motivation of the previous one 
expressed in this code comment:

```c++
  // We downgrade severity for certain noisy warnings, like deprecated
  // declartions. These already have visible decorations inside the editor and
  // most users find the extra clutter in the UI (gutter, minimap, diagnostics
  // views) overwhelming.
```

I think clang-tidy "modernize" warnings can definitely be noisy in this way.

That said, we've also received feedback that the strike-through style that some 
editors apply for the `Deprecated` tag is even more distracting than the 
underline (https://github.com/clangd/vscode-clangd/issues/482).

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


[clang-tools-extra] [clangd] Expand response files before CDB interpolation (PR #75753)

2023-12-18 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 requested changes to this pull request.

Thanks for having a look at this!

Instead of performing the "expand response files" operation twice for commands 
coming from a `compile_commands.json` source, what do you think about the 
following:

 * Restore the call in `parseJSON()` (i.e. what the patch is doing now), **and**
 * Move the call in `CommandMangler` to a place that is only used for commands 
coming from the LSP, such as around 
[here](https://searchfox.org/llvm/rev/b6cce87110072a2db19276e042cd40b06285abbc/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp#745)?
   * We could consider abstracting `OverlayCDB::Commands` into a dedicated 
`tooling::CompilationDatabase` implementation so that we can simply wrap it 
using `clang::tooling::expandResponseFiles()`, but feel free to leave that for 
later; a direct call to `tooling::addExpandedResponseFiles`, as we had in the 
mangler itself, is fine for now.

It would be nice to have a unit test for this regression as well. We have tests 
exercising `OverlayCDB` in 
[GlobalCompilationDatabaseTests.cpp](https://searchfox.org/llvm/source/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp),
 I think that should be suitable.

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


[clang-tools-extra] [clangd] Add languages as server capabilities (PR #75633)

2023-12-18 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 commented:

Thanks for the patch!

I like the idea of having the server announce support for a list of languages, 
that seems nice and general and extensible.

A couple of thoughts:

 1. Since the key we're adding to the server capabilities is a non-standard 
extension, I'm a bit uneasy about giving it a general name like `"languages"`. 
If the LSP were to add a key with that name but a different format or 
interpretation, we could run into trouble. Can we name it `"clangdLanguages"` 
instead, thereby staying within our own (improvised) "namespace"?
 2. Given that the plan described by Sam in [this 
comment](https://github.com/clangd/vscode-clangd/pull/392#issuecomment-1285902875)
 is to enable vscode-clangd support for HLSL by default once clang's support 
for HLSL is a good enough state, what do you think about the following 
arrangement:
 * don't include `"hlsl"` in `"clangdLanguages"` yet
 * add `"hlsl"` to `"clangdLanguages"` once the "good enough" threshold is 
reached
 * on the client side, add HLSL to the document selector if the server 
announces support for `"hlsl"` in `"clangdLanguages"`, **or** a client-side 
preference (which we could name "experimental", e.g. 
`"clangd.experimentalHLSLSupport"`) is enabled?
 
 This way:
  * early adopters can set `"clangd.experimentalHLSLSupport"` with an 
up-to-date client paired even with a clangd 17 or older server, and get the 
corresponding level of support
 * once the implementation quality is good enough, the server can start 
announcing the support and all clients (not just early adopters who set the 
pref) will have it by default with newer server versions

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


[clang-tools-extra] [clangd] Expand response files before CDB interpolation (PR #75753)

2023-12-19 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

LGTM, thanks for the fix and test!

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


[clang-tools-extra] [clangd] Expand response files before CDB interpolation (PR #75753)

2023-12-19 Thread Nathan Ridge via cfe-commits

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


[clang] [clang-tools-extra] [Sema][clangd] add noexcept to override functions during code completion (PR #75937)

2023-12-19 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

Thanks for the patch.

For the test, it would be better to write it in [this 
format](https://github.com/llvm/llvm-project/tree/main/clang/test/CodeCompletion)
 rather than using clangd.

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


[clang-tools-extra] [clangd] Add languages as server capabilities (PR #75633)

2023-12-19 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> What about a slightly different take? What if in addition to adding 
> `clangdLanguages` (without HLSL) we also add `clangdExperimentalFeatures` and 
> add `HLSL` there. The problem I'm trying to solve here is to avoid someone 
> enabling HLSL on a language server that doesn't advertise that it has support.

That sounds fine to me!

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-25 Thread Nathan Ridge via cfe-commits


@@ -589,6 +589,24 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
 return true;
   }
 
+  bool TraversePseudoObjectExpr(PseudoObjectExpr *E) {
+// Do not show inlay hints for the __builtin_dump_struct, which would
+// expand to a PseudoObjectExpr that includes a couple of calls to a
+// printf function. Printing parameter names for that anyway would end up
+// with duplicate parameter names (which, however, got de-duplicated after
+// visiting) for the printf function.
+if (auto *CE = dyn_cast(E->getSyntacticForm());
+CE && CE->getBuiltinCallee() == Builtin::BI__builtin_dump_struct)
+  // Only traverse the syntactic forms. This leaves the door open in case
+  // the arguments in the syntactic form for __builtin_dump_struct could
+  // possibly get parameter names.
+  return RecursiveASTVisitor::TraverseStmt(
+  E->getSyntacticForm());
+// FIXME: Shall we ignore semantic forms for other pseudo object

HighCommander4 wrote:

This is not a case where the **syntactic** form is a `CallExpr` (here the 
syntactic form is an `MSPropertySubscriptExpr`), so here the hints would be 
retained.

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-25 Thread Nathan Ridge via cfe-commits


@@ -1724,6 +1724,36 @@ TEST(InlayHints, RestrictRange) {
   ElementsAre(labelIs(": int"), labelIs(": char")));
 }
 
+TEST(ParameterHints, PseudoObjectExpr) {
+  Annotations Code(R"cpp(
+struct S {
+  __declspec(property(get=GetX, put=PutX)) int x[];
+  int GetX(int y, int z) { return 42 + y; }
+  // FIXME: Undesired hint `x = y: y`. This builds a PseudoObjectExpr too.
+  void PutX(int y) { x = $one[[y]]; }

HighCommander4 wrote:

While it may not be ill-formed, I think the fact that this causes an infinite 
recursion at runtime is a distraction for someone reading the test.

I would suggest instead something like:

```
void PutX(int y) {}

// FIXME: Undesired hint `x = y: y`. This builds a PseudoObjectExpr too.
void SomeOtherFunction(int y) { x = $one[[y]]; }
```

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


[clang-tools-extra] [clangd] Don't show inlay hints for __builtin_dump_struct (PR #71366)

2023-11-25 Thread Nathan Ridge via cfe-commits


@@ -1724,6 +1724,33 @@ TEST(InlayHints, RestrictRange) {
   ElementsAre(labelIs(": int"), labelIs(": char")));
 }
 
+TEST(ParameterHints, PseudoObjectExpr) {
+  Annotations Code(R"cpp(
+struct S {
+  __declspec(property(get=GetX, put=PutX)) int x[];
+  int GetX(int y, int z) { return 42 + y; }
+  void PutX(int y) { x = $one[[y]]; } // FIXME: Undesired `x = y: y` for 
this ill-formed expression.

HighCommander4 wrote:

I'm not sure what other bad cases there might be, but excluding cases where the 
syntactic form is a `BinaryOperator` to avoid this case sounds fine to me.

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


[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-25 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

I thought some more about this.

I appreciate better now the question you asked here:

> I realized that we had to tackle synthesized types e.g.
> > ```c++
> > template  typename C, typename D, int E>
> > void work() {
> >   C complicated_type;
> >   // ^ Shall we perform the type substitution once again? ;)
> > }
> > ```

My previous suggestion side-steps this by saying that we're only going to do 
lookups in the primary template scope of the argument for `C`, so we don't need 
to worry about substituting the arguments for `D` and `E`.

However, if in the future we want to be more accurate and e.g. handle cases 
where a template specialization resolves to something different than the 
primary template (e.g. a partial specialization), then your question becomes 
relevant: do we perform type substitution again with the arguments for `D` and 
`E`, or do we just fish out the already-substituted type from the "only 
instantiation"?

I realized that this consideration actually applies to any other "resolution" 
step performed in `HeuristicResolver`, including steps it already does today 
such as name lookup.

To illustrate, let's go back to the `vector` example:

```c++
template 
void work() {
  std::vector a;
  a.pop_back();
}
```

To resolve the dependent member expression `a.pop_back`, `HeuristicResolver` 
currently performs name lookup in the primary template scope of `std::vector` 
for the name `pop_back`.

The name lookup step could also be avoided in principle if we had an "only 
instantiation": if we find the non-dependent `MemberExpr` that `a.pop_back` 
instantiates to in the "only instantiation", that will point directly to a 
`CXXMethoDecl`, and we have our result without having done the work of a name 
lookup in the primary template scope.

And this method can lead to more accurate results, e.g. if instead of 
`pop_back` we have an overloaded method name, the name lookup in the primary 
template scope will just return all overloads (since we're not using 
information about the argument types), whereas the instantiated expression in 
the "only instantiation" will point to the correct overload resolution result.

---

So, I think we could consider two alternative approaches to this:

**Approach 1**: What I suggested in the previous review: a limited use of the 
"only instantiation" in `HeuristicResolver` to map template parameter types to 
the type of their argument in the "only instantiation".

**Approach 2**: If there is an "only instantiation", then resolve any 
expression, type, etc. in the template body to the corresponding expression, 
type, etc. in the "only instantiation".

The implementation of "Approach 2" could look similar to the current 
`InstantiatedDeclVisitor` in the patch, except the node type we are searching 
for is not limited to a Decl, it can also be other node types like Stmt etc.

"Approach 2" can be largely independent of `HeuristicResolver`: since we are 
finding a concrete result for the thing we're trying to resolve in the "only 
instantiation", no further resolution steps (e.g. name lookup, or anything else 
that `HeuristicResolver` does) should be necessary. However, the entry point to 
the check can be the same (e.g. for resolving a dependent member expr, we'd 
want to do the "only instantiation" check in the same cases where we call 
`HeuristicResolver::resolveMemberExpr()` from external code), so the 
functionality could still live in `HeuristicResolver` for organizational 
purposes.

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


[clang-tools-extra] [clangd] Improve BlockEnd inlay hints presentation (PR #72345)

2023-11-26 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

Thanks, the behaviour changes look reasonable to me.

> I haven't update the test because the hard-coded limit 10 makes it hard to 
> write the tests. Any opinion of how to structure this?

I would suggest running most tests with `HintMinLineLimit = 2` (and then have 
one test for the behaviour with `HintMinLineLimit = 10`).

To allow the tests to change `HintMinLineLimit`, we could give the 
`inlayHints()` function an optional parameter to specify it (could wrap it in 
an `InlayHintOptions` class for adding other options in the future).

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


[clang-tools-extra] [clangd] Improve BlockEnd inlay hints presentation (PR #72345)

2023-11-26 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 requested changes to this pull request.

(see previous comment)

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


[clang] [clang] Bounds checking on unclosed parentheses, brackets or braces in Expanded Tokens (PR #69849)

2023-11-26 Thread Nathan Ridge via cfe-commits


@@ -585,6 +585,17 @@ TEST_F(TokenCollectorTest, DelayedParsing) {
   EXPECT_THAT(collectAndDump(Code), StartsWith(ExpectedTokens));
 }
 
+TEST_F(TokenCollectorTest, UnclosedToken) {

HighCommander4 wrote:

I started looking at this to try and make some progress towards getting this 
landed. However, when running this test locally, I'm not seeing either of the 
branches added to `spelledForExpandedToken()` being taken.

Am I missing something, or is this test not exercising the intended codepath?

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


[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-27 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

Thinking some more about "Approach 2", I realized there is a challenge with it: 
given the node we are trying to resolve (for example, a dependent member expr) 
as a starting point, we need to find the enclosing template decl, so that we 
can query it for its "only instantiation".

The current patch does this by introspecting the starting node, and in a subset 
of cases (base expression is `MemberExpr` or `DeclRefExpr`) extracting a `Decl` 
from it, and then walking its `DeclContext` chain to find the template decl.

However, we would ideally like our "only instantiation" heuristic to work for 
any AST node inside a template (and so, for dependent member exprs, we would 
like it to work for any base expression type, not just specific ones).

In principle, it could be possible to extend the introspection approach to 
handle all expression types, since if an expression is dependent, it will 
ultimately reference a template parameter (or a Decl whose type references a 
template parameter, etc.) However, I feel like this may be a lot of work to 
implement and could be error-prone.

I wonder if we could do something easier: require that the caller pass in a 
`DeclContext*` which it knows to be enclosing the node we are trying to resolve 
(and then we can walk the chain from there to find the template).

Editor operations like go-to-def which involve taking an action at a cursor 
position use `SelectionTree` to "hit-test" the node under the cursor. 
`SelectionTree` exposes the chain of node that was hit (see e.g. 
`SelectionTree::print()` which prints the chain), so we can recover an 
enclosing `DeclContext*` from there; we'd just need to plumb the information 
through to `HeuristicResolver`.

In the future when we want to use `HeuristicResolver` for code completion, it 
can get the enclosing `DeclContext*` even more easily (`Sema::CurContext`).

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


[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-11-27 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> > I also discovered some complications related to nested templates [...]
> 
> Does my previous comment elaborate on the same issue you've encountered?

I believe so, yes.

> Could you kindly share your thoughts more?

Let's consider a nested template like this:

```c++
template 
struct Outer {
  template 
  void inner(U u) {
u.foo();
  }
}
```

I believe our heuristic needs to require two things:
  1. `Outer` has an "only instantiation", say `Outer`
  2. `Outer::inner` also has an "only instantiation", say 
`Outer::inner`

Now, suppose we have written an algorithm for "given a template `X`, and some 
AST node `N` inside the body of `X`, find the corresponding AST node inside an 
instantiation `X`.

Then, I think we can proceed as follows:

 1. Start with the expression `u.foo` in the uninstantiated template
 2. Get the enclosing template decl, it's `Outer::inner`
 3. (As you observed, `Outer::inner` has no "only instantiation", only 
`Outer::inner` does.)
 4. Walk the `DeclContext` chain further to see if there are any further 
enclosing templates. We find `Outer`
 5. Check `Outer` for an "only instantiation". It has one, `Outer`!
 6. Run our algorithm with `X = Outer`, `N = Outer::inner`, `C = A`. It 
finds `Outer::inner`
 7. Run our algorithm with `X = Outer::inner`, `N = u.foo`, `C = B`. It 
finds the concrete `MemberExpr` which `u.foo` instantiated to inside 
`Outer::inner`.

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


[clang] [clang] Bounds checking on unclosed parentheses, brackets or braces in Expanded Tokens (PR #69849)

2023-11-27 Thread Nathan Ridge via cfe-commits


@@ -585,6 +585,17 @@ TEST_F(TokenCollectorTest, DelayedParsing) {
   EXPECT_THAT(collectAndDump(Code), StartsWith(ExpectedTokens));
 }
 
+TEST_F(TokenCollectorTest, UnclosedToken) {

HighCommander4 wrote:

Indeed, it looks like `TokenBuffer::spelledForExpanded()` (which is the only 
call site of `spelledForExpandedToken()`)  is not called by anything currently 
in this test.

To exercise `spelledForExpanded()`, we will need to make an explicit call to 
it, the way a number of other tests in this file do.

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


[clang-tools-extra] [clangd] Carefully handle PseudoObjectExprs for inlay hints (PR #71366)

2023-12-02 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

LGTM, thank you!

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


[clang-tools-extra] [clangd] Carefully handle PseudoObjectExprs for inlay hints (PR #71366)

2023-12-02 Thread Nathan Ridge via cfe-commits

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


[clang] [clang] Bounds checking on unclosed parentheses, brackets or braces in Expanded Tokens (PR #69849)

2023-12-03 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

I spent a bit more time looking at this. I'd say I'm still quite far from 
having a complete understanding of this code, but two things occur to me:

 1. `TokenBuffer` operates at the level of the preprocessor. 
"spelledForExpanded" is basically an operation which takes as input a range of 
tokens in the preprocessed token stream ("expanded tokens"), and maps them back 
to a range of tokens in the un-preprocessed token stream ("spelled tokens").
* The preprocessor has no notion of matching or balancing braces. Braces 
only become relevant later, during parsing.
* So, I don't understand why an input token stream that contains unbalanced 
braces would pose a problem for the "spelledForExpanded" operation.
* I'm hesitant to approve a patch that adds an early exit to 
"spelledForExpanded" to prevent an out-of-bounds array access, without 
understanding in more detail **how** the out-of-bounds array access arises / 
how it's connected to the unbalanced braces. It's possible that the 
out-of-bounds access is indicative of a deeper logic error which we'd be 
covering up.
 2. Since we've observed the problem arise during the `dumpAST` operation 
(frame 10 of the stack trace 
[here](https://github.com/clangd/clangd/issues/1559#issue-1646293852)), it 
would be good to (also) add a test that exercises the `dumpAST` operation as a 
whole.
* We have such tests in 
[DumpASTTests.cpp](https://searchfox.org/llvm/source/clang-tools-extra/clangd/unittests/DumpASTTests.cpp).
* I think it would be preferable if the AST dump for an input with 
unbalanced braces, such as `int main() {`, was **not** empty. (I suspect the 
current patch may make it empty.) `clang -Xclang -ast-dump` manages to print 
AST nodes in this case, I think so should we.

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


[clang-tools-extra] [clangd] Avoid crash when summarizing pointer-to-member expr for block-end hint (PR #76492)

2023-12-27 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/76492

Fixes https://github.com/clangd/clangd/issues/1873

>From b60a2515bbfbfc79bc3b0bb81ef6fe1db13404bd Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Thu, 28 Dec 2023 02:47:04 -0500
Subject: [PATCH] [clangd] Avoid crash when summarizing pointer-to-member expr
 for block-end hint

Fixes https://github.com/clangd/clangd/issues/1873
---
 clang-tools-extra/clangd/InlayHints.cpp |  2 +-
 .../clangd/unittests/InlayHintTests.cpp | 13 +
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index 3da047f9542138..fd28b48b5a0b02 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -286,7 +286,7 @@ std::string summarizeExpr(const Expr *E) {
 // Step through implicit nodes that clang doesn't classify as such.
 std::string VisitCXXMemberCallExpr(const CXXMemberCallExpr *E) {
   // Call to operator bool() inside if (X): dispatch to X.
-  if (E->getNumArgs() == 0 &&
+  if (E->getNumArgs() == 0 && E->getMethodDecl() &&
   E->getMethodDecl()->getDeclName().getNameKind() ==
   DeclarationName::CXXConversionFunctionName &&
   E->getSourceRange() ==
diff --git a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp 
b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
index 20c1cdd985dbc0..ea5ee18f1da65c 100644
--- a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -2172,6 +2172,19 @@ TEST(BlockEndHints, Macro) {
   ExpectedHint{" // struct S1", "S1"});
 }
 
+TEST(BlockEndHints, PointerToMemberFunction) {
+  // Do not crash trying to summarize `a->*p`.
+  assertBlockEndHints(R"cpp(
+class A {};
+using Predicate = bool(A::*)();
+void foo(A* a, Predicate p) {
+  if ((a->*p)()) {
+  $ptrmem[[}]]
+} // suppress
+  )cpp",
+  ExpectedHint{" // if", "ptrmem"});
+}
+
 // FIXME: Low-hanging fruit where we could omit a type hint:
 //  - auto x = TypeName(...);
 //  - auto x = (TypeName) (...);

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


[clang-tools-extra] [clangd] Avoid crash when summarizing pointer-to-member expr for block-end hint (PR #76492)

2023-12-28 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/76492

>From ec31d400915dba372501c49db8bab7c8123228df Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Thu, 28 Dec 2023 02:47:04 -0500
Subject: [PATCH] [clangd] Avoid crash when summarizing pointer-to-member expr
 for block-end hint

For calls through a pointer to member, CXXMemberCallExpr::getCallee() is
a BinaryOperator with operator ->* (after unwrapping parens).

getMethodDecl() only returns non-null if the callee is a MemberExpr.

Fixes https://github.com/clangd/clangd/issues/1873
---
 clang-tools-extra/clangd/InlayHints.cpp |  2 +-
 .../clangd/unittests/InlayHintTests.cpp | 13 +
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index 3da047f9542138..fd28b48b5a0b02 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -286,7 +286,7 @@ std::string summarizeExpr(const Expr *E) {
 // Step through implicit nodes that clang doesn't classify as such.
 std::string VisitCXXMemberCallExpr(const CXXMemberCallExpr *E) {
   // Call to operator bool() inside if (X): dispatch to X.
-  if (E->getNumArgs() == 0 &&
+  if (E->getNumArgs() == 0 && E->getMethodDecl() &&
   E->getMethodDecl()->getDeclName().getNameKind() ==
   DeclarationName::CXXConversionFunctionName &&
   E->getSourceRange() ==
diff --git a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp 
b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
index 20c1cdd985dbc0..ea5ee18f1da65c 100644
--- a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -2172,6 +2172,19 @@ TEST(BlockEndHints, Macro) {
   ExpectedHint{" // struct S1", "S1"});
 }
 
+TEST(BlockEndHints, PointerToMemberFunction) {
+  // Do not crash trying to summarize `a->*p`.
+  assertBlockEndHints(R"cpp(
+class A {};
+using Predicate = bool(A::*)();
+void foo(A* a, Predicate p) {
+  if ((a->*p)()) {
+  $ptrmem[[}]]
+} // suppress
+  )cpp",
+  ExpectedHint{" // if", "ptrmem"});
+}
+
 // FIXME: Low-hanging fruit where we could omit a type hint:
 //  - auto x = TypeName(...);
 //  - auto x = (TypeName) (...);

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


[clang-tools-extra] [clangd] Avoid crash when summarizing pointer-to-member expr for block-end hint (PR #76492)

2023-12-28 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> btw, it looks like there is a FIXME 
> (https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/ExprCXX.cpp#L677)
>  for supporting this particular case.

I saw it, but I'm not clear on what that would look like.

Which member function a member function pointer resolves to is a runtime 
property of the pointer variable. I don't think we can produce a 
`CXXMethodDecl` there unless perhaps the pointer is a constant expression, 
which seems like an edge case.

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


[clang-tools-extra] [clangd] Avoid crash when summarizing pointer-to-member expr for block-end hint (PR #76492)

2023-12-28 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] don't lower severity of clang-tidy modernize-* checks to remarks (PR #75706)

2024-01-02 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> You mentioned `inconsistencies`, is it inside clangd or in other places that 
> surface clang-tidy findings?

I understood it as, the appearance of `modernize-*` clang-tidy diagnostics in 
the editor is not consistent with the appearance of other (non-`modernize-*`) 
clang-tidy diagnostics.

(I don't have a strong opinion on this change, just providing clarification.)

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


[clang-tools-extra] [clangd] Handle lambda scopes inside Node::getDeclContext() (PR #76329)

2024-01-07 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

Thanks, the change looks good to me!

I went through the existing callers of `Node::getDeclContext()`, and I was able 
to construct a test case where the patch actually changes behaviour (in a good 
way):

```c++
namespace NS {
void unrelated();
void foo();
}

auto L = [] {
  using NS::unrelated;
  NS::foo();
};
```

Here, if the "add using-declaration" code action is invoked on `NS::foo`, 
before this patch the result is:

```c++
namespace NS {
void unrelated();
void foo();
}

using NS::foo;

auto L = [] {
  using NS::unrelated;
  foo();
};
```

but after this patch the result is:

```c++
namespace NS {
void unrelated();
void foo();
}

auto L = [] {
  using NS::foo;
  using NS::unrelated;
  foo();
};
```

Let's add this test case to `AddUsingTests` while we're at it.

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


[clang-tools-extra] [clangd] Handle lambda scopes inside Node::getDeclContext() (PR #76329)

2024-01-07 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> Happy New Year 2024!

You too!

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


[clang-tools-extra] [clangd] Fix sysroot flag handling in CommandMangler to prevent duplicates (PR #75694)

2024-01-07 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

Thanks, LGTM!

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


[clang-tools-extra] [clangd] Fix is spelled in source bug (PR #76668)

2024-01-07 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 approved this pull request.

Thanks, looks good with the added comments.

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


  1   2   3   4   5   6   7   8   9   10   >