[PATCH] D40481: [libclang] Fix cursors for arguments of Subscript and Call operators

2018-08-23 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan accepted this revision.
yvvan added a comment.
This revision is now accepted and ready to land.

Let's proceed with this one. I really see that it's going to be useful.


https://reviews.llvm.org/D40481



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


[PATCH] D40481: [libclang] Fix cursors for arguments of Subscript and Call operators

2018-08-23 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL340521: [libclang] Fix cursors for arguments of Subscript 
and Call operators (authored by yvvan, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D40481?vs=124341&id=162145#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D40481

Files:
  cfe/trunk/test/Index/annotate-operator-call-expr.cpp
  cfe/trunk/tools/libclang/CIndex.cpp

Index: cfe/trunk/test/Index/annotate-operator-call-expr.cpp
===
--- cfe/trunk/test/Index/annotate-operator-call-expr.cpp
+++ cfe/trunk/test/Index/annotate-operator-call-expr.cpp
@@ -0,0 +1,84 @@
+struct Foo {
+  int operator[](int key);
+  int operator()(int key = 2);
+};
+
+void testFoo(Foo foo, int index) {
+  foo();
+  foo(index);
+
+  foo[index];
+  foo[index + index];
+
+  foo[foo[index]];
+  foo[foo() + foo[index]];
+  foo[foo(index) + foo[index]];
+}
+
+// RUN: c-index-test -test-annotate-tokens=%s:7:1:7:100 %s -std=c++11 -Wno-unused-value | FileCheck %s -check-prefix=CHECK1
+// CHECK1: Identifier: "foo" [7:3 - 7:6] DeclRefExpr=foo:6:18
+// CHECK1: Punctuation: "(" [7:6 - 7:7] DeclRefExpr=operator():3:7 RefName=[7:6 - 7:7] RefName=[7:7 - 7:8]
+// CHECK1: Punctuation: ")" [7:7 - 7:8] DeclRefExpr=operator():3:7 RefName=[7:6 - 7:7] RefName=[7:7 - 7:8]
+// CHECK1: Punctuation: ";" [7:8 - 7:9] CompoundStmt=
+
+// RUN: c-index-test -test-annotate-tokens=%s:8:1:8:100 %s -std=c++11 -Wno-unused-value | FileCheck %s -check-prefix=CHECK2
+// CHECK2: Punctuation: "(" [8:6 - 8:7] DeclRefExpr=operator():3:7 RefName=[8:6 - 8:7] RefName=[8:12 - 8:13]
+// CHECK2: Identifier: "index" [8:7 - 8:12] DeclRefExpr=index:6:27
+// CHECK2: Punctuation: ")" [8:12 - 8:13] DeclRefExpr=operator():3:7 RefName=[8:6 - 8:7] RefName=[8:12 - 8:13]
+// CHECK2: Punctuation: ";" [8:13 - 8:14] CompoundStmt=
+
+// RUN: c-index-test -test-annotate-tokens=%s:10:1:10:100 %s -std=c++11 -Wno-unused-value | FileCheck %s -check-prefix=CHECK3
+// CHECK3: Identifier: "foo" [10:3 - 10:6] DeclRefExpr=foo:6:18
+// CHECK3: Punctuation: "[" [10:6 - 10:7] DeclRefExpr=operator[]:2:7 RefName=[10:6 - 10:7] RefName=[10:12 - 10:13]
+// CHECK3: Identifier: "index" [10:7 - 10:12] DeclRefExpr=index:6:27
+// CHECK3: Punctuation: "]" [10:12 - 10:13] DeclRefExpr=operator[]:2:7 RefName=[10:6 - 10:7] RefName=[10:12 - 10:13]
+// CHECK3: Punctuation: ";" [10:13 - 10:14] CompoundStmt=
+
+// RUN: c-index-test -test-annotate-tokens=%s:11:1:11:100 %s -std=c++11 -Wno-unused-value | FileCheck %s -check-prefix=CHECK4
+// CHECK4: Identifier: "foo" [11:3 - 11:6] DeclRefExpr=foo:6:18
+// CHECK4: Punctuation: "[" [11:6 - 11:7] DeclRefExpr=operator[]:2:7 RefName=[11:6 - 11:7] RefName=[11:20 - 11:21]
+// CHECK4: Identifier: "index" [11:7 - 11:12] DeclRefExpr=index:6:27
+// CHECK4: Punctuation: "+" [11:13 - 11:14] BinaryOperator=
+// CHECK4: Identifier: "index" [11:15 - 11:20] DeclRefExpr=index:6:27
+// CHECK4: Punctuation: "]" [11:20 - 11:21] DeclRefExpr=operator[]:2:7 RefName=[11:6 - 11:7] RefName=[11:20 - 11:21]
+// CHECK4: Punctuation: ";" [11:21 - 11:22] CompoundStmt=
+
+// RUN: c-index-test -test-annotate-tokens=%s:13:1:13:100 %s -std=c++11 -Wno-unused-value | FileCheck %s -check-prefix=CHECK5
+// CHECK5: Identifier: "foo" [13:3 - 13:6] DeclRefExpr=foo:6:18
+// CHECK5: Punctuation: "[" [13:6 - 13:7] DeclRefExpr=operator[]:2:7 RefName=[13:6 - 13:7] RefName=[13:17 - 13:18]
+// CHECK5: Identifier: "foo" [13:7 - 13:10] DeclRefExpr=foo:6:18
+// CHECK5: Punctuation: "[" [13:10 - 13:11] DeclRefExpr=operator[]:2:7 RefName=[13:10 - 13:11] RefName=[13:16 - 13:17]
+// CHECK5: Identifier: "index" [13:11 - 13:16] DeclRefExpr=index:6:27
+// CHECK5: Punctuation: "]" [13:16 - 13:17] DeclRefExpr=operator[]:2:7 RefName=[13:10 - 13:11] RefName=[13:16 - 13:17]
+// CHECK5: Punctuation: "]" [13:17 - 13:18] DeclRefExpr=operator[]:2:7 RefName=[13:6 - 13:7] RefName=[13:17 - 13:18]
+// CHECK5: Punctuation: ";" [13:18 - 13:19] CompoundStmt=
+
+// RUN: c-index-test -test-annotate-tokens=%s:14:1:14:100 %s -std=c++11 -Wno-unused-value | FileCheck %s -check-prefix=CHECK6
+// CHECK6: Identifier: "foo" [14:3 - 14:6] DeclRefExpr=foo:6:18
+// CHECK6: Punctuation: "[" [14:6 - 14:7] DeclRefExpr=operator[]:2:7 RefName=[14:6 - 14:7] RefName=[14:25 - 14:26]
+// CHECK6: Identifier: "foo" [14:7 - 14:10] DeclRefExpr=foo:6:18
+// CHECK6: Punctuation: "(" [14:10 - 14:11] DeclRefExpr=operator():3:7 RefName=[14:10 - 14:11] RefName=[14:11 - 14:12]
+// CHECK6: Punctuation: ")" [14:11 - 14:12] DeclRefExpr=operator():3:7 RefName=[14:10 - 14:11] RefName=[14:11 - 14:12]
+// CHECK6: Punctuation: "+" [14:13 - 14:14] BinaryOperator=
+// CHECK6: Identifier: "foo" [14:15 - 14:18] DeclRefExpr=foo:6:18
+// CHECK6: Punctuation: "[" [14:18 - 14:19] DeclRefExpr=operator[]:2:7 RefName=[14:18 - 14:19] RefName=[14:24 - 14:25]
+// CHECK6: Identifier: "index" [14:19 - 14:24] DeclRefExpr=operator[]:2:7

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-09 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan marked 3 inline comments as done.
yvvan added a comment.

I have some failing tests... So I will update the diff a bit later (Friday most 
likely)




Comment at: include/clang/Sema/CodeCompleteConsumer.h:564
+
+  /// \brief For this completion result correction is required.
+  std::vector Corrections;

ilya-biryukov wrote:
> yvvan wrote:
> > yvvan wrote:
> > > ilya-biryukov wrote:
> > > > Adding some docs here would be useful. These fix-its could be 
> > > > interpreted too broadly at this point.
> > > > I suggest the following semantics and the comment:
> > > > 
> > > > ```
> > > > /// \brief FixIts that *must* be applied before inserting the text for 
> > > > the corresponding completion item.
> > > > /// Completion items with non-empty fixits will not be returned by 
> > > > default, they should be explicitly requested by setting 
> > > > CompletionOptions::IncludeCorrections.
> > > > /// For the editors to be able to compute position of the cursor for 
> > > > the completion item itself, the following conditions are guaranteed to 
> > > > hold for RemoveRange of the stored fixits:
> > > > ///  - Ranges in the fixits are guaranteed to never contain the 
> > > > completion point (or identifier under completion point, if any) inside 
> > > > them, except at the start or at the end of the range.
> > > > ///  - If a fixit range starts or ends with completion point (or starts 
> > > > or ends after the identifier under completion point), it will contain 
> > > > at least one character. It allows to unambiguously recompute completion 
> > > > point after applying the fixit.
> > > > /// The intuition is that provided fixits change code around the 
> > > > identifier we complete, but are not allowed to touch the identifier 
> > > > itself or the completion point.
> > > > /// One example of completion items with corrections are the ones 
> > > > replacing '.' with '->' and vice versa:
> > > > ///  std::unique_ptr> vec_ptr;
> > > > ///  vec_ptr.^  // completion returns an item 'push_back', 
> > > > replacing '.' with '->'
> > > > ///  vec_ptr->^ // completion returns an item 'release', replacing 
> > > > '->' with '.'let's put 
> > > > ```
> > > > 
> > > > Do those invariants sound reasonable? Could we add asserts that they 
> > > > hold when constructing the completion results?
> > > Thanks! I usually feel the lack of patience when writing descriptions :)
> > "Could we add asserts that they hold when constructing the completion 
> > results"
> > 
> > The current way of creating them actually assures that by default. And to 
> > check it once again it's required to change many things.
> > Starting with the fact that there is no SourceRange contains() methos or 
> > something similar,
> > The current way of creating them actually assures that by default. And to 
> > check it once again it's required to change many things.
> It's still nice to have a sanity check there, mostly for the sake of new 
> checks that are gonna get added.
> But even the current one is tricky, since it may actually contain a range 
> that ends exactly at the cursor (when completing right after the dot/arrow 
> `foo->|`).
> 
> > Starting with the fact that there is no SourceRange contains() methos or 
> > something similar,
> Moreover, `SourceRange` doesn't have clear semantics AFAIK. It can either be 
> a half-open or closed range.
> Let's add a FIXME, at least, that we should add those asserts later.
> 
It's removed from CodeCompletionString therefore it's now only above the public 
declaration.



Comment at: include/clang/Sema/CodeCompleteConsumer.h:592
+   StringRef ParentName, const char *BriefComment,
+   std::vector FixIts);
   ~CodeCompletionString() = default;

ilya-biryukov wrote:
> We can't store fixits in `CodeCompletionString`, it should not contain source 
> locatins, which are only valid for the lifetime of SourceManager.
> Note that CCS has a lifetime independent of both the SourceManager and the 
> AST.
> Storing them in CodeCompletionResult should be good enough for all our 
> use-cases.
To support that I had to make libclang calls even worse but whatever.



Comment at: include/clang/Sema/CodeCompleteConsumer.h:814
 
+  /// \brief FixIts that *must* be applied before inserting the text for the
+  /// corresponding completion item. Completion items with non-empty fixits 
will

ilya-biryukov wrote:
> We shouldn't duplicate such a large comment in too many places, it would be 
> impossible to keep it in sync.
> I would suggest only keeping it in `CodeCompletionResult` and add a reference 
> to it in other places.
> libclang is a bit tricky, though. It is distributed without other LLVM 
> headers, right?
I will keep the comment only here and in libclang


https://reviews.llvm.org/D41537



___
cfe-commits mailing list
cfe-commits

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-11 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 146289.
yvvan marked 3 inline comments as done.
yvvan added a comment.

Only keep small completion fixit-s in CodeCompletionResults.
Change libclang calls to overcome that and not use CXCompletionString


https://reviews.llvm.org/D41537

Files:
  include/clang-c/Index.h
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  include/clang/Sema/Sema.h
  lib/Frontend/ASTUnit.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/FixIt/fixit.cpp
  test/Index/complete-arrow-dot.cpp
  test/SemaCXX/member-expr.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -171,6 +171,8 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionNumFixIts
+clang_getCompletionFixIt
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -16,6 +16,7 @@
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
 #include "CXCursor.h"
+#include "CXSourceLocation.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
 #include "clang/AST/Decl.h"
@@ -302,10 +303,53 @@
   /// \brief A string containing the Objective-C selector entered thus far for a
   /// message send.
   std::string Selector;
+
+  /// \brief Vector of fix-its for each completion result that *must* be applied
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };
 
 } // end anonymous namespace
 
+unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
+  unsigned completion_index) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
+return 0;
+
+  return static_cast(allocated_results->FixItsVector[completion_index].size());
+}
+
+CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
+  unsigned completion_index,
+  unsigned fixit_index,
+  CXSourceRange *replacement_range) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  ArrayRef FixIts = allocated_results->FixItsVector[completion_index];
+  if (FixIts.size() <= fixit_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  const FixItHint &FixIt = FixIts[fixit_index];
+  if (replacement_range) {
+*replacement_range = cxloc::translateSourceRange(
+*allocated_results->SourceMgr, allocated_results->LangOpts,
+FixIt.RemoveRange);
+  }
+
+  return cxstring::createRef(FixIt.CodeToInsert.c_str());
+}
+
 /// \brief Tracks the number of code-completion result objects that are 
 /// currently active.
 ///
@@ -531,18 +575,22 @@
 CodeCompletionResult *Results,
 unsigned NumResults) override {
   StoredResults.reserve(StoredResults.size() + NumResults);
+  if (includeFixIts())
+AllocatedResults.FixItsVector.reserve(NumResults);
   for (unsigned I = 0; I != NumResults; ++I) {
-CodeCompletionString *StoredCompletion
+CodeCompletionString *StoredCompletion
   = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
   getCodeCompletionTUInfo(),
   includeBriefComments());
 
 CXCompletionResult R;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
+if (includeFixIts())
+  AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
   }
-  
+
   enum CodeCompletionContext::Kind contextKind = Context.getKind();
   
   AllocatedResults.ContextKind = contextKind;
@@ -644,13 +692,13 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeFixIts = options & CX

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

ping

I hope this review won't take forever :)


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

In https://reviews.llvm.org/D41537#1097763, @ilya-biryukov wrote:

> I should've suggested splitting the change into two earlier.


Next time I will do that from the beginning :)




Comment at: tools/libclang/CIndexCodeCompletion.cpp:309
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };

ilya-biryukov wrote:
> Storing `vector>` here makes looks like a hack. Even though it might 
> seem more tricky, I suggest storing an opaque pointer to `vector` 
> in each `CXCompletionResult`.  Managing the lifetime of vectors in the 
> `AllocatedCXCodeCompleteResults` seems totally fine, but there should be a 
> way to get to the fixits in a similar way we can get to the completion string.
> More concretely, I suggest the following API:
> ```
> // === Index.h
> typedef void* CXCompletionFixIts;
> typedef struct {
>// ...
>CXCompletionFixIts FixIts;
> };
> 
> // Get the number of fix-its.
> unsigned clang_getCompletionNumFixIts(CXCompletionResult *Result);
> // ... Similar to getDiagnosticFixIt
> CXString clang_getCompletionFixIt((CXCompletionResult *Result, unsigned 
> fixit_index, CXSourceRange *replacement_range);
> 
> 
> 
> // === Impl.cpp
> struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
> // .
> // Pool for allocating non-empty fixit vectors in the CXCompletionResult.
> std::vector> FixItsVector
> };
> 
> unsigned clang_getCompletionNumFixIts(CXCompletionResult *Result) {
>   auto* FixIts = static_cast*>(Result->FixIts);
>   if (!FixIts)
> return 0;
>   return FixIts->size();
> }
> ```
unsigned clang_getCompletionNumFixIts(CXCompletionResult *Result);

Do you mean appending CXCompletionResult struct with the "CXCompletionFixIts 
FixIts" member? Doesn't it break binary compatibility (changing the struct 
size)?


https://reviews.llvm.org/D41537



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


[PATCH] D46862: Optionally add code completion results for arrow instead of dot (libclang)

2018-05-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.
yvvan added reviewers: ilya-biryukov, klimek, bkramer, arphaman.

Follow up for https://reviews.llvm.org/D41537 - libclang part is extracted into 
this review


https://reviews.llvm.org/D46862

Files:
  include/clang-c/Index.h
  test/Index/complete-arrow-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -171,6 +171,8 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionNumFixIts
+clang_getCompletionFixIt
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -16,6 +16,7 @@
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
 #include "CXCursor.h"
+#include "CXSourceLocation.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
 #include "clang/AST/Decl.h"
@@ -302,10 +303,53 @@
   /// \brief A string containing the Objective-C selector entered thus far for a
   /// message send.
   std::string Selector;
+
+  /// \brief Vector of fix-its for each completion result that *must* be applied
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };
 
 } // end anonymous namespace
 
+unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
+  unsigned completion_index) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
+return 0;
+
+  return static_cast(allocated_results->FixItsVector[completion_index].size());
+}
+
+CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
+  unsigned completion_index,
+  unsigned fixit_index,
+  CXSourceRange *replacement_range) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  ArrayRef FixIts = allocated_results->FixItsVector[completion_index];
+  if (FixIts.size() <= fixit_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  const FixItHint &FixIt = FixIts[fixit_index];
+  if (replacement_range) {
+*replacement_range = cxloc::translateSourceRange(
+*allocated_results->SourceMgr, allocated_results->LangOpts,
+FixIt.RemoveRange);
+  }
+
+  return cxstring::createRef(FixIt.CodeToInsert.c_str());
+}
+
 /// \brief Tracks the number of code-completion result objects that are 
 /// currently active.
 ///
@@ -531,18 +575,22 @@
 CodeCompletionResult *Results,
 unsigned NumResults) override {
   StoredResults.reserve(StoredResults.size() + NumResults);
+  if (includeFixIts())
+AllocatedResults.FixItsVector.reserve(NumResults);
   for (unsigned I = 0; I != NumResults; ++I) {
-CodeCompletionString *StoredCompletion
+CodeCompletionString *StoredCompletion
   = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
   getCodeCompletionTUInfo(),
   includeBriefComments());
 
 CXCompletionResult R;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
+if (includeFixIts())
+  AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
   }
-  
+
   enum CodeCompletionContext::Kind contextKind = Context.getKind();
   
   AllocatedResults.ContextKind = contextKind;
@@ -644,13 +692,13 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeFixIts = options & CXCodeComplete_IncludeFixIts;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
 #endif
 #endif
-
   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
 
   if (cxtu::isNotUsableTU(TU)) {
@@ -691,6 +739,7 @@
   CodeCompleteO

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 146749.
yvvan marked 2 inline comments as done.
yvvan added a comment.

Only C++ part, libclang part has moved to https://reviews.llvm.org/D46862


https://reviews.llvm.org/D41537

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  include/clang/Sema/Sema.h
  lib/Frontend/ASTUnit.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/SemaCXX/member-expr.cpp

Index: test/SemaCXX/member-expr.cpp
===
--- test/SemaCXX/member-expr.cpp
+++ test/SemaCXX/member-expr.cpp
@@ -188,6 +188,11 @@
 return c->a;  // expected-error {{member reference type 'PR15045::Cl0' is not a pointer; did you mean to use '.'?}}
   }
 
+  int g() {
+Cl0* c;
+return c.a;  // expected-error {{member reference type 'PR15045::Cl0 *' is a pointer; did you mean to use '->'?}}
+  }
+
   struct bar {
 void func();  // expected-note {{'func' declared here}}
   };
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1291,19 +1291,22 @@
   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
 ResultBuilder &Results;
 DeclContext *CurContext;
+std::vector FixIts;
 
   public:
-CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
-  : Results(Results), CurContext(CurContext) { }
+CodeCompletionDeclConsumer(
+ResultBuilder &Results, DeclContext *CurContext,
+std::vector FixIts = std::vector())
+: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) {}
 
 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override {
   bool Accessible = true;
   if (Ctx)
 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
 
   ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
-   false, Accessible);
+   false, Accessible, FixIts);
   Results.AddResult(Result, CurContext, Hiding, InBaseClass);
 }
 
@@ -3947,14 +3950,15 @@
 static void AddRecordMembersCompletionResults(Sema &SemaRef,
   ResultBuilder &Results, Scope *S,
   QualType BaseType,
-  RecordDecl *RD) {
+  RecordDecl *RD,
+  std::vector &&FixIts) {
   // Indicate that we are performing a member access, and the cv-qualifiers
   // for the base object type.
   Results.setObjectTypeQualifiers(BaseType.getQualifiers());
 
   // Access to a C/C++ class, struct, or union.
   Results.allowNestedNameSpecifiers();
-  CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
+  CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext, std::move(FixIts));
   SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
  SemaRef.CodeCompleter->includeGlobals(),
  /*IncludeDependentBases=*/true,
@@ -3981,107 +3985,138 @@
 }
 
 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
+   Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement) {
   if (!Base || !CodeCompleter)
 return;
-  
+
   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
   if (ConvertedBase.isInvalid())
 return;
-  Base = ConvertedBase.get();
-  
-  QualType BaseType = Base->getType();
+  QualType ConvertedBaseType = ConvertedBase.get()->getType();
+
+  enum CodeCompletionContext::Kind contextKind;
 
   if (IsArrow) {
-if (const PointerType *Ptr = BaseType->getAs())
-  BaseType = Ptr->getPointeeType();
-else if (BaseType->isObjCObjectPointerType())
-  /*Do nothing*/ ;
-else
-  return;
+if (const PointerType *Ptr = ConvertedBaseType->getAs())
+  ConvertedBaseType = Ptr->getPointeeType();
   }
-  
-  enum CodeCompletionContext::Kind contextKind;
-  
+
   if (IsArrow) {
 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
-  }
-  else {
-if (BaseType->isObjCObjectPointerType() ||
-BaseType->isObjCObjectOrInterfaceType()) {
+  } else {
+if (ConvertedBaseType->isObjCObjectPointerType() ||
+ConvertedBaseType->isObjCObjectOrInterfaceType()) {
   contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
-}
-else {
+} else {
   contextKind = CodeCompletionContext::CCC_DotMemberAccess;
 }
   }
 
-  CodeCompletionContext CCContext(contextKind, BaseType);
+  CodeCompletionContext CCC

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:4118
+  : diag::err_typecheck_member_reference_suggestion;
+  Diag(OpLoc, DiagID) << ConvertedBaseType << IsArrow
+  << Base->getSourceRange() << FixIt;

ilya-biryukov wrote:
> Why do we need to report an extra diagnostic here in completion?
> Our completion items contain all the relevant information for actually doing 
> the change, and having different diagnostics in completion vs non-completion 
> modes does not seem like the right way to do things.
In current version of this patch it's not needed anymore. Removed.



Comment at: tools/libclang/CIndexCodeCompletion.cpp:309
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };

ilya-biryukov wrote:
> yvvan wrote:
> > ilya-biryukov wrote:
> > > Storing `vector>` here makes looks like a hack. Even though it 
> > > might seem more tricky, I suggest storing an opaque pointer to 
> > > `vector` in each `CXCompletionResult`.  Managing the lifetime 
> > > of vectors in the `AllocatedCXCodeCompleteResults` seems totally fine, 
> > > but there should be a way to get to the fixits in a similar way we can 
> > > get to the completion string.
> > > More concretely, I suggest the following API:
> > > ```
> > > // === Index.h
> > > typedef void* CXCompletionFixIts;
> > > typedef struct {
> > >// ...
> > >CXCompletionFixIts FixIts;
> > > };
> > > 
> > > // Get the number of fix-its.
> > > unsigned clang_getCompletionNumFixIts(CXCompletionResult *Result);
> > > // ... Similar to getDiagnosticFixIt
> > > CXString clang_getCompletionFixIt((CXCompletionResult *Result, unsigned 
> > > fixit_index, CXSourceRange *replacement_range);
> > > 
> > > 
> > > 
> > > // === Impl.cpp
> > > struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
> > > // .
> > > // Pool for allocating non-empty fixit vectors in the CXCompletionResult.
> > > std::vector> FixItsVector
> > > };
> > > 
> > > unsigned clang_getCompletionNumFixIts(CXCompletionResult *Result) {
> > >   auto* FixIts = static_cast*>(Result->FixIts);
> > >   if (!FixIts)
> > > return 0;
> > >   return FixIts->size();
> > > }
> > > ```
> > unsigned clang_getCompletionNumFixIts(CXCompletionResult *Result);
> > 
> > Do you mean appending CXCompletionResult struct with the 
> > "CXCompletionFixIts FixIts" member? Doesn't it break binary compatibility 
> > (changing the struct size)?
> Ah, you're right. If libclang promises binary compatibility with binaries 
> compiled from headers with previous versions, we're not allowed to do this 
> change.
> I'm not sure what's the best way to do that, probably the interface you 
> propose does what we want with the least amount of friction.
> I'd be fine with leaving as is, but given that `libclang` has a stable 
> interface, I'd get more opinions from someone who owns the code before adding 
> this. (Another reason to split this change into two?)
> 
> A possible alternative that won't break binary compatibility would be to 
> change the opaque `CXCompletionString` to point into a struct that has both 
> `CodeCompletionString` and the fixits vector, but that means finding all 
> use-sites of `CXCompletionString` and that might be tricky.
I already tried to have it in CXCompletionString. And I've even found and 
replaced all usages. But there's a bigger issue: CXCompletionString does not 
have dispose method and it exists not only in context of CXCompletionChunkKind 
(for example as a return value of clang_getCompletionChunkCompletionString). 
It's easy to add such dispose method but it will introduce leaks in already 
existing code bases.

By all that I mean that "the interface you propose does what we want with the 
least amount of friction".


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-15 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I will add more tests...




Comment at: test/SemaCXX/member-expr.cpp:193
+Cl0* c;
+return c.a;  // expected-error {{member reference type 'PR15045::Cl0 *' is 
a pointer; did you mean to use '->'?}}
+  }

ilya-biryukov wrote:
> Is this still needed after we removed the diagnostics code?
Yes, even if it does not fail it is not related to that change anymore


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 147039.
yvvan marked 4 inline comments as done.
yvvan added a comment.

Append PrintingCodeCompleteConsumer and CompilerInvocation options, add 
CodeCompletion tests.


https://reviews.llvm.org/D41537

Files:
  include/clang/Driver/CC1Options.td
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  include/clang/Sema/Sema.h
  lib/Frontend/ASTUnit.cpp
  lib/Frontend/CompilerInvocation.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/CodeCompleteConsumer.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/member-access.cpp

Index: test/CodeCompletion/member-access.cpp
===
--- test/CodeCompletion/member-access.cpp
+++ test/CodeCompletion/member-access.cpp
@@ -166,3 +166,47 @@
   typename Template::Nested m;
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:166:25 %s -o - | FileCheck -check-prefix=CHECK-CC7 %s
 }
+
+class Proxy2 {
+public:
+  Derived *operator->() const;
+  int member5;
+};
+
+void test2(const Proxy2 &p) {
+  p->
+}
+
+void test3(const Proxy2 &p) {
+  p.
+}
+
+// RUN: %clang_cc1 -fsyntax-only -code-completion-include-fixits -code-completion-at=%s:177:6 %s -o - | FileCheck -check-prefix=CHECK-CC8 --implicit-check-not="Derived : Derived(" %s
+// CHECK-CC8: Base1 : Base1::
+// CHECK-CC8: member1 : [#int#][#Base1::#]member1
+// CHECK-CC8: member1 : [#int#][#Base2::#]member1
+// CHECK-CC8: member2 : [#float#][#Base1::#]member2
+// CHECK-CC8: member3 : [#double#][#Base2::#]member3
+// CHECK-CC8: member4 : [#int#]member4
+// CHECK-CC8: member5 : [#int#]member5 (requires fix: "->" to ".")
+// CHECK-CC8: memfun1 : [#void#][#Base3::#]memfun1(<#float#>)
+// CHECK-CC8: memfun1 : [#void#][#Base3::#]memfun1(<#double#>)[# const#]
+// CHECK-CC8: memfun1 (Hidden) : [#void#]Base2::memfun1(<#int#>)
+// CHECK-CC8: memfun2 : [#void#][#Base3::#]memfun2(<#int#>)
+// CHECK-CC8: memfun3 : [#int#]memfun3(<#int#>)
+// CHECK-CC8: operator-> : [#Derived *#]operator->()[# const#] (requires fix: "->" to ".")
+
+// RUN: %clang_cc1 -fsyntax-only -code-completion-include-fixits -code-completion-at=%s:181:6 %s -o - | FileCheck -check-prefix=CHECK-CC9 --implicit-check-not="Derived : Derived(" %s
+// CHECK-CC9: Base1 : Base1::
+// CHECK-CC9: member1 : [#int#][#Base1::#]member1 (requires fix: "." to "->")
+// CHECK-CC9: member1 : [#int#][#Base2::#]member1 (requires fix: "." to "->")
+// CHECK-CC9: member2 : [#float#][#Base1::#]member2 (requires fix: "." to "->")
+// CHECK-CC9: member3 : [#double#][#Base2::#]member3 (requires fix: "." to "->")
+// CHECK-CC9: member4 : [#int#]member4 (requires fix: "." to "->")
+// CHECK-CC9: member5 : [#int#]member5
+// CHECK-CC9: memfun1 : [#void#][#Base3::#]memfun1(<#float#>) (requires fix: "." to "->")
+// CHECK-CC9: memfun1 : [#void#][#Base3::#]memfun1(<#double#>)[# const#] (requires fix: "." to "->")
+// CHECK-CC9: memfun1 (Hidden) : [#void#]Base2::memfun1(<#int#>) (requires fix: "." to "->")
+// CHECK-CC9: memfun2 : [#void#][#Base3::#]memfun2(<#int#>) (requires fix: "." to "->")
+// CHECK-CC9: memfun3 : [#int#]memfun3(<#int#>) (requires fix: "." to "->")
+// CHECK-CC9: operator-> : [#Derived *#]operator->()[# const#]
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1291,19 +1291,22 @@
   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
 ResultBuilder &Results;
 DeclContext *CurContext;
+std::vector FixIts;
 
   public:
-CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
-  : Results(Results), CurContext(CurContext) { }
+CodeCompletionDeclConsumer(
+ResultBuilder &Results, DeclContext *CurContext,
+std::vector FixIts = std::vector())
+: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) {}
 
 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override {
   bool Accessible = true;
   if (Ctx)
 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
 
   ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
-   false, Accessible);
+   false, Accessible, FixIts);
   Results.AddResult(Result, CurContext, Hiding, InBaseClass);
 }
 
@@ -3947,14 +3950,18 @@
 static void AddRecordMembersCompletionResults(Sema &SemaRef,
   ResultBuilder &Results, Scope *S,
   QualType BaseType,
-  RecordDecl *RD) {
+  RecordDecl *RD,
+  Optional AccessOpFixIt) {
   // Indicate that we are performing a member access, and the cv-qualifiers
   // for the base object type.

[PATCH] D46862: Optionally add code completion results for arrow instead of dot (libclang)

2018-05-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 147042.
yvvan added a comment.

The base revision has changed - some minor changes were also required here.


https://reviews.llvm.org/D46862

Files:
  include/clang-c/Index.h
  test/Index/complete-arrow-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -171,6 +171,8 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionNumFixIts
+clang_getCompletionFixIt
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -16,6 +16,7 @@
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
 #include "CXCursor.h"
+#include "CXSourceLocation.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
 #include "clang/AST/Decl.h"
@@ -302,10 +303,53 @@
   /// \brief A string containing the Objective-C selector entered thus far for a
   /// message send.
   std::string Selector;
+
+  /// \brief Vector of fix-its for each completion result that *must* be applied
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };
 
 } // end anonymous namespace
 
+unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
+  unsigned completion_index) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
+return 0;
+
+  return static_cast(allocated_results->FixItsVector[completion_index].size());
+}
+
+CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
+  unsigned completion_index,
+  unsigned fixit_index,
+  CXSourceRange *replacement_range) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  ArrayRef FixIts = allocated_results->FixItsVector[completion_index];
+  if (FixIts.size() <= fixit_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  const FixItHint &FixIt = FixIts[fixit_index];
+  if (replacement_range) {
+*replacement_range = cxloc::translateSourceRange(
+*allocated_results->SourceMgr, allocated_results->LangOpts,
+FixIt.RemoveRange);
+  }
+
+  return cxstring::createRef(FixIt.CodeToInsert.c_str());
+}
+
 /// \brief Tracks the number of code-completion result objects that are 
 /// currently active.
 ///
@@ -531,18 +575,22 @@
 CodeCompletionResult *Results,
 unsigned NumResults) override {
   StoredResults.reserve(StoredResults.size() + NumResults);
+  if (includeFixIts())
+AllocatedResults.FixItsVector.reserve(NumResults);
   for (unsigned I = 0; I != NumResults; ++I) {
-CodeCompletionString *StoredCompletion
+CodeCompletionString *StoredCompletion
   = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
   getCodeCompletionTUInfo(),
   includeBriefComments());
 
 CXCompletionResult R;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
+if (includeFixIts())
+  AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
   }
-  
+
   enum CodeCompletionContext::Kind contextKind = Context.getKind();
   
   AllocatedResults.ContextKind = contextKind;
@@ -644,13 +692,13 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeFixIts = options & CXCodeComplete_IncludeFixIts;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
 #endif
 #endif
-
   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
 
   if (cxtu::isNotUsableTU(TU)) {
@@ -691,6 +739,7 @@
   CodeCompleteOptions Opts;
   Opts.IncludeBriefComments = 

[PATCH] D46050: [Frontend] Avoid running plugins during code completion parse

2018-05-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL332469: [Frontend] Avoid running plugins during code 
completion parse (authored by yvvan, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D46050?vs=146999&id=147078#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D46050

Files:
  cfe/trunk/lib/Frontend/FrontendAction.cpp
  cfe/trunk/test/Index/complete-and-plugins.c


Index: cfe/trunk/test/Index/complete-and-plugins.c
===
--- cfe/trunk/test/Index/complete-and-plugins.c
+++ cfe/trunk/test/Index/complete-and-plugins.c
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load 
%llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck 
%s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
Index: cfe/trunk/lib/Frontend/FrontendAction.cpp
===
--- cfe/trunk/lib/Frontend/FrontendAction.cpp
+++ cfe/trunk/lib/Frontend/FrontendAction.cpp
@@ -150,12 +150,16 @@
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();


Index: cfe/trunk/test/Index/complete-and-plugins.c
===
--- cfe/trunk/test/Index/complete-and-plugins.c
+++ cfe/trunk/test/Index/complete-and-plugins.c
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load %llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck %s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
Index: cfe/trunk/lib/Frontend/FrontendAction.cpp
===
--- cfe/trunk/lib/Frontend/FrontendAction.cpp
+++ cfe/trunk/lib/Frontend/FrontendAction.cpp
@@ -150,12 +150,16 @@
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46050: [Frontend] Avoid running plugins during code completion parse

2018-05-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC332469: [Frontend] Avoid running plugins during code 
completion parse (authored by yvvan, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D46050?vs=146999&id=147077#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D46050

Files:
  lib/Frontend/FrontendAction.cpp
  test/Index/complete-and-plugins.c


Index: test/Index/complete-and-plugins.c
===
--- test/Index/complete-and-plugins.c
+++ test/Index/complete-and-plugins.c
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load 
%llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck 
%s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
Index: lib/Frontend/FrontendAction.cpp
===
--- lib/Frontend/FrontendAction.cpp
+++ lib/Frontend/FrontendAction.cpp
@@ -150,12 +150,16 @@
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();


Index: test/Index/complete-and-plugins.c
===
--- test/Index/complete-and-plugins.c
+++ test/Index/complete-and-plugins.c
@@ -0,0 +1,6 @@
+// RUN: c-index-test -code-completion-at=%s:7:1 -load %llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns %s | FileCheck %s
+// REQUIRES: plugins, examples
+// CHECK: macro definition:{{.*}}
+// CHECK-NOT: top-level-decl: "x"
+
+void x();
Index: lib/Frontend/FrontendAction.cpp
===
--- lib/Frontend/FrontendAction.cpp
+++ lib/Frontend/FrontendAction.cpp
@@ -150,12 +150,16 @@
 return nullptr;
 
   // If there are no registered plugins we don't need to wrap the consumer
-  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
-return Consumer;
-
-  // Collect the list of plugins that go before the main action (in Consumers)
-  // or after it (in AfterConsumers)
-  std::vector> Consumers;
+  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
+return Consumer;
+
+  // If this is a code completion run, avoid invoking the plugin consumers
+  if (CI.hasCodeCompletionConsumer())
+return Consumer;
+
+  // Collect the list of plugins that go before the main action (in Consumers)
+  // or after it (in AfterConsumers)
+  std::vector> Consumers;
   std::vector> AfterConsumers;
   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
 ie = FrontendPluginRegistry::end();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D45815: [libclang] Allow skipping function bodies in preamble only

2018-05-17 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC332578: [libclang] Allow skipping function bodies in 
preamble only (authored by yvvan, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D45815?vs=145648&id=147253#toc

Repository:
  rC Clang

https://reviews.llvm.org/D45815

Files:
  include/clang-c/Index.h
  include/clang/Frontend/ASTUnit.h
  lib/Frontend/ASTUnit.cpp
  test/Parser/skip-function-bodies.h
  test/Parser/skip-function-bodies.mm
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp

Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -1268,13 +1268,13 @@
 /// \returns If the precompiled preamble can be used, returns a newly-allocated
 /// buffer that should be used in place of the main file when doing so.
 /// Otherwise, returns a NULL pointer.
-std::unique_ptr
-ASTUnit::getMainBufferWithPrecompiledPreamble(
-std::shared_ptr PCHContainerOps,
-const CompilerInvocation &PreambleInvocationIn,
-IntrusiveRefCntPtr VFS, bool AllowRebuild,
-unsigned MaxLines) {
-  auto MainFilePath =
+std::unique_ptr
+ASTUnit::getMainBufferWithPrecompiledPreamble(
+std::shared_ptr PCHContainerOps,
+CompilerInvocation &PreambleInvocationIn,
+IntrusiveRefCntPtr VFS, bool AllowRebuild,
+unsigned MaxLines) {
+  auto MainFilePath =
   PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
   std::unique_ptr MainFileBuffer =
   getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
@@ -1335,15 +1335,24 @@
   &NewPreambleDiagsStandalone);
 
 // We did not previously compute a preamble, or it can't be reused anyway.
-SimpleTimer PreambleTimer(WantTiming);
-PreambleTimer.setOutput("Precompiling preamble");
-
-llvm::ErrorOr NewPreamble = PrecompiledPreamble::Build(
-PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
-PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
-if (NewPreamble) {
-  Preamble = std::move(*NewPreamble);
-  PreambleRebuildCounter = 1;
+SimpleTimer PreambleTimer(WantTiming);
+PreambleTimer.setOutput("Precompiling preamble");
+
+const bool PreviousSkipFunctionBodies =
+PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
+if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
+  PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
+
+llvm::ErrorOr NewPreamble = PrecompiledPreamble::Build(
+PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
+PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
+
+PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
+PreviousSkipFunctionBodies;
+
+if (NewPreamble) {
+  Preamble = std::move(*NewPreamble);
+  PreambleRebuildCounter = 1;
 } else {
   switch (static_cast(NewPreamble.getError().value())) {
   case BuildPreambleError::CouldntCreateTempFile:
@@ -1688,13 +1697,13 @@
 std::shared_ptr PCHContainerOps,
 IntrusiveRefCntPtr Diags, StringRef ResourceFilesPath,
 bool OnlyLocalDecls, bool CaptureDiagnostics,
-ArrayRef RemappedFiles, bool RemappedFilesKeepOriginalName,
-unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
-bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
-bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
-bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
-llvm::Optional ModuleFormat, std::unique_ptr *ErrAST,
-IntrusiveRefCntPtr VFS) {
+ArrayRef RemappedFiles, bool RemappedFilesKeepOriginalName,
+unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
+bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
+bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
+bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
+llvm::Optional ModuleFormat, std::unique_ptr *ErrAST,
+IntrusiveRefCntPtr VFS) {
   assert(Diags.get() && "no DiagnosticsEngine was provided");
 
   SmallVector StoredDiagnostics;
@@ -1721,13 +1730,14 @@
   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
   PPOpts.SingleFileParseMode = SingleFileParse;
 
-  // Override the resources path.
-  CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
-
-  CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
-
-  if (ModuleFormat)
-CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
+  // Override the resources path.
+  CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
+
+  CI->getFrontendOpts().SkipFunctionBodies =
+  SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
+
+  if (ModuleFormat)
+CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
 

[PATCH] D40481: [libclang] Fix cursors for arguments of Subscript and Call operators

2018-05-17 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Tests run fine but the solution feels like a workaround.

Nevertheless if we are sure that extending the subscript/call operator range 
does not work properly or breaks too many other things than it's probably fine 
to have this workaround.


https://reviews.llvm.org/D40481



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-22 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added inline comments.



Comment at: lib/Sema/CodeCompleteConsumer.cpp:559
+const char *Begin =
+SemaRef.SourceMgr.getCharacterData(FixIt.RemoveRange.getBegin());
+const char *End =

ilya-biryukov wrote:
> Unfortunately, that might not work for some ranges, see docs of 
> `CharSourceRange`:
> ```
> /// In the token range case, the
> /// size of the last token must be measured to determine the actual end of the
> /// range.
> ```
> 
> The `TextDiagnostic::emitParseableFixits` handles it, I suggest we do it 
> similarly:
> ```
> FixItHint*I = //;
> SourceLocation BLoc = I->RemoveRange.getBegin();
> SourceLocation ELoc = I->RemoveRange.getEnd();
> 
> std::pair BInfo = SM.getDecomposedLoc(BLoc);
> std::pair EInfo = SM.getDecomposedLoc(ELoc);
> 
> // Adjust for token ranges.
> if (I->RemoveRange.isTokenRange())
>   EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
> 
> // We specifically do not do word-wrapping or tab-expansion here,
> // because this is supposed to be easy to parse.
> PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
> if (PLoc.isInvalid())
>   break;
> 
> OS << "fix-it:\"";
> OS.write_escaped(PLoc.getFilename());
> OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
>   << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
>   << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
>   << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
>   << "}:\"";
> OS.write_escaped(I->CodeToInsert);
> OS << "\"\n";
> ```
yeah. sorry. it's always like that with source ranges. thanks for a hint



Comment at: lib/Sema/SemaCodeComplete.cpp:4109
+  if (CodeCompleter->includeFixIts()) {
+const SourceRange OpRange(OpLoc, OpLoc.getLocWithOffset(IsArrow ? 2 : 1));
+CompletionSucceded =

ilya-biryukov wrote:
> I'd use token ranges here to avoid assumptions about sizes of tokens, e.g. 
> `CreateReplacemen(CharSourceRange::getTokenRange(OpLoc, OpLoc), IsArrow ? '.' 
> : '->')`
> There are complicated cases like `\` that end of the line and macros and it's 
> definitely better to use an abstraction that hides those cases.
the problem is that I need the range, not just a location and I don't know 
how to extract it here. is there a way to get next token location here?


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-22 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:4109
+  if (CodeCompleter->includeFixIts()) {
+const SourceRange OpRange(OpLoc, OpLoc.getLocWithOffset(IsArrow ? 2 : 1));
+CompletionSucceded =

ilya-biryukov wrote:
> yvvan wrote:
> > ilya-biryukov wrote:
> > > I'd use token ranges here to avoid assumptions about sizes of tokens, 
> > > e.g. `CreateReplacemen(CharSourceRange::getTokenRange(OpLoc, OpLoc), 
> > > IsArrow ? '.' : '->')`
> > > There are complicated cases like `\` that end of the line and macros and 
> > > it's definitely better to use an abstraction that hides those cases.
> > the problem is that I need the range, not just a location and I don't 
> > know how to extract it here. is there a way to get next token location here?
> IIUC, using `CharSourceRange::getTokenRange(OpLoc, OpLoc)` will do what you 
> want.
> When `CharSourceRange` is a token range, the client code should measurements 
> the token length and the producing code would use the starting location of 
> the last token.
> Here are the relevant bits from the comment of the `CharSourceRange`:
> ```
> /// In the token range case, the
> /// size of the last token must be measured to determine the actual end of the
> /// range.
>  ```
ok, i will recheck that it does calculate the token range


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-23 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 148164.
yvvan marked 4 inline comments as done.

https://reviews.llvm.org/D41537

Files:
  include/clang/Driver/CC1Options.td
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  include/clang/Sema/Sema.h
  lib/Frontend/ASTUnit.cpp
  lib/Frontend/CompilerInvocation.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/CodeCompleteConsumer.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/member-access.cpp

Index: test/CodeCompletion/member-access.cpp
===
--- test/CodeCompletion/member-access.cpp
+++ test/CodeCompletion/member-access.cpp
@@ -166,3 +166,47 @@
   typename Template::Nested m;
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:166:25 %s -o - | FileCheck -check-prefix=CHECK-CC7 %s
 }
+
+class Proxy2 {
+public:
+  Derived *operator->() const;
+  int member5;
+};
+
+void test2(const Proxy2 &p) {
+  p->
+}
+
+void test3(const Proxy2 &p) {
+  p.
+}
+
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits -code-completion-at=%s:177:6 %s -o - | FileCheck -check-prefix=CHECK-CC8 --implicit-check-not="Derived : Derived(" %s
+// CHECK-CC8: Base1 : Base1::
+// CHECK-CC8: member1 : [#int#][#Base1::#]member1
+// CHECK-CC8: member1 : [#int#][#Base2::#]member1
+// CHECK-CC8: member2 : [#float#][#Base1::#]member2
+// CHECK-CC8: member3 : [#double#][#Base2::#]member3
+// CHECK-CC8: member4 : [#int#]member4
+// CHECK-CC8: member5 : [#int#]member5 (requires fix-it: {177:4-177:6} to ".")
+// CHECK-CC8: memfun1 : [#void#][#Base3::#]memfun1(<#float#>)
+// CHECK-CC8: memfun1 : [#void#][#Base3::#]memfun1(<#double#>)[# const#]
+// CHECK-CC8: memfun1 (Hidden) : [#void#]Base2::memfun1(<#int#>)
+// CHECK-CC8: memfun2 : [#void#][#Base3::#]memfun2(<#int#>)
+// CHECK-CC8: memfun3 : [#int#]memfun3(<#int#>)
+// CHECK-CC8: operator-> : [#Derived *#]operator->()[# const#] (requires fix-it: {177:4-177:6} to ".")
+
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits -code-completion-at=%s:181:6 %s -o - | FileCheck -check-prefix=CHECK-CC9 --implicit-check-not="Derived : Derived(" %s
+// CHECK-CC9: Base1 : Base1::
+// CHECK-CC9: member1 : [#int#][#Base1::#]member1 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member1 : [#int#][#Base2::#]member1 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member2 : [#float#][#Base1::#]member2 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member3 : [#double#][#Base2::#]member3 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member4 : [#int#]member4 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member5 : [#int#]member5
+// CHECK-CC9: memfun1 : [#void#][#Base3::#]memfun1(<#float#>) (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: memfun1 : [#void#][#Base3::#]memfun1(<#double#>)[# const#] (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: memfun1 (Hidden) : [#void#]Base2::memfun1(<#int#>) (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: memfun2 : [#void#][#Base3::#]memfun2(<#int#>) (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: memfun3 : [#int#]memfun3(<#int#>) (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: operator-> : [#Derived *#]operator->()[# const#]
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1291,19 +1291,22 @@
   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
 ResultBuilder &Results;
 DeclContext *CurContext;
+std::vector FixIts;
 
   public:
-CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
-  : Results(Results), CurContext(CurContext) { }
+CodeCompletionDeclConsumer(
+ResultBuilder &Results, DeclContext *CurContext,
+std::vector FixIts = std::vector())
+: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) {}
 
 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override {
   bool Accessible = true;
   if (Ctx)
 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
 
   ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
-   false, Accessible);
+   false, Accessible, FixIts);
   Results.AddResult(Result, CurContext, Hiding, InBaseClass);
 }
 
@@ -3979,14 +3982,18 @@
 static void AddRecordMembersCompletionResults(Sema &SemaRef,
   ResultBuilder &Results, Scope *S,
   QualType BaseType,
-  RecordDecl *RD) {
+  RecordDecl *RD,
+  Optional AccessOpFixIt) {
   // Indicate that we are performing a member access, and the cv-qualifiers
   /

[PATCH] D46862: [libclang] Optionally add code completion results for arrow instead of dot

2018-05-23 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 148177.
yvvan added a comment.

Output range of token being replaced instead of it's text

As a side-effect introduce a call to get a Token starting from specified 
location.


https://reviews.llvm.org/D46862

Files:
  include/clang-c/Index.h
  test/Index/complete-arrow-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -171,6 +171,8 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionNumFixIts
+clang_getCompletionFixIt
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
@@ -260,6 +262,7 @@
 clang_getSpellingLocation
 clang_getTUResourceUsageName
 clang_getTemplateCursorKind
+clang_getToken
 clang_getTokenExtent
 clang_getTokenKind
 clang_getTokenLocation
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -16,6 +16,7 @@
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
 #include "CXCursor.h"
+#include "CXSourceLocation.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
 #include "clang/AST/Decl.h"
@@ -302,10 +303,53 @@
   /// A string containing the Objective-C selector entered thus far for a
   /// message send.
   std::string Selector;
+
+  /// \brief Vector of fix-its for each completion result that *must* be applied
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };
 
 } // end anonymous namespace
 
+unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
+  unsigned completion_index) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
+return 0;
+
+  return static_cast(allocated_results->FixItsVector[completion_index].size());
+}
+
+CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
+  unsigned completion_index,
+  unsigned fixit_index,
+  CXSourceRange *replacement_range) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  ArrayRef FixIts = allocated_results->FixItsVector[completion_index];
+  if (FixIts.size() <= fixit_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  const FixItHint &FixIt = FixIts[fixit_index];
+  if (replacement_range) {
+*replacement_range = cxloc::translateSourceRange(
+*allocated_results->SourceMgr, allocated_results->LangOpts,
+FixIt.RemoveRange);
+  }
+
+  return cxstring::createRef(FixIt.CodeToInsert.c_str());
+}
+
 /// Tracks the number of code-completion result objects that are 
 /// currently active.
 ///
@@ -531,18 +575,22 @@
 CodeCompletionResult *Results,
 unsigned NumResults) override {
   StoredResults.reserve(StoredResults.size() + NumResults);
+  if (includeFixIts())
+AllocatedResults.FixItsVector.reserve(NumResults);
   for (unsigned I = 0; I != NumResults; ++I) {
-CodeCompletionString *StoredCompletion
+CodeCompletionString *StoredCompletion
   = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
   getCodeCompletionTUInfo(),
   includeBriefComments());
 
 CXCompletionResult R;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
+if (includeFixIts())
+  AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
   }
-  
+
   enum CodeCompletionContext::Kind contextKind = Context.getKind();
   
   AllocatedResults.ContextKind = contextKind;
@@ -644,13 +692,13 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeFixIts = options & CXCodeComplete_IncludeFixIts;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeR

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-24 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan marked 4 inline comments as done.
yvvan added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:4148
+
+  CompletionSucceded |= DoCompletion(Base, IsArrow, None);
+

ilya-biryukov wrote:
> NIT: maybe swap the two cases to do the non-fixit ones first? It is the most 
> common case, so it should probably go first.
The actual completion should be the last because of the "Completion context". 
I've put them in this order intentionally. I will add comment about that.


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-25 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan marked an inline comment as done.
yvvan added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:4148
+
+  CompletionSucceded |= DoCompletion(Base, IsArrow, None);
+

yvvan wrote:
> ilya-biryukov wrote:
> > NIT: maybe swap the two cases to do the non-fixit ones first? It is the 
> > most common case, so it should probably go first.
> The actual completion should be the last because of the "Completion context". 
> I've put them in this order intentionally. I will add comment about that.
I've rechecked this part - I can actually now move it without breaking anything


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-25 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 148553.
yvvan added a comment.

NIT-s addressed


https://reviews.llvm.org/D41537

Files:
  include/clang/Driver/CC1Options.td
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  include/clang/Sema/Sema.h
  lib/Frontend/ASTUnit.cpp
  lib/Frontend/CompilerInvocation.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/CodeCompleteConsumer.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/member-access.cpp

Index: test/CodeCompletion/member-access.cpp
===
--- test/CodeCompletion/member-access.cpp
+++ test/CodeCompletion/member-access.cpp
@@ -166,3 +166,47 @@
   typename Template::Nested m;
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:166:25 %s -o - | FileCheck -check-prefix=CHECK-CC7 %s
 }
+
+class Proxy2 {
+public:
+  Derived *operator->() const;
+  int member5;
+};
+
+void test2(const Proxy2 &p) {
+  p->
+}
+
+void test3(const Proxy2 &p) {
+  p.
+}
+
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits -code-completion-at=%s:177:6 %s -o - | FileCheck -check-prefix=CHECK-CC8 --implicit-check-not="Derived : Derived(" %s
+// CHECK-CC8: Base1 : Base1::
+// CHECK-CC8: member1 : [#int#][#Base1::#]member1
+// CHECK-CC8: member1 : [#int#][#Base2::#]member1
+// CHECK-CC8: member2 : [#float#][#Base1::#]member2
+// CHECK-CC8: member3 : [#double#][#Base2::#]member3
+// CHECK-CC8: member4 : [#int#]member4
+// CHECK-CC8: member5 : [#int#]member5 (requires fix-it: {177:4-177:6} to ".")
+// CHECK-CC8: memfun1 : [#void#][#Base3::#]memfun1(<#float#>)
+// CHECK-CC8: memfun1 : [#void#][#Base3::#]memfun1(<#double#>)[# const#]
+// CHECK-CC8: memfun1 (Hidden) : [#void#]Base2::memfun1(<#int#>)
+// CHECK-CC8: memfun2 : [#void#][#Base3::#]memfun2(<#int#>)
+// CHECK-CC8: memfun3 : [#int#]memfun3(<#int#>)
+// CHECK-CC8: operator-> : [#Derived *#]operator->()[# const#] (requires fix-it: {177:4-177:6} to ".")
+
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits -code-completion-at=%s:181:6 %s -o - | FileCheck -check-prefix=CHECK-CC9 --implicit-check-not="Derived : Derived(" %s
+// CHECK-CC9: Base1 : Base1::
+// CHECK-CC9: member1 : [#int#][#Base1::#]member1 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member1 : [#int#][#Base2::#]member1 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member2 : [#float#][#Base1::#]member2 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member3 : [#double#][#Base2::#]member3 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member4 : [#int#]member4 (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: member5 : [#int#]member5
+// CHECK-CC9: memfun1 : [#void#][#Base3::#]memfun1(<#float#>) (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: memfun1 : [#void#][#Base3::#]memfun1(<#double#>)[# const#] (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: memfun1 (Hidden) : [#void#]Base2::memfun1(<#int#>) (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: memfun2 : [#void#][#Base3::#]memfun2(<#int#>) (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: memfun3 : [#int#]memfun3(<#int#>) (requires fix-it: {181:4-181:5} to "->")
+// CHECK-CC9: operator-> : [#Derived *#]operator->()[# const#]
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1291,19 +1291,22 @@
   class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
 ResultBuilder &Results;
 DeclContext *CurContext;
+std::vector FixIts;
 
   public:
-CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
-  : Results(Results), CurContext(CurContext) { }
+CodeCompletionDeclConsumer(
+ResultBuilder &Results, DeclContext *CurContext,
+std::vector FixIts = std::vector())
+: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) {}
 
 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override {
   bool Accessible = true;
   if (Ctx)
 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
 
   ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
-   false, Accessible);
+   false, Accessible, FixIts);
   Results.AddResult(Result, CurContext, Hiding, InBaseClass);
 }
 
@@ -3979,14 +3982,18 @@
 static void AddRecordMembersCompletionResults(Sema &SemaRef,
   ResultBuilder &Results, Scope *S,
   QualType BaseType,
-  RecordDecl *RD) {
+  RecordDecl *RD,
+  Optional AccessOpFixIt) {
   // Indicate that we are performing a member access, and the cv-qualifiers
   

[PATCH] D46862: [libclang] Optionally add code completion results for arrow instead of dot

2018-05-25 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 148559.
yvvan added a comment.

Update according to c++ part changes


https://reviews.llvm.org/D46862

Files:
  include/clang-c/Index.h
  test/Index/complete-arrow-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -171,6 +171,8 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionNumFixIts
+clang_getCompletionFixIt
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
@@ -260,6 +262,7 @@
 clang_getSpellingLocation
 clang_getTUResourceUsageName
 clang_getTemplateCursorKind
+clang_getToken
 clang_getTokenExtent
 clang_getTokenKind
 clang_getTokenLocation
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -16,6 +16,7 @@
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
 #include "CXCursor.h"
+#include "CXSourceLocation.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
 #include "clang/AST/Decl.h"
@@ -302,10 +303,53 @@
   /// A string containing the Objective-C selector entered thus far for a
   /// message send.
   std::string Selector;
+
+  /// Vector of fix-its for each completion result that *must* be applied
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };
 
 } // end anonymous namespace
 
+unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
+  unsigned completion_index) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
+return 0;
+
+  return static_cast(allocated_results->FixItsVector[completion_index].size());
+}
+
+CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
+  unsigned completion_index,
+  unsigned fixit_index,
+  CXSourceRange *replacement_range) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  ArrayRef FixIts = allocated_results->FixItsVector[completion_index];
+  if (FixIts.size() <= fixit_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  const FixItHint &FixIt = FixIts[fixit_index];
+  if (replacement_range) {
+*replacement_range = cxloc::translateSourceRange(
+*allocated_results->SourceMgr, allocated_results->LangOpts,
+FixIt.RemoveRange);
+  }
+
+  return cxstring::createRef(FixIt.CodeToInsert.c_str());
+}
+
 /// Tracks the number of code-completion result objects that are 
 /// currently active.
 ///
@@ -531,18 +575,22 @@
 CodeCompletionResult *Results,
 unsigned NumResults) override {
   StoredResults.reserve(StoredResults.size() + NumResults);
+  if (includeFixIts())
+AllocatedResults.FixItsVector.reserve(NumResults);
   for (unsigned I = 0; I != NumResults; ++I) {
-CodeCompletionString *StoredCompletion
+CodeCompletionString *StoredCompletion
   = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
   getCodeCompletionTUInfo(),
   includeBriefComments());
 
 CXCompletionResult R;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
+if (includeFixIts())
+  AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
   }
-  
+
   enum CodeCompletionContext::Kind contextKind = Context.getKind();
   
   AllocatedResults.ContextKind = contextKind;
@@ -644,13 +692,13 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeFixIts = options & CXCodeComplete_IncludeFixIts;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
 #endif
 #endif
-
   bool EnableLogging = getenv("LIBCLAN

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-05-25 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL333272: Optionally add code completion results for arrow 
instead of dot (authored by yvvan, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D41537?vs=148553&id=148591#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D41537

Files:
  cfe/trunk/include/clang/Driver/CC1Options.td
  cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
  cfe/trunk/include/clang/Sema/CodeCompleteOptions.h
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/lib/Frontend/ASTUnit.cpp
  cfe/trunk/lib/Frontend/CompilerInvocation.cpp
  cfe/trunk/lib/Parse/ParseExpr.cpp
  cfe/trunk/lib/Sema/CodeCompleteConsumer.cpp
  cfe/trunk/lib/Sema/SemaCodeComplete.cpp
  cfe/trunk/test/CodeCompletion/member-access.cpp

Index: cfe/trunk/include/clang/Driver/CC1Options.td
===
--- cfe/trunk/include/clang/Driver/CC1Options.td
+++ cfe/trunk/include/clang/Driver/CC1Options.td
@@ -445,6 +445,8 @@
   HelpText<"Do not include declarations inside namespaces (incl. global namespace) in the code-completion results.">;
 def code_completion_brief_comments : Flag<["-"], "code-completion-brief-comments">,
   HelpText<"Include brief documentation comments in code-completion results.">;
+def code_completion_with_fixits : Flag<["-"], "code-completion-with-fixits">,
+  HelpText<"Include code completion results which require small fix-its.">;
 def disable_free : Flag<["-"], "disable-free">,
   HelpText<"Disable freeing of memory on exit">;
 def discard_value_names : Flag<["-"], "discard-value-names">,
Index: cfe/trunk/include/clang/Sema/Sema.h
===
--- cfe/trunk/include/clang/Sema/Sema.h
+++ cfe/trunk/include/clang/Sema/Sema.h
@@ -10231,7 +10231,7 @@
   struct CodeCompleteExpressionData;
   void CodeCompleteExpression(Scope *S,
   const CodeCompleteExpressionData &Data);
-  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
+  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement);
   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
Index: cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
===
--- cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
+++ cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
@@ -783,6 +783,33 @@
   /// The availability of this result.
   CXAvailabilityKind Availability = CXAvailability_Available;
 
+  /// FixIts that *must* be applied before inserting the text for the
+  /// corresponding completion item.
+  ///
+  /// Completion items with non-empty fixits will not be returned by default,
+  /// they should be explicitly requested by setting
+  /// CompletionOptions::IncludeFixIts. For the editors to be able to
+  /// compute position of the cursor for the completion item itself, the
+  /// following conditions are guaranteed to hold for RemoveRange of the stored
+  /// fixits:
+  ///  - Ranges in the fixits are guaranteed to never contain the completion
+  ///  point (or identifier under completion point, if any) inside them, except
+  ///  at the start or at the end of the range.
+  ///  - If a fixit range starts or ends with completion point (or starts or
+  ///  ends after the identifier under completion point), it will contain at
+  ///  least one character. It allows to unambiguously recompute completion
+  ///  point after applying the fixit.
+  /// The intuition is that provided fixits change code around the identifier we
+  /// complete, but are not allowed to touch the identifier itself or the
+  /// completion point. One example of completion items with corrections are the
+  /// ones replacing '.' with '->' and vice versa:
+  /// std::unique_ptr> vec_ptr;
+  /// In 'vec_ptr.^', one of completion items is 'push_back', it requires
+  /// replacing '.' with '->'.
+  /// In 'vec_ptr->^', one of completion items is 'release', it requires
+  /// replacing '->' with '.'.
+  std::vector FixIts;
+
   /// Whether this result is hidden by another name.
   bool Hidden : 1;
 
@@ -807,15 +834,17 @@
   NestedNameSpecifier *Qualifier = nullptr;
 
   /// Build a result that refers to a declaration.
-  CodeCompletionResult(const NamedDecl *Declaration,
-   unsigned Priority,
+  CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority,
NestedNameSpecifier *Qualifier = nullptr,
bool QualifierIsInformative = false,
-   bool Accessible = true)
+   bool Accessible = true,
+   std::vector FixIts = std::vector())
   : Declaration(Declaration), Priority(Priori

[PATCH] D47460: Treat files as volatile by default

2018-05-29 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.
yvvan added reviewers: ilya-biryukov, nik, klimek, bkramer.

Prevent accidental memory mapping for main file which sometimes happens through 
FileSystem::getBufferForFile


https://reviews.llvm.org/D47460

Files:
  include/clang/Basic/VirtualFileSystem.h


Index: include/clang/Basic/VirtualFileSystem.h
===
--- include/clang/Basic/VirtualFileSystem.h
+++ include/clang/Basic/VirtualFileSystem.h
@@ -234,7 +234,7 @@
   /// closes the file.
   llvm::ErrorOr>
   getBufferForFile(const Twine &Name, int64_t FileSize = -1,
-   bool RequiresNullTerminator = true, bool IsVolatile = 
false);
+   bool RequiresNullTerminator = true, bool IsVolatile = true);
 
   /// Get a directory_iterator for \p Dir.
   /// \note The 'end' iterator is directory_iterator().


Index: include/clang/Basic/VirtualFileSystem.h
===
--- include/clang/Basic/VirtualFileSystem.h
+++ include/clang/Basic/VirtualFileSystem.h
@@ -234,7 +234,7 @@
   /// closes the file.
   llvm::ErrorOr>
   getBufferForFile(const Twine &Name, int64_t FileSize = -1,
-   bool RequiresNullTerminator = true, bool IsVolatile = false);
+   bool RequiresNullTerminator = true, bool IsVolatile = true);
 
   /// Get a directory_iterator for \p Dir.
   /// \note The 'end' iterator is directory_iterator().
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D47460: Treat files as volatile by default

2018-05-29 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

The precise path which leads here is yet unclear for me (it requires much more 
time to research) but changing this specific default value to true fixes main 
file from being memory mapped and therefore being blocked (on Windows)
I assume it comes from FileManager::getBufferForFile(StringRef Filename) but 
not sure about prior events causing it.

Usually the wrong behavior can be encountered via reparsing the file.


https://reviews.llvm.org/D47460



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


[PATCH] D46862: [libclang] Optionally add code completion results for arrow instead of dot

2018-05-29 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 149049.
yvvan marked 6 inline comments as done.
yvvan added a comment.

Address review comments


https://reviews.llvm.org/D46862

Files:
  include/clang-c/Index.h
  include/clang/Sema/CodeCompleteConsumer.h
  test/Index/complete-arrow-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -171,6 +171,8 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionNumFixIts
+clang_getCompletionFixIt
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
@@ -260,6 +262,7 @@
 clang_getSpellingLocation
 clang_getTUResourceUsageName
 clang_getTemplateCursorKind
+clang_getToken
 clang_getTokenExtent
 clang_getTokenKind
 clang_getTokenLocation
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -16,6 +16,7 @@
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
 #include "CXCursor.h"
+#include "CXSourceLocation.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
 #include "clang/AST/Decl.h"
@@ -302,10 +303,53 @@
   /// A string containing the Objective-C selector entered thus far for a
   /// message send.
   std::string Selector;
+
+  /// Vector of fix-its for each completion result that *must* be applied
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };
 
 } // end anonymous namespace
 
+unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
+  unsigned completion_index) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
+return 0;
+
+  return static_cast(allocated_results->FixItsVector[completion_index].size());
+}
+
+CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
+  unsigned completion_index,
+  unsigned fixit_index,
+  CXSourceRange *replacement_range) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  ArrayRef FixIts = allocated_results->FixItsVector[completion_index];
+  if (FixIts.size() <= fixit_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  const FixItHint &FixIt = FixIts[fixit_index];
+  if (replacement_range) {
+*replacement_range = cxloc::translateSourceRange(
+*allocated_results->SourceMgr, allocated_results->LangOpts,
+FixIt.RemoveRange);
+  }
+
+  return cxstring::createRef(FixIt.CodeToInsert.c_str());
+}
+
 /// Tracks the number of code-completion result objects that are 
 /// currently active.
 ///
@@ -531,18 +575,22 @@
 CodeCompletionResult *Results,
 unsigned NumResults) override {
   StoredResults.reserve(StoredResults.size() + NumResults);
+  if (includeFixIts())
+AllocatedResults.FixItsVector.reserve(NumResults);
   for (unsigned I = 0; I != NumResults; ++I) {
-CodeCompletionString *StoredCompletion
+CodeCompletionString *StoredCompletion
   = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
   getCodeCompletionTUInfo(),
   includeBriefComments());
 
 CXCompletionResult R;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
+if (includeFixIts())
+  AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
   }
-  
+
   enum CodeCompletionContext::Kind contextKind = Context.getKind();
   
   AllocatedResults.ContextKind = contextKind;
@@ -644,13 +692,13 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeFixIts = options & CXCodeComplete_IncludeFixIts;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getC

[PATCH] D46862: [libclang] Optionally add code completion results for arrow instead of dot

2018-05-29 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added inline comments.



Comment at: include/clang-c/Index.h:5264
+ * FixIts that *must* be applied before inserting the text for the
+ * corresponding completion item.
+ *

nik wrote:
> * Please use proper documentation style, e.g. make use of "\brief", "\param", 
> "\returns". Currently one has to somewhat guess that the returned string is 
> related to the replacement_range parameter.
> 
> * Is this a behavior change now? What happens to old code not aware of this 
> function?
'\brief' is not used anymore.

> Is this a behavior change now?

No, without CXCodeComplete_IncludeFixIts set you won't event have extra 
completions. And existing ones won't get any fix-its (because why would they?)



Comment at: include/clang-c/Index.h:5269
+ * the editors to be able to compute position of the cursor for the completion
+ * item itself, the following conditions are guaranteed to hold for RemoveRange
+ * of the stored fixits:

nik wrote:
> Do you mean replacement_range instead of RemoveRange?
Yes, it's repalcement_range here



Comment at: include/clang-c/Index.h:5284
+ *  vec_ptr.^  // completion returns an item 'push_back', replacing '.'
+ *  with '->' vec_ptr->^ // completion returns an item 'release',
+ *  replacing '->' with '.'

nik wrote:
> The vec_ptr-> example should go to its own line.
I've fixed it the same way it's done in CodeCompleteConsumer.h



Comment at: include/clang-c/Index.h:5326
+   * Whether to include completion items with small
+   * fix-its, e.g. change '.' to '->' on member access, etc.
+   */

nik wrote:
> Currently there is not more, so I would avoid the "etc.".
It might change without Index.h being updated.


https://reviews.llvm.org/D46862



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


[PATCH] D36390: Fix overloaded static functions in SemaCodeComplete

2017-09-28 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

ping 3


https://reviews.llvm.org/D36390



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


[PATCH] D38618: Do not add a colon chunk to the code completion of class inheritance access modifiers

2017-10-06 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.

With enabled CINDEXTEST_CODE_COMPLETE_PATTERNS env option (which enables 
IncludeCodePatterns in completion options) code completion after colon 
currently suggests access modifiers with 2 completion chunks which is incorrect.

Example:
class A : B
{
}

Currently we get 'NotImplemented:{TypedText public}{Colon :} (40)'
but the correct line is just 'NotImplemented:{TypedText public} (40)'

The fix introduces more specific scope that occurs between ':' and '{'
It allows us to determine when we don't need to add ':' as a second chunk to 
the public/protected/private access modifiers.


https://reviews.llvm.org/D38618

Files:
  include/clang/Sema/Scope.h
  lib/Parse/ParseDeclCXX.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/Index/complete-super.cpp


Index: test/Index/complete-super.cpp
===
--- test/Index/complete-super.cpp
+++ test/Index/complete-super.cpp
@@ -40,3 +40,8 @@
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText private}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText protected}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText public}{Colon :} (40)
+
+// RUN: env CINDEXTEST_CODE_COMPLETE_PATTERNS=1 c-index-test 
-code-completion-at=%s:10:12 %s | FileCheck 
-check-prefix=CHECK-INHERITANCE-PATTERN %s
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText private} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText protected} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText public} (40)
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1647,21 +1647,22 @@
   if (CCC == Sema::PCC_Class) {
 AddTypedefResult(Results);
 
+bool IsNotInheritanceScope = !(S->getFlags() & 
Scope::ClassInheritanceScope);
 // public:
 Builder.AddTypedTextChunk("public");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
 
 // protected:
 Builder.AddTypedTextChunk("protected");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
 
 // private:
 Builder.AddTypedTextChunk("private");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
   }
Index: lib/Parse/ParseDeclCXX.cpp
===
--- lib/Parse/ParseDeclCXX.cpp
+++ lib/Parse/ParseDeclCXX.cpp
@@ -3193,6 +3193,8 @@
   }
 
   if (Tok.is(tok::colon)) {
+ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope | 
Scope::ClassInheritanceScope);
+
 ParseBaseClause(TagDecl);
 if (!Tok.is(tok::l_brace)) {
   bool SuggestFixIt = false;
Index: include/clang/Sema/Scope.h
===
--- include/clang/Sema/Scope.h
+++ include/clang/Sema/Scope.h
@@ -124,6 +124,9 @@
 
 /// We are currently in the filter expression of an SEH except block.
 SEHFilterScope = 0x20,
+
+/// We are between inheritance colon and the real class/struct definition 
scope
+ClassInheritanceScope = 0x40,
   };
 private:
   /// The parent scope for this scope.  This is null for the translation-unit


Index: test/Index/complete-super.cpp
===
--- test/Index/complete-super.cpp
+++ test/Index/complete-super.cpp
@@ -40,3 +40,8 @@
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText private}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText protected}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText public}{Colon :} (40)
+
+// RUN: env CINDEXTEST_CODE_COMPLETE_PATTERNS=1 c-index-test -code-completion-at=%s:10:12 %s | FileCheck -check-prefix=CHECK-INHERITANCE-PATTERN %s
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText private} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText protected} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText public} (40)
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1647,21 +1647,22 @@
   if (CCC == Sema::PCC_Class) {
 AddTypedefResult(Results);
 
+bool IsNotInheritanceScope = !(S->getFlags() & Scope::ClassInheritanceScope);
 // public:
 Builder.AddTypedTextChunk("public");
-  

[PATCH] D38618: Do not add a colon chunk to the code completion of class inheritance access modifiers

2017-10-06 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 117988.
yvvan added a comment.

Fix according to the review comment


https://reviews.llvm.org/D38618

Files:
  include/clang/Sema/Scope.h
  lib/Parse/ParseDeclCXX.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/Index/complete-super.cpp


Index: test/Index/complete-super.cpp
===
--- test/Index/complete-super.cpp
+++ test/Index/complete-super.cpp
@@ -40,3 +40,8 @@
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText private}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText protected}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText public}{Colon :} (40)
+
+// RUN: env CINDEXTEST_CODE_COMPLETE_PATTERNS=1 c-index-test 
-code-completion-at=%s:10:12 %s | FileCheck 
-check-prefix=CHECK-INHERITANCE-PATTERN %s
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText private} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText protected} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText public} (40)
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1647,21 +1647,22 @@
   if (CCC == Sema::PCC_Class) {
 AddTypedefResult(Results);
 
+bool IsNotInheritanceScope = !(S->getFlags() & 
Scope::ClassInheritanceScope);
 // public:
 Builder.AddTypedTextChunk("public");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
 
 // protected:
 Builder.AddTypedTextChunk("protected");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
 
 // private:
 Builder.AddTypedTextChunk("private");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
   }
Index: lib/Parse/ParseDeclCXX.cpp
===
--- lib/Parse/ParseDeclCXX.cpp
+++ lib/Parse/ParseDeclCXX.cpp
@@ -3193,6 +3193,9 @@
   }
 
   if (Tok.is(tok::colon)) {
+ParseScope InheritanceScope(this, Scope::ClassScope | Scope::DeclScope |
+  Scope::ClassInheritanceScope);
+
 ParseBaseClause(TagDecl);
 if (!Tok.is(tok::l_brace)) {
   bool SuggestFixIt = false;
Index: include/clang/Sema/Scope.h
===
--- include/clang/Sema/Scope.h
+++ include/clang/Sema/Scope.h
@@ -124,6 +124,9 @@
 
 /// We are currently in the filter expression of an SEH except block.
 SEHFilterScope = 0x20,
+
+/// We are between inheritance colon and the real class/struct definition 
scope
+ClassInheritanceScope = 0x40,
   };
 private:
   /// The parent scope for this scope.  This is null for the translation-unit


Index: test/Index/complete-super.cpp
===
--- test/Index/complete-super.cpp
+++ test/Index/complete-super.cpp
@@ -40,3 +40,8 @@
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText private}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText protected}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText public}{Colon :} (40)
+
+// RUN: env CINDEXTEST_CODE_COMPLETE_PATTERNS=1 c-index-test -code-completion-at=%s:10:12 %s | FileCheck -check-prefix=CHECK-INHERITANCE-PATTERN %s
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText private} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText protected} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText public} (40)
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1647,21 +1647,22 @@
   if (CCC == Sema::PCC_Class) {
 AddTypedefResult(Results);
 
+bool IsNotInheritanceScope = !(S->getFlags() & Scope::ClassInheritanceScope);
 // public:
 Builder.AddTypedTextChunk("public");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
 
 // protected:
 Builder.AddTypedTextChunk("protected");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK

[PATCH] D38618: Do not add a colon chunk to the code completion of class inheritance access modifiers

2017-10-17 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 119273.
yvvan added a comment.

Rebased to update ScopeFlags.
Rereview please


https://reviews.llvm.org/D38618

Files:
  include/clang/Sema/Scope.h
  lib/Parse/ParseDeclCXX.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/Index/complete-super.cpp


Index: test/Index/complete-super.cpp
===
--- test/Index/complete-super.cpp
+++ test/Index/complete-super.cpp
@@ -40,3 +40,8 @@
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText private}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText protected}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText public}{Colon :} (40)
+
+// RUN: env CINDEXTEST_CODE_COMPLETE_PATTERNS=1 c-index-test 
-code-completion-at=%s:10:12 %s | FileCheck 
-check-prefix=CHECK-INHERITANCE-PATTERN %s
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText private} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText protected} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText public} (40)
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1658,21 +1658,22 @@
   if (CCC == Sema::PCC_Class) {
 AddTypedefResult(Results);
 
+bool IsNotInheritanceScope = !(S->getFlags() & 
Scope::ClassInheritanceScope);
 // public:
 Builder.AddTypedTextChunk("public");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
 
 // protected:
 Builder.AddTypedTextChunk("protected");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
 
 // private:
 Builder.AddTypedTextChunk("private");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
   }
Index: lib/Parse/ParseDeclCXX.cpp
===
--- lib/Parse/ParseDeclCXX.cpp
+++ lib/Parse/ParseDeclCXX.cpp
@@ -3195,6 +3195,9 @@
   }
 
   if (Tok.is(tok::colon)) {
+ParseScope InheritanceScope(this, Scope::ClassScope | Scope::DeclScope |
+  Scope::ClassInheritanceScope);
+
 ParseBaseClause(TagDecl);
 if (!Tok.is(tok::l_brace)) {
   bool SuggestFixIt = false;
Index: include/clang/Sema/Scope.h
===
--- include/clang/Sema/Scope.h
+++ include/clang/Sema/Scope.h
@@ -127,6 +127,9 @@
 
 /// This is a compound statement scope.
 CompoundStmtScope = 0x40,
+
+/// We are between inheritance colon and the real class/struct definition 
scope
+ClassInheritanceScope = 0x80,
   };
 private:
   /// The parent scope for this scope.  This is null for the translation-unit


Index: test/Index/complete-super.cpp
===
--- test/Index/complete-super.cpp
+++ test/Index/complete-super.cpp
@@ -40,3 +40,8 @@
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText private}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText protected}{Colon :} (40)
 // CHECK-ACCESS-PATTERN: NotImplemented:{TypedText public}{Colon :} (40)
+
+// RUN: env CINDEXTEST_CODE_COMPLETE_PATTERNS=1 c-index-test -code-completion-at=%s:10:12 %s | FileCheck -check-prefix=CHECK-INHERITANCE-PATTERN %s
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText private} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText protected} (40)
+// CHECK-INHERITANCE-PATTERN: NotImplemented:{TypedText public} (40)
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1658,21 +1658,22 @@
   if (CCC == Sema::PCC_Class) {
 AddTypedefResult(Results);
 
+bool IsNotInheritanceScope = !(S->getFlags() & Scope::ClassInheritanceScope);
 // public:
 Builder.AddTypedTextChunk("public");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
 
 // protected:
 Builder.AddTypedTextChunk("protected");
-if (Results.includeCodePatterns())
+if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);

[PATCH] D38618: Do not add a colon chunk to the code completion of class inheritance access modifiers

2017-10-23 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

ping


https://reviews.llvm.org/D38618



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


[PATCH] D51281: [libclang] Return the proper pointee type for 'auto' deduced to pointer

2018-08-26 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.
yvvan added reviewers: erikjv, arphaman, michaelwu.

Currently the resulting type is always invalid in such case.


https://reviews.llvm.org/D51281

Files:
  tools/libclang/CXType.cpp


Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -427,6 +427,7 @@
   if (!TP)
 return MakeCXType(QualType(), GetTU(CT));
 
+try_again:
   switch (TP->getTypeClass()) {
 case Type::Pointer:
   T = cast(TP)->getPointeeType();
@@ -444,6 +445,11 @@
 case Type::MemberPointer:
   T = cast(TP)->getPointeeType();
   break;
+case Type::Auto:
+  TP = cast(TP)->getDeducedType().getTypePtrOrNull();
+  if (TP)
+goto try_again;
+  break;
 default:
   T = QualType();
   break;


Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -427,6 +427,7 @@
   if (!TP)
 return MakeCXType(QualType(), GetTU(CT));
 
+try_again:
   switch (TP->getTypeClass()) {
 case Type::Pointer:
   T = cast(TP)->getPointeeType();
@@ -444,6 +445,11 @@
 case Type::MemberPointer:
   T = cast(TP)->getPointeeType();
   break;
+case Type::Auto:
+  TP = cast(TP)->getDeducedType().getTypePtrOrNull();
+  if (TP)
+goto try_again;
+  break;
 default:
   T = QualType();
   break;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D51281: [libclang] Return the proper pointee type for 'auto' deduced to pointer

2018-08-28 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

You are completely right! Thanks!
I did not think that -test-print-type also checks for the pointee.


https://reviews.llvm.org/D51281



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


[PATCH] D51281: [libclang] Return the proper pointee type for 'auto' deduced to pointer

2018-09-05 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 164151.
yvvan added a comment.

Comments addressed


https://reviews.llvm.org/D51281

Files:
  test/Index/print-type.cpp
  tools/libclang/CXType.cpp


Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -427,6 +427,7 @@
   if (!TP)
 return MakeCXType(QualType(), GetTU(CT));
 
+try_again:
   switch (TP->getTypeClass()) {
 case Type::Pointer:
   T = cast(TP)->getPointeeType();
@@ -444,6 +445,12 @@
 case Type::MemberPointer:
   T = cast(TP)->getPointeeType();
   break;
+case Type::Auto:
+case Type::DeducedTemplateSpecialization:
+  TP = cast(TP)->getDeducedType().getTypePtrOrNull();
+  if (TP)
+goto try_again;
+  break;
 default:
   T = QualType();
   break;
Index: test/Index/print-type.cpp
===
--- test/Index/print-type.cpp
+++ test/Index/print-type.cpp
@@ -75,6 +75,8 @@
 template using C = T;
 using baz = C>;
 
+auto autoTemplPointer = &autoTemplRefParam;
+
 // RUN: c-index-test -test-print-type %s -std=c++14 | FileCheck %s
 // CHECK: Namespace=outer:1:11 (Definition) [type=] [typekind=Invalid] 
[isPOD=0]
 // CHECK: ClassTemplate=Foo:4:8 (Definition) [type=] [typekind=Invalid] 
[isPOD=0]
@@ -182,3 +184,4 @@
 // CHECK: UnexposedExpr=templRefParam:71:40 [type=const 
Specialization &>] [typekind=Unexposed] const 
[templateargs/1= [type=Specialization &] [typekind=LValueReference]] 
[canonicaltype=const Specialization &>] 
[canonicaltypekind=Record] [canonicaltemplateargs/1= [type=Specialization 
&] [typekind=LValueReference]] [isPOD=1]
 // CHECK: DeclRefExpr=templRefParam:71:40 
[type=Specialization &>] [typekind=Unexposed] 
[templateargs/1= [type=Specialization &] [typekind=LValueReference]] 
[canonicaltype=Specialization &>] 
[canonicaltypekind=Record] [canonicaltemplateargs/1= [type=Specialization 
&] [typekind=LValueReference]] [isPOD=1]
 // CHECK: TypeAliasDecl=baz:76:7 (Definition) [type=baz] [typekind=Typedef] 
[templateargs/1= [type=A] [typekind=Unexposed]] [canonicaltype=A] 
[canonicaltypekind=Record] [canonicaltemplateargs/1= [type=void] 
[typekind=Void]] [isPOD=0]
+// CHECK: VarDecl=autoTemplPointer:78:6 (Definition) 
[type=Specialization &> *] [typekind=Auto] 
[canonicaltype=Specialization &> *] 
[canonicaltypekind=Pointer] [isPOD=1] 
[pointeetype=Specialization &>] [pointeekind=Record]


Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -427,6 +427,7 @@
   if (!TP)
 return MakeCXType(QualType(), GetTU(CT));
 
+try_again:
   switch (TP->getTypeClass()) {
 case Type::Pointer:
   T = cast(TP)->getPointeeType();
@@ -444,6 +445,12 @@
 case Type::MemberPointer:
   T = cast(TP)->getPointeeType();
   break;
+case Type::Auto:
+case Type::DeducedTemplateSpecialization:
+  TP = cast(TP)->getDeducedType().getTypePtrOrNull();
+  if (TP)
+goto try_again;
+  break;
 default:
   T = QualType();
   break;
Index: test/Index/print-type.cpp
===
--- test/Index/print-type.cpp
+++ test/Index/print-type.cpp
@@ -75,6 +75,8 @@
 template using C = T;
 using baz = C>;
 
+auto autoTemplPointer = &autoTemplRefParam;
+
 // RUN: c-index-test -test-print-type %s -std=c++14 | FileCheck %s
 // CHECK: Namespace=outer:1:11 (Definition) [type=] [typekind=Invalid] [isPOD=0]
 // CHECK: ClassTemplate=Foo:4:8 (Definition) [type=] [typekind=Invalid] [isPOD=0]
@@ -182,3 +184,4 @@
 // CHECK: UnexposedExpr=templRefParam:71:40 [type=const Specialization &>] [typekind=Unexposed] const [templateargs/1= [type=Specialization &] [typekind=LValueReference]] [canonicaltype=const Specialization &>] [canonicaltypekind=Record] [canonicaltemplateargs/1= [type=Specialization &] [typekind=LValueReference]] [isPOD=1]
 // CHECK: DeclRefExpr=templRefParam:71:40 [type=Specialization &>] [typekind=Unexposed] [templateargs/1= [type=Specialization &] [typekind=LValueReference]] [canonicaltype=Specialization &>] [canonicaltypekind=Record] [canonicaltemplateargs/1= [type=Specialization &] [typekind=LValueReference]] [isPOD=1]
 // CHECK: TypeAliasDecl=baz:76:7 (Definition) [type=baz] [typekind=Typedef] [templateargs/1= [type=A] [typekind=Unexposed]] [canonicaltype=A] [canonicaltypekind=Record] [canonicaltemplateargs/1= [type=void] [typekind=Void]] [isPOD=0]
+// CHECK: VarDecl=autoTemplPointer:78:6 (Definition) [type=Specialization &> *] [typekind=Auto] [canonicaltype=Specialization &> *] [canonicaltypekind=Pointer] [isPOD=1] [pointeetype=Specialization &>] [pointeekind=Record]
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D51281: [libclang] Return the proper pointee type for 'auto' deduced to pointer

2018-09-07 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL341656: [libclang] Return the proper pointee type for 
'auto' deduced to pointer (authored by yvvan, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D51281?vs=164151&id=164399#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D51281

Files:
  cfe/trunk/test/Index/print-type.cpp
  cfe/trunk/tools/libclang/CXType.cpp


Index: cfe/trunk/tools/libclang/CXType.cpp
===
--- cfe/trunk/tools/libclang/CXType.cpp
+++ cfe/trunk/tools/libclang/CXType.cpp
@@ -442,6 +442,7 @@
   if (!TP)
 return MakeCXType(QualType(), GetTU(CT));
 
+try_again:
   switch (TP->getTypeClass()) {
 case Type::Pointer:
   T = cast(TP)->getPointeeType();
@@ -459,6 +460,12 @@
 case Type::MemberPointer:
   T = cast(TP)->getPointeeType();
   break;
+case Type::Auto:
+case Type::DeducedTemplateSpecialization:
+  TP = cast(TP)->getDeducedType().getTypePtrOrNull();
+  if (TP)
+goto try_again;
+  break;
 default:
   T = QualType();
   break;
Index: cfe/trunk/test/Index/print-type.cpp
===
--- cfe/trunk/test/Index/print-type.cpp
+++ cfe/trunk/test/Index/print-type.cpp
@@ -75,6 +75,8 @@
 template using C = T;
 using baz = C>;
 
+auto autoTemplPointer = &autoTemplRefParam;
+
 // RUN: c-index-test -test-print-type %s -std=c++14 | FileCheck %s
 // CHECK: Namespace=outer:1:11 (Definition) [type=] [typekind=Invalid] 
[isPOD=0]
 // CHECK: ClassTemplate=Foo:4:8 (Definition) [type=] [typekind=Invalid] 
[isPOD=0]
@@ -182,3 +184,4 @@
 // CHECK: UnexposedExpr=templRefParam:71:40 [type=const 
Specialization &>] [typekind=Unexposed] const 
[templateargs/1= [type=Specialization &] [typekind=LValueReference]] 
[canonicaltype=const Specialization &>] 
[canonicaltypekind=Record] [canonicaltemplateargs/1= [type=Specialization 
&] [typekind=LValueReference]] [isPOD=1]
 // CHECK: DeclRefExpr=templRefParam:71:40 
[type=Specialization &>] [typekind=Unexposed] 
[templateargs/1= [type=Specialization &] [typekind=LValueReference]] 
[canonicaltype=Specialization &>] 
[canonicaltypekind=Record] [canonicaltemplateargs/1= [type=Specialization 
&] [typekind=LValueReference]] [isPOD=1]
 // CHECK: TypeAliasDecl=baz:76:7 (Definition) [type=baz] [typekind=Typedef] 
[templateargs/1= [type=A] [typekind=Unexposed]] [canonicaltype=A] 
[canonicaltypekind=Record] [canonicaltemplateargs/1= [type=void] 
[typekind=Void]] [isPOD=0]
+// CHECK: VarDecl=autoTemplPointer:78:6 (Definition) 
[type=Specialization &> *] [typekind=Auto] 
[canonicaltype=Specialization &> *] 
[canonicaltypekind=Pointer] [isPOD=1] 
[pointeetype=Specialization &>] [pointeekind=Record]


Index: cfe/trunk/tools/libclang/CXType.cpp
===
--- cfe/trunk/tools/libclang/CXType.cpp
+++ cfe/trunk/tools/libclang/CXType.cpp
@@ -442,6 +442,7 @@
   if (!TP)
 return MakeCXType(QualType(), GetTU(CT));
 
+try_again:
   switch (TP->getTypeClass()) {
 case Type::Pointer:
   T = cast(TP)->getPointeeType();
@@ -459,6 +460,12 @@
 case Type::MemberPointer:
   T = cast(TP)->getPointeeType();
   break;
+case Type::Auto:
+case Type::DeducedTemplateSpecialization:
+  TP = cast(TP)->getDeducedType().getTypePtrOrNull();
+  if (TP)
+goto try_again;
+  break;
 default:
   T = QualType();
   break;
Index: cfe/trunk/test/Index/print-type.cpp
===
--- cfe/trunk/test/Index/print-type.cpp
+++ cfe/trunk/test/Index/print-type.cpp
@@ -75,6 +75,8 @@
 template using C = T;
 using baz = C>;
 
+auto autoTemplPointer = &autoTemplRefParam;
+
 // RUN: c-index-test -test-print-type %s -std=c++14 | FileCheck %s
 // CHECK: Namespace=outer:1:11 (Definition) [type=] [typekind=Invalid] [isPOD=0]
 // CHECK: ClassTemplate=Foo:4:8 (Definition) [type=] [typekind=Invalid] [isPOD=0]
@@ -182,3 +184,4 @@
 // CHECK: UnexposedExpr=templRefParam:71:40 [type=const Specialization &>] [typekind=Unexposed] const [templateargs/1= [type=Specialization &] [typekind=LValueReference]] [canonicaltype=const Specialization &>] [canonicaltypekind=Record] [canonicaltemplateargs/1= [type=Specialization &] [typekind=LValueReference]] [isPOD=1]
 // CHECK: DeclRefExpr=templRefParam:71:40 [type=Specialization &>] [typekind=Unexposed] [templateargs/1= [type=Specialization &] [typekind=LValueReference]] [canonicaltype=Specialization &>] [canonicaltypekind=Record] [canonicaltemplateargs/1= [type=Specialization &] [typekind=LValueReference]] [isPOD=1]
 // CHECK: TypeAliasDecl=baz:76:7 (Definition) [type=baz] [typekind=Typedef] [templateargs/1= [type=A] [typekind=Unexposed]] [canonicaltype=A] [canonicaltypekind=Record] [canonicaltemplateargs/1= [type=void] [typekind=Void]] [isPOD=0]

[PATCH] D49010: YAML output for index-while-building

2018-07-24 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

@ilya-biryukov I would name this revision "for test purpose". It works at some 
extent with the current clangd version and can be used by someone else. But  
since we had a discussion about YAML being a temporary solution I never planned 
to commit this revision.
So yes, I totally agree that using a binary format would be ideal for the 
"index while build' use case.


https://reviews.llvm.org/D49010



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


[PATCH] D49794: [libclang] Allow skipping warnings from all included files

2018-07-25 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.
yvvan added reviewers: ilya-biryukov, bkramer, akyrtzi, malaperle.

Updated clone for https://reviews.llvm.org/D48116 by Nikolai, now also adds the 
clang driver flag and the test for it.
If clang has plugins they are also affected by this filtering.

Depending on the included files and the used warning flags, e.g. -
Weverything, a huge number of warnings can be reported for included
files. As processing that many diagnostics comes with a performance
impact and not all clients are interested in those diagnostics, add a
flag to skip them.


https://reviews.llvm.org/D49794

Files:
  include/clang-c/Index.h
  include/clang/Basic/Diagnostic.h
  include/clang/Basic/DiagnosticOptions.def
  include/clang/Driver/Options.td
  lib/Basic/DiagnosticIDs.cpp
  lib/Basic/Warnings.cpp
  lib/Frontend/CompilerInvocation.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp

Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -3398,6 +3398,9 @@
   if (options & CXTranslationUnit_KeepGoing)
 Diags->setSuppressAfterFatalError(false);
 
+  if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
+  Diags->setSuppressNonErrorsFromIncludedFiles(true);
+
   // Recover resources if we crash before exiting this function.
   llvm::CrashRecoveryContextCleanupRegistrar >
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -84,6 +84,8 @@
 options |= CXTranslationUnit_KeepGoing;
   if (getenv("CINDEXTEST_LIMIT_SKIP_FUNCTION_BODIES_TO_PREAMBLE"))
 options |= CXTranslationUnit_LimitSkipFunctionBodiesToPreamble;
+  if (getenv("CINDEXTEST_IGNORE_NONERRORS_FROM_INCLUDED_FILES"))
+options |= CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles;
 
   return options;
 }
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -1223,6 +1223,8 @@
   Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
 Opts.DiagnosticSerializationFile = A->getValue();
   Opts.IgnoreWarnings = Args.hasArg(OPT_w);
+  Opts.SuppressNonErrorsFromIncludedFiles =
+  Args.hasArg(OPT_fsuppress_non_errors_from_included_files);
   Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
   Opts.Pedantic = Args.hasArg(OPT_pedantic);
   Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
Index: lib/Basic/Warnings.cpp
===
--- lib/Basic/Warnings.cpp
+++ lib/Basic/Warnings.cpp
@@ -46,6 +46,7 @@
   bool ReportDiags) {
   Diags.setSuppressSystemWarnings(true);  // Default to -Wno-system-headers
   Diags.setIgnoreAllWarnings(Opts.IgnoreWarnings);
+  Diags.setSuppressNonErrorsFromIncludedFiles(Opts.SuppressNonErrorsFromIncludedFiles);
   Diags.setShowOverloads(Opts.getShowOverloads());
 
   Diags.setElideType(Opts.ElideType);
Index: lib/Basic/DiagnosticIDs.cpp
===
--- lib/Basic/DiagnosticIDs.cpp
+++ lib/Basic/DiagnosticIDs.cpp
@@ -477,6 +477,14 @@
   Result = diag::Severity::Fatal;
   }
 
+  // If requested, ignore non-errors from all included files.
+  if (Diag.SuppressNonErrorsFromIncludedFiles &&
+  Result <= diag::Severity::Warning && Loc.isValid() &&
+  !Diag.getSourceManager().isInMainFile(
+  Diag.getSourceManager().getExpansionLoc(Loc))) {
+return diag::Severity::Ignored;
+  }
+
   // Custom diagnostics always are emitted in system headers.
   bool ShowInSystemHeader =
   !GetDiagInfo(DiagID) || GetDiagInfo(DiagID)->WarnShowInSystemHeader;
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1742,6 +1742,8 @@
 def fdebug_prefix_map_EQ
   : Joined<["-"], "fdebug-prefix-map=">, Group, Flags<[CC1Option]>,
 HelpText<"remap file source paths in debug info">;
+def fsuppress_non_errors_from_included_files : Flag<["-"], "fsuppress-non-errors-from-included-files">,
+  Group, Flags<[CC1Option]>;
 def g_Flag : Flag<["-"], "g">, Group,
   HelpText<"Generate source-level debug information">;
 def gline_tables_only : Flag<["-"], "gline-tables-only">, Group,
Index: include/clang/Basic/DiagnosticOptions.def
===
--- include/clang/Basic/DiagnosticOptions.def
+++ include/clang/Basic/DiagnosticOptions.def
@@ -45,6 +45,7 @@
 #endif
 
 SEMANTIC_DIAGOPT(IgnoreWarnings, 1, 0)   /// -w
+DIAGOPT(SuppressNonErrorsFromIncludedFiles, 1, 0)  /// -fsuppress-non-errors-from-included-files
 DIAGOPT(NoRewriteMacros, 1, 0)  /// -Wno-rewrite-macr

[PATCH] D49063: [libclang 1/8] Add support for ObjCObjectType

2018-07-25 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I'm mostly fine with your set of patches. Let me double check and we can get it 
in.


https://reviews.llvm.org/D49063



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


[PATCH] D49794: [libclang] Allow skipping warnings from all included files

2018-07-31 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 158211.
yvvan added a comment.

Restore missing tests


https://reviews.llvm.org/D49794

Files:
  include/clang-c/Index.h
  include/clang/Basic/Diagnostic.h
  include/clang/Basic/DiagnosticOptions.def
  include/clang/Driver/Options.td
  lib/Basic/DiagnosticIDs.cpp
  lib/Basic/Warnings.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/Frontend/Inputs/header-with-warning.h
  test/Frontend/warnings-ignore-from-includes.cpp
  test/Index/ignore-warnings-from-headers.cpp
  test/Index/ignore-warnings-from-headers.h
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp

Index: test/Index/ignore-warnings-from-headers.h
===
--- /dev/null
+++ test/Index/ignore-warnings-from-headers.h
@@ -0,0 +1 @@
+void f(int unusedInHeader) {}
Index: test/Index/ignore-warnings-from-headers.cpp
===
--- /dev/null
+++ test/Index/ignore-warnings-from-headers.cpp
@@ -0,0 +1,7 @@
+#include "ignore-warnings-from-headers.h"
+
+void g(int unusedInMainFile) {}
+
+// RUN: env CINDEXTEST_IGNORE_NONERRORS_FROM_INCLUDED_FILES=1 c-index-test -test-load-source function %s -Wunused-parameter 2>&1 | FileCheck %s
+// CHECK-NOT: warning: unused parameter 'unusedInHeader'
+// CHECK: warning: unused parameter 'unusedInMainFile'
Index: test/Frontend/warnings-ignore-from-includes.cpp
===
--- /dev/null
+++ test/Frontend/warnings-ignore-from-includes.cpp
@@ -0,0 +1,7 @@
+#include "header-with-warning.h"
+
+static void f1(void) {}
+
+// RUN: %clang_cc1 -I%S/Inputs/ -Wunused-function -fsuppress-non-errors-from-included-files %s 2>&1 | FileCheck %s
+// CHECK-NOT: warning: unused function 'f0'
+// CHECK: warning: unused function 'f1'
Index: test/Frontend/Inputs/header-with-warning.h
===
--- /dev/null
+++ test/Frontend/Inputs/header-with-warning.h
@@ -0,0 +1 @@
+static void f0(void) {}
Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -3398,6 +3398,9 @@
   if (options & CXTranslationUnit_KeepGoing)
 Diags->setSuppressAfterFatalError(false);
 
+  if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
+  Diags->setSuppressNonErrorsFromIncludedFiles(true);
+
   // Recover resources if we crash before exiting this function.
   llvm::CrashRecoveryContextCleanupRegistrar >
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -84,6 +84,8 @@
 options |= CXTranslationUnit_KeepGoing;
   if (getenv("CINDEXTEST_LIMIT_SKIP_FUNCTION_BODIES_TO_PREAMBLE"))
 options |= CXTranslationUnit_LimitSkipFunctionBodiesToPreamble;
+  if (getenv("CINDEXTEST_IGNORE_NONERRORS_FROM_INCLUDED_FILES"))
+options |= CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles;
 
   return options;
 }
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -1223,6 +1223,8 @@
   Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
 Opts.DiagnosticSerializationFile = A->getValue();
   Opts.IgnoreWarnings = Args.hasArg(OPT_w);
+  Opts.SuppressNonErrorsFromIncludedFiles =
+  Args.hasArg(OPT_fsuppress_non_errors_from_included_files);
   Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
   Opts.Pedantic = Args.hasArg(OPT_pedantic);
   Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
Index: lib/Basic/Warnings.cpp
===
--- lib/Basic/Warnings.cpp
+++ lib/Basic/Warnings.cpp
@@ -46,6 +46,7 @@
   bool ReportDiags) {
   Diags.setSuppressSystemWarnings(true);  // Default to -Wno-system-headers
   Diags.setIgnoreAllWarnings(Opts.IgnoreWarnings);
+  Diags.setSuppressNonErrorsFromIncludedFiles(Opts.SuppressNonErrorsFromIncludedFiles);
   Diags.setShowOverloads(Opts.getShowOverloads());
 
   Diags.setElideType(Opts.ElideType);
Index: lib/Basic/DiagnosticIDs.cpp
===
--- lib/Basic/DiagnosticIDs.cpp
+++ lib/Basic/DiagnosticIDs.cpp
@@ -477,6 +477,14 @@
   Result = diag::Severity::Fatal;
   }
 
+  // If requested, ignore non-errors from all included files.
+  if (Diag.SuppressNonErrorsFromIncludedFiles &&
+  Result <= diag::Severity::Warning && Loc.isValid() &&
+  !Diag.getSourceManager().isInMainFile(
+  Diag.getSourceManager().getExpansionLoc(Loc))) {
+return diag::Severity::Ignored;
+  }
+
   // Custom diagnostics always are emitted in system headers.
   bool ShowInSystemHeader =
   !GetDia

[PATCH] D49794: [libclang] Allow skipping warnings from all included files

2018-07-31 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I already mentioned in the review inherited by this one that this way covers 
also loaded plugins with different consumers. So let's assume that driver loads 
clang-tidy and some other plugins and runs over each file in the project.
It makes sense not to include clang-tidy diagnostics coming from headers, at 
least for third-party headers (you can still run clang over specific headers 
themselves to get diagnostics for them).


https://reviews.llvm.org/D49794



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


[PATCH] D49794: [libclang] Allow skipping warnings from all included files

2018-07-31 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

And we already saw, that -isystem is not the best choice for that. And by the 
way - clang-tidy has this filtering in consumer which does not exist in it's 
plugin-mode so it spits all system diagnostics all the time...


https://reviews.llvm.org/D49794



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


[PATCH] D49794: [libclang] Allow skipping warnings from all included files

2018-07-31 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Anyways, if c++ part does not seem relevant I'm fine if we only have libclang 
part from https://reviews.llvm.org/D48116.

BTW I don't remember if you answered something to my suggestion of adding flag 
-ithird-party as an alternative to -isystem which does not lock files and helps 
to filter diagnostics, etc.


https://reviews.llvm.org/D49794



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


[PATCH] D49794: [libclang] Allow skipping warnings from all included files

2018-07-31 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

In https://reviews.llvm.org/D49794#1182272, @ilya-biryukov wrote:

> In https://reviews.llvm.org/D49794#1182220, @yvvan wrote:
>
> > And we already saw, that -isystem is not the best choice for that.
>
>
> Are you referring to the file-locking on Windows? 
>  Any other reasons why the -isystem trick might be non-ideal?


File locking is the first one. Another one comes with "plugin mode" of tidy.

>> And by the way - clang-tidy has this filtering in consumer which does not 
>> exist in it's plugin-mode so it spits all system diagnostics all the time...
> 
> I would still argue against adding this option in the current form to the 
> compiler. I don't see how that might be useful to non-clang-tidy, 
> non-editor-integration users.
> 
> What's the 'plugin mode' of clang-tidy? I don't seem to able to Google it :-)

Clang tidy is not only a standalone tool but also a plugin. It's almost never 
used this way (but we do that in Qt Creator to combine it with Clazy) and it 
also seems that some of the recent checks are added only to standalone tool 
(which is easy to fix).
Being loaded into clang as plugin it does not support most of clang-tidy 
command line options and is not able to filter system includes. I'm not sure 
it's possible to fix both of these issues (and probably some other).


https://reviews.llvm.org/D49794



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


[PATCH] D42895: [libclang] Add `CXSymbolRole role` to CXIdxEntityRefInfo

2018-02-05 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I feel quite ok about this patch.

Can you please add unit-tests?


Repository:
  rC Clang

https://reviews.llvm.org/D42895



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-02-07 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

ping...


https://reviews.llvm.org/D41537



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


[PATCH] D42895: [libclang] Add `CXSymbolRole role` to CXIdxEntityRefInfo

2018-02-07 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added reviewers: ilya-biryukov, bkramer, arphaman.
yvvan added a comment.

Looks ok-ish, I haven't built it though.
Also I don't have much exp with indexing part of libclang. Adding more 
reviewers.


Repository:
  rC Clang

https://reviews.llvm.org/D42895



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


[PATCH] D41005: Reuse preamble even if an unsaved file does not exist

2018-02-08 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

In https://reviews.llvm.org/D41005#1001854, @cameron314 wrote:

> @yvvan: The clang frontend tests (`PCHPreambleTest` and friends) are disabled 
> on Windows in the makefile (I think because the VFS tests depend on 
> linux-like paths). So running the tests on Windows without failures is 
> encouraging but not the whole story.


Nice to know. But the bad thing is that it is not obvious at all from the code. 
And another bad thing is that tests are platform dependent.


Repository:
  rC Clang

https://reviews.llvm.org/D41005



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-02-20 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

ping


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-02-21 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I've already added hints in this patch and it also do not add extra completions 
unless the flag IncludeCorrections is set. So this will not force editors to 
use corrections.

Did you mean that you think it's good to have extra fixit hints even if this 
flag is not set?


https://reviews.llvm.org/D41537



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-02-22 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Or is your idea is to return the char sequence instead to use this correction 
in some universal way?


https://reviews.llvm.org/D41537



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


[PATCH] D33493: Speed up preamble loading, reduce global completion cache calls

2017-05-24 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.

On Windows loading preamble and caching global completion takes a while.
This is the way to improve it.
Please comment if I misuse something.


https://reviews.llvm.org/D33493

Files:
  include/clang/Frontend/ASTUnit.h
  lib/Frontend/ASTUnit.cpp


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -455,7 +455,7 @@
   }
   
   // Save the current top-level hash value.
-  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
+  CompletionCacheTopLevelHashValue = PreambleTopLevelHashValue;
 }
 
 void ASTUnit::ClearCachedCompletionResults() {
@@ -1126,6 +1126,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+FIDsCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -1476,6 +1478,8 @@
   SimpleTimer PreambleTimer(WantTiming);
   PreambleTimer.setOutput("Precompiling preamble");
 
+  CompletionCacheTopLevelHashValue = 0;
+
   // Save the preamble text for later; we'll need to compare against it for
   // subsequent reparses.
   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
@@ -1626,7 +1630,6 @@
   // entities the last time we rebuilt the preamble, clear out the completion
   // cache.
   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
-CompletionCacheTopLevelHashValue = 0;
 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
   }
 
@@ -2061,7 +2064,7 @@
   // If we're caching global code-completion results, and the top-level 
   // declarations have changed, clear out the code-completion cache.
   if (!Result && ShouldCacheCodeCompletionResults &&
-  CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
+  PreambleTopLevelHashValue != CompletionCacheTopLevelHashValue)
 CacheCodeCompletionResults();
 
   // We now need to clear out the completion info related to this translation
@@ -2531,8 +2534,7 @@
 
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
@@ -2540,11 +2542,17 @@
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
+FileID FID;
+SourceLocation FileLoc;
+auto ItFileID = FIDsCache.find(SD.Filename);
+if (ItFileID == FIDsCache.end()) {
   FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  FIDsCache.insert(std::make_pair(SD.Filename, FileLoc));
+} else {
+  FileLoc = ItFileID->second;
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -181,6 +181,8 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  std::map FIDsCache;
+
 public:
   class PreambleData {
 const FileEntry *File;


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -455,7 +455,7 @@
   }
   
   // Save the current top-level hash value.
-  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
+  CompletionCacheTopLevelHashValue = PreambleTopLevelHashValue;
 }
 
 void ASTUnit::ClearCachedCompletionResults() {
@@ -1126,6 +1126,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+FIDsCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -1476,6 +1478,8 @@
   SimpleTimer PreambleTimer(WantTiming);
   PreambleTimer.setOutput("Precompiling preamble");
 
+  CompletionCacheTopLevelHashValue = 0;
+
   // Save the preamble text for later; we'll need to compare against it for
   // subsequent reparses.
   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
@@ -1626,7 +1630,6 @@
   // entities the last time we rebuilt the preamble, clear out the completion
   // cache.
   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
-CompletionCacheTopLevelHashValue = 0;
 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
   }
 
@@ -2061,7 +2064,7 @@
   // If we're caching global code-completion results, and the top-level 
   // declarations have changed, clear out the code-completion cache.
   if (!Result && ShouldCacheCodeCompletionResults &&
-  CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
+  PreambleTopLevelHashValue != CompletionCacheTopLevelHas

[PATCH] D33493: Speed up preamble loading, reduce global completion cache calls

2017-05-24 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 100075.
yvvan added a comment.

fix member variable name, add comments


https://reviews.llvm.org/D33493

Files:
  include/clang/Frontend/ASTUnit.h
  lib/Frontend/ASTUnit.cpp


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -455,7 +455,7 @@
   }
   
   // Save the current top-level hash value.
-  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
+  CompletionCacheTopLevelHashValue = PreambleTopLevelHashValue;
 }
 
 void ASTUnit::ClearCachedCompletionResults() {
@@ -1126,6 +1126,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+SrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -1476,6 +1478,8 @@
   SimpleTimer PreambleTimer(WantTiming);
   PreambleTimer.setOutput("Precompiling preamble");
 
+  CompletionCacheTopLevelHashValue = 0;
+
   // Save the preamble text for later; we'll need to compare against it for
   // subsequent reparses.
   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
@@ -1626,7 +1630,6 @@
   // entities the last time we rebuilt the preamble, clear out the completion
   // cache.
   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
-CompletionCacheTopLevelHashValue = 0;
 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
   }
 
@@ -2061,7 +2064,7 @@
   // If we're caching global code-completion results, and the top-level 
   // declarations have changed, clear out the code-completion cache.
   if (!Result && ShouldCacheCodeCompletionResults &&
-  CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
+  PreambleTopLevelHashValue != CompletionCacheTopLevelHashValue)
 CacheCodeCompletionResults();
 
   // We now need to clear out the completion info related to this translation
@@ -2531,8 +2534,7 @@
 
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
@@ -2540,11 +2542,17 @@
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
+FileID FID;
+SourceLocation FileLoc;
+auto ItFileID = SrcLocCache.find(SD.Filename);
+if (ItFileID == SrcLocCache.end()) {
   FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  SrcLocCache.insert(std::make_pair(SD.Filename, FileLoc));
+} else {
+  FileLoc = ItFileID->second;
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -181,6 +181,12 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  /// \brief Cache pairs "filename - source location"
+  ///
+  /// This cache is used when loading preambule to increase performance
+  /// of that loading
+  std::map SrcLocCache;
+
 public:
   class PreambleData {
 const FileEntry *File;


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -455,7 +455,7 @@
   }
   
   // Save the current top-level hash value.
-  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
+  CompletionCacheTopLevelHashValue = PreambleTopLevelHashValue;
 }
 
 void ASTUnit::ClearCachedCompletionResults() {
@@ -1126,6 +1126,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+SrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -1476,6 +1478,8 @@
   SimpleTimer PreambleTimer(WantTiming);
   PreambleTimer.setOutput("Precompiling preamble");
 
+  CompletionCacheTopLevelHashValue = 0;
+
   // Save the preamble text for later; we'll need to compare against it for
   // subsequent reparses.
   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
@@ -1626,7 +1630,6 @@
   // entities the last time we rebuilt the preamble, clear out the completion
   // cache.
   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
-CompletionCacheTopLevelHashValue = 0;
 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
   }
 
@@ -2061,7 +2064,7 @@
   // If we're caching global code-completion results, and the top-level 
   // declarations have changed, clear out the code-completion cache.
   if (!Result && ShouldCacheCodeCompletionResults &&
-  CurrentTopLevelHas

[PATCH] D33493: Speed up preamble loading, reduce global completion cache calls

2017-05-29 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 100605.
yvvan added a comment.

diff with -U


https://reviews.llvm.org/D33493

Files:
  include/clang/Frontend/ASTUnit.h
  lib/Frontend/ASTUnit.cpp


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -470,7 +470,7 @@
   }
   
   // Save the current top-level hash value.
-  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
+  CompletionCacheTopLevelHashValue = PreambleTopLevelHashValue;
 }
 
 void ASTUnit::ClearCachedCompletionResults() {
@@ -1148,6 +1148,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+SrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -1506,6 +1508,8 @@
   SimpleTimer PreambleTimer(WantTiming);
   PreambleTimer.setOutput("Precompiling preamble");
 
+  CompletionCacheTopLevelHashValue = 0;
+
   // Save the preamble text for later; we'll need to compare against it for
   // subsequent reparses.
   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
@@ -1656,7 +1660,6 @@
   // entities the last time we rebuilt the preamble, clear out the completion
   // cache.
   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
-CompletionCacheTopLevelHashValue = 0;
 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
   }
 
@@ -2105,7 +2108,7 @@
   // If we're caching global code-completion results, and the top-level 
   // declarations have changed, clear out the code-completion cache.
   if (!Result && ShouldCacheCodeCompletionResults &&
-  CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
+  PreambleTopLevelHashValue != CompletionCacheTopLevelHashValue)
 CacheCodeCompletionResults();
 
   // We now need to clear out the completion info related to this translation
@@ -2579,20 +2582,25 @@
 
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
   continue;
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
+FileID FID;
+SourceLocation FileLoc;
+auto ItFileID = SrcLocCache.find(SD.Filename);
+if (ItFileID == SrcLocCache.end()) {
   FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  SrcLocCache.insert(std::make_pair(SD.Filename, FileLoc));
+} else {
+  FileLoc = ItFileID->second;
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -185,6 +185,12 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  /// \brief Cache pairs "filename - source location"
+  ///
+  /// This cache is used when loading preambule to increase performance
+  /// of that loading
+  std::map SrcLocCache;
+
 public:
   class PreambleData {
 const FileEntry *File;


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -470,7 +470,7 @@
   }
   
   // Save the current top-level hash value.
-  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
+  CompletionCacheTopLevelHashValue = PreambleTopLevelHashValue;
 }
 
 void ASTUnit::ClearCachedCompletionResults() {
@@ -1148,6 +1148,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+SrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -1506,6 +1508,8 @@
   SimpleTimer PreambleTimer(WantTiming);
   PreambleTimer.setOutput("Precompiling preamble");
 
+  CompletionCacheTopLevelHashValue = 0;
+
   // Save the preamble text for later; we'll need to compare against it for
   // subsequent reparses.
   StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
@@ -1656,7 +1660,6 @@
   // entities the last time we rebuilt the preamble, clear out the completion
   // cache.
   if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
-CompletionCacheTopLevelHashValue = 0;
 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
   }
 
@@ -2105,7 +2108,7 @@
   // If we're caching global code-completion results, and the top-level 
   // declarations have changed, clear out the code-completion cache.
   if (!Result && ShouldCacheCodeCompletionResults &&
-  CurrentTopLevelHashValue != CompletionCacheTo

[PATCH] D33644: Add default values for function parameter chunks

2017-05-29 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.

Append optional chunks with their default values. For example: before - "int 
i", after - "int i = 10". This change affects only simple types.


https://reviews.llvm.org/D33644

Files:
  lib/Sema/SemaCodeComplete.cpp


Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2279,6 +2279,15 @@
 } else {
   Type.getAsStringInternal(Result, Policy);
 }
+if (Param->hasDefaultArg()) {
+  APValue *defaultValue = Param->evaluateValue();
+  if (defaultValue) {
+std::string defaultValueStr = defaultValue->getAsString(
+Param->getASTContext(), Param->getType());
+if (!defaultValueStr.empty())
+  Result += " = " + defaultValueStr;
+  }
+}
 return Result;
   }
 


Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2279,6 +2279,15 @@
 } else {
   Type.getAsStringInternal(Result, Policy);
 }
+if (Param->hasDefaultArg()) {
+  APValue *defaultValue = Param->evaluateValue();
+  if (defaultValue) {
+std::string defaultValueStr = defaultValue->getAsString(
+Param->getASTContext(), Param->getType());
+if (!defaultValueStr.empty())
+  Result += " = " + defaultValueStr;
+  }
+}
 return Result;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D33644: Add default values for function parameter chunks

2017-05-30 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 100705.
yvvan edited the summary of this revision.
yvvan added a comment.

Support for non-simple types. Drop results with macros.


https://reviews.llvm.org/D33644

Files:
  lib/Sema/SemaCodeComplete.cpp


Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2279,6 +2279,15 @@
 } else {
   Type.getAsStringInternal(Result, Policy);
 }
+if (Param->hasDefaultArg()) {
+  APValue *defaultValue = Param->evaluateValue();
+  if (defaultValue) {
+std::string defaultValueStr = defaultValue->getAsString(
+Param->getASTContext(), Param->getType());
+if (!defaultValueStr.empty())
+  Result += " = " + defaultValueStr;
+  }
+}
 return Result;
   }
 
@@ -2395,6 +2404,19 @@
   return Result;
 }
 
+static std::string GetDefaultValueString(const ParmVarDecl *Param,
+ const SourceManager &SM,
+ const LangOptions &LangOpts) {
+  const SourceRange SrcRange = Param->getDefaultArg()->getSourceRange();
+  const SourceLocation StartLoc = SrcRange.getBegin();
+  const SourceLocation EndLoc = SrcRange.getEnd();
+  if (StartLoc != SM.getExpansionLoc(StartLoc) || EndLoc != 
SM.getExpansionLoc(EndLoc))
+  return "";
+  const size_t PtrDiff = EndLoc.getRawEncoding() - StartLoc.getRawEncoding()
+  + Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
+  return std::string{SM.getCharacterData(StartLoc), PtrDiff};
+}
+
 /// \brief Add function parameter chunks to the given code completion string.
 static void AddFunctionParameterChunks(Preprocessor &PP,
const PrintingPolicy &Policy,
@@ -2423,11 +2445,17 @@
   FirstParameter = false;
 else
   Result.AddChunk(CodeCompletionString::CK_Comma);
-
+
 InOptional = false;
 
 // Format the placeholder string.
 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
+if (Param->hasDefaultArg() && PlaceholderStr.find("=") == 
std::string::npos) {
+std::string DefaultValue =
+GetDefaultValueString(Param, PP.getSourceManager(), 
PP.getLangOpts());
+if (!DefaultValue.empty())
+PlaceholderStr += DefaultValue;
+}
 
 if (Function->isVariadic() && P == N - 1)
   PlaceholderStr += ", ...";
@@ -3009,10 +3037,18 @@
 
 // Format the placeholder string.
 std::string Placeholder;
-if (Function)
-  Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
-else
+if (Function) {
+  const ParmVarDecl *Param = Function->getParamDecl(P);
+  Placeholder = FormatFunctionParameter(Policy, Param);
+  if (Param->hasDefaultArg() && Placeholder.find("=") == 
std::string::npos) {
+std::string DefaultValue =
+GetDefaultValueString(Param, Context.getSourceManager(), 
Context.getLangOpts());
+if (!DefaultValue.empty())
+  Placeholder += DefaultValue;
+  }
+ } else {
   Placeholder = Prototype->getParamType(P).getAsString(Policy);
+}
 
 if (P == CurrentArg)
   Result.AddCurrentParameterChunk(


Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2279,6 +2279,15 @@
 } else {
   Type.getAsStringInternal(Result, Policy);
 }
+if (Param->hasDefaultArg()) {
+  APValue *defaultValue = Param->evaluateValue();
+  if (defaultValue) {
+std::string defaultValueStr = defaultValue->getAsString(
+Param->getASTContext(), Param->getType());
+if (!defaultValueStr.empty())
+  Result += " = " + defaultValueStr;
+  }
+}
 return Result;
   }
 
@@ -2395,6 +2404,19 @@
   return Result;
 }
 
+static std::string GetDefaultValueString(const ParmVarDecl *Param,
+ const SourceManager &SM,
+ const LangOptions &LangOpts) {
+  const SourceRange SrcRange = Param->getDefaultArg()->getSourceRange();
+  const SourceLocation StartLoc = SrcRange.getBegin();
+  const SourceLocation EndLoc = SrcRange.getEnd();
+  if (StartLoc != SM.getExpansionLoc(StartLoc) || EndLoc != SM.getExpansionLoc(EndLoc))
+  return "";
+  const size_t PtrDiff = EndLoc.getRawEncoding() - StartLoc.getRawEncoding()
+  + Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
+  return std::string{SM.getCharacterData(StartLoc), PtrDiff};
+}
+
 /// \brief Add function parameter chunks to the given code completion string.
 static void AddFunctionParameterChunks(Preprocessor &PP,
const PrintingPolicy &Policy,
@@ -2423,11 +2445,17 @@
   FirstParameter = false;
 else
   Result.AddChunk(Co

[PATCH] D33644: Add default values for function parameter chunks

2017-06-06 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Waiting for review...


https://reviews.llvm.org/D33644



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


[PATCH] D33493: Speed up preamble loading, reduce global completion cache calls

2017-06-06 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 101533.
yvvan added a comment.

Remove global completion cache part because it's probably not always valid.


https://reviews.llvm.org/D33493

Files:
  include/clang/Frontend/ASTUnit.h
  lib/Frontend/ASTUnit.cpp


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -1148,6 +1148,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+SrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -2579,20 +2581,25 @@
 
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
   continue;
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
+FileID FID;
+SourceLocation FileLoc;
+auto ItFileID = SrcLocCache.find(SD.Filename);
+if (ItFileID == SrcLocCache.end()) {
   FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  SrcLocCache.insert(std::make_pair(SD.Filename, FileLoc));
+} else {
+  FileLoc = ItFileID->second;
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -185,6 +185,12 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  /// \brief Cache pairs "filename - source location"
+  ///
+  /// This cache is used when loading preambule to increase performance
+  /// of that loading
+  std::map SrcLocCache;
+
 public:
   class PreambleData {
 const FileEntry *File;


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -1148,6 +1148,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+SrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -2579,20 +2581,25 @@
 
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
   continue;
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
+FileID FID;
+SourceLocation FileLoc;
+auto ItFileID = SrcLocCache.find(SD.Filename);
+if (ItFileID == SrcLocCache.end()) {
   FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  SrcLocCache.insert(std::make_pair(SD.Filename, FileLoc));
+} else {
+  FileLoc = ItFileID->second;
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -185,6 +185,12 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  /// \brief Cache pairs "filename - source location"
+  ///
+  /// This cache is used when loading preambule to increase performance
+  /// of that loading
+  std::map SrcLocCache;
+
 public:
   class PreambleData {
 const FileEntry *File;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D33493: Speed up preamble loading

2017-06-06 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

In https://reviews.llvm.org/D33493#774264, @arphaman wrote:

> Can you use a local map in `TranslateStoredDiagnostics` instead of storing 
> one in the `ASTUnit`, or do you need to keep it around?


The whole purpose is to use it between different TranslateStoredDiagnostics 
calls because it scans the same files every time. And this cache allows it to 
reuse the source location.


https://reviews.llvm.org/D33493



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


[PATCH] D33493: Speed up preamble loading

2017-06-07 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added inline comments.



Comment at: include/clang/Frontend/ASTUnit.h:192
+  /// of that loading
+  std::map SrcLocCache;
+

arphaman wrote:
> You can use an `llvm::StringMap` instead.
I will change that



Comment at: lib/Frontend/ASTUnit.cpp:1152
+  else
+SrcLocCache.clear();
 

arphaman wrote:
> Why is `clear` in an `else` here? We always create a new `SourceManager` in 
> this function, so the previously cached locations will be invalid, so 
> shouldn't we always clear the cache before `TranslateStoredDiagnostics`?
When we load diagnostics that means that preamble has not changed. Doesn't that 
mean that source locations can be reused? What can cause them to become invalid?
When preamble is invalidated - cache is cleared.

I can keep cache only during TranslateStoredDiagnostics calls but in that case 
performance improvement is way less.

But if you say that current solution is invalid I will do that


https://reviews.llvm.org/D33493



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


[PATCH] D33493: Speed up preamble loading

2017-06-08 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 101865.
yvvan added a comment.

Improve commentary. Use StringMap


https://reviews.llvm.org/D33493

Files:
  include/clang/Frontend/ASTUnit.h
  lib/Frontend/ASTUnit.cpp


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -1159,6 +1159,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+PreambleSrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -2601,23 +2603,27 @@
   // remap all the locations to the new view. This includes the diag location,
   // any associated source ranges, and the source ranges of associated fix-its.
   // FIXME: There should be a cleaner way to do this.
-
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
   continue;
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
+FileID FID;
+SourceLocation FileLoc;
+auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
+if (ItFileID == PreambleSrcLocCache.end()) {
   FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  PreambleSrcLocCache[SD.Filename] = FileLoc;
+} else {
+  FileLoc = ItFileID->getValue();
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -188,6 +188,14 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  /// \brief Cache pairs "filename - source location"
+  ///
+  /// Cache contains only source locations from preamble so it is
+  /// guaranteed that they stay valid when the SourceManager is recreated.
+  /// This cache is used when loading preambule to increase performance
+  /// of that loading. It must be cleared when preamble is recreated.
+  llvm::StringMap PreambleSrcLocCache;
+
 public:
   class PreambleData {
 const FileEntry *File;


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -1159,6 +1159,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+PreambleSrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -2601,23 +2603,27 @@
   // remap all the locations to the new view. This includes the diag location,
   // any associated source ranges, and the source ranges of associated fix-its.
   // FIXME: There should be a cleaner way to do this.
-
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
   continue;
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
+FileID FID;
+SourceLocation FileLoc;
+auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
+if (ItFileID == PreambleSrcLocCache.end()) {
   FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  PreambleSrcLocCache[SD.Filename] = FileLoc;
+} else {
+  FileLoc = ItFileID->getValue();
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -188,6 +188,14 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  /// \brief Cache pairs "filename - source location"
+  ///
+  /// Cache contains only source locations from preamble so it is
+  /// guaranteed that they stay valid when the SourceManager is recreated.
+  /// This cache is used when loading preambule to increase performance
+  /// of that loading. It must be cleared when preamble is recreated.
+  llvm::StringMap PreambleSrcLocCache;
+
 public:
   class PreambleData {
 const FileEntry *File;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/l

[PATCH] D33493: Speed up preamble loading

2017-06-08 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 101995.
yvvan added a comment.

"what kind of performance benefits do you get for the preamble load times?"
In cases where many windows headers are included preamble loading takes almost 
the half of reparse time. With this fix time to load preamble goes towards zero.


https://reviews.llvm.org/D33493

Files:
  include/clang/Frontend/ASTUnit.h
  lib/Frontend/ASTUnit.cpp


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -1159,6 +1159,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+PreambleSrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -2601,23 +2603,26 @@
   // remap all the locations to the new view. This includes the diag location,
   // any associated source ranges, and the source ranges of associated fix-its.
   // FIXME: There should be a cleaner way to do this.
-
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
   continue;
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
-  FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+SourceLocation FileLoc;
+auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
+if (ItFileID == PreambleSrcLocCache.end()) {
+  FileID FID = SrcMgr.translateFile(FE);
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  PreambleSrcLocCache[SD.Filename] = FileLoc;
+} else {
+  FileLoc = ItFileID->getValue();
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -188,6 +188,14 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  /// \brief Cache pairs "filename - source location"
+  ///
+  /// Cache contains only source locations from preamble so it is
+  /// guaranteed that they stay valid when the SourceManager is recreated.
+  /// This cache is used when loading preambule to increase performance
+  /// of that loading. It must be cleared when preamble is recreated.
+  llvm::StringMap PreambleSrcLocCache;
+
 public:
   class PreambleData {
 const FileEntry *File;


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -1159,6 +1159,8 @@
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
PreambleDiagnostics, StoredDiagnostics);
+  else
+PreambleSrcLocCache.clear();
 
   if (!Act->Execute())
 goto error;
@@ -2601,23 +2603,26 @@
   // remap all the locations to the new view. This includes the diag location,
   // any associated source ranges, and the source ranges of associated fix-its.
   // FIXME: There should be a cleaner way to do this.
-
   SmallVector Result;
   Result.reserve(Diags.size());
-  const FileEntry *PreviousFE = nullptr;
-  FileID FID;
+
   for (const StandaloneDiagnostic &SD : Diags) {
 // Rebuild the StoredDiagnostic.
 if (SD.Filename.empty())
   continue;
 const FileEntry *FE = FileMgr.getFile(SD.Filename);
 if (!FE)
   continue;
-if (FE != PreviousFE) {
-  FID = SrcMgr.translateFile(FE);
-  PreviousFE = FE;
+SourceLocation FileLoc;
+auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
+if (ItFileID == PreambleSrcLocCache.end()) {
+  FileID FID = SrcMgr.translateFile(FE);
+  FileLoc = SrcMgr.getLocForStartOfFile(FID);
+  PreambleSrcLocCache[SD.Filename] = FileLoc;
+} else {
+  FileLoc = ItFileID->getValue();
 }
-SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
+
 if (FileLoc.isInvalid())
   continue;
 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -188,6 +188,14 @@
   /// some number of calls.
   unsigned PreambleRebuildCounter;
 
+  /// \brief Cache pairs "filename - source location"
+  ///
+  /// Cache contains only source locations from preamble so it is
+  /// guaranteed that they stay valid when the SourceManager is recreated.
+  /// This cache is used when loading preambule to increase performance
+  /// of that loading. It must be cleared when prea

[PATCH] D33644: Add default values for function parameter chunks

2017-06-11 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Can someone check my review please?


https://reviews.llvm.org/D33644



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


[PATCH] D34098: Allow to set incremental processing from CIndex

2017-06-11 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.

Make possible to parse translation Unit in CIndex with incremental processing 
turned on.

1. Why to do that? - Reparse with that option takes less time.
2. What's the affected area? - I don't know. Can someone explain me what 
incremental processing is and what I loose if I parse with that option?


https://reviews.llvm.org/D34098

Files:
  include/clang-c/Index.h
  include/clang/Frontend/ASTUnit.h
  include/clang/Lex/Preprocessor.h
  include/clang/Lex/PreprocessorOptions.h
  lib/Frontend/ASTUnit.cpp
  lib/Lex/Preprocessor.cpp
  tools/libclang/CIndex.cpp

Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -3309,6 +3309,7 @@
   bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
   bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
   bool ForSerialization = options & CXTranslationUnit_ForSerialization;
+  bool IncrementalProcessing = options & CXTranslationUnit_IncrementalProcessing;
 
   // Configure the diagnostics.
   IntrusiveRefCntPtr
@@ -3393,7 +3394,7 @@
   /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
   TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
   /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
-  /*UserFilesAreVolatile=*/true, ForSerialization,
+  /*UserFilesAreVolatile=*/true, ForSerialization, IncrementalProcessing,
   CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
   &ErrUnit));
 
Index: lib/Lex/Preprocessor.cpp
===
--- lib/Lex/Preprocessor.cpp
+++ lib/Lex/Preprocessor.cpp
@@ -942,6 +942,14 @@
   return true;
 }
 
+bool Preprocessor::isIncrementalProcessingEnabled() const {
+  return PPOpts->IncrementalProcessing;
+}
+
+void Preprocessor::enableIncrementalProcessing(bool value) {
+  PPOpts->IncrementalProcessing = value;
+}
+
 ModuleLoader::~ModuleLoader() { }
 
 CommentHandler::~CommentHandler() { }
Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -1985,8 +1985,8 @@
 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
-llvm::Optional ModuleFormat, std::unique_ptr *ErrAST,
-IntrusiveRefCntPtr VFS) {
+bool IncrementalProcessing, llvm::Optional ModuleFormat,
+std::unique_ptr *ErrAST, IntrusiveRefCntPtr VFS) {
   assert(Diags.get() && "no DiagnosticsEngine was provided");
 
   SmallVector StoredDiagnostics;
@@ -2014,6 +2014,7 @@
   PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
   PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0;
   PPOpts.SingleFileParseMode = SingleFileParse;
+  PPOpts.IncrementalProcessing = IncrementalProcessing;
   
   // Override the resources path.
   CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Index: include/clang/Lex/PreprocessorOptions.h
===
--- include/clang/Lex/PreprocessorOptions.h
+++ include/clang/Lex/PreprocessorOptions.h
@@ -98,6 +98,9 @@
   /// When enabled, preprocessor is in a mode for parsing a single file only.
   bool SingleFileParseMode = false;
 
+  /// Do incremental processing
+  bool IncrementalProcessing = false;
+
   /// \brief True if the SourceManager should report the original file name for
   /// contents of files that were remapped to other files. Defaults to true.
   bool RemappedFilesKeepOriginalName;
Index: include/clang/Lex/Preprocessor.h
===
--- include/clang/Lex/Preprocessor.h
+++ include/clang/Lex/Preprocessor.h
@@ -1314,12 +1314,10 @@
   void recomputeCurLexerKind();
 
   /// \brief Returns true if incremental processing is enabled
-  bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; }
+  bool isIncrementalProcessingEnabled() const;
 
   /// \brief Enables the incremental processing
-  void enableIncrementalProcessing(bool value = true) {
-IncrementalProcessing = value;
-  }
+  void enableIncrementalProcessing(bool value = true);
   
   /// \brief Specify the point at which code-completion will be performed.
   ///
Index: include/clang/Frontend/ASTUnit.h
===
--- include/clang/Frontend/ASTUnit.h
+++ include/clang/Frontend/ASTUnit.h
@@ -881,6 +881,7 @@
   bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
   bool SingleFileParse = false,
   bool UserFilesAreVolatile = false, bool ForSerialization = false,
+  bool IncrementalProcessing = false,
   llvm::Optional ModuleFormat =

[PATCH] D33644: Add default values for function parameter chunks

2017-06-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Anyone? :)


https://reviews.llvm.org/D33644



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


[PATCH] D33644: Add default values for function parameter chunks

2017-06-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

In https://reviews.llvm.org/D33644#780188, @klimek wrote:

> Can you give a bit more background what this is trying to do?


Sure :)
Currently default value string does not contain default value itself. This 
change fixes it and adds the default value to the string.


https://reviews.llvm.org/D33644



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


[PATCH] D33644: Add default values for function parameter chunks

2017-06-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:2411-2417
+  const SourceLocation StartLoc = SrcRange.getBegin();
+  const SourceLocation EndLoc = SrcRange.getEnd();
+  if (StartLoc != SM.getExpansionLoc(StartLoc) || EndLoc != 
SM.getExpansionLoc(EndLoc))
+  return "";
+  const size_t PtrDiff = EndLoc.getRawEncoding() - StartLoc.getRawEncoding()
+  + Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
+  return std::string{SM.getCharacterData(StartLoc), PtrDiff};

klimek wrote:
> Can you use Lexer::getSourceText instead?
If that does the same i will use it in the next diff update



Comment at: lib/Sema/SemaCodeComplete.cpp:2453
 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
+if (Param->hasDefaultArg() && PlaceholderStr.find("=") == 
std::string::npos) {
+std::string DefaultValue =

klimek wrote:
> Why the check for = in the PlaceholderStr?
Not to add default value twice. If there's already "=" in placeholder string 
that means we've already added it in FormatFunctionParameter call


https://reviews.llvm.org/D33644



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


[PATCH] D33644: Add default values for function parameter chunks

2017-06-14 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:2453
 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
+if (Param->hasDefaultArg() && PlaceholderStr.find("=") == 
std::string::npos) {
+std::string DefaultValue =

klimek wrote:
> yvvan wrote:
> > klimek wrote:
> > > Why the check for = in the PlaceholderStr?
> > Not to add default value twice. If there's already "=" in placeholder 
> > string that means we've already added it in FormatFunctionParameter call
> In which cases would the default value not be added in 
> FormatFunctionParameter if there is one, and need to be added here?
If Param->evaluateValue() can evaluate it it will set the default value in 
FormatFunctionParameter (that means it's a primitive type like "void func(int i 
= 0)").
In case it's some kind of non-primitive type like "void func(Foo foo = Foo(0, 
0))" it will not be evaluated and we can use here the source manager to get the 
default value string. In this example it will be Foo(0, 0).


https://reviews.llvm.org/D33644



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


[PATCH] D33644: Add default values for function parameter chunks

2017-06-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 102800.
yvvan added a comment.

Use Lexer::getSourceText


https://reviews.llvm.org/D33644

Files:
  lib/Sema/SemaCodeComplete.cpp


Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2282,6 +2282,15 @@
 } else {
   Type.getAsStringInternal(Result, Policy);
 }
+if (Param->hasDefaultArg()) {
+  APValue *defaultValue = Param->evaluateValue();
+  if (defaultValue) {
+std::string defaultValueStr = defaultValue->getAsString(
+Param->getASTContext(), Param->getType());
+if (!defaultValueStr.empty())
+  Result += " = " + defaultValueStr;
+  }
+}
 return Result;
   }
 
@@ -2398,6 +2407,13 @@
   return Result;
 }
 
+static std::string GetDefaultValueString(const ParmVarDecl *Param,
+ const SourceManager &SM,
+ const LangOptions &LangOpts) {
+  const SourceRange SrcRange = Param->getDefaultArg()->getSourceRange();
+  return Lexer::getSourceText(CharSourceRange::getTokenRange(SrcRange), SM, 
LangOpts);
+}
+
 /// \brief Add function parameter chunks to the given code completion string.
 static void AddFunctionParameterChunks(Preprocessor &PP,
const PrintingPolicy &Policy,
@@ -2426,11 +2442,17 @@
   FirstParameter = false;
 else
   Result.AddChunk(CodeCompletionString::CK_Comma);
-
+
 InOptional = false;
 
 // Format the placeholder string.
 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
+if (Param->hasDefaultArg() && PlaceholderStr.find("=") == 
std::string::npos) {
+std::string DefaultValue =
+GetDefaultValueString(Param, PP.getSourceManager(), 
PP.getLangOpts());
+if (!DefaultValue.empty())
+PlaceholderStr += " = " + DefaultValue;
+}
 
 if (Function->isVariadic() && P == N - 1)
   PlaceholderStr += ", ...";
@@ -3012,10 +3034,18 @@
 
 // Format the placeholder string.
 std::string Placeholder;
-if (Function)
-  Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
-else
+if (Function) {
+  const ParmVarDecl *Param = Function->getParamDecl(P);
+  Placeholder = FormatFunctionParameter(Policy, Param);
+  if (Param->hasDefaultArg() && Placeholder.find("=") == 
std::string::npos) {
+std::string DefaultValue =
+GetDefaultValueString(Param, Context.getSourceManager(), 
Context.getLangOpts());
+if (!DefaultValue.empty())
+  Placeholder += " = " + DefaultValue;
+  }
+} else {
   Placeholder = Prototype->getParamType(P).getAsString(Policy);
+}
 
 if (P == CurrentArg)
   Result.AddCurrentParameterChunk(


Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2282,6 +2282,15 @@
 } else {
   Type.getAsStringInternal(Result, Policy);
 }
+if (Param->hasDefaultArg()) {
+  APValue *defaultValue = Param->evaluateValue();
+  if (defaultValue) {
+std::string defaultValueStr = defaultValue->getAsString(
+Param->getASTContext(), Param->getType());
+if (!defaultValueStr.empty())
+  Result += " = " + defaultValueStr;
+  }
+}
 return Result;
   }
 
@@ -2398,6 +2407,13 @@
   return Result;
 }
 
+static std::string GetDefaultValueString(const ParmVarDecl *Param,
+ const SourceManager &SM,
+ const LangOptions &LangOpts) {
+  const SourceRange SrcRange = Param->getDefaultArg()->getSourceRange();
+  return Lexer::getSourceText(CharSourceRange::getTokenRange(SrcRange), SM, LangOpts);
+}
+
 /// \brief Add function parameter chunks to the given code completion string.
 static void AddFunctionParameterChunks(Preprocessor &PP,
const PrintingPolicy &Policy,
@@ -2426,11 +2442,17 @@
   FirstParameter = false;
 else
   Result.AddChunk(CodeCompletionString::CK_Comma);
-
+
 InOptional = false;
 
 // Format the placeholder string.
 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
+if (Param->hasDefaultArg() && PlaceholderStr.find("=") == std::string::npos) {
+std::string DefaultValue =
+GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
+if (!DefaultValue.empty())
+PlaceholderStr += " = " + DefaultValue;
+}
 
 if (Function->isVariadic() && P == N - 1)
   PlaceholderStr += ", ...";
@@ -3012,10 +3034,18 @@
 
 // Format the placeholder string.
 std::string Placeholder;
-if (Function)
-  Placeholder = FormatFunction

[PATCH] D34279: Fix release_40 build with MSVC (VS 2015)

2017-06-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.

I currently have narrowing conversion error without that fix.
I try building with 64 and 32 bit compilers - both reproduce that error.


https://reviews.llvm.org/D34279

Files:
  include/llvm/Target/TargetOpcodes.h


Index: include/llvm/Target/TargetOpcodes.h
===
--- include/llvm/Target/TargetOpcodes.h
+++ include/llvm/Target/TargetOpcodes.h
@@ -19,7 +19,7 @@
 /// Invariant opcodes: All instruction sets have these as their low opcodes.
 ///
 namespace TargetOpcode {
-enum {
+enum : unsigned {
 #define HANDLE_TARGET_OPCODE(OPC) OPC,
 #define HANDLE_TARGET_OPCODE_MARKER(IDENT, OPC) IDENT = OPC,
 #include "llvm/Target/TargetOpcodes.def"


Index: include/llvm/Target/TargetOpcodes.h
===
--- include/llvm/Target/TargetOpcodes.h
+++ include/llvm/Target/TargetOpcodes.h
@@ -19,7 +19,7 @@
 /// Invariant opcodes: All instruction sets have these as their low opcodes.
 ///
 namespace TargetOpcode {
-enum {
+enum : unsigned {
 #define HANDLE_TARGET_OPCODE(OPC) OPC,
 #define HANDLE_TARGET_OPCODE_MARKER(IDENT, OPC) IDENT = OPC,
 #include "llvm/Target/TargetOpcodes.def"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34279: Fix release_40 build with MSVC (VS 2015)

2017-06-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

error list 



https://reviews.llvm.org/D34279



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


[PATCH] D34279: Fix release_40 build with MSVC (VS 2015)

2017-06-16 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I also did not have any local patches applied - just checked out release_40 
branch for llvm and clang.
I believe I also don't have warnings as errors enabled. At least I've checked 
for the extra flags and did not find such. I'll search once again if I have /WX 
somewhere in my build config.
But this patch should not break anything in any case.


https://reviews.llvm.org/D34279



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


[PATCH] D34279: Fix release_40 build with MSVC (VS 2015)

2017-06-18 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I've checked once again. Werror is disabled and no /WX flag is used. So this is 
a compiler error in case of msvc even without these flags.


https://reviews.llvm.org/D34279



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


[PATCH] D34279: Fix release_40 build with MSVC (VS 2015)

2017-06-18 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

btw my cl version is 19.00.24215.1 (MS VS 2015 Update 3). Do you use the same 
one?


https://reviews.llvm.org/D34279



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


[PATCH] D33644: Add default values for function parameter chunks

2017-06-19 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:2453
 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
+if (Param->hasDefaultArg() && PlaceholderStr.find("=") == 
std::string::npos) {
+std::string DefaultValue =

klimek wrote:
> yvvan wrote:
> > klimek wrote:
> > > yvvan wrote:
> > > > klimek wrote:
> > > > > Why the check for = in the PlaceholderStr?
> > > > Not to add default value twice. If there's already "=" in placeholder 
> > > > string that means we've already added it in FormatFunctionParameter call
> > > In which cases would the default value not be added in 
> > > FormatFunctionParameter if there is one, and need to be added here?
> > If Param->evaluateValue() can evaluate it it will set the default value in 
> > FormatFunctionParameter (that means it's a primitive type like "void 
> > func(int i = 0)").
> > In case it's some kind of non-primitive type like "void func(Foo foo = 
> > Foo(0, 0))" it will not be evaluated and we can use here the source manager 
> > to get the default value string. In this example it will be Foo(0, 0).
> Why don't we always add it in the unevaluated form? I'd expect constants from 
> macros are useful to see unevaluated?
Hm, after using Lexer::getSourceText that makes sense! I had some issues 
getting source parts on my own without evaluation in some complicated cases 
with macros usage, etc.
I will test the solution without evaluation and update diff here if nothing 
breaks.


https://reviews.llvm.org/D33644



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


[PATCH] D33644: Add default values for function parameter chunks

2017-06-19 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 103016.
yvvan added a comment.

Do not evaluate numbers.
Check for != "=" is needed not to mess with invalid default arguments or their 
types (without it I get "const Bar& bar = =" when Bar is not defined)


https://reviews.llvm.org/D33644

Files:
  lib/Sema/SemaCodeComplete.cpp


Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2351,6 +2351,13 @@
   return Result;
 }
 
+static std::string GetDefaultValueString(const ParmVarDecl *Param,
+ const SourceManager &SM,
+ const LangOptions &LangOpts) {
+  const SourceRange SrcRange = Param->getDefaultArg()->getSourceRange();
+  return Lexer::getSourceText(CharSourceRange::getTokenRange(SrcRange), SM, 
LangOpts);
+}
+
 /// \brief Add function parameter chunks to the given code completion string.
 static void AddFunctionParameterChunks(Preprocessor &PP,
const PrintingPolicy &Policy,
@@ -2379,11 +2386,17 @@
   FirstParameter = false;
 else
   Result.AddChunk(CodeCompletionString::CK_Comma);
-
+
 InOptional = false;
 
 // Format the placeholder string.
 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
+if (Param->hasDefaultArg()) {
+std::string DefaultValue =
+GetDefaultValueString(Param, PP.getSourceManager(), 
PP.getLangOpts());
+if (!DefaultValue.empty() && DefaultValue != "=")
+PlaceholderStr += " = " + DefaultValue;
+}
 
 if (Function->isVariadic() && P == N - 1)
   PlaceholderStr += ", ...";
@@ -2964,10 +2977,18 @@
 
 // Format the placeholder string.
 std::string Placeholder;
-if (Function)
-  Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
-else
+if (Function) {
+  const ParmVarDecl *Param = Function->getParamDecl(P);
+  Placeholder = FormatFunctionParameter(Policy, Param);
+  if (Param->hasDefaultArg()) {
+std::string DefaultValue =
+GetDefaultValueString(Param, Context.getSourceManager(), 
Context.getLangOpts());
+if (!DefaultValue.empty() && DefaultValue != "=")
+  Placeholder += " = " + DefaultValue;
+  }
+} else {
   Placeholder = Prototype->getParamType(P).getAsString(Policy);
+}
 
 if (P == CurrentArg)
   Result.AddCurrentParameterChunk(


Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2351,6 +2351,13 @@
   return Result;
 }
 
+static std::string GetDefaultValueString(const ParmVarDecl *Param,
+ const SourceManager &SM,
+ const LangOptions &LangOpts) {
+  const SourceRange SrcRange = Param->getDefaultArg()->getSourceRange();
+  return Lexer::getSourceText(CharSourceRange::getTokenRange(SrcRange), SM, LangOpts);
+}
+
 /// \brief Add function parameter chunks to the given code completion string.
 static void AddFunctionParameterChunks(Preprocessor &PP,
const PrintingPolicy &Policy,
@@ -2379,11 +2386,17 @@
   FirstParameter = false;
 else
   Result.AddChunk(CodeCompletionString::CK_Comma);
-
+
 InOptional = false;
 
 // Format the placeholder string.
 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
+if (Param->hasDefaultArg()) {
+std::string DefaultValue =
+GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
+if (!DefaultValue.empty() && DefaultValue != "=")
+PlaceholderStr += " = " + DefaultValue;
+}
 
 if (Function->isVariadic() && P == N - 1)
   PlaceholderStr += ", ...";
@@ -2964,10 +2977,18 @@
 
 // Format the placeholder string.
 std::string Placeholder;
-if (Function)
-  Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
-else
+if (Function) {
+  const ParmVarDecl *Param = Function->getParamDecl(P);
+  Placeholder = FormatFunctionParameter(Policy, Param);
+  if (Param->hasDefaultArg()) {
+std::string DefaultValue =
+GetDefaultValueString(Param, Context.getSourceManager(), Context.getLangOpts());
+if (!DefaultValue.empty() && DefaultValue != "=")
+  Placeholder += " = " + DefaultValue;
+  }
+} else {
   Placeholder = Prototype->getParamType(P).getAsString(Policy);
+}
 
 if (P == CurrentArg)
   Result.AddCurrentParameterChunk(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34279: Fix release_40 build with MSVC (VS 2015)

2017-06-19 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

In https://reviews.llvm.org/D34279#784089, @hans wrote:

> I have 19.00.24210, so slightly earlier I suppose, but I believe we use 
> Update 3 on our Chromium buildbots, and they seem happy.
>
> Can you paste the full error message? The part I see in your screenshot 
> doesn't really make sense. Why should converting 1 to unsigned int be a 
> narrowing conversion? I'm just trying to understand why we need this.


You can look at the file from screenshot and line numbers inside it - there's 
an implicit conversion from the enumeration TargetOpcode (which is signed int 
for my compiler without my change) to the unsigned int.


https://reviews.llvm.org/D34279



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


[PATCH] D34279: Fix release_40 build with MSVC (VS 2015)

2017-06-20 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I've tried once again to make a clean build and it worked... :)
And I can't imagine what kind of configuration issue could it be because I 
always use quite the same one :)


https://reviews.llvm.org/D34279



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2017-12-22 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.
yvvan added reviewers: klimek, bkramer, arphaman, ilya-biryukov, erikjv.

Currently getting such completions requires source correction, reparsing and 
calling completion again. And if it shows no results and rollback is required 
then it costs one more reparse.
With this change it's possible to get all results which can be later filtered 
to split changes which require correction.


https://reviews.llvm.org/D41537

Files:
  include/clang-c/Index.h
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  lib/Frontend/ASTUnit.cpp
  lib/Sema/CodeCompleteConsumer.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/Index/complete-arrow-for-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndexCodeCompletion.cpp

Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -238,6 +238,16 @@
   return cxstring::createRef(CCStr->getBriefComment());
 }
 
+unsigned
+clang_getCompletionRequiresDotToArrowCorrection(CXCompletionString completion_string) {
+  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
+
+  if (!CCStr)
+return false;
+
+  return CCStr->requiresDotToArrowCorrection();
+}
+
 namespace {
 
 /// \brief The CXCodeCompleteResults structure we allocate internally;
@@ -643,13 +653,13 @@
   ArrayRef unsaved_files,
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
+  bool TryArrowInsteadOfDot = options & CXCodeComplete_TryArrowInsteadOfDot;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
 #endif
 #endif
-
   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
 
   if (cxtu::isNotUsableTU(TU)) {
@@ -689,6 +699,7 @@
   // Create a code-completion consumer to capture the results.
   CodeCompleteOptions Opts;
   Opts.IncludeBriefComments = IncludeBriefComments;
+  Opts.TryArrowInsteadOfDot = TryArrowInsteadOfDot;
   CaptureCompletionResults Capture(Opts, *Results, &TU);
 
   // Perform completion.
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -2227,7 +2227,13 @@
 fprintf(file, "(brief comment: %s)", BriefCommentCString);
   }
   clang_disposeString(BriefComment);
-  
+
+  unsigned RequiresDotToArrowCorrection =
+  clang_getCompletionRequiresDotToArrowCorrection(
+  completion_result->CompletionString);
+  if (RequiresDotToArrowCorrection) {
+fprintf(file, " (requires correction: \".\" to \"->\")");
+  }
   fprintf(file, "\n");
 }
 
@@ -2324,6 +2330,8 @@
 completionOptions |= CXCodeComplete_IncludeCodePatterns;
   if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
 completionOptions |= CXCodeComplete_IncludeBriefComments;
+  if (getenv("CINDEXTEST_COMPLETION_TRY_ARROW_INSTEAD_OF_DOT"))
+completionOptions |= CXCodeComplete_TryArrowInsteadOfDot;
   
   if (timing_only)
 input += strlen("-code-completion-timing=");
Index: test/Index/complete-arrow-for-dot.cpp
===
--- /dev/null
+++ test/Index/complete-arrow-for-dot.cpp
@@ -0,0 +1,29 @@
+struct X {
+  void doSomething();
+
+  int field;
+};
+
+void X::doSomething() {
+  // RUN: c-index-test -code-completion-at=%s:10:8 %s | FileCheck %s
+  // RUN: env CINDEXTEST_COMPLETION_TRY_ARROW_INSTEAD_OF_DOT=1 c-index-test -code-completion-at=%s:10:8 %s | FileCheck -check-prefix=CHECK-WITH-CORRECTION %s
+  this.;
+}
+
+// CHECK-NOT: CXXMethod:{ResultType void}{TypedText doSomething}{LeftParen (}{RightParen )} (34) (requires correction: "." to "->")
+// CHECK-NOT: FieldDecl:{ResultType int}{TypedText field} (35) (requires correction: "." to "->")
+// CHECK-NOT: CXXMethod:{ResultType X &}{TypedText operator=}{LeftParen (}{Placeholder const X &}{RightParen )} (79) (requires correction: "." to "->")
+// CHECK-NOT: CXXMethod:{ResultType X &}{TypedText operator=}{LeftParen (}{Placeholder X &&}{RightParen )} (79) (requires correction: "." to "->")
+// CHECK-NOT: StructDecl:{TypedText X}{Text ::} (75) (requires correction: "." to "->")
+// CHECK-NOT: CXXDestructor:{ResultType void}{TypedText ~X}{LeftParen (}{RightParen )} (79) (requires correction: "." to "->")
+// CHECK: Completion contexts:
+// CHECK: Dot member access
+
+// CHECK-WITH-CORRECTION: CXXMethod:{ResultType void}{TypedText doSomething}{LeftParen (}{RightParen )} (34) (requires correction: "." to "->")
+// CHECK-WITH-CORRECTION: FieldDecl:{ResultType int}{TypedText field} (35) (requires correction: "." to "->")
+// CHECK-WITH-CORRECTION: CXXMethod:{ResultType X &}{TypedText operator=}{LeftParen (}{Placeholder const X &}{RightPar

[PATCH] D41005: Reuse preamble even if an unsaved file does not exist

2018-01-03 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

No regression in tests on Windows with and without extra patch ([PATCH] Use 
file path instead of uniqueID)


Repository:
  rC Clang

https://reviews.llvm.org/D41005



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


[PATCH] D40072: [libclang] Support querying whether a declaration is invalid

2018-01-03 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC321697: [libclang] Support querying whether a declaration is 
invalid (authored by yvvan, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D40072?vs=128491&id=128497#toc

Repository:
  rC Clang

https://reviews.llvm.org/D40072

Files:
  include/clang-c/Index.h
  test/Index/print-type-size.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp
  tools/libclang/libclang.exports

Index: test/Index/print-type-size.cpp
===
--- test/Index/print-type-size.cpp
+++ test/Index/print-type-size.cpp
@@ -1,14 +1,14 @@
 // from SemaCXX/class-layout.cpp
 // RUN: c-index-test -test-print-type-size %s -target x86_64-pc-linux-gnu | FileCheck -check-prefix=CHECK64 %s
 // RUN: c-index-test -test-print-type-size %s -target i386-apple-darwin9 | FileCheck -check-prefix=CHECK32 %s
-
-namespace basic {
-
-// CHECK64: VarDecl=v:[[@LINE+2]]:6 (Definition) [type=void] [typekind=Void]
-// CHECK32: VarDecl=v:[[@LINE+1]]:6 (Definition) [type=void] [typekind=Void]
-void v;
-
-// CHECK64: VarDecl=v1:[[@LINE+2]]:7 (Definition) [type=void *] [typekind=Pointer] [sizeof=8] [alignof=8]
+
+namespace basic {
+
+// CHECK64: VarDecl=v:[[@LINE+2]]:6 (Definition) (invalid) [type=void] [typekind=Void]
+// CHECK32: VarDecl=v:[[@LINE+1]]:6 (Definition) (invalid) [type=void] [typekind=Void]
+void v;
+
+// CHECK64: VarDecl=v1:[[@LINE+2]]:7 (Definition) [type=void *] [typekind=Pointer] [sizeof=8] [alignof=8]
 // CHECK32: VarDecl=v1:[[@LINE+1]]:7 (Definition) [type=void *] [typekind=Pointer] [sizeof=4] [alignof=4]
 void *v1;
 
Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -5418,12 +5418,21 @@
 
 unsigned clang_isDeclaration(enum CXCursorKind K) {
   return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
- (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
-}
-
-unsigned clang_isReference(enum CXCursorKind K) {
-  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
-}
+ (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
+}
+
+unsigned clang_isInvalidDeclaration(CXCursor C) {
+  if (clang_isDeclaration(C.kind)) {
+if (const Decl *D = getCursorDecl(C))
+  return D->isInvalidDecl();
+  }
+
+  return 0;
+}
+
+unsigned clang_isReference(enum CXCursorKind K) {
+  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
+}
 
 unsigned clang_isExpression(enum CXCursorKind K) {
   return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -288,12 +288,13 @@
 clang_index_setClientContainer
 clang_index_setClientEntity
 clang_isAttribute
-clang_isConstQualifiedType
-clang_isCursorDefinition
-clang_isDeclaration
-clang_isExpression
-clang_isFileMultipleIncludeGuarded
-clang_isFunctionTypeVariadic
+clang_isConstQualifiedType
+clang_isCursorDefinition
+clang_isDeclaration
+clang_isInvalidDeclaration
+clang_isExpression
+clang_isFileMultipleIncludeGuarded
+clang_isFunctionTypeVariadic
 clang_isInvalid
 clang_isPODType
 clang_isPreprocessing
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -809,12 +809,14 @@
 if (clang_EnumDecl_isScoped(Cursor))
   printf(" (scoped)");
 if (clang_Cursor_isVariadic(Cursor))
-  printf(" (variadic)");
-if (clang_Cursor_isObjCOptional(Cursor))
-  printf(" (@optional)");
-
-switch (clang_getCursorExceptionSpecificationType(Cursor))
-{
+  printf(" (variadic)");
+if (clang_Cursor_isObjCOptional(Cursor))
+  printf(" (@optional)");
+if (clang_isInvalidDeclaration(Cursor))
+  printf(" (invalid)");
+
+switch (clang_getCursorExceptionSpecificationType(Cursor))
+{
   case CXCursor_ExceptionSpecificationKind_None:
 break;
 
Index: include/clang-c/Index.h
===
--- include/clang-c/Index.h
+++ include/clang-c/Index.h
@@ -29,13 +29,13 @@
  * CINDEX_VERSION_MAJOR is intended for "major" source/ABI breaking changes.
  *
  * The policy about the libclang API was always to keep it source and ABI
- * compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
- */
-#define CINDEX_VERSION_MAJOR 0
-#define CINDEX_VERSION_MINOR 45
-
-#define CINDEX_VERSION_ENCODE(major, minor) ( \
-  ((major) * 1)   \
+ * compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
+ */
+#define CINDEX_VERSION_MAJOR 0
+#define CINDEX_VERSION_MINOR 46
+
+#define CINDEX_VERSION_ENCODE(major, minor) ( \
+  ((major) * 1)   

[PATCH] D40561: [libclang] Fix cursors for functions with trailing return type

2018-01-03 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC321698: [libclang] Fix cursors for functions with trailing 
return type (authored by yvvan, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D40561?vs=124576&id=128499#toc

Repository:
  rC Clang

https://reviews.llvm.org/D40561

Files:
  test/Index/annotate-tokens.cpp
  tools/libclang/CIndex.cpp

Index: test/Index/annotate-tokens.cpp
===
--- test/Index/annotate-tokens.cpp
+++ test/Index/annotate-tokens.cpp
@@ -34,13 +34,15 @@
 }
 
 class C {
-  ~C();
-};
-
-// RUN: c-index-test -test-annotate-tokens=%s:1:1:38:1 %s -fno-delayed-template-parsing | FileCheck %s
-// CHECK: Keyword: "struct" [1:1 - 1:7] StructDecl=bonk:1:8 (Definition)
-// CHECK: Identifier: "bonk" [1:8 - 1:12] StructDecl=bonk:1:8 (Definition)
-// CHECK: Punctuation: "{" [1:13 - 1:14] StructDecl=bonk:1:8 (Definition)
+  ~C();
+};
+
+auto test5(X) -> X;
+
+// RUN: c-index-test -test-annotate-tokens=%s:1:1:41:1 %s -std=c++14 -fno-delayed-template-parsing | FileCheck %s
+// CHECK: Keyword: "struct" [1:1 - 1:7] StructDecl=bonk:1:8 (Definition)
+// CHECK: Identifier: "bonk" [1:8 - 1:12] StructDecl=bonk:1:8 (Definition)
+// CHECK: Punctuation: "{" [1:13 - 1:14] StructDecl=bonk:1:8 (Definition)
 // CHECK: Punctuation: "}" [1:15 - 1:16] StructDecl=bonk:1:8 (Definition)
 // CHECK: Punctuation: ";" [1:16 - 1:17]
 // CHECK: Keyword: "void" [2:1 - 2:5] FunctionDecl=test:2:6 (Definition)
@@ -181,12 +183,20 @@
 // CHECK: Punctuation: "(" [29:18 - 29:19] CXXMethod=foo:29:15 (Definition)
 // CHECK: Punctuation: ")" [29:19 - 29:20] CXXMethod=foo:29:15 (Definition)
 // CHECK: Punctuation: "{" [29:21 - 29:22] CompoundStmt=
-// CHECK: Punctuation: "}" [29:22 - 29:23] CompoundStmt=
-// CHECK: Punctuation: "~" [37:3 - 37:4] CXXDestructor=~C:37:3
-// CHECK: Identifier: "C" [37:4 - 37:5] CXXDestructor=~C:37:3
-
-// RUN: env LIBCLANG_DISABLE_CRASH_RECOVERY=1 c-index-test -test-annotate-tokens=%s:32:1:32:13 %s | FileCheck %s -check-prefix=CHECK2
-// CHECK2: Keyword: "if" [32:3 - 32:5] IfStmt=
+// CHECK: Punctuation: "}" [29:22 - 29:23] CompoundStmt=
+// CHECK: Punctuation: "~" [37:3 - 37:4] CXXDestructor=~C:37:3
+// CHECK: Identifier: "C" [37:4 - 37:5] CXXDestructor=~C:37:3
+// CHECK: Keyword: "auto" [40:1 - 40:5] FunctionDecl=test5:40:6
+// CHECK: Identifier: "test5" [40:6 - 40:11] FunctionDecl=test5:40:6
+// CHECK: Punctuation: "(" [40:11 - 40:12] FunctionDecl=test5:40:6
+// CHECK: Identifier: "X" [40:12 - 40:13] TypeRef=struct X:7:8
+// CHECK: Punctuation: ")" [40:13 - 40:14] FunctionDecl=test5:40:6
+// CHECK: Punctuation: "->" [40:15 - 40:17] FunctionDecl=test5:40:6
+// CHECK: Identifier: "X" [40:18 - 40:19] TypeRef=struct X:7:8
+// CHECK: Punctuation: ";" [40:19 - 40:20]
+
+// RUN: env LIBCLANG_DISABLE_CRASH_RECOVERY=1 c-index-test -test-annotate-tokens=%s:32:1:32:13 %s | FileCheck %s -check-prefix=CHECK2
+// CHECK2: Keyword: "if" [32:3 - 32:5] IfStmt=
 // CHECK2: Punctuation: "(" [32:6 - 32:7] IfStmt=
 // CHECK2: Keyword: "int" [32:7 - 32:10] VarDecl=p:32:11 (Definition)
 // CHECK2: Identifier: "p" [32:11 - 32:12] VarDecl=p:32:11 (Definition)
Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -782,12 +782,22 @@
 if (VisitNestedNameSpecifierLoc(QualifierLoc))
   return true;
 
-  return false;
-}
-
-/// \brief Compare two base or member initializers based on their source order.
-static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
-  CXXCtorInitializer *const *Y) {
+  return false;
+}
+
+static bool HasTrailingReturnType(FunctionDecl *ND) {
+  const QualType Ty = ND->getType();
+  if (const FunctionType *AFT = Ty->getAs()) {
+if (const FunctionProtoType *FT = dyn_cast(AFT))
+  return FT->hasTrailingReturn();
+  }
+
+  return false;
+}
+
+/// \brief Compare two base or member initializers based on their source order.
+static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
+  CXXCtorInitializer *const *Y) {
   return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
 }
 
@@ -801,20 +811,22 @@
 
   if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
 // Visit the function declaration's syntactic components in the order
-// written. This requires a bit of work.
-TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
-FunctionTypeLoc FTL = TL.getAs();
-
-// If we have a function declared directly (without the use of a typedef),
-// visit just the return type. Otherwise, just visit the function's type
-// now.
-if ((FTL && !isa(ND) && Visit(FTL.getReturnLoc())) ||
-(!FTL && Visit(TL)))
-  return true;
-
-// Visit the nested-name-specifier, if present.
-if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-01-03 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 128509.
yvvan added a comment.

Update CIndex minor version, add call to libclang.exports


https://reviews.llvm.org/D41537

Files:
  include/clang-c/Index.h
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  lib/Frontend/ASTUnit.cpp
  lib/Sema/CodeCompleteConsumer.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/Index/complete-arrow-for-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -173,6 +173,7 @@
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
+clang_getCompletionRequiresDotToArrowCorrection
 clang_getCursor
 clang_getCursorAvailability
 clang_getCursorCompletionString
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -238,6 +238,16 @@
   return cxstring::createRef(CCStr->getBriefComment());
 }
 
+unsigned
+clang_getCompletionRequiresDotToArrowCorrection(CXCompletionString completion_string) {
+  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
+
+  if (!CCStr)
+return false;
+
+  return CCStr->requiresDotToArrowCorrection();
+}
+
 namespace {
 
 /// \brief The CXCodeCompleteResults structure we allocate internally;
@@ -643,13 +653,13 @@
   ArrayRef unsaved_files,
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
+  bool TryArrowInsteadOfDot = options & CXCodeComplete_TryArrowInsteadOfDot;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
 #endif
 #endif
-
   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
 
   if (cxtu::isNotUsableTU(TU)) {
@@ -689,6 +699,7 @@
   // Create a code-completion consumer to capture the results.
   CodeCompleteOptions Opts;
   Opts.IncludeBriefComments = IncludeBriefComments;
+  Opts.TryArrowInsteadOfDot = TryArrowInsteadOfDot;
   CaptureCompletionResults Capture(Opts, *Results, &TU);
 
   // Perform completion.
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -2229,7 +2229,13 @@
 fprintf(file, "(brief comment: %s)", BriefCommentCString);
   }
   clang_disposeString(BriefComment);
-  
+
+  unsigned RequiresDotToArrowCorrection =
+  clang_getCompletionRequiresDotToArrowCorrection(
+  completion_result->CompletionString);
+  if (RequiresDotToArrowCorrection) {
+fprintf(file, " (requires correction: \".\" to \"->\")");
+  }
   fprintf(file, "\n");
 }
 
@@ -2326,6 +2332,8 @@
 completionOptions |= CXCodeComplete_IncludeCodePatterns;
   if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
 completionOptions |= CXCodeComplete_IncludeBriefComments;
+  if (getenv("CINDEXTEST_COMPLETION_TRY_ARROW_INSTEAD_OF_DOT"))
+completionOptions |= CXCodeComplete_TryArrowInsteadOfDot;
   
   if (timing_only)
 input += strlen("-code-completion-timing=");
Index: test/Index/complete-arrow-for-dot.cpp
===
--- /dev/null
+++ test/Index/complete-arrow-for-dot.cpp
@@ -0,0 +1,29 @@
+struct X {
+  void doSomething();
+
+  int field;
+};
+
+void X::doSomething() {
+  // RUN: c-index-test -code-completion-at=%s:10:8 %s | FileCheck %s
+  // RUN: env CINDEXTEST_COMPLETION_TRY_ARROW_INSTEAD_OF_DOT=1 c-index-test -code-completion-at=%s:10:8 %s | FileCheck -check-prefix=CHECK-WITH-CORRECTION %s
+  this.;
+}
+
+// CHECK-NOT: CXXMethod:{ResultType void}{TypedText doSomething}{LeftParen (}{RightParen )} (34) (requires correction: "." to "->")
+// CHECK-NOT: FieldDecl:{ResultType int}{TypedText field} (35) (requires correction: "." to "->")
+// CHECK-NOT: CXXMethod:{ResultType X &}{TypedText operator=}{LeftParen (}{Placeholder const X &}{RightParen )} (79) (requires correction: "." to "->")
+// CHECK-NOT: CXXMethod:{ResultType X &}{TypedText operator=}{LeftParen (}{Placeholder X &&}{RightParen )} (79) (requires correction: "." to "->")
+// CHECK-NOT: StructDecl:{TypedText X}{Text ::} (75) (requires correction: "." to "->")
+// CHECK-NOT: CXXDestructor:{ResultType void}{TypedText ~X}{LeftParen (}{RightParen )} (79) (requires correction: "." to "->")
+// CHECK: Completion contexts:
+// CHECK: Dot member access
+
+// CHECK-WITH-CORRECTION: CXXMethod:{ResultType void}{TypedText doSomething}{LeftParen (}{RightParen )} (34) (requires correction: "." to "->")
+// CHECK-WITH-CORRECTION: FieldDecl:{ResultType int}{TypedText fi

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-01-10 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

ping


https://reviews.llvm.org/D41537



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


[PATCH] D35200: Don't use mmap on Windows

2018-03-12 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan abandoned this revision.
yvvan added a comment.

It was the wrong direction


https://reviews.llvm.org/D35200



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


[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-03-13 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 138139.
yvvan added a comment.

Return possibly required corrections in the string form


https://reviews.llvm.org/D41537

Files:
  include/clang-c/Index.h
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/CodeCompleteConsumer.h
  include/clang/Sema/CodeCompleteOptions.h
  include/clang/Sema/Sema.h
  lib/Frontend/ASTUnit.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/CodeCompleteConsumer.cpp
  lib/Sema/SemaCodeComplete.cpp
  test/FixIt/fixit.cpp
  test/Index/complete-arrow-dot.cpp
  test/SemaCXX/member-expr.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -170,6 +170,7 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionCorrection
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -238,6 +238,20 @@
   return cxstring::createRef(CCStr->getBriefComment());
 }
 
+CXString
+clang_getCompletionCorrection(CXCompletionString completion_string) {
+  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
+
+  if (!CCStr)
+return cxstring::createNull();
+
+  const Optional &Corr = CCStr->getCorrection();
+  if (!Corr)
+  return cxstring::createNull();
+
+  return cxstring::createRef(Corr->c_str());
+}
+
 namespace {
 
 /// \brief The CXCodeCompleteResults structure we allocate internally;
@@ -644,6 +658,7 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeCorrections = options & CXCodeComplete_IncludeCorrections;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
@@ -650,7 +665,6 @@
   const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
 #endif
 #endif
-
   bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
 
   if (cxtu::isNotUsableTU(TU)) {
@@ -691,6 +705,7 @@
   CodeCompleteOptions Opts;
   Opts.IncludeBriefComments = IncludeBriefComments;
   Opts.LoadExternal = !SkipPreamble;
+  Opts.IncludeCorrections = IncludeCorrections;
   CaptureCompletionResults Capture(Opts, *Results, &TU);
 
   // Perform completion.
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -2276,6 +2276,7 @@
   CXString ParentName;
   CXString BriefComment;
   CXString Annotation;
+  CXString Corr;
   const char *BriefCommentCString;
   
   fprintf(file, "%s:", clang_getCString(ks));
@@ -2337,7 +2338,10 @@
 fprintf(file, "(brief comment: %s)", BriefCommentCString);
   }
   clang_disposeString(BriefComment);
-  
+
+  Corr = clang_getCompletionCorrection(completion_result->CompletionString);
+  fprintf(file, " (requires correction to \"%s\")", clang_getCString(Corr));
+
   fprintf(file, "\n");
 }
 
@@ -2436,6 +2440,8 @@
 completionOptions |= CXCodeComplete_IncludeBriefComments;
   if (getenv("CINDEXTEST_COMPLETION_SKIP_PREAMBLE"))
 completionOptions |= CXCodeComplete_SkipPreamble;
+  if (getenv("CINDEXTEST_COMPLETION_INCLUDE_CORRECTIONS"))
+completionOptions |= CXCodeComplete_IncludeCorrections;
   
   if (timing_only)
 input += strlen("-code-completion-timing=");
Index: test/SemaCXX/member-expr.cpp
===
--- test/SemaCXX/member-expr.cpp
+++ test/SemaCXX/member-expr.cpp
@@ -188,6 +188,11 @@
 return c->a;  // expected-error {{member reference type 'PR15045::Cl0' is not a pointer; did you mean to use '.'?}}
   }
 
+  int g() {
+Cl0* c;
+return c.a;  // expected-error {{member reference type 'PR15045::Cl0 *' is a pointer; did you mean to use '->'?}}
+  }
+
   struct bar {
 void func();  // expected-note {{'func' declared here}}
   };
Index: test/Index/complete-arrow-dot.cpp
===
--- test/Index/complete-arrow-dot.cpp
+++ test/Index/complete-arrow-dot.cpp
@@ -0,0 +1,54 @@
+struct X {
+  void doSomething();
+
+  int field;
+};
+
+void X::doSomething() {
+  // RUN: c-index-test -code-completion-at=%s:10:8 %s | FileCheck %s
+  // RUN: env CINDEXTEST_COMPLETION_INCLUDE_CORRECTIONS=1 c-index-test -code-completion-at=%s:10:8 %s | FileCheck -check-prefix=CHECK-WITH-CORRECTION %s
+  this.;
+}
+
+void doSomething() {
+  // RUN: c-index-test -code-completion-at=%s:17:6 %s | FileCheck -check-prefix=CHECK-ARROW-TO-DOT %

[PATCH] D44426: Fix llvm + clang build with Intel compiler

2018-03-13 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.
yvvan added reviewers: bkramer, klimek.
Herald added subscribers: JDevlieghere, nhaehnle, arsenm.
Herald added a reviewer: deadalnix.

I've tested it on Windows with 64-bit icl

These are mostly workarounds for 
https://software.intel.com/en-us/comment/1919743 , 
https://software.intel.com/en-us/forums/intel-c-compiler/topic/749369 and few 
more enum-related issues


https://reviews.llvm.org/D44426

Files:
  include/llvm-c/Target.h
  include/llvm/ADT/BitmaskEnum.h
  include/llvm/Analysis/AliasAnalysis.h
  lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp
  lib/Target/AMDGPU/SIISelLowering.cpp
  tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
  tools/llvm-nm/llvm-nm.cpp

Index: tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
===
--- tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
+++ tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
@@ -282,8 +282,12 @@
 
   /// SExpr objects cannot be deleted.
   // This declaration is public to workaround a gcc bug that breaks building
-  // with REQUIRES_EH=1.
+  // with REQUIRES_EH=1. Do not mark it 'delete' to avoid error with intel compiler.
+#ifdef __INTEL_COMPILER
+  void operator delete(void *);
+#else
   void operator delete(void *) = delete;
+#endif
 
   /// Returns the instruction ID for this expression.
   /// All basic block instructions have a unique ID (i.e. virtual register).
Index: tools/llvm-nm/llvm-nm.cpp
===
--- tools/llvm-nm/llvm-nm.cpp
+++ tools/llvm-nm/llvm-nm.cpp
@@ -876,14 +876,14 @@
 case ELF::SHT_PROGBITS:
 case ELF::SHT_DYNAMIC:
   switch (SecI->getFlags()) {
-  case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
+  case (ELF::SHF_ALLOC | static_cast(ELF::SHF_EXECINSTR)):
 return 't';
-  case (ELF::SHF_TLS | ELF::SHF_ALLOC | ELF::SHF_WRITE):
-  case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
+  case (ELF::SHF_TLS | static_cast(ELF::SHF_ALLOC) | static_cast(ELF::SHF_WRITE)):
+  case (ELF::SHF_ALLOC | static_cast(ELF::SHF_WRITE)):
 return 'd';
   case ELF::SHF_ALLOC:
-  case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
-  case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
+  case (ELF::SHF_ALLOC | static_cast(ELF::SHF_MERGE)):
+  case (ELF::SHF_ALLOC | static_cast(ELF::SHF_MERGE) | static_cast(ELF::SHF_STRINGS)):
 return 'r';
   }
   break;
Index: lib/Target/AMDGPU/SIISelLowering.cpp
===
--- lib/Target/AMDGPU/SIISelLowering.cpp
+++ lib/Target/AMDGPU/SIISelLowering.cpp
@@ -6128,11 +6128,13 @@
   SIInstrFlags::P_SUBNORMAL |
   SIInstrFlags::P_NORMAL;
 
+#ifndef __INTEL_COMPILER
 static_assert(((~(SIInstrFlags::S_NAN |
   SIInstrFlags::Q_NAN |
   SIInstrFlags::N_INFINITY |
   SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
   "mask not equal");
+#endif
 
 SDLoc DL(N);
 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
Index: lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp
===
--- lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp
+++ lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp
@@ -76,24 +76,24 @@
 return "sdata4";
   case dwarf::DW_EH_PE_sdata8:
 return "sdata8";
-  case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
+  case dwarf::DW_EH_PE_pcrel | static_cast(dwarf::DW_EH_PE_udata4):
 return "pcrel udata4";
-  case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
+  case dwarf::DW_EH_PE_pcrel | static_cast(dwarf::DW_EH_PE_sdata4):
 return "pcrel sdata4";
-  case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
+  case dwarf::DW_EH_PE_pcrel | static_cast(dwarf::DW_EH_PE_udata8):
 return "pcrel udata8";
-  case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
+  case dwarf::DW_EH_PE_pcrel | static_cast(dwarf::DW_EH_PE_sdata8):
 return "pcrel sdata8";
-  case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4
+  case dwarf::DW_EH_PE_indirect | static_cast(dwarf::DW_EH_PE_pcrel) | static_cast(dwarf::DW_EH_PE_udata4)
   :
 return "indirect pcrel udata4";
-  case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
+  case dwarf::DW_EH_PE_indirect | static_cast(dwarf::DW_EH_PE_pcrel) | static_cast(dwarf::DW_EH_PE_sdata4)
   :
 return "indirect pcrel sdata4";
-  case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8
+  case dwarf::DW_EH_PE_indirect | static_cast(dwarf::DW_EH_PE_pcrel) | static_cast(dwarf::DW_EH_PE_udata8)
   :
 return "indirect pcrel udata8";
-  case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8
+  case dwarf::DW_EH_PE_indirect | static_cast(dwarf::DW

[PATCH] D41537: Optionally add code completion results for arrow instead of dot

2018-03-19 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Ping


https://reviews.llvm.org/D41537



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


[PATCH] D44426: Fix llvm + clang build with Intel compiler

2018-03-19 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

@nhaehnle And that's the problem. There's no build machine for intel compiler 
and nobody cares.
And if somebody like me want to build it - there's no solution rather than 
searching for workarounds yourself.
This patch is not that complex in the end as you see so it should be possible 
to support one more compiler with not too many headache.

That's why I suggest this patch to at least make people know that it's possible 
to build. Or probably to grab someone's interest to the problem and set up 
builds.


https://reviews.llvm.org/D44426



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


[PATCH] D47460: Treat files as volatile by default

2018-05-30 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Memory mapping locks the file on Windows. That means that in the addressed case 
it locks main file which we are editing. After that happens many tools struggle 
to do something with this file, for example git.
It's the quickest solution, probably not the best. Better one would introduce 
isVolatile parameter in FileSystem::getBufferForFile which should be set to 
true somewhere (I didn't have to to search for the specific location yet)


https://reviews.llvm.org/D47460



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


[PATCH] D47460: Treat files as volatile by default

2018-05-31 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 149249.
yvvan added a comment.

This is the proper fix. When we get a buffer for main file we should use the 
UserFilesAreVolatile flag to specify if memory mapping needs to occur or not.


https://reviews.llvm.org/D47460

Files:
  lib/Frontend/ASTUnit.cpp


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -100,7 +100,8 @@
 static std::unique_ptr
 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
   vfs::FileSystem *VFS,
-  StringRef FilePath) {
+  StringRef FilePath,
+  bool isVolatile) {
   const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
 
   // Try to determine if the main file has been remapped, either from the
@@ -120,7 +121,8 @@
 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
 if (MainFileID == MID) {
   // We found a remapping. Try to load the resulting, remapped source.
-  BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
+  BufferOwner = valueOrNull(
+  VFS->getBufferForFile(RF.second, -1, true, isVolatile));
   if (!BufferOwner)
 return nullptr;
 }
@@ -145,7 +147,8 @@
 
   // If the main source file was not remapped, load it now.
   if (!Buffer && !BufferOwner) {
-BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
+BufferOwner =
+valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
 if (!BufferOwner)
   return nullptr;
   }
@@ -1231,7 +1234,7 @@
   PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
   std::unique_ptr MainFileBuffer =
   getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
-MainFilePath);
+MainFilePath, UserFilesAreVolatile);
   if (!MainFileBuffer)
 return nullptr;
 


Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -100,7 +100,8 @@
 static std::unique_ptr
 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
   vfs::FileSystem *VFS,
-  StringRef FilePath) {
+  StringRef FilePath,
+  bool isVolatile) {
   const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
 
   // Try to determine if the main file has been remapped, either from the
@@ -120,7 +121,8 @@
 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
 if (MainFileID == MID) {
   // We found a remapping. Try to load the resulting, remapped source.
-  BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
+  BufferOwner = valueOrNull(
+  VFS->getBufferForFile(RF.second, -1, true, isVolatile));
   if (!BufferOwner)
 return nullptr;
 }
@@ -145,7 +147,8 @@
 
   // If the main source file was not remapped, load it now.
   if (!Buffer && !BufferOwner) {
-BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
+BufferOwner =
+valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
 if (!BufferOwner)
   return nullptr;
   }
@@ -1231,7 +1234,7 @@
   PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
   std::unique_ptr MainFileBuffer =
   getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
-MainFilePath);
+MainFilePath, UserFilesAreVolatile);
   if (!MainFileBuffer)
 return nullptr;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D47460: [Frontend] Honor UserFilesAreVolatile flag getting file buffer in ASTUnit

2018-06-01 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

In https://reviews.llvm.org/D47460#1118694, @ilya-biryukov wrote:

> Is it plausible to add a unit-test for this?


i think I can add a unit-test for it since we have the 'getBufferKind' method 
in MemoryBuffer.


https://reviews.llvm.org/D47460



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


[PATCH] D47460: [Frontend] Honor UserFilesAreVolatile flag getting file buffer in ASTUnit

2018-06-04 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 149683.
yvvan added a comment.

I could not properly test getMainBufferWithPrecompiledPreamble because it's 
private and requires some extra context to be called.

But there's another getBufferForFile call in ASTUnit which has similar symptoms 
and might cause wrong mmap behavior. I've also appended it with the same 
parameter 'UserFilesAreVolatile' and added unit-test for it.


https://reviews.llvm.org/D47460

Files:
  include/clang/Basic/FileManager.h
  lib/Basic/FileManager.cpp
  lib/Frontend/ASTUnit.cpp
  unittests/Frontend/ASTUnitTest.cpp

Index: unittests/Frontend/ASTUnitTest.cpp
===
--- unittests/Frontend/ASTUnitTest.cpp
+++ unittests/Frontend/ASTUnitTest.cpp
@@ -18,6 +18,33 @@
 #include "llvm/Support/ToolOutputFile.h"
 #include "gtest/gtest.h"
 
+#define CREATE_AST_UNIT(isVolatile)\
+  int FD;  \
+  llvm::SmallString<256> InputFileName;\
+  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD,   \
+  InputFileName)); \
+  ToolOutputFile input_file(InputFileName, FD);\
+  input_file.os() << "";   \
+   \
+  const char *Args[] = {"clang", "-xc++", InputFileName.c_str()};  \
+   \
+  IntrusiveRefCntPtr Diags =\
+  CompilerInstance::createDiagnostics(new DiagnosticOptions());\
+   \
+  std::shared_ptr CInvok = \
+  createInvocationFromCommandLine(Args, Diags);\
+   \
+  if (!CInvok) \
+FAIL() << "could not create compiler invocation";  \
+   \
+  FileManager *FileMgr =   \
+  new FileManager(FileSystemOptions(), vfs::getRealFileSystem());  \
+  auto PCHContainerOps = std::make_shared();   \
+   \
+  std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation(  \
+  CInvok, PCHContainerOps, Diags, FileMgr, false, false, 0, TU_Complete,   \
+  false, false, isVolatile);
+
 using namespace llvm;
 using namespace clang;
 
@@ -38,29 +65,7 @@
 EXPECT_TRUE(PolicyWithDefaultLangOpt.UseVoidForZeroParams);
   }
 
-  int FD;
-  llvm::SmallString<256> InputFileName;
-  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD, InputFileName));
-  ToolOutputFile input_file(InputFileName, FD);
-  input_file.os() << "";
-
-  const char* Args[] = {"clang", "-xc++", InputFileName.c_str()};
-
-  IntrusiveRefCntPtr Diags =
-  CompilerInstance::createDiagnostics(new DiagnosticOptions());
-
-  std::shared_ptr CInvok =
-  createInvocationFromCommandLine(Args, Diags);
-
-  if (!CInvok)
-FAIL() << "could not create compiler invocation";
-
-  FileManager *FileMgr =
-  new FileManager(FileSystemOptions(), vfs::getRealFileSystem());
-  auto PCHContainerOps = std::make_shared();
-
-  std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation(
-  CInvok, PCHContainerOps, Diags, FileMgr);
+  CREATE_AST_UNIT(false);
 
   if (!AST)
 FAIL() << "failed to create ASTUnit";
@@ -84,4 +89,17 @@
   EXPECT_FALSE(AU->getASTContext().getPrintingPolicy().UseVoidForZeroParams);
 }
 
+TEST(ASTUnit, GetBufferForFileMemoryMapping) {
+CREATE_AST_UNIT(true);
+
+if (!AST)
+  FAIL() << "failed to create ASTUnit";
+
+std::unique_ptr memoryBuffer =
+AST->getBufferForFile(InputFileName);
+
+EXPECT_NE(memoryBuffer->getBufferKind(),
+  llvm::MemoryBuffer::MemoryBuffer_MMap);
+}
+
 } // anonymous namespace
Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -156,7 +156,8 @@
 static std::unique_ptr
 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
   vfs::FileSystem *VFS,
-  StringRef FilePath) {
+  StringRef FilePath,
+  bool isVolatile) {
   const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
 
   // Try to determine if the main file has been remapped, either 

[PATCH] D47460: [Frontend] Honor UserFilesAreVolatile flag getting file buffer in ASTUnit

2018-06-04 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 149684.
yvvan added a comment.

fix indentation in unit-test


https://reviews.llvm.org/D47460

Files:
  include/clang/Basic/FileManager.h
  lib/Basic/FileManager.cpp
  lib/Frontend/ASTUnit.cpp
  unittests/Frontend/ASTUnitTest.cpp

Index: unittests/Frontend/ASTUnitTest.cpp
===
--- unittests/Frontend/ASTUnitTest.cpp
+++ unittests/Frontend/ASTUnitTest.cpp
@@ -18,6 +18,33 @@
 #include "llvm/Support/ToolOutputFile.h"
 #include "gtest/gtest.h"
 
+#define CREATE_AST_UNIT(isVolatile)\
+  int FD;  \
+  llvm::SmallString<256> InputFileName;\
+  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD,   \
+  InputFileName)); \
+  ToolOutputFile input_file(InputFileName, FD);\
+  input_file.os() << "";   \
+   \
+  const char *Args[] = {"clang", "-xc++", InputFileName.c_str()};  \
+   \
+  IntrusiveRefCntPtr Diags =\
+  CompilerInstance::createDiagnostics(new DiagnosticOptions());\
+   \
+  std::shared_ptr CInvok = \
+  createInvocationFromCommandLine(Args, Diags);\
+   \
+  if (!CInvok) \
+FAIL() << "could not create compiler invocation";  \
+   \
+  FileManager *FileMgr =   \
+  new FileManager(FileSystemOptions(), vfs::getRealFileSystem());  \
+  auto PCHContainerOps = std::make_shared();   \
+   \
+  std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation(  \
+  CInvok, PCHContainerOps, Diags, FileMgr, false, false, 0, TU_Complete,   \
+  false, false, isVolatile);
+
 using namespace llvm;
 using namespace clang;
 
@@ -38,29 +65,7 @@
 EXPECT_TRUE(PolicyWithDefaultLangOpt.UseVoidForZeroParams);
   }
 
-  int FD;
-  llvm::SmallString<256> InputFileName;
-  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD, InputFileName));
-  ToolOutputFile input_file(InputFileName, FD);
-  input_file.os() << "";
-
-  const char* Args[] = {"clang", "-xc++", InputFileName.c_str()};
-
-  IntrusiveRefCntPtr Diags =
-  CompilerInstance::createDiagnostics(new DiagnosticOptions());
-
-  std::shared_ptr CInvok =
-  createInvocationFromCommandLine(Args, Diags);
-
-  if (!CInvok)
-FAIL() << "could not create compiler invocation";
-
-  FileManager *FileMgr =
-  new FileManager(FileSystemOptions(), vfs::getRealFileSystem());
-  auto PCHContainerOps = std::make_shared();
-
-  std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation(
-  CInvok, PCHContainerOps, Diags, FileMgr);
+  CREATE_AST_UNIT(false);
 
   if (!AST)
 FAIL() << "failed to create ASTUnit";
@@ -84,4 +89,17 @@
   EXPECT_FALSE(AU->getASTContext().getPrintingPolicy().UseVoidForZeroParams);
 }
 
+TEST(ASTUnit, GetBufferForFileMemoryMapping) {
+  CREATE_AST_UNIT(true);
+
+  if (!AST)
+FAIL() << "failed to create ASTUnit";
+
+  std::unique_ptr memoryBuffer =
+  AST->getBufferForFile(InputFileName);
+
+  EXPECT_NE(memoryBuffer->getBufferKind(),
+llvm::MemoryBuffer::MemoryBuffer_MMap);
+}
+
 } // anonymous namespace
Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -156,7 +156,8 @@
 static std::unique_ptr
 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
   vfs::FileSystem *VFS,
-  StringRef FilePath) {
+  StringRef FilePath,
+  bool isVolatile) {
   const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
 
   // Try to determine if the main file has been remapped, either from the
@@ -176,7 +177,7 @@
 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
 if (MainFileID == MID) {
   // We found a remapping. Try to load the resulting, remapped source.
-  BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
+  BufferOwner = valueOrNull(VFS->getBuffer

[PATCH] D47460: [Frontend] Honor UserFilesAreVolatile flag getting file buffer in ASTUnit

2018-06-04 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 149697.
yvvan added a comment.

Use fixture in unit-test


https://reviews.llvm.org/D47460

Files:
  include/clang/Basic/FileManager.h
  lib/Basic/FileManager.cpp
  lib/Frontend/ASTUnit.cpp
  unittests/Frontend/ASTUnitTest.cpp

Index: unittests/Frontend/ASTUnitTest.cpp
===
--- unittests/Frontend/ASTUnitTest.cpp
+++ unittests/Frontend/ASTUnitTest.cpp
@@ -23,7 +23,41 @@
 
 namespace {
 
-TEST(ASTUnit, SaveLoadPreservesLangOptionsInPrintingPolicy) {
+class ASTUnitTest : public ::testing::Test {
+protected:
+  int FD;
+  llvm::SmallString<256> InputFileName;
+  std::unique_ptr input_file;
+  IntrusiveRefCntPtr Diags;
+  std::shared_ptr CInvok;
+  std::shared_ptr PCHContainerOps;
+
+  std::unique_ptr createASTUnit(bool isVolatile) {
+EXPECT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD,
+InputFileName));
+input_file = std::make_unique(InputFileName, FD);
+input_file->os() << "";
+
+const char *Args[] = {"clang", "-xc++", InputFileName.c_str()};
+
+Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
+
+CInvok = createInvocationFromCommandLine(Args, Diags);
+
+if (!CInvok)
+  return nullptr;
+
+FileManager *FileMgr =
+new FileManager(FileSystemOptions(), vfs::getRealFileSystem());
+PCHContainerOps = std::make_shared();
+
+return ASTUnit::LoadFromCompilerInvocation(
+CInvok, PCHContainerOps, Diags, FileMgr, false, false, 0, TU_Complete,
+false, false, isVolatile);
+  }
+};
+
+TEST_F(ASTUnitTest, SaveLoadPreservesLangOptionsInPrintingPolicy) {
   // Check that the printing policy is restored with the correct language
   // options when loading an ASTUnit from a file.  To this end, an ASTUnit
   // for a C++ translation unit is set up and written to a temporary file.
@@ -38,50 +72,43 @@
 EXPECT_TRUE(PolicyWithDefaultLangOpt.UseVoidForZeroParams);
   }
 
-  int FD;
-  llvm::SmallString<256> InputFileName;
-  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD, InputFileName));
-  ToolOutputFile input_file(InputFileName, FD);
-  input_file.os() << "";
-
-  const char* Args[] = {"clang", "-xc++", InputFileName.c_str()};
-
-  IntrusiveRefCntPtr Diags =
-  CompilerInstance::createDiagnostics(new DiagnosticOptions());
-
-  std::shared_ptr CInvok =
-  createInvocationFromCommandLine(Args, Diags);
-
-  if (!CInvok)
-FAIL() << "could not create compiler invocation";
-
-  FileManager *FileMgr =
-  new FileManager(FileSystemOptions(), vfs::getRealFileSystem());
-  auto PCHContainerOps = std::make_shared();
-
-  std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation(
-  CInvok, PCHContainerOps, Diags, FileMgr);
+  std::unique_ptr AST = createASTUnit(false);
 
   if (!AST)
 FAIL() << "failed to create ASTUnit";
 
   EXPECT_FALSE(AST->getASTContext().getPrintingPolicy().UseVoidForZeroParams);
 
   llvm::SmallString<256> ASTFileName;
-  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "ast", FD, ASTFileName));
+  ASSERT_FALSE(
+  llvm::sys::fs::createTemporaryFile("ast-unit", "ast", FD, ASTFileName));
   ToolOutputFile ast_file(ASTFileName, FD);
   AST->Save(ASTFileName.str());
 
   EXPECT_TRUE(llvm::sys::fs::exists(ASTFileName));
 
   std::unique_ptr AU = ASTUnit::LoadFromASTFile(
-  ASTFileName.str(), PCHContainerOps->getRawReader(), ASTUnit::LoadEverything, Diags,
-  FileSystemOptions(), /*UseDebugInfo=*/false);
+  ASTFileName.str(), PCHContainerOps->getRawReader(),
+  ASTUnit::LoadEverything, Diags, FileSystemOptions(),
+  /*UseDebugInfo=*/false);
 
   if (!AU)
 FAIL() << "failed to load ASTUnit";
 
   EXPECT_FALSE(AU->getASTContext().getPrintingPolicy().UseVoidForZeroParams);
 }
 
+TEST_F(ASTUnitTest, GetBufferForFileMemoryMapping) {
+  std::unique_ptr AST = createASTUnit(true);
+
+  if (!AST)
+FAIL() << "failed to create ASTUnit";
+
+  std::unique_ptr memoryBuffer =
+  AST->getBufferForFile(InputFileName);
+
+  EXPECT_NE(memoryBuffer->getBufferKind(),
+llvm::MemoryBuffer::MemoryBuffer_MMap);
+}
+
 } // anonymous namespace
Index: lib/Frontend/ASTUnit.cpp
===
--- lib/Frontend/ASTUnit.cpp
+++ lib/Frontend/ASTUnit.cpp
@@ -156,7 +156,8 @@
 static std::unique_ptr
 getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
   vfs::FileSystem *VFS,
-  StringRef FilePath) {
+  StringRef FilePath,
+  bool isVolatile) {
   const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
 
   // Try to determine if the main file has been remapped, either from the
@@ -176,7 +177,7 @@
 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
 if (MainFileID == MID)

[PATCH] D47460: [Frontend] Honor UserFilesAreVolatile flag getting file buffer in ASTUnit

2018-06-06 Thread Ivan Donchevskii via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL334070: [Frontend] Honor UserFilesAreVolatile flag getting 
file buffer in ASTUnit (authored by yvvan, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D47460?vs=149697&id=150080#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D47460

Files:
  cfe/trunk/include/clang/Basic/FileManager.h
  cfe/trunk/lib/Basic/FileManager.cpp
  cfe/trunk/lib/Frontend/ASTUnit.cpp
  cfe/trunk/unittests/Frontend/ASTUnitTest.cpp

Index: cfe/trunk/unittests/Frontend/ASTUnitTest.cpp
===
--- cfe/trunk/unittests/Frontend/ASTUnitTest.cpp
+++ cfe/trunk/unittests/Frontend/ASTUnitTest.cpp
@@ -23,7 +23,41 @@
 
 namespace {
 
-TEST(ASTUnit, SaveLoadPreservesLangOptionsInPrintingPolicy) {
+class ASTUnitTest : public ::testing::Test {
+protected:
+  int FD;
+  llvm::SmallString<256> InputFileName;
+  std::unique_ptr input_file;
+  IntrusiveRefCntPtr Diags;
+  std::shared_ptr CInvok;
+  std::shared_ptr PCHContainerOps;
+
+  std::unique_ptr createASTUnit(bool isVolatile) {
+EXPECT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD,
+InputFileName));
+input_file = std::make_unique(InputFileName, FD);
+input_file->os() << "";
+
+const char *Args[] = {"clang", "-xc++", InputFileName.c_str()};
+
+Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
+
+CInvok = createInvocationFromCommandLine(Args, Diags);
+
+if (!CInvok)
+  return nullptr;
+
+FileManager *FileMgr =
+new FileManager(FileSystemOptions(), vfs::getRealFileSystem());
+PCHContainerOps = std::make_shared();
+
+return ASTUnit::LoadFromCompilerInvocation(
+CInvok, PCHContainerOps, Diags, FileMgr, false, false, 0, TU_Complete,
+false, false, isVolatile);
+  }
+};
+
+TEST_F(ASTUnitTest, SaveLoadPreservesLangOptionsInPrintingPolicy) {
   // Check that the printing policy is restored with the correct language
   // options when loading an ASTUnit from a file.  To this end, an ASTUnit
   // for a C++ translation unit is set up and written to a temporary file.
@@ -38,50 +72,43 @@
 EXPECT_TRUE(PolicyWithDefaultLangOpt.UseVoidForZeroParams);
   }
 
-  int FD;
-  llvm::SmallString<256> InputFileName;
-  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "cpp", FD, InputFileName));
-  ToolOutputFile input_file(InputFileName, FD);
-  input_file.os() << "";
-
-  const char* Args[] = {"clang", "-xc++", InputFileName.c_str()};
-
-  IntrusiveRefCntPtr Diags =
-  CompilerInstance::createDiagnostics(new DiagnosticOptions());
-
-  std::shared_ptr CInvok =
-  createInvocationFromCommandLine(Args, Diags);
-
-  if (!CInvok)
-FAIL() << "could not create compiler invocation";
-
-  FileManager *FileMgr =
-  new FileManager(FileSystemOptions(), vfs::getRealFileSystem());
-  auto PCHContainerOps = std::make_shared();
-
-  std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation(
-  CInvok, PCHContainerOps, Diags, FileMgr);
+  std::unique_ptr AST = createASTUnit(false);
 
   if (!AST)
 FAIL() << "failed to create ASTUnit";
 
   EXPECT_FALSE(AST->getASTContext().getPrintingPolicy().UseVoidForZeroParams);
 
   llvm::SmallString<256> ASTFileName;
-  ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("ast-unit", "ast", FD, ASTFileName));
+  ASSERT_FALSE(
+  llvm::sys::fs::createTemporaryFile("ast-unit", "ast", FD, ASTFileName));
   ToolOutputFile ast_file(ASTFileName, FD);
   AST->Save(ASTFileName.str());
 
   EXPECT_TRUE(llvm::sys::fs::exists(ASTFileName));
 
   std::unique_ptr AU = ASTUnit::LoadFromASTFile(
-  ASTFileName.str(), PCHContainerOps->getRawReader(), ASTUnit::LoadEverything, Diags,
-  FileSystemOptions(), /*UseDebugInfo=*/false);
+  ASTFileName.str(), PCHContainerOps->getRawReader(),
+  ASTUnit::LoadEverything, Diags, FileSystemOptions(),
+  /*UseDebugInfo=*/false);
 
   if (!AU)
 FAIL() << "failed to load ASTUnit";
 
   EXPECT_FALSE(AU->getASTContext().getPrintingPolicy().UseVoidForZeroParams);
 }
 
+TEST_F(ASTUnitTest, GetBufferForFileMemoryMapping) {
+  std::unique_ptr AST = createASTUnit(true);
+
+  if (!AST)
+FAIL() << "failed to create ASTUnit";
+
+  std::unique_ptr memoryBuffer =
+  AST->getBufferForFile(InputFileName);
+
+  EXPECT_NE(memoryBuffer->getBufferKind(),
+llvm::MemoryBuffer::MemoryBuffer_MMap);
+}
+
 } // anonymous namespace
Index: cfe/trunk/include/clang/Basic/FileManager.h
===
--- cfe/trunk/include/clang/Basic/FileManager.h
+++ cfe/trunk/include/clang/Basic/FileManager.h
@@ -239,7 +239,7 @@
   getBufferForFile(const FileEntry *Entry, bool isVolatile = false,
bool ShouldCloseOpenFile = true);
   llvm::ErrorOr>
-  getBufferForFile(StringRef Filename);
+  getBu

[PATCH] D46862: [libclang] Optionally add code completion results for arrow instead of dot

2018-06-07 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan updated this revision to Diff 150291.
yvvan marked 8 inline comments as done.
yvvan added a comment.

Address review comments


https://reviews.llvm.org/D46862

Files:
  include/clang-c/Index.h
  include/clang/Sema/CodeCompleteConsumer.h
  test/Index/complete-arrow-dot.cpp
  tools/c-index-test/c-index-test.c
  tools/libclang/CIndex.cpp
  tools/libclang/CIndexCodeCompletion.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -171,6 +171,8 @@
 clang_getCompletionChunkCompletionString
 clang_getCompletionChunkKind
 clang_getCompletionChunkText
+clang_getCompletionNumFixIts
+clang_getCompletionFixIt
 clang_getCompletionNumAnnotations
 clang_getCompletionParent
 clang_getCompletionPriority
@@ -260,6 +262,7 @@
 clang_getSpellingLocation
 clang_getTUResourceUsageName
 clang_getTemplateCursorKind
+clang_getToken
 clang_getTokenExtent
 clang_getTokenKind
 clang_getTokenLocation
Index: tools/libclang/CIndexCodeCompletion.cpp
===
--- tools/libclang/CIndexCodeCompletion.cpp
+++ tools/libclang/CIndexCodeCompletion.cpp
@@ -16,6 +16,7 @@
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
 #include "CXCursor.h"
+#include "CXSourceLocation.h"
 #include "CXString.h"
 #include "CXTranslationUnit.h"
 #include "clang/AST/Decl.h"
@@ -302,10 +303,53 @@
   /// A string containing the Objective-C selector entered thus far for a
   /// message send.
   std::string Selector;
+
+  /// Vector of fix-its for each completion result that *must* be applied
+  /// before that result for the corresponding completion item.
+  std::vector> FixItsVector;
 };
 
 } // end anonymous namespace
 
+unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
+  unsigned completion_index) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
+return 0;
+
+  return static_cast(allocated_results->FixItsVector[completion_index].size());
+}
+
+CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
+  unsigned completion_index,
+  unsigned fixit_index,
+  CXSourceRange *replacement_range) {
+  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
+
+  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  ArrayRef FixIts = allocated_results->FixItsVector[completion_index];
+  if (FixIts.size() <= fixit_index) {
+if (replacement_range)
+  *replacement_range = clang_getNullRange();
+return cxstring::createNull();
+  }
+
+  const FixItHint &FixIt = FixIts[fixit_index];
+  if (replacement_range) {
+*replacement_range = cxloc::translateSourceRange(
+*allocated_results->SourceMgr, allocated_results->LangOpts,
+FixIt.RemoveRange);
+  }
+
+  return cxstring::createRef(FixIt.CodeToInsert.c_str());
+}
+
 /// Tracks the number of code-completion result objects that are 
 /// currently active.
 ///
@@ -531,18 +575,22 @@
 CodeCompletionResult *Results,
 unsigned NumResults) override {
   StoredResults.reserve(StoredResults.size() + NumResults);
+  if (includeFixIts())
+AllocatedResults.FixItsVector.reserve(NumResults);
   for (unsigned I = 0; I != NumResults; ++I) {
-CodeCompletionString *StoredCompletion
+CodeCompletionString *StoredCompletion
   = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
   getCodeCompletionTUInfo(),
   includeBriefComments());
 
 CXCompletionResult R;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
+if (includeFixIts())
+  AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
   }
-  
+
   enum CodeCompletionContext::Kind contextKind = Context.getKind();
   
   AllocatedResults.ContextKind = contextKind;
@@ -644,13 +692,13 @@
   unsigned options) {
   bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
   bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
+  bool IncludeFixIts = options & CXCodeComplete_IncludeCompletionsWithFixIts;
 
 #ifdef UDP_CODE_COMPLETION_LOGGER
 #ifdef UDP_CODE_COMPLETION_LOGGER_PORT
   const llvm::TimeRecord &StartTime =  llvm::T

[PATCH] D48116: [libclang] Allow skipping warnings from all included files

2018-06-13 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

Cool! That's actually quite a small change with big outcome!




Comment at: include/clang/Basic/Diagnostic.h:216
 
+  // Suppress warnings from all included files.
+  bool SuppressWarningsFromIncludedFiles = false;

Probably mention that it also suppresses everything with lower priority? 



Comment at: lib/Basic/DiagnosticIDs.cpp:484
+  !Diag.getSourceManager().isInMainFile(
+  Diag.getSourceManager().getExpansionLoc(Loc)))
+return diag::Severity::Ignored;

{ } around return


Repository:
  rC Clang

https://reviews.llvm.org/D48116



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


  1   2   3   >