Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 1 | //===--- ClangdUnit.cpp -----------------------------------------*- C++-*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===---------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "ClangdUnit.h" |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 11 | |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 12 | #include "clang/Frontend/CompilerInstance.h" |
| 13 | #include "clang/Frontend/CompilerInvocation.h" |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 14 | #include "clang/Frontend/FrontendActions.h" |
Ilya Biryukov | 0f62ed2 | 2017-05-26 12:26:51 +0000 | [diff] [blame] | 15 | #include "clang/Frontend/Utils.h" |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 16 | #include "clang/Index/IndexDataConsumer.h" |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 17 | #include "clang/Index/IndexingAction.h" |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 18 | #include "clang/Lex/Lexer.h" |
| 19 | #include "clang/Lex/MacroInfo.h" |
| 20 | #include "clang/Lex/Preprocessor.h" |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 21 | #include "clang/Lex/PreprocessorOptions.h" |
| 22 | #include "clang/Sema/Sema.h" |
| 23 | #include "clang/Serialization/ASTWriter.h" |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 24 | #include "clang/Tooling/CompilationDatabase.h" |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/ArrayRef.h" |
| 26 | #include "llvm/ADT/SmallVector.h" |
| 27 | #include "llvm/Support/CrashRecoveryContext.h" |
Krasimir Georgiev | a1de3c9 | 2017-06-15 09:11:57 +0000 | [diff] [blame] | 28 | #include "llvm/Support/Format.h" |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 29 | #include "Logger.h" |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 30 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 31 | #include <algorithm> |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 32 | #include <chrono> |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 33 | |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 34 | using namespace clang::clangd; |
| 35 | using namespace clang; |
| 36 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 37 | namespace { |
| 38 | |
| 39 | class DeclTrackingASTConsumer : public ASTConsumer { |
| 40 | public: |
| 41 | DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls) |
| 42 | : TopLevelDecls(TopLevelDecls) {} |
| 43 | |
| 44 | bool HandleTopLevelDecl(DeclGroupRef DG) override { |
| 45 | for (const Decl *D : DG) { |
| 46 | // ObjCMethodDecl are not actually top-level decls. |
| 47 | if (isa<ObjCMethodDecl>(D)) |
| 48 | continue; |
| 49 | |
| 50 | TopLevelDecls.push_back(D); |
| 51 | } |
| 52 | return true; |
| 53 | } |
| 54 | |
| 55 | private: |
| 56 | std::vector<const Decl *> &TopLevelDecls; |
| 57 | }; |
| 58 | |
| 59 | class ClangdFrontendAction : public SyntaxOnlyAction { |
| 60 | public: |
| 61 | std::vector<const Decl *> takeTopLevelDecls() { |
| 62 | return std::move(TopLevelDecls); |
| 63 | } |
| 64 | |
| 65 | protected: |
| 66 | std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, |
| 67 | StringRef InFile) override { |
| 68 | return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls); |
| 69 | } |
| 70 | |
| 71 | private: |
| 72 | std::vector<const Decl *> TopLevelDecls; |
| 73 | }; |
| 74 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 75 | class CppFilePreambleCallbacks : public PreambleCallbacks { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 76 | public: |
| 77 | std::vector<serialization::DeclID> takeTopLevelDeclIDs() { |
| 78 | return std::move(TopLevelDeclIDs); |
| 79 | } |
| 80 | |
| 81 | void AfterPCHEmitted(ASTWriter &Writer) override { |
| 82 | TopLevelDeclIDs.reserve(TopLevelDecls.size()); |
| 83 | for (Decl *D : TopLevelDecls) { |
| 84 | // Invalid top-level decls may not have been serialized. |
| 85 | if (D->isInvalidDecl()) |
| 86 | continue; |
| 87 | TopLevelDeclIDs.push_back(Writer.getDeclID(D)); |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | void HandleTopLevelDecl(DeclGroupRef DG) override { |
| 92 | for (Decl *D : DG) { |
| 93 | if (isa<ObjCMethodDecl>(D)) |
| 94 | continue; |
| 95 | TopLevelDecls.push_back(D); |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | private: |
| 100 | std::vector<Decl *> TopLevelDecls; |
| 101 | std::vector<serialization::DeclID> TopLevelDeclIDs; |
| 102 | }; |
| 103 | |
| 104 | /// Convert from clang diagnostic level to LSP severity. |
| 105 | static int getSeverity(DiagnosticsEngine::Level L) { |
| 106 | switch (L) { |
| 107 | case DiagnosticsEngine::Remark: |
| 108 | return 4; |
| 109 | case DiagnosticsEngine::Note: |
| 110 | return 3; |
| 111 | case DiagnosticsEngine::Warning: |
| 112 | return 2; |
| 113 | case DiagnosticsEngine::Fatal: |
| 114 | case DiagnosticsEngine::Error: |
| 115 | return 1; |
| 116 | case DiagnosticsEngine::Ignored: |
| 117 | return 0; |
| 118 | } |
| 119 | llvm_unreachable("Unknown diagnostic level!"); |
| 120 | } |
| 121 | |
| 122 | llvm::Optional<DiagWithFixIts> toClangdDiag(StoredDiagnostic D) { |
| 123 | auto Location = D.getLocation(); |
| 124 | if (!Location.isValid() || !Location.getManager().isInMainFile(Location)) |
| 125 | return llvm::None; |
| 126 | |
| 127 | Position P; |
| 128 | P.line = Location.getSpellingLineNumber() - 1; |
| 129 | P.character = Location.getSpellingColumnNumber(); |
| 130 | Range R = {P, P}; |
| 131 | clangd::Diagnostic Diag = {R, getSeverity(D.getLevel()), D.getMessage()}; |
| 132 | |
| 133 | llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic; |
| 134 | for (const FixItHint &Fix : D.getFixIts()) { |
| 135 | FixItsForDiagnostic.push_back(clang::tooling::Replacement( |
| 136 | Location.getManager(), Fix.RemoveRange, Fix.CodeToInsert)); |
| 137 | } |
| 138 | return DiagWithFixIts{Diag, std::move(FixItsForDiagnostic)}; |
| 139 | } |
| 140 | |
| 141 | class StoreDiagsConsumer : public DiagnosticConsumer { |
| 142 | public: |
| 143 | StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {} |
| 144 | |
| 145 | void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
| 146 | const clang::Diagnostic &Info) override { |
| 147 | DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info); |
| 148 | |
| 149 | if (auto convertedDiag = toClangdDiag(StoredDiagnostic(DiagLevel, Info))) |
| 150 | Output.push_back(std::move(*convertedDiag)); |
| 151 | } |
| 152 | |
| 153 | private: |
| 154 | std::vector<DiagWithFixIts> &Output; |
| 155 | }; |
| 156 | |
| 157 | class EmptyDiagsConsumer : public DiagnosticConsumer { |
| 158 | public: |
| 159 | void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
| 160 | const clang::Diagnostic &Info) override {} |
| 161 | }; |
| 162 | |
| 163 | std::unique_ptr<CompilerInvocation> |
| 164 | createCompilerInvocation(ArrayRef<const char *> ArgList, |
| 165 | IntrusiveRefCntPtr<DiagnosticsEngine> Diags, |
| 166 | IntrusiveRefCntPtr<vfs::FileSystem> VFS) { |
| 167 | auto CI = createInvocationFromCommandLine(ArgList, std::move(Diags), |
| 168 | std::move(VFS)); |
| 169 | // We rely on CompilerInstance to manage the resource (i.e. free them on |
| 170 | // EndSourceFile), but that won't happen if DisableFree is set to true. |
| 171 | // Since createInvocationFromCommandLine sets it to true, we have to override |
| 172 | // it. |
| 173 | CI->getFrontendOpts().DisableFree = false; |
| 174 | return CI; |
| 175 | } |
| 176 | |
| 177 | /// Creates a CompilerInstance from \p CI, with main buffer overriden to \p |
| 178 | /// Buffer and arguments to read the PCH from \p Preamble, if \p Preamble is not |
| 179 | /// null. Note that vfs::FileSystem inside returned instance may differ from \p |
| 180 | /// VFS if additional file remapping were set in command-line arguments. |
| 181 | /// On some errors, returns null. When non-null value is returned, it's expected |
| 182 | /// to be consumed by the FrontendAction as it will have a pointer to the \p |
| 183 | /// Buffer that will only be deleted if BeginSourceFile is called. |
| 184 | std::unique_ptr<CompilerInstance> |
| 185 | prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI, |
| 186 | const PrecompiledPreamble *Preamble, |
| 187 | std::unique_ptr<llvm::MemoryBuffer> Buffer, |
| 188 | std::shared_ptr<PCHContainerOperations> PCHs, |
| 189 | IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 190 | DiagnosticConsumer &DiagsClient) { |
| 191 | assert(VFS && "VFS is null"); |
| 192 | assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers && |
| 193 | "Setting RetainRemappedFileBuffers to true will cause a memory leak " |
| 194 | "of ContentsBuffer"); |
| 195 | |
| 196 | // NOTE: we use Buffer.get() when adding remapped files, so we have to make |
| 197 | // sure it will be released if no error is emitted. |
| 198 | if (Preamble) { |
| 199 | Preamble->AddImplicitPreamble(*CI, Buffer.get()); |
| 200 | } else { |
| 201 | CI->getPreprocessorOpts().addRemappedFile( |
| 202 | CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get()); |
| 203 | } |
| 204 | |
| 205 | auto Clang = llvm::make_unique<CompilerInstance>(PCHs); |
| 206 | Clang->setInvocation(std::move(CI)); |
| 207 | Clang->createDiagnostics(&DiagsClient, false); |
| 208 | |
| 209 | if (auto VFSWithRemapping = createVFSFromCompilerInvocation( |
| 210 | Clang->getInvocation(), Clang->getDiagnostics(), VFS)) |
| 211 | VFS = VFSWithRemapping; |
| 212 | Clang->setVirtualFileSystem(VFS); |
| 213 | |
| 214 | Clang->setTarget(TargetInfo::CreateTargetInfo( |
| 215 | Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); |
| 216 | if (!Clang->hasTarget()) |
| 217 | return nullptr; |
| 218 | |
| 219 | // RemappedFileBuffers will handle the lifetime of the Buffer pointer, |
| 220 | // release it. |
| 221 | Buffer.release(); |
| 222 | return Clang; |
| 223 | } |
| 224 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 225 | template <class T> bool futureIsReady(std::shared_future<T> const &Future) { |
| 226 | return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready; |
| 227 | } |
| 228 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 229 | } // namespace |
| 230 | |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 231 | namespace { |
| 232 | |
| 233 | CompletionItemKind getKind(CXCursorKind K) { |
| 234 | switch (K) { |
| 235 | case CXCursor_MacroInstantiation: |
| 236 | case CXCursor_MacroDefinition: |
| 237 | return CompletionItemKind::Text; |
| 238 | case CXCursor_CXXMethod: |
| 239 | return CompletionItemKind::Method; |
| 240 | case CXCursor_FunctionDecl: |
| 241 | case CXCursor_FunctionTemplate: |
| 242 | return CompletionItemKind::Function; |
| 243 | case CXCursor_Constructor: |
| 244 | case CXCursor_Destructor: |
| 245 | return CompletionItemKind::Constructor; |
| 246 | case CXCursor_FieldDecl: |
| 247 | return CompletionItemKind::Field; |
| 248 | case CXCursor_VarDecl: |
| 249 | case CXCursor_ParmDecl: |
| 250 | return CompletionItemKind::Variable; |
| 251 | case CXCursor_ClassDecl: |
| 252 | case CXCursor_StructDecl: |
| 253 | case CXCursor_UnionDecl: |
| 254 | case CXCursor_ClassTemplate: |
| 255 | case CXCursor_ClassTemplatePartialSpecialization: |
| 256 | return CompletionItemKind::Class; |
| 257 | case CXCursor_Namespace: |
| 258 | case CXCursor_NamespaceAlias: |
| 259 | case CXCursor_NamespaceRef: |
| 260 | return CompletionItemKind::Module; |
| 261 | case CXCursor_EnumConstantDecl: |
| 262 | return CompletionItemKind::Value; |
| 263 | case CXCursor_EnumDecl: |
| 264 | return CompletionItemKind::Enum; |
| 265 | case CXCursor_TypeAliasDecl: |
| 266 | case CXCursor_TypeAliasTemplateDecl: |
| 267 | case CXCursor_TypedefDecl: |
| 268 | case CXCursor_MemberRef: |
| 269 | case CXCursor_TypeRef: |
| 270 | return CompletionItemKind::Reference; |
| 271 | default: |
| 272 | return CompletionItemKind::Missing; |
| 273 | } |
| 274 | } |
| 275 | |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 276 | std::string escapeSnippet(const llvm::StringRef Text) { |
| 277 | std::string Result; |
| 278 | Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare. |
| 279 | for (const auto Character : Text) { |
| 280 | if (Character == '$' || Character == '}' || Character == '\\') |
| 281 | Result.push_back('\\'); |
| 282 | Result.push_back(Character); |
| 283 | } |
| 284 | return Result; |
| 285 | } |
| 286 | |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 287 | class CompletionItemsCollector : public CodeCompleteConsumer { |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 288 | |
| 289 | public: |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 290 | CompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts, |
| 291 | std::vector<CompletionItem> &Items) |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 292 | : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false), |
| 293 | Items(Items), |
| 294 | Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()), |
| 295 | CCTUInfo(Allocator) {} |
| 296 | |
| 297 | void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, |
| 298 | CodeCompletionResult *Results, |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 299 | unsigned NumResults) override final { |
| 300 | Items.reserve(NumResults); |
| 301 | for (unsigned I = 0; I < NumResults; ++I) { |
| 302 | auto &Result = Results[I]; |
| 303 | const auto *CCS = Result.CreateCodeCompletionString( |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 304 | S, Context, *Allocator, CCTUInfo, |
| 305 | CodeCompleteOpts.IncludeBriefComments); |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 306 | assert(CCS && "Expected the CodeCompletionString to be non-null"); |
| 307 | Items.push_back(ProcessCodeCompleteResult(Result, *CCS)); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 308 | } |
| 309 | } |
| 310 | |
| 311 | GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; } |
| 312 | |
| 313 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 314 | |
| 315 | private: |
| 316 | CompletionItem |
| 317 | ProcessCodeCompleteResult(const CodeCompletionResult &Result, |
| 318 | const CodeCompletionString &CCS) const { |
| 319 | |
| 320 | // Adjust this to InsertTextFormat::Snippet iff we encounter a |
| 321 | // CK_Placeholder chunk in SnippetCompletionItemsCollector. |
| 322 | CompletionItem Item; |
| 323 | Item.insertTextFormat = InsertTextFormat::PlainText; |
| 324 | |
| 325 | FillDocumentation(CCS, Item); |
| 326 | |
| 327 | // Fill in the label, detail, insertText and filterText fields of the |
| 328 | // CompletionItem. |
| 329 | ProcessChunks(CCS, Item); |
| 330 | |
| 331 | // Fill in the kind field of the CompletionItem. |
| 332 | Item.kind = getKind(Result.CursorKind); |
| 333 | |
| 334 | FillSortText(CCS, Item); |
| 335 | |
| 336 | return Item; |
| 337 | } |
| 338 | |
| 339 | virtual void ProcessChunks(const CodeCompletionString &CCS, |
| 340 | CompletionItem &Item) const = 0; |
| 341 | |
| 342 | void FillDocumentation(const CodeCompletionString &CCS, |
| 343 | CompletionItem &Item) const { |
| 344 | // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this |
| 345 | // information in the documentation field. |
| 346 | const unsigned AnnotationCount = CCS.getAnnotationCount(); |
| 347 | if (AnnotationCount > 0) { |
| 348 | Item.documentation += "Annotation"; |
| 349 | if (AnnotationCount == 1) { |
| 350 | Item.documentation += ": "; |
| 351 | } else /* AnnotationCount > 1 */ { |
| 352 | Item.documentation += "s: "; |
| 353 | } |
| 354 | for (unsigned I = 0; I < AnnotationCount; ++I) { |
| 355 | Item.documentation += CCS.getAnnotation(I); |
| 356 | Item.documentation.push_back(I == AnnotationCount - 1 ? '\n' : ' '); |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // Add brief documentation (if there is any). |
| 361 | if (CCS.getBriefComment() != nullptr) { |
| 362 | if (!Item.documentation.empty()) { |
| 363 | // This means we previously added annotations. Add an extra newline |
| 364 | // character to make the annotations stand out. |
| 365 | Item.documentation.push_back('\n'); |
| 366 | } |
| 367 | Item.documentation += CCS.getBriefComment(); |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | void FillSortText(const CodeCompletionString &CCS, |
| 372 | CompletionItem &Item) const { |
| 373 | // Fill in the sortText of the CompletionItem. |
| 374 | assert(CCS.getPriority() < 99999 && "Expecting code completion result " |
| 375 | "priority to have at most 5-digits"); |
| 376 | llvm::raw_string_ostream(Item.sortText) |
| 377 | << llvm::format("%05d%s", CCS.getPriority(), Item.filterText.c_str()); |
| 378 | } |
| 379 | |
| 380 | std::vector<CompletionItem> &Items; |
| 381 | std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator; |
| 382 | CodeCompletionTUInfo CCTUInfo; |
| 383 | |
| 384 | }; // CompletionItemsCollector |
| 385 | |
| 386 | class PlainTextCompletionItemsCollector final |
| 387 | : public CompletionItemsCollector { |
| 388 | |
| 389 | public: |
| 390 | PlainTextCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts, |
| 391 | std::vector<CompletionItem> &Items) |
| 392 | : CompletionItemsCollector(CodeCompleteOpts, Items) {} |
| 393 | |
| 394 | private: |
| 395 | void ProcessChunks(const CodeCompletionString &CCS, |
| 396 | CompletionItem &Item) const override { |
| 397 | for (const auto &Chunk : CCS) { |
| 398 | switch (Chunk.Kind) { |
| 399 | case CodeCompletionString::CK_TypedText: |
| 400 | // There's always exactly one CK_TypedText chunk. |
| 401 | Item.insertText = Item.filterText = Chunk.Text; |
| 402 | Item.label += Chunk.Text; |
| 403 | break; |
| 404 | case CodeCompletionString::CK_ResultType: |
| 405 | assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType"); |
| 406 | Item.detail = Chunk.Text; |
| 407 | break; |
| 408 | case CodeCompletionString::CK_Optional: |
| 409 | break; |
| 410 | default: |
| 411 | Item.label += Chunk.Text; |
| 412 | break; |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 | }; // PlainTextCompletionItemsCollector |
| 417 | |
| 418 | class SnippetCompletionItemsCollector final : public CompletionItemsCollector { |
| 419 | |
| 420 | public: |
| 421 | SnippetCompletionItemsCollector(const CodeCompleteOptions &CodeCompleteOpts, |
| 422 | std::vector<CompletionItem> &Items) |
| 423 | : CompletionItemsCollector(CodeCompleteOpts, Items) {} |
| 424 | |
| 425 | private: |
| 426 | void ProcessChunks(const CodeCompletionString &CCS, |
| 427 | CompletionItem &Item) const override { |
| 428 | unsigned ArgCount = 0; |
| 429 | for (const auto &Chunk : CCS) { |
| 430 | switch (Chunk.Kind) { |
| 431 | case CodeCompletionString::CK_TypedText: |
| 432 | // The piece of text that the user is expected to type to match |
| 433 | // the code-completion string, typically a keyword or the name of |
| 434 | // a declarator or macro. |
| 435 | Item.filterText = Chunk.Text; |
| 436 | // Note intentional fallthrough here. |
| 437 | case CodeCompletionString::CK_Text: |
| 438 | // A piece of text that should be placed in the buffer, |
| 439 | // e.g., parentheses or a comma in a function call. |
| 440 | Item.label += Chunk.Text; |
| 441 | Item.insertText += Chunk.Text; |
| 442 | break; |
| 443 | case CodeCompletionString::CK_Optional: |
| 444 | // A code completion string that is entirely optional. |
| 445 | // For example, an optional code completion string that |
| 446 | // describes the default arguments in a function call. |
| 447 | |
| 448 | // FIXME: Maybe add an option to allow presenting the optional chunks? |
| 449 | break; |
| 450 | case CodeCompletionString::CK_Placeholder: |
| 451 | // A string that acts as a placeholder for, e.g., a function call |
| 452 | // argument. |
| 453 | ++ArgCount; |
| 454 | Item.insertText += "${" + std::to_string(ArgCount) + ':' + |
| 455 | escapeSnippet(Chunk.Text) + '}'; |
| 456 | Item.label += Chunk.Text; |
| 457 | Item.insertTextFormat = InsertTextFormat::Snippet; |
| 458 | break; |
| 459 | case CodeCompletionString::CK_Informative: |
| 460 | // A piece of text that describes something about the result |
| 461 | // but should not be inserted into the buffer. |
| 462 | // For example, the word "const" for a const method, or the name of |
| 463 | // the base class for methods that are part of the base class. |
| 464 | Item.label += Chunk.Text; |
| 465 | // Don't put the informative chunks in the insertText. |
| 466 | break; |
| 467 | case CodeCompletionString::CK_ResultType: |
| 468 | // A piece of text that describes the type of an entity or, |
| 469 | // for functions and methods, the return type. |
| 470 | assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType"); |
| 471 | Item.detail = Chunk.Text; |
| 472 | break; |
| 473 | case CodeCompletionString::CK_CurrentParameter: |
| 474 | // A piece of text that describes the parameter that corresponds to |
| 475 | // the code-completion location within a function call, message send, |
| 476 | // macro invocation, etc. |
| 477 | // |
| 478 | // This should never be present while collecting completion items, |
| 479 | // only while collecting overload candidates. |
| 480 | llvm_unreachable("Unexpected CK_CurrentParameter while collecting " |
| 481 | "CompletionItems"); |
| 482 | break; |
| 483 | case CodeCompletionString::CK_LeftParen: |
| 484 | // A left parenthesis ('('). |
| 485 | case CodeCompletionString::CK_RightParen: |
| 486 | // A right parenthesis (')'). |
| 487 | case CodeCompletionString::CK_LeftBracket: |
| 488 | // A left bracket ('['). |
| 489 | case CodeCompletionString::CK_RightBracket: |
| 490 | // A right bracket (']'). |
| 491 | case CodeCompletionString::CK_LeftBrace: |
| 492 | // A left brace ('{'). |
| 493 | case CodeCompletionString::CK_RightBrace: |
| 494 | // A right brace ('}'). |
| 495 | case CodeCompletionString::CK_LeftAngle: |
| 496 | // A left angle bracket ('<'). |
| 497 | case CodeCompletionString::CK_RightAngle: |
| 498 | // A right angle bracket ('>'). |
| 499 | case CodeCompletionString::CK_Comma: |
| 500 | // A comma separator (','). |
| 501 | case CodeCompletionString::CK_Colon: |
| 502 | // A colon (':'). |
| 503 | case CodeCompletionString::CK_SemiColon: |
| 504 | // A semicolon (';'). |
| 505 | case CodeCompletionString::CK_Equal: |
| 506 | // An '=' sign. |
| 507 | case CodeCompletionString::CK_HorizontalSpace: |
| 508 | // Horizontal whitespace (' '). |
| 509 | Item.insertText += Chunk.Text; |
| 510 | Item.label += Chunk.Text; |
| 511 | break; |
| 512 | case CodeCompletionString::CK_VerticalSpace: |
| 513 | // Vertical whitespace ('\n' or '\r\n', depending on the |
| 514 | // platform). |
| 515 | Item.insertText += Chunk.Text; |
| 516 | // Don't even add a space to the label. |
| 517 | break; |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | }; // SnippetCompletionItemsCollector |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 522 | } // namespace |
| 523 | |
Ilya Biryukov | 0f62ed2 | 2017-05-26 12:26:51 +0000 | [diff] [blame] | 524 | std::vector<CompletionItem> |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 525 | clangd::codeComplete(PathRef FileName, tooling::CompileCommand Command, |
| 526 | PrecompiledPreamble const *Preamble, StringRef Contents, |
| 527 | Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 528 | std::shared_ptr<PCHContainerOperations> PCHs, |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 529 | bool SnippetCompletions, clangd::Logger &Logger) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 530 | std::vector<const char *> ArgStrs; |
| 531 | for (const auto &S : Command.CommandLine) |
| 532 | ArgStrs.push_back(S.c_str()); |
| 533 | |
Krasimir Georgiev | e4130d5 | 2017-07-25 11:37:43 +0000 | [diff] [blame] | 534 | VFS->setCurrentWorkingDirectory(Command.Directory); |
| 535 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 536 | std::unique_ptr<CompilerInvocation> CI; |
| 537 | EmptyDiagsConsumer DummyDiagsConsumer; |
| 538 | { |
| 539 | IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine = |
| 540 | CompilerInstance::createDiagnostics(new DiagnosticOptions, |
| 541 | &DummyDiagsConsumer, false); |
| 542 | CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS); |
| 543 | } |
| 544 | assert(CI && "Couldn't create CompilerInvocation"); |
| 545 | |
| 546 | std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = |
| 547 | llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName); |
| 548 | |
| 549 | // Attempt to reuse the PCH from precompiled preamble, if it was built. |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 550 | if (Preamble) { |
| 551 | auto Bounds = |
| 552 | ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 553 | if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get())) |
| 554 | Preamble = nullptr; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 555 | } |
| 556 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 557 | auto Clang = prepareCompilerInstance(std::move(CI), Preamble, |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 558 | std::move(ContentsBuffer), PCHs, VFS, |
| 559 | DummyDiagsConsumer); |
| 560 | auto &DiagOpts = Clang->getDiagnosticOpts(); |
| 561 | DiagOpts.IgnoreWarnings = true; |
| 562 | |
| 563 | auto &FrontendOpts = Clang->getFrontendOpts(); |
| 564 | FrontendOpts.SkipFunctionBodies = true; |
| 565 | |
| 566 | FrontendOpts.CodeCompleteOpts.IncludeGlobals = true; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 567 | FrontendOpts.CodeCompleteOpts.IncludeMacros = true; |
| 568 | FrontendOpts.CodeCompleteOpts.IncludeBriefComments = true; |
| 569 | |
| 570 | FrontendOpts.CodeCompletionAt.FileName = FileName; |
| 571 | FrontendOpts.CodeCompletionAt.Line = Pos.line + 1; |
| 572 | FrontendOpts.CodeCompletionAt.Column = Pos.character + 1; |
| 573 | |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 574 | std::vector<CompletionItem> Items; |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 575 | if (SnippetCompletions) { |
| 576 | FrontendOpts.CodeCompleteOpts.IncludeCodePatterns = true; |
| 577 | Clang->setCodeCompletionConsumer(new SnippetCompletionItemsCollector( |
| 578 | FrontendOpts.CodeCompleteOpts, Items)); |
| 579 | } else { |
| 580 | FrontendOpts.CodeCompleteOpts.IncludeCodePatterns = false; |
| 581 | Clang->setCodeCompletionConsumer(new PlainTextCompletionItemsCollector( |
| 582 | FrontendOpts.CodeCompleteOpts, Items)); |
| 583 | } |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 584 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 585 | SyntaxOnlyAction Action; |
| 586 | if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) { |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 587 | Logger.log("BeginSourceFile() failed when running codeComplete for " + |
| 588 | FileName); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 589 | return Items; |
| 590 | } |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 591 | if (!Action.Execute()) |
| 592 | Logger.log("Execute() failed when running codeComplete for " + FileName); |
| 593 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 594 | Action.EndSourceFile(); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 595 | |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 596 | return Items; |
| 597 | } |
| 598 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 599 | void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) { |
| 600 | AST.getASTContext().getTranslationUnitDecl()->dump(OS, true); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 601 | } |
Ilya Biryukov | f01af68 | 2017-05-23 13:42:59 +0000 | [diff] [blame] | 602 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 603 | llvm::Optional<ParsedAST> |
| 604 | ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI, |
| 605 | const PrecompiledPreamble *Preamble, |
| 606 | ArrayRef<serialization::DeclID> PreambleDeclIDs, |
| 607 | std::unique_ptr<llvm::MemoryBuffer> Buffer, |
| 608 | std::shared_ptr<PCHContainerOperations> PCHs, |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 609 | IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 610 | clangd::Logger &Logger) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 611 | |
| 612 | std::vector<DiagWithFixIts> ASTDiags; |
| 613 | StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags); |
| 614 | |
| 615 | auto Clang = |
| 616 | prepareCompilerInstance(std::move(CI), Preamble, std::move(Buffer), PCHs, |
| 617 | VFS, /*ref*/ UnitDiagsConsumer); |
| 618 | |
| 619 | // Recover resources if we crash before exiting this method. |
| 620 | llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup( |
| 621 | Clang.get()); |
| 622 | |
| 623 | auto Action = llvm::make_unique<ClangdFrontendAction>(); |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 624 | const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0]; |
| 625 | if (!Action->BeginSourceFile(*Clang, MainInput)) { |
| 626 | Logger.log("BeginSourceFile() failed when building AST for " + |
| 627 | MainInput.getFile()); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 628 | return llvm::None; |
| 629 | } |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 630 | if (!Action->Execute()) |
| 631 | Logger.log("Execute() failed when building AST for " + MainInput.getFile()); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 632 | |
| 633 | // UnitDiagsConsumer is local, we can not store it in CompilerInstance that |
| 634 | // has a longer lifetime. |
| 635 | Clang->getDiagnostics().setClient(new EmptyDiagsConsumer); |
| 636 | |
| 637 | std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls(); |
| 638 | std::vector<serialization::DeclID> PendingDecls; |
| 639 | if (Preamble) { |
| 640 | PendingDecls.reserve(PreambleDeclIDs.size()); |
| 641 | PendingDecls.insert(PendingDecls.begin(), PreambleDeclIDs.begin(), |
| 642 | PreambleDeclIDs.end()); |
| 643 | } |
| 644 | |
| 645 | return ParsedAST(std::move(Clang), std::move(Action), std::move(ParsedDecls), |
| 646 | std::move(PendingDecls), std::move(ASTDiags)); |
| 647 | } |
| 648 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 649 | namespace { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 650 | |
| 651 | SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr, |
| 652 | const FileEntry *FE, |
| 653 | unsigned Offset) { |
| 654 | SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1); |
| 655 | return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset)); |
| 656 | } |
| 657 | |
| 658 | SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr, |
| 659 | const FileEntry *FE, Position Pos) { |
| 660 | SourceLocation InputLoc = |
| 661 | Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1); |
| 662 | return Mgr.getMacroArgExpandedLocation(InputLoc); |
| 663 | } |
| 664 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 665 | /// Finds declarations locations that a given source location refers to. |
| 666 | class DeclarationLocationsFinder : public index::IndexDataConsumer { |
| 667 | std::vector<Location> DeclarationLocations; |
| 668 | const SourceLocation &SearchedLocation; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 669 | const ASTContext &AST; |
| 670 | Preprocessor &PP; |
| 671 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 672 | public: |
| 673 | DeclarationLocationsFinder(raw_ostream &OS, |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 674 | const SourceLocation &SearchedLocation, |
| 675 | ASTContext &AST, Preprocessor &PP) |
| 676 | : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {} |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 677 | |
| 678 | std::vector<Location> takeLocations() { |
| 679 | // Don't keep the same location multiple times. |
| 680 | // This can happen when nodes in the AST are visited twice. |
| 681 | std::sort(DeclarationLocations.begin(), DeclarationLocations.end()); |
Kirill Bobyrev | 4621387 | 2017-06-28 20:57:28 +0000 | [diff] [blame] | 682 | auto last = |
| 683 | std::unique(DeclarationLocations.begin(), DeclarationLocations.end()); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 684 | DeclarationLocations.erase(last, DeclarationLocations.end()); |
| 685 | return std::move(DeclarationLocations); |
| 686 | } |
| 687 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 688 | bool |
| 689 | handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles, |
| 690 | ArrayRef<index::SymbolRelation> Relations, FileID FID, |
| 691 | unsigned Offset, |
| 692 | index::IndexDataConsumer::ASTNodeInfo ASTNode) override { |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 693 | if (isSearchedLocation(FID, Offset)) { |
| 694 | addDeclarationLocation(D->getSourceRange()); |
| 695 | } |
| 696 | return true; |
| 697 | } |
| 698 | |
| 699 | private: |
| 700 | bool isSearchedLocation(FileID FID, unsigned Offset) const { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 701 | const SourceManager &SourceMgr = AST.getSourceManager(); |
| 702 | return SourceMgr.getFileOffset(SearchedLocation) == Offset && |
| 703 | SourceMgr.getFileID(SearchedLocation) == FID; |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 704 | } |
| 705 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 706 | void addDeclarationLocation(const SourceRange &ValSourceRange) { |
| 707 | const SourceManager &SourceMgr = AST.getSourceManager(); |
| 708 | const LangOptions &LangOpts = AST.getLangOpts(); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 709 | SourceLocation LocStart = ValSourceRange.getBegin(); |
| 710 | SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(), |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 711 | 0, SourceMgr, LangOpts); |
Kirill Bobyrev | 4621387 | 2017-06-28 20:57:28 +0000 | [diff] [blame] | 712 | Position Begin; |
| 713 | Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1; |
| 714 | Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1; |
| 715 | Position End; |
| 716 | End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1; |
| 717 | End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1; |
| 718 | Range R = {Begin, End}; |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 719 | Location L; |
| 720 | L.uri = URI::fromFile( |
| 721 | SourceMgr.getFilename(SourceMgr.getSpellingLoc(LocStart))); |
| 722 | L.range = R; |
| 723 | DeclarationLocations.push_back(L); |
| 724 | } |
| 725 | |
Kirill Bobyrev | 4621387 | 2017-06-28 20:57:28 +0000 | [diff] [blame] | 726 | void finish() override { |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 727 | // Also handle possible macro at the searched location. |
| 728 | Token Result; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 729 | if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(), |
| 730 | AST.getLangOpts(), false)) { |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 731 | if (Result.is(tok::raw_identifier)) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 732 | PP.LookUpIdentifierInfo(Result); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 733 | } |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 734 | IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo(); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 735 | if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) { |
| 736 | std::pair<FileID, unsigned int> DecLoc = |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 737 | AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 738 | // Get the definition just before the searched location so that a macro |
| 739 | // referenced in a '#undef MACRO' can still be found. |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 740 | SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation( |
| 741 | AST.getSourceManager(), |
| 742 | AST.getSourceManager().getFileEntryForID(DecLoc.first), |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 743 | DecLoc.second - 1); |
| 744 | MacroDefinition MacroDef = |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 745 | PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation); |
| 746 | MacroInfo *MacroInf = MacroDef.getMacroInfo(); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 747 | if (MacroInf) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 748 | addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(), |
| 749 | MacroInf->getDefinitionEndLoc())); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 750 | } |
| 751 | } |
| 752 | } |
| 753 | } |
| 754 | }; |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 755 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 756 | SourceLocation getBeginningOfIdentifier(ParsedAST &Unit, const Position &Pos, |
| 757 | const FileEntry *FE) { |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 758 | // The language server protocol uses zero-based line and column numbers. |
| 759 | // Clang uses one-based numbers. |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 760 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 761 | const ASTContext &AST = Unit.getASTContext(); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 762 | const SourceManager &SourceMgr = AST.getSourceManager(); |
| 763 | |
| 764 | SourceLocation InputLocation = |
| 765 | getMacroArgExpandedLocation(SourceMgr, FE, Pos); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 766 | if (Pos.character == 0) { |
| 767 | return InputLocation; |
| 768 | } |
| 769 | |
| 770 | // This handle cases where the position is in the middle of a token or right |
| 771 | // after the end of a token. In theory we could just use GetBeginningOfToken |
| 772 | // to find the start of the token at the input position, but this doesn't |
| 773 | // work when right after the end, i.e. foo|. |
| 774 | // So try to go back by one and see if we're still inside the an identifier |
| 775 | // token. If so, Take the beginning of this token. |
| 776 | // (It should be the same identifier because you can't have two adjacent |
| 777 | // identifiers without another token in between.) |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 778 | SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation( |
| 779 | SourceMgr, FE, Position{Pos.line, Pos.character - 1}); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 780 | Token Result; |
Ilya Biryukov | 4203d2a | 2017-06-29 17:11:32 +0000 | [diff] [blame] | 781 | if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr, |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 782 | AST.getLangOpts(), false)) { |
Ilya Biryukov | 4203d2a | 2017-06-29 17:11:32 +0000 | [diff] [blame] | 783 | // getRawToken failed, just use InputLocation. |
| 784 | return InputLocation; |
| 785 | } |
| 786 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 787 | if (Result.is(tok::raw_identifier)) { |
| 788 | return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr, |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 789 | AST.getLangOpts()); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 790 | } |
| 791 | |
| 792 | return InputLocation; |
| 793 | } |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 794 | } // namespace |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 795 | |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 796 | std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos, |
| 797 | clangd::Logger &Logger) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 798 | const SourceManager &SourceMgr = AST.getASTContext().getSourceManager(); |
| 799 | const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()); |
| 800 | if (!FE) |
| 801 | return {}; |
| 802 | |
| 803 | SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE); |
| 804 | |
| 805 | auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>( |
| 806 | llvm::errs(), SourceLocationBeg, AST.getASTContext(), |
| 807 | AST.getPreprocessor()); |
| 808 | index::IndexingOptions IndexOpts; |
| 809 | IndexOpts.SystemSymbolFilter = |
| 810 | index::IndexingOptions::SystemSymbolFilterKind::All; |
| 811 | IndexOpts.IndexFunctionLocals = true; |
| 812 | |
| 813 | indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(), |
| 814 | DeclLocationsFinder, IndexOpts); |
| 815 | |
| 816 | return DeclLocationsFinder->takeLocations(); |
| 817 | } |
| 818 | |
| 819 | void ParsedAST::ensurePreambleDeclsDeserialized() { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 820 | if (PendingTopLevelDecls.empty()) |
| 821 | return; |
| 822 | |
| 823 | std::vector<const Decl *> Resolved; |
| 824 | Resolved.reserve(PendingTopLevelDecls.size()); |
| 825 | |
| 826 | ExternalASTSource &Source = *getASTContext().getExternalSource(); |
| 827 | for (serialization::DeclID TopLevelDecl : PendingTopLevelDecls) { |
| 828 | // Resolve the declaration ID to an actual declaration, possibly |
| 829 | // deserializing the declaration in the process. |
| 830 | if (Decl *D = Source.GetExternalDecl(TopLevelDecl)) |
| 831 | Resolved.push_back(D); |
| 832 | } |
| 833 | |
| 834 | TopLevelDecls.reserve(TopLevelDecls.size() + PendingTopLevelDecls.size()); |
| 835 | TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); |
| 836 | |
| 837 | PendingTopLevelDecls.clear(); |
| 838 | } |
| 839 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 840 | ParsedAST::ParsedAST(ParsedAST &&Other) = default; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 841 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 842 | ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 843 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 844 | ParsedAST::~ParsedAST() { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 845 | if (Action) { |
| 846 | Action->EndSourceFile(); |
| 847 | } |
| 848 | } |
| 849 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 850 | ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); } |
| 851 | |
| 852 | const ASTContext &ParsedAST::getASTContext() const { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 853 | return Clang->getASTContext(); |
| 854 | } |
| 855 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 856 | Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); } |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 857 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 858 | const Preprocessor &ParsedAST::getPreprocessor() const { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 859 | return Clang->getPreprocessor(); |
| 860 | } |
| 861 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 862 | ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 863 | ensurePreambleDeclsDeserialized(); |
| 864 | return TopLevelDecls; |
| 865 | } |
| 866 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 867 | const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 868 | return Diags; |
| 869 | } |
| 870 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 871 | ParsedAST::ParsedAST(std::unique_ptr<CompilerInstance> Clang, |
| 872 | std::unique_ptr<FrontendAction> Action, |
| 873 | std::vector<const Decl *> TopLevelDecls, |
| 874 | std::vector<serialization::DeclID> PendingTopLevelDecls, |
| 875 | std::vector<DiagWithFixIts> Diags) |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 876 | : Clang(std::move(Clang)), Action(std::move(Action)), |
| 877 | Diags(std::move(Diags)), TopLevelDecls(std::move(TopLevelDecls)), |
| 878 | PendingTopLevelDecls(std::move(PendingTopLevelDecls)) { |
| 879 | assert(this->Clang); |
| 880 | assert(this->Action); |
| 881 | } |
| 882 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 883 | ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper) |
| 884 | : AST(std::move(Wrapper.AST)) {} |
| 885 | |
| 886 | ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST) |
| 887 | : AST(std::move(AST)) {} |
| 888 | |
| 889 | PreambleData::PreambleData(PrecompiledPreamble Preamble, |
| 890 | std::vector<serialization::DeclID> TopLevelDeclIDs, |
| 891 | std::vector<DiagWithFixIts> Diags) |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 892 | : Preamble(std::move(Preamble)), |
| 893 | TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {} |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 894 | |
| 895 | std::shared_ptr<CppFile> |
| 896 | CppFile::Create(PathRef FileName, tooling::CompileCommand Command, |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 897 | std::shared_ptr<PCHContainerOperations> PCHs, clangd::Logger &Logger) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 898 | return std::shared_ptr<CppFile>( |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 899 | new CppFile(FileName, std::move(Command), std::move(PCHs), Logger)); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 900 | } |
| 901 | |
| 902 | CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command, |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 903 | std::shared_ptr<PCHContainerOperations> PCHs, |
| 904 | clangd::Logger &Logger) |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 905 | : FileName(FileName), Command(std::move(Command)), RebuildCounter(0), |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 906 | RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 907 | |
| 908 | std::lock_guard<std::mutex> Lock(Mutex); |
| 909 | LatestAvailablePreamble = nullptr; |
| 910 | PreamblePromise.set_value(nullptr); |
| 911 | PreambleFuture = PreamblePromise.get_future(); |
| 912 | |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 913 | ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None)); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 914 | ASTFuture = ASTPromise.get_future(); |
| 915 | } |
| 916 | |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 917 | void CppFile::cancelRebuild() { deferCancelRebuild().get(); } |
| 918 | |
| 919 | std::future<void> CppFile::deferCancelRebuild() { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 920 | std::unique_lock<std::mutex> Lock(Mutex); |
| 921 | // Cancel an ongoing rebuild, if any, and wait for it to finish. |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 922 | unsigned RequestRebuildCounter = ++this->RebuildCounter; |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 923 | // Rebuild asserts that futures aren't ready if rebuild is cancelled. |
| 924 | // We want to keep this invariant. |
| 925 | if (futureIsReady(PreambleFuture)) { |
| 926 | PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>(); |
| 927 | PreambleFuture = PreamblePromise.get_future(); |
| 928 | } |
| 929 | if (futureIsReady(ASTFuture)) { |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 930 | ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>(); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 931 | ASTFuture = ASTPromise.get_future(); |
| 932 | } |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 933 | |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 934 | Lock.unlock(); |
| 935 | // Notify about changes to RebuildCounter. |
| 936 | RebuildCond.notify_all(); |
| 937 | |
| 938 | std::shared_ptr<CppFile> That = shared_from_this(); |
| 939 | return std::async(std::launch::deferred, [That, RequestRebuildCounter]() { |
| 940 | std::unique_lock<std::mutex> Lock(That->Mutex); |
| 941 | CppFile *This = &*That; |
| 942 | This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() { |
| 943 | return !This->RebuildInProgress || |
| 944 | This->RebuildCounter != RequestRebuildCounter; |
| 945 | }); |
| 946 | |
| 947 | // This computation got cancelled itself, do nothing. |
| 948 | if (This->RebuildCounter != RequestRebuildCounter) |
| 949 | return; |
| 950 | |
| 951 | // Set empty results for Promises. |
| 952 | That->PreamblePromise.set_value(nullptr); |
| 953 | That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None)); |
| 954 | }); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 955 | } |
| 956 | |
| 957 | llvm::Optional<std::vector<DiagWithFixIts>> |
| 958 | CppFile::rebuild(StringRef NewContents, |
| 959 | IntrusiveRefCntPtr<vfs::FileSystem> VFS) { |
| 960 | return deferRebuild(NewContents, std::move(VFS)).get(); |
| 961 | } |
| 962 | |
| 963 | std::future<llvm::Optional<std::vector<DiagWithFixIts>>> |
| 964 | CppFile::deferRebuild(StringRef NewContents, |
| 965 | IntrusiveRefCntPtr<vfs::FileSystem> VFS) { |
| 966 | std::shared_ptr<const PreambleData> OldPreamble; |
| 967 | std::shared_ptr<PCHContainerOperations> PCHs; |
| 968 | unsigned RequestRebuildCounter; |
| 969 | { |
| 970 | std::unique_lock<std::mutex> Lock(Mutex); |
| 971 | // Increase RebuildCounter to cancel all ongoing FinishRebuild operations. |
| 972 | // They will try to exit as early as possible and won't call set_value on |
| 973 | // our promises. |
| 974 | RequestRebuildCounter = ++this->RebuildCounter; |
| 975 | PCHs = this->PCHs; |
| 976 | |
| 977 | // Remember the preamble to be used during rebuild. |
| 978 | OldPreamble = this->LatestAvailablePreamble; |
| 979 | // Setup std::promises and std::futures for Preamble and AST. Corresponding |
| 980 | // futures will wait until the rebuild process is finished. |
| 981 | if (futureIsReady(this->PreambleFuture)) { |
| 982 | this->PreamblePromise = |
| 983 | std::promise<std::shared_ptr<const PreambleData>>(); |
| 984 | this->PreambleFuture = this->PreamblePromise.get_future(); |
| 985 | } |
| 986 | if (futureIsReady(this->ASTFuture)) { |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 987 | this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>(); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 988 | this->ASTFuture = this->ASTPromise.get_future(); |
| 989 | } |
| 990 | } // unlock Mutex. |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 991 | // Notify about changes to RebuildCounter. |
| 992 | RebuildCond.notify_all(); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 993 | |
| 994 | // A helper to function to finish the rebuild. May be run on a different |
| 995 | // thread. |
| 996 | |
| 997 | // Don't let this CppFile die before rebuild is finished. |
| 998 | std::shared_ptr<CppFile> That = shared_from_this(); |
| 999 | auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs, |
| 1000 | That](std::string NewContents) |
| 1001 | -> llvm::Optional<std::vector<DiagWithFixIts>> { |
| 1002 | // Only one execution of this method is possible at a time. |
| 1003 | // RebuildGuard will wait for any ongoing rebuilds to finish and will put us |
| 1004 | // into a state for doing a rebuild. |
| 1005 | RebuildGuard Rebuild(*That, RequestRebuildCounter); |
| 1006 | if (Rebuild.wasCancelledBeforeConstruction()) |
| 1007 | return llvm::None; |
| 1008 | |
| 1009 | std::vector<const char *> ArgStrs; |
| 1010 | for (const auto &S : That->Command.CommandLine) |
| 1011 | ArgStrs.push_back(S.c_str()); |
| 1012 | |
| 1013 | VFS->setCurrentWorkingDirectory(That->Command.Directory); |
| 1014 | |
| 1015 | std::unique_ptr<CompilerInvocation> CI; |
| 1016 | { |
| 1017 | // FIXME(ibiryukov): store diagnostics from CommandLine when we start |
| 1018 | // reporting them. |
| 1019 | EmptyDiagsConsumer CommandLineDiagsConsumer; |
| 1020 | IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine = |
| 1021 | CompilerInstance::createDiagnostics(new DiagnosticOptions, |
| 1022 | &CommandLineDiagsConsumer, false); |
| 1023 | CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS); |
| 1024 | } |
| 1025 | assert(CI && "Couldn't create CompilerInvocation"); |
| 1026 | |
| 1027 | std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = |
| 1028 | llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName); |
| 1029 | |
| 1030 | // A helper function to rebuild the preamble or reuse the existing one. Does |
| 1031 | // not mutate any fields, only does the actual computation. |
| 1032 | auto DoRebuildPreamble = [&]() -> std::shared_ptr<const PreambleData> { |
| 1033 | auto Bounds = |
| 1034 | ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0); |
| 1035 | if (OldPreamble && OldPreamble->Preamble.CanReuse( |
| 1036 | *CI, ContentsBuffer.get(), Bounds, VFS.get())) { |
| 1037 | return OldPreamble; |
| 1038 | } |
| 1039 | |
| 1040 | std::vector<DiagWithFixIts> PreambleDiags; |
| 1041 | StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags); |
| 1042 | IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine = |
| 1043 | CompilerInstance::createDiagnostics( |
| 1044 | &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false); |
| 1045 | CppFilePreambleCallbacks SerializedDeclsCollector; |
| 1046 | auto BuiltPreamble = PrecompiledPreamble::Build( |
| 1047 | *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs, |
| 1048 | SerializedDeclsCollector); |
| 1049 | |
| 1050 | if (BuiltPreamble) { |
| 1051 | return std::make_shared<PreambleData>( |
| 1052 | std::move(*BuiltPreamble), |
| 1053 | SerializedDeclsCollector.takeTopLevelDeclIDs(), |
| 1054 | std::move(PreambleDiags)); |
| 1055 | } else { |
| 1056 | return nullptr; |
| 1057 | } |
| 1058 | }; |
| 1059 | |
| 1060 | // Compute updated Preamble. |
| 1061 | std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble(); |
| 1062 | // Publish the new Preamble. |
| 1063 | { |
| 1064 | std::lock_guard<std::mutex> Lock(That->Mutex); |
| 1065 | // We always set LatestAvailablePreamble to the new value, hoping that it |
| 1066 | // will still be usable in the further requests. |
| 1067 | That->LatestAvailablePreamble = NewPreamble; |
| 1068 | if (RequestRebuildCounter != That->RebuildCounter) |
| 1069 | return llvm::None; // Our rebuild request was cancelled, do nothing. |
| 1070 | That->PreamblePromise.set_value(NewPreamble); |
| 1071 | } // unlock Mutex |
| 1072 | |
| 1073 | // Prepare the Preamble and supplementary data for rebuilding AST. |
| 1074 | const PrecompiledPreamble *PreambleForAST = nullptr; |
| 1075 | ArrayRef<serialization::DeclID> SerializedPreambleDecls = llvm::None; |
| 1076 | std::vector<DiagWithFixIts> Diagnostics; |
| 1077 | if (NewPreamble) { |
| 1078 | PreambleForAST = &NewPreamble->Preamble; |
| 1079 | SerializedPreambleDecls = NewPreamble->TopLevelDeclIDs; |
| 1080 | Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(), |
| 1081 | NewPreamble->Diags.end()); |
| 1082 | } |
| 1083 | |
| 1084 | // Compute updated AST. |
| 1085 | llvm::Optional<ParsedAST> NewAST = |
| 1086 | ParsedAST::Build(std::move(CI), PreambleForAST, SerializedPreambleDecls, |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame^] | 1087 | std::move(ContentsBuffer), PCHs, VFS, That->Logger); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1088 | |
| 1089 | if (NewAST) { |
| 1090 | Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(), |
| 1091 | NewAST->getDiagnostics().end()); |
| 1092 | } else { |
| 1093 | // Don't report even Preamble diagnostics if we coulnd't build AST. |
| 1094 | Diagnostics.clear(); |
| 1095 | } |
| 1096 | |
| 1097 | // Publish the new AST. |
| 1098 | { |
| 1099 | std::lock_guard<std::mutex> Lock(That->Mutex); |
| 1100 | if (RequestRebuildCounter != That->RebuildCounter) |
| 1101 | return Diagnostics; // Our rebuild request was cancelled, don't set |
| 1102 | // ASTPromise. |
| 1103 | |
Ilya Biryukov | 574b753 | 2017-08-02 09:08:39 +0000 | [diff] [blame] | 1104 | That->ASTPromise.set_value( |
| 1105 | std::make_shared<ParsedASTWrapper>(std::move(NewAST))); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1106 | } // unlock Mutex |
| 1107 | |
| 1108 | return Diagnostics; |
| 1109 | }; |
| 1110 | |
| 1111 | return std::async(std::launch::deferred, FinishRebuild, NewContents.str()); |
| 1112 | } |
| 1113 | |
| 1114 | std::shared_future<std::shared_ptr<const PreambleData>> |
| 1115 | CppFile::getPreamble() const { |
| 1116 | std::lock_guard<std::mutex> Lock(Mutex); |
| 1117 | return PreambleFuture; |
| 1118 | } |
| 1119 | |
| 1120 | std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const { |
| 1121 | std::lock_guard<std::mutex> Lock(Mutex); |
| 1122 | return LatestAvailablePreamble; |
| 1123 | } |
| 1124 | |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 1125 | std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1126 | std::lock_guard<std::mutex> Lock(Mutex); |
| 1127 | return ASTFuture; |
| 1128 | } |
| 1129 | |
| 1130 | tooling::CompileCommand const &CppFile::getCompileCommand() const { |
| 1131 | return Command; |
| 1132 | } |
| 1133 | |
| 1134 | CppFile::RebuildGuard::RebuildGuard(CppFile &File, |
| 1135 | unsigned RequestRebuildCounter) |
| 1136 | : File(File), RequestRebuildCounter(RequestRebuildCounter) { |
| 1137 | std::unique_lock<std::mutex> Lock(File.Mutex); |
| 1138 | WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter; |
| 1139 | if (WasCancelledBeforeConstruction) |
| 1140 | return; |
| 1141 | |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 1142 | File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() { |
| 1143 | return !File.RebuildInProgress || |
| 1144 | File.RebuildCounter != RequestRebuildCounter; |
| 1145 | }); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1146 | |
| 1147 | WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter; |
| 1148 | if (WasCancelledBeforeConstruction) |
| 1149 | return; |
| 1150 | |
| 1151 | File.RebuildInProgress = true; |
| 1152 | } |
| 1153 | |
| 1154 | bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const { |
| 1155 | return WasCancelledBeforeConstruction; |
| 1156 | } |
| 1157 | |
| 1158 | CppFile::RebuildGuard::~RebuildGuard() { |
| 1159 | if (WasCancelledBeforeConstruction) |
| 1160 | return; |
| 1161 | |
| 1162 | std::unique_lock<std::mutex> Lock(File.Mutex); |
| 1163 | assert(File.RebuildInProgress); |
| 1164 | File.RebuildInProgress = false; |
| 1165 | |
| 1166 | if (File.RebuildCounter == RequestRebuildCounter) { |
| 1167 | // Our rebuild request was successful. |
| 1168 | assert(futureIsReady(File.ASTFuture)); |
| 1169 | assert(futureIsReady(File.PreambleFuture)); |
| 1170 | } else { |
| 1171 | // Our rebuild request was cancelled, because further reparse was requested. |
| 1172 | assert(!futureIsReady(File.ASTFuture)); |
| 1173 | assert(!futureIsReady(File.PreambleFuture)); |
| 1174 | } |
| 1175 | |
| 1176 | Lock.unlock(); |
| 1177 | File.RebuildCond.notify_all(); |
| 1178 | } |