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 | 83ca8a2 | 2017-09-20 10:46:58 +0000 | [diff] [blame] | 12 | #include "Logger.h" |
Sam McCall | 8567cb3 | 2017-11-02 09:21:51 +0000 | [diff] [blame] | 13 | #include "Trace.h" |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 14 | #include "clang/Frontend/CompilerInstance.h" |
| 15 | #include "clang/Frontend/CompilerInvocation.h" |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 16 | #include "clang/Frontend/FrontendActions.h" |
Ilya Biryukov | 0f62ed2 | 2017-05-26 12:26:51 +0000 | [diff] [blame] | 17 | #include "clang/Frontend/Utils.h" |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 18 | #include "clang/Index/IndexDataConsumer.h" |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 19 | #include "clang/Index/IndexingAction.h" |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 20 | #include "clang/Lex/Lexer.h" |
| 21 | #include "clang/Lex/MacroInfo.h" |
| 22 | #include "clang/Lex/Preprocessor.h" |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 23 | #include "clang/Lex/PreprocessorOptions.h" |
| 24 | #include "clang/Sema/Sema.h" |
| 25 | #include "clang/Serialization/ASTWriter.h" |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 26 | #include "clang/Tooling/CompilationDatabase.h" |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 27 | #include "llvm/ADT/ArrayRef.h" |
| 28 | #include "llvm/ADT/SmallVector.h" |
| 29 | #include "llvm/Support/CrashRecoveryContext.h" |
Krasimir Georgiev | a1de3c9 | 2017-06-15 09:11:57 +0000 | [diff] [blame] | 30 | #include "llvm/Support/Format.h" |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 31 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 32 | #include <algorithm> |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 33 | #include <chrono> |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 34 | |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 35 | using namespace clang::clangd; |
| 36 | using namespace clang; |
| 37 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 38 | namespace { |
| 39 | |
| 40 | class DeclTrackingASTConsumer : public ASTConsumer { |
| 41 | public: |
| 42 | DeclTrackingASTConsumer(std::vector<const Decl *> &TopLevelDecls) |
| 43 | : TopLevelDecls(TopLevelDecls) {} |
| 44 | |
| 45 | bool HandleTopLevelDecl(DeclGroupRef DG) override { |
| 46 | for (const Decl *D : DG) { |
| 47 | // ObjCMethodDecl are not actually top-level decls. |
| 48 | if (isa<ObjCMethodDecl>(D)) |
| 49 | continue; |
| 50 | |
| 51 | TopLevelDecls.push_back(D); |
| 52 | } |
| 53 | return true; |
| 54 | } |
| 55 | |
| 56 | private: |
| 57 | std::vector<const Decl *> &TopLevelDecls; |
| 58 | }; |
| 59 | |
| 60 | class ClangdFrontendAction : public SyntaxOnlyAction { |
| 61 | public: |
| 62 | std::vector<const Decl *> takeTopLevelDecls() { |
| 63 | return std::move(TopLevelDecls); |
| 64 | } |
| 65 | |
| 66 | protected: |
| 67 | std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, |
| 68 | StringRef InFile) override { |
| 69 | return llvm::make_unique<DeclTrackingASTConsumer>(/*ref*/ TopLevelDecls); |
| 70 | } |
| 71 | |
| 72 | private: |
| 73 | std::vector<const Decl *> TopLevelDecls; |
| 74 | }; |
| 75 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 76 | class CppFilePreambleCallbacks : public PreambleCallbacks { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 77 | public: |
| 78 | std::vector<serialization::DeclID> takeTopLevelDeclIDs() { |
| 79 | return std::move(TopLevelDeclIDs); |
| 80 | } |
| 81 | |
| 82 | void AfterPCHEmitted(ASTWriter &Writer) override { |
| 83 | TopLevelDeclIDs.reserve(TopLevelDecls.size()); |
| 84 | for (Decl *D : TopLevelDecls) { |
| 85 | // Invalid top-level decls may not have been serialized. |
| 86 | if (D->isInvalidDecl()) |
| 87 | continue; |
| 88 | TopLevelDeclIDs.push_back(Writer.getDeclID(D)); |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | void HandleTopLevelDecl(DeclGroupRef DG) override { |
| 93 | for (Decl *D : DG) { |
| 94 | if (isa<ObjCMethodDecl>(D)) |
| 95 | continue; |
| 96 | TopLevelDecls.push_back(D); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | private: |
| 101 | std::vector<Decl *> TopLevelDecls; |
| 102 | std::vector<serialization::DeclID> TopLevelDeclIDs; |
| 103 | }; |
| 104 | |
| 105 | /// Convert from clang diagnostic level to LSP severity. |
| 106 | static int getSeverity(DiagnosticsEngine::Level L) { |
| 107 | switch (L) { |
| 108 | case DiagnosticsEngine::Remark: |
| 109 | return 4; |
| 110 | case DiagnosticsEngine::Note: |
| 111 | return 3; |
| 112 | case DiagnosticsEngine::Warning: |
| 113 | return 2; |
| 114 | case DiagnosticsEngine::Fatal: |
| 115 | case DiagnosticsEngine::Error: |
| 116 | return 1; |
| 117 | case DiagnosticsEngine::Ignored: |
| 118 | return 0; |
| 119 | } |
| 120 | llvm_unreachable("Unknown diagnostic level!"); |
| 121 | } |
| 122 | |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 123 | /// Get the optional chunk as a string. This function is possibly recursive. |
| 124 | /// |
| 125 | /// The parameter info for each parameter is appended to the Parameters. |
| 126 | std::string |
| 127 | getOptionalParameters(const CodeCompletionString &CCS, |
| 128 | std::vector<ParameterInformation> &Parameters) { |
| 129 | std::string Result; |
| 130 | for (const auto &Chunk : CCS) { |
| 131 | switch (Chunk.Kind) { |
| 132 | case CodeCompletionString::CK_Optional: |
| 133 | assert(Chunk.Optional && |
| 134 | "Expected the optional code completion string to be non-null."); |
| 135 | Result += getOptionalParameters(*Chunk.Optional, Parameters); |
| 136 | break; |
| 137 | case CodeCompletionString::CK_VerticalSpace: |
| 138 | break; |
| 139 | case CodeCompletionString::CK_Placeholder: |
| 140 | // A string that acts as a placeholder for, e.g., a function call |
| 141 | // argument. |
| 142 | // Intentional fallthrough here. |
| 143 | case CodeCompletionString::CK_CurrentParameter: { |
| 144 | // A piece of text that describes the parameter that corresponds to |
| 145 | // the code-completion location within a function call, message send, |
| 146 | // macro invocation, etc. |
| 147 | Result += Chunk.Text; |
| 148 | ParameterInformation Info; |
| 149 | Info.label = Chunk.Text; |
| 150 | Parameters.push_back(std::move(Info)); |
| 151 | break; |
| 152 | } |
| 153 | default: |
| 154 | Result += Chunk.Text; |
| 155 | break; |
| 156 | } |
| 157 | } |
| 158 | return Result; |
| 159 | } |
| 160 | |
Benjamin Kramer | 5349eed | 2017-10-28 17:32:56 +0000 | [diff] [blame] | 161 | llvm::Optional<DiagWithFixIts> toClangdDiag(const StoredDiagnostic &D) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 162 | auto Location = D.getLocation(); |
| 163 | if (!Location.isValid() || !Location.getManager().isInMainFile(Location)) |
| 164 | return llvm::None; |
| 165 | |
| 166 | Position P; |
| 167 | P.line = Location.getSpellingLineNumber() - 1; |
| 168 | P.character = Location.getSpellingColumnNumber(); |
| 169 | Range R = {P, P}; |
| 170 | clangd::Diagnostic Diag = {R, getSeverity(D.getLevel()), D.getMessage()}; |
| 171 | |
| 172 | llvm::SmallVector<tooling::Replacement, 1> FixItsForDiagnostic; |
| 173 | for (const FixItHint &Fix : D.getFixIts()) { |
| 174 | FixItsForDiagnostic.push_back(clang::tooling::Replacement( |
| 175 | Location.getManager(), Fix.RemoveRange, Fix.CodeToInsert)); |
| 176 | } |
| 177 | return DiagWithFixIts{Diag, std::move(FixItsForDiagnostic)}; |
| 178 | } |
| 179 | |
| 180 | class StoreDiagsConsumer : public DiagnosticConsumer { |
| 181 | public: |
| 182 | StoreDiagsConsumer(std::vector<DiagWithFixIts> &Output) : Output(Output) {} |
| 183 | |
| 184 | void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
| 185 | const clang::Diagnostic &Info) override { |
| 186 | DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info); |
| 187 | |
| 188 | if (auto convertedDiag = toClangdDiag(StoredDiagnostic(DiagLevel, Info))) |
| 189 | Output.push_back(std::move(*convertedDiag)); |
| 190 | } |
| 191 | |
| 192 | private: |
| 193 | std::vector<DiagWithFixIts> &Output; |
| 194 | }; |
| 195 | |
| 196 | class EmptyDiagsConsumer : public DiagnosticConsumer { |
| 197 | public: |
| 198 | void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
| 199 | const clang::Diagnostic &Info) override {} |
| 200 | }; |
| 201 | |
| 202 | std::unique_ptr<CompilerInvocation> |
| 203 | createCompilerInvocation(ArrayRef<const char *> ArgList, |
| 204 | IntrusiveRefCntPtr<DiagnosticsEngine> Diags, |
| 205 | IntrusiveRefCntPtr<vfs::FileSystem> VFS) { |
| 206 | auto CI = createInvocationFromCommandLine(ArgList, std::move(Diags), |
| 207 | std::move(VFS)); |
| 208 | // We rely on CompilerInstance to manage the resource (i.e. free them on |
| 209 | // EndSourceFile), but that won't happen if DisableFree is set to true. |
| 210 | // Since createInvocationFromCommandLine sets it to true, we have to override |
| 211 | // it. |
| 212 | CI->getFrontendOpts().DisableFree = false; |
| 213 | return CI; |
| 214 | } |
| 215 | |
| 216 | /// Creates a CompilerInstance from \p CI, with main buffer overriden to \p |
| 217 | /// Buffer and arguments to read the PCH from \p Preamble, if \p Preamble is not |
| 218 | /// null. Note that vfs::FileSystem inside returned instance may differ from \p |
| 219 | /// VFS if additional file remapping were set in command-line arguments. |
| 220 | /// On some errors, returns null. When non-null value is returned, it's expected |
| 221 | /// to be consumed by the FrontendAction as it will have a pointer to the \p |
| 222 | /// Buffer that will only be deleted if BeginSourceFile is called. |
| 223 | std::unique_ptr<CompilerInstance> |
| 224 | prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI, |
| 225 | const PrecompiledPreamble *Preamble, |
| 226 | std::unique_ptr<llvm::MemoryBuffer> Buffer, |
| 227 | std::shared_ptr<PCHContainerOperations> PCHs, |
| 228 | IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 229 | DiagnosticConsumer &DiagsClient) { |
| 230 | assert(VFS && "VFS is null"); |
| 231 | assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers && |
| 232 | "Setting RetainRemappedFileBuffers to true will cause a memory leak " |
| 233 | "of ContentsBuffer"); |
| 234 | |
| 235 | // NOTE: we use Buffer.get() when adding remapped files, so we have to make |
| 236 | // sure it will be released if no error is emitted. |
| 237 | if (Preamble) { |
Ilya Biryukov | e9eb7f0 | 2017-11-16 16:25:18 +0000 | [diff] [blame] | 238 | Preamble->AddImplicitPreamble(*CI, VFS, Buffer.get()); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 239 | } else { |
| 240 | CI->getPreprocessorOpts().addRemappedFile( |
| 241 | CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get()); |
| 242 | } |
| 243 | |
| 244 | auto Clang = llvm::make_unique<CompilerInstance>(PCHs); |
| 245 | Clang->setInvocation(std::move(CI)); |
| 246 | Clang->createDiagnostics(&DiagsClient, false); |
| 247 | |
| 248 | if (auto VFSWithRemapping = createVFSFromCompilerInvocation( |
| 249 | Clang->getInvocation(), Clang->getDiagnostics(), VFS)) |
| 250 | VFS = VFSWithRemapping; |
| 251 | Clang->setVirtualFileSystem(VFS); |
| 252 | |
| 253 | Clang->setTarget(TargetInfo::CreateTargetInfo( |
| 254 | Clang->getDiagnostics(), Clang->getInvocation().TargetOpts)); |
| 255 | if (!Clang->hasTarget()) |
| 256 | return nullptr; |
| 257 | |
| 258 | // RemappedFileBuffers will handle the lifetime of the Buffer pointer, |
| 259 | // release it. |
| 260 | Buffer.release(); |
| 261 | return Clang; |
| 262 | } |
| 263 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 264 | template <class T> bool futureIsReady(std::shared_future<T> const &Future) { |
| 265 | return Future.wait_for(std::chrono::seconds(0)) == std::future_status::ready; |
| 266 | } |
| 267 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 268 | } // namespace |
| 269 | |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 270 | namespace { |
| 271 | |
Ilya Biryukov | 01e3bf8 | 2017-10-23 06:06:21 +0000 | [diff] [blame] | 272 | CompletionItemKind getKindOfDecl(CXCursorKind CursorKind) { |
| 273 | switch (CursorKind) { |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 274 | case CXCursor_MacroInstantiation: |
| 275 | case CXCursor_MacroDefinition: |
| 276 | return CompletionItemKind::Text; |
| 277 | case CXCursor_CXXMethod: |
| 278 | return CompletionItemKind::Method; |
| 279 | case CXCursor_FunctionDecl: |
| 280 | case CXCursor_FunctionTemplate: |
| 281 | return CompletionItemKind::Function; |
| 282 | case CXCursor_Constructor: |
| 283 | case CXCursor_Destructor: |
| 284 | return CompletionItemKind::Constructor; |
| 285 | case CXCursor_FieldDecl: |
| 286 | return CompletionItemKind::Field; |
| 287 | case CXCursor_VarDecl: |
| 288 | case CXCursor_ParmDecl: |
| 289 | return CompletionItemKind::Variable; |
| 290 | case CXCursor_ClassDecl: |
| 291 | case CXCursor_StructDecl: |
| 292 | case CXCursor_UnionDecl: |
| 293 | case CXCursor_ClassTemplate: |
| 294 | case CXCursor_ClassTemplatePartialSpecialization: |
| 295 | return CompletionItemKind::Class; |
| 296 | case CXCursor_Namespace: |
| 297 | case CXCursor_NamespaceAlias: |
| 298 | case CXCursor_NamespaceRef: |
| 299 | return CompletionItemKind::Module; |
| 300 | case CXCursor_EnumConstantDecl: |
| 301 | return CompletionItemKind::Value; |
| 302 | case CXCursor_EnumDecl: |
| 303 | return CompletionItemKind::Enum; |
| 304 | case CXCursor_TypeAliasDecl: |
| 305 | case CXCursor_TypeAliasTemplateDecl: |
| 306 | case CXCursor_TypedefDecl: |
| 307 | case CXCursor_MemberRef: |
| 308 | case CXCursor_TypeRef: |
| 309 | return CompletionItemKind::Reference; |
| 310 | default: |
| 311 | return CompletionItemKind::Missing; |
| 312 | } |
| 313 | } |
| 314 | |
Ilya Biryukov | 01e3bf8 | 2017-10-23 06:06:21 +0000 | [diff] [blame] | 315 | CompletionItemKind getKind(CodeCompletionResult::ResultKind ResKind, |
| 316 | CXCursorKind CursorKind) { |
| 317 | switch (ResKind) { |
| 318 | case CodeCompletionResult::RK_Declaration: |
| 319 | return getKindOfDecl(CursorKind); |
| 320 | case CodeCompletionResult::RK_Keyword: |
| 321 | return CompletionItemKind::Keyword; |
| 322 | case CodeCompletionResult::RK_Macro: |
| 323 | return CompletionItemKind::Text; // unfortunately, there's no 'Macro' |
| 324 | // completion items in LSP. |
| 325 | case CodeCompletionResult::RK_Pattern: |
| 326 | return CompletionItemKind::Snippet; |
| 327 | } |
| 328 | llvm_unreachable("Unhandled CodeCompletionResult::ResultKind."); |
| 329 | } |
| 330 | |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 331 | std::string escapeSnippet(const llvm::StringRef Text) { |
| 332 | std::string Result; |
| 333 | Result.reserve(Text.size()); // Assume '$', '}' and '\\' are rare. |
| 334 | for (const auto Character : Text) { |
| 335 | if (Character == '$' || Character == '}' || Character == '\\') |
| 336 | Result.push_back('\\'); |
| 337 | Result.push_back(Character); |
| 338 | } |
| 339 | return Result; |
| 340 | } |
| 341 | |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 342 | std::string getDocumentation(const CodeCompletionString &CCS) { |
| 343 | // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this |
| 344 | // information in the documentation field. |
| 345 | std::string Result; |
| 346 | const unsigned AnnotationCount = CCS.getAnnotationCount(); |
| 347 | if (AnnotationCount > 0) { |
| 348 | Result += "Annotation"; |
| 349 | if (AnnotationCount == 1) { |
| 350 | Result += ": "; |
| 351 | } else /* AnnotationCount > 1 */ { |
| 352 | Result += "s: "; |
| 353 | } |
| 354 | for (unsigned I = 0; I < AnnotationCount; ++I) { |
| 355 | Result += CCS.getAnnotation(I); |
| 356 | Result.push_back(I == AnnotationCount - 1 ? '\n' : ' '); |
| 357 | } |
| 358 | } |
| 359 | // Add brief documentation (if there is any). |
| 360 | if (CCS.getBriefComment() != nullptr) { |
| 361 | if (!Result.empty()) { |
| 362 | // This means we previously added annotations. Add an extra newline |
| 363 | // character to make the annotations stand out. |
| 364 | Result.push_back('\n'); |
| 365 | } |
| 366 | Result += CCS.getBriefComment(); |
| 367 | } |
| 368 | return Result; |
| 369 | } |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 370 | |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 371 | /// A scored code completion result. |
| 372 | /// It may be promoted to a CompletionItem if it's among the top-ranked results. |
| 373 | struct CompletionCandidate { |
| 374 | CompletionCandidate(CodeCompletionResult &Result) |
| 375 | : Result(&Result), Score(score(Result)) {} |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 376 | |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 377 | CodeCompletionResult *Result; |
Sam McCall | b8d548a | 2017-11-23 17:09:04 +0000 | [diff] [blame] | 378 | float Score; // 0 to 1, higher is better. |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 379 | |
| 380 | // Comparison reflects rank: better candidates are smaller. |
| 381 | bool operator<(const CompletionCandidate &C) const { |
| 382 | if (Score != C.Score) |
Sam McCall | b8d548a | 2017-11-23 17:09:04 +0000 | [diff] [blame] | 383 | return Score > C.Score; |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 384 | return *Result < *C.Result; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 385 | } |
| 386 | |
Sam McCall | b8d548a | 2017-11-23 17:09:04 +0000 | [diff] [blame] | 387 | // Returns a string that sorts in the same order as operator<, for LSP. |
| 388 | // Conceptually, this is [-Score, Name]. We convert -Score to an integer, and |
| 389 | // hex-encode it for readability. Example: [0.5, "foo"] -> "41000000foo" |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 390 | std::string sortText() const { |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 391 | std::string S, NameStorage; |
Sam McCall | b8d548a | 2017-11-23 17:09:04 +0000 | [diff] [blame] | 392 | llvm::raw_string_ostream OS(S); |
| 393 | write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower, |
| 394 | /*Width=*/2 * sizeof(Score)); |
| 395 | OS << Result->getOrderedName(NameStorage); |
| 396 | return OS.str(); |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 397 | } |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 398 | |
| 399 | private: |
Sam McCall | b8d548a | 2017-11-23 17:09:04 +0000 | [diff] [blame] | 400 | static float score(const CodeCompletionResult &Result) { |
| 401 | // Priority 80 is a really bad score. |
| 402 | float Score = 1 - std::min<float>(80, Result.Priority) / 80; |
Ilya Biryukov | 77f61ba | 2017-09-20 15:09:14 +0000 | [diff] [blame] | 403 | |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 404 | switch (static_cast<CXAvailabilityKind>(Result.Availability)) { |
Ilya Biryukov | 77f61ba | 2017-09-20 15:09:14 +0000 | [diff] [blame] | 405 | case CXAvailability_Available: |
| 406 | // No penalty. |
| 407 | break; |
| 408 | case CXAvailability_Deprecated: |
Sam McCall | b8d548a | 2017-11-23 17:09:04 +0000 | [diff] [blame] | 409 | Score *= 0.1; |
Ilya Biryukov | 77f61ba | 2017-09-20 15:09:14 +0000 | [diff] [blame] | 410 | break; |
| 411 | case CXAvailability_NotAccessible: |
Ilya Biryukov | 77f61ba | 2017-09-20 15:09:14 +0000 | [diff] [blame] | 412 | case CXAvailability_NotAvailable: |
Sam McCall | b8d548a | 2017-11-23 17:09:04 +0000 | [diff] [blame] | 413 | Score = 0; |
Ilya Biryukov | 77f61ba | 2017-09-20 15:09:14 +0000 | [diff] [blame] | 414 | break; |
| 415 | } |
Ilya Biryukov | 77f61ba | 2017-09-20 15:09:14 +0000 | [diff] [blame] | 416 | return Score; |
| 417 | } |
Sam McCall | b8d548a | 2017-11-23 17:09:04 +0000 | [diff] [blame] | 418 | |
| 419 | // Produces an integer that sorts in the same order as F. |
| 420 | // That is: a < b <==> encodeFloat(a) < encodeFloat(b). |
| 421 | static uint32_t encodeFloat(float F) { |
| 422 | static_assert(std::numeric_limits<float>::is_iec559, ""); |
| 423 | static_assert(sizeof(float) == sizeof(uint32_t), ""); |
| 424 | constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1); |
| 425 | |
| 426 | // Get the bits of the float. Endianness is the same as for integers. |
| 427 | uint32_t U; |
| 428 | memcpy(&U, &F, sizeof(float)); |
| 429 | // IEEE 754 floats compare like sign-magnitude integers. |
| 430 | if (U & TopBit) // Negative float. |
| 431 | return 0 - U; // Map onto the low half of integers, order reversed. |
| 432 | return U + TopBit; // Positive floats map onto the high half of integers. |
| 433 | } |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 434 | }; |
Ilya Biryukov | 77f61ba | 2017-09-20 15:09:14 +0000 | [diff] [blame] | 435 | |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 436 | class CompletionItemsCollector : public CodeCompleteConsumer { |
| 437 | public: |
| 438 | CompletionItemsCollector(const clangd::CodeCompleteOptions &CodeCompleteOpts, |
| 439 | CompletionList &Items) |
| 440 | : CodeCompleteConsumer(CodeCompleteOpts.getClangCompleteOpts(), |
| 441 | /*OutputIsBinary=*/false), |
| 442 | ClangdOpts(CodeCompleteOpts), Items(Items), |
| 443 | Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()), |
| 444 | CCTUInfo(Allocator) {} |
| 445 | |
| 446 | void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, |
| 447 | CodeCompletionResult *Results, |
| 448 | unsigned NumResults) override final { |
| 449 | std::priority_queue<CompletionCandidate> Candidates; |
| 450 | for (unsigned I = 0; I < NumResults; ++I) { |
Sam McCall | adccab6 | 2017-11-23 16:58:22 +0000 | [diff] [blame] | 451 | auto &Result = Results[I]; |
| 452 | if (!ClangdOpts.IncludeIneligibleResults && |
| 453 | (Result.Availability == CXAvailability_NotAvailable || |
| 454 | Result.Availability == CXAvailability_NotAccessible)) |
| 455 | continue; |
| 456 | Candidates.emplace(Result); |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 457 | if (ClangdOpts.Limit && Candidates.size() > ClangdOpts.Limit) { |
| 458 | Candidates.pop(); |
| 459 | Items.isIncomplete = true; |
| 460 | } |
| 461 | } |
| 462 | while (!Candidates.empty()) { |
| 463 | auto &Candidate = Candidates.top(); |
| 464 | const auto *CCS = Candidate.Result->CreateCodeCompletionString( |
| 465 | S, Context, *Allocator, CCTUInfo, |
| 466 | CodeCompleteOpts.IncludeBriefComments); |
| 467 | assert(CCS && "Expected the CodeCompletionString to be non-null"); |
| 468 | Items.items.push_back(ProcessCodeCompleteResult(Candidate, *CCS)); |
| 469 | Candidates.pop(); |
| 470 | } |
| 471 | std::reverse(Items.items.begin(), Items.items.end()); |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 472 | } |
| 473 | |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 474 | GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; } |
| 475 | |
| 476 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } |
| 477 | |
| 478 | private: |
| 479 | CompletionItem |
| 480 | ProcessCodeCompleteResult(const CompletionCandidate &Candidate, |
| 481 | const CodeCompletionString &CCS) const { |
| 482 | |
| 483 | // Adjust this to InsertTextFormat::Snippet iff we encounter a |
| 484 | // CK_Placeholder chunk in SnippetCompletionItemsCollector. |
| 485 | CompletionItem Item; |
| 486 | Item.insertTextFormat = InsertTextFormat::PlainText; |
| 487 | |
| 488 | Item.documentation = getDocumentation(CCS); |
| 489 | Item.sortText = Candidate.sortText(); |
| 490 | |
| 491 | // Fill in the label, detail, insertText and filterText fields of the |
| 492 | // CompletionItem. |
| 493 | ProcessChunks(CCS, Item); |
| 494 | |
| 495 | // Fill in the kind field of the CompletionItem. |
| 496 | Item.kind = getKind(Candidate.Result->Kind, Candidate.Result->CursorKind); |
| 497 | |
| 498 | return Item; |
| 499 | } |
| 500 | |
| 501 | virtual void ProcessChunks(const CodeCompletionString &CCS, |
| 502 | CompletionItem &Item) const = 0; |
| 503 | |
| 504 | clangd::CodeCompleteOptions ClangdOpts; |
| 505 | CompletionList &Items; |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 506 | std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator; |
| 507 | CodeCompletionTUInfo CCTUInfo; |
| 508 | |
| 509 | }; // CompletionItemsCollector |
| 510 | |
Ilya Biryukov | 686ff9a | 2017-09-28 18:39:59 +0000 | [diff] [blame] | 511 | bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) { |
| 512 | return Chunk.Kind == CodeCompletionString::CK_Informative && |
| 513 | StringRef(Chunk.Text).endswith("::"); |
| 514 | } |
| 515 | |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 516 | class PlainTextCompletionItemsCollector final |
| 517 | : public CompletionItemsCollector { |
| 518 | |
| 519 | public: |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 520 | PlainTextCompletionItemsCollector( |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 521 | const clangd::CodeCompleteOptions &CodeCompleteOpts, |
| 522 | CompletionList &Items) |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 523 | : CompletionItemsCollector(CodeCompleteOpts, Items) {} |
| 524 | |
| 525 | private: |
| 526 | void ProcessChunks(const CodeCompletionString &CCS, |
| 527 | CompletionItem &Item) const override { |
| 528 | for (const auto &Chunk : CCS) { |
Ilya Biryukov | 686ff9a | 2017-09-28 18:39:59 +0000 | [diff] [blame] | 529 | // Informative qualifier chunks only clutter completion results, skip |
| 530 | // them. |
| 531 | if (isInformativeQualifierChunk(Chunk)) |
| 532 | continue; |
| 533 | |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 534 | switch (Chunk.Kind) { |
| 535 | case CodeCompletionString::CK_TypedText: |
| 536 | // There's always exactly one CK_TypedText chunk. |
| 537 | Item.insertText = Item.filterText = Chunk.Text; |
| 538 | Item.label += Chunk.Text; |
| 539 | break; |
| 540 | case CodeCompletionString::CK_ResultType: |
| 541 | assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType"); |
| 542 | Item.detail = Chunk.Text; |
| 543 | break; |
| 544 | case CodeCompletionString::CK_Optional: |
| 545 | break; |
| 546 | default: |
| 547 | Item.label += Chunk.Text; |
| 548 | break; |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | }; // PlainTextCompletionItemsCollector |
| 553 | |
| 554 | class SnippetCompletionItemsCollector final : public CompletionItemsCollector { |
| 555 | |
| 556 | public: |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 557 | SnippetCompletionItemsCollector( |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 558 | const clangd::CodeCompleteOptions &CodeCompleteOpts, |
| 559 | CompletionList &Items) |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 560 | : CompletionItemsCollector(CodeCompleteOpts, Items) {} |
| 561 | |
| 562 | private: |
| 563 | void ProcessChunks(const CodeCompletionString &CCS, |
| 564 | CompletionItem &Item) const override { |
| 565 | unsigned ArgCount = 0; |
| 566 | for (const auto &Chunk : CCS) { |
Ilya Biryukov | 686ff9a | 2017-09-28 18:39:59 +0000 | [diff] [blame] | 567 | // Informative qualifier chunks only clutter completion results, skip |
| 568 | // them. |
| 569 | if (isInformativeQualifierChunk(Chunk)) |
| 570 | continue; |
| 571 | |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 572 | switch (Chunk.Kind) { |
| 573 | case CodeCompletionString::CK_TypedText: |
| 574 | // The piece of text that the user is expected to type to match |
| 575 | // the code-completion string, typically a keyword or the name of |
| 576 | // a declarator or macro. |
| 577 | Item.filterText = Chunk.Text; |
Simon Pilgrim | 948c0bc | 2017-11-01 09:22:03 +0000 | [diff] [blame] | 578 | LLVM_FALLTHROUGH; |
Ilya Biryukov | b33c157 | 2017-09-12 13:57:14 +0000 | [diff] [blame] | 579 | case CodeCompletionString::CK_Text: |
| 580 | // A piece of text that should be placed in the buffer, |
| 581 | // e.g., parentheses or a comma in a function call. |
| 582 | Item.label += Chunk.Text; |
| 583 | Item.insertText += Chunk.Text; |
| 584 | break; |
| 585 | case CodeCompletionString::CK_Optional: |
| 586 | // A code completion string that is entirely optional. |
| 587 | // For example, an optional code completion string that |
| 588 | // describes the default arguments in a function call. |
| 589 | |
| 590 | // FIXME: Maybe add an option to allow presenting the optional chunks? |
| 591 | break; |
| 592 | case CodeCompletionString::CK_Placeholder: |
| 593 | // A string that acts as a placeholder for, e.g., a function call |
| 594 | // argument. |
| 595 | ++ArgCount; |
| 596 | Item.insertText += "${" + std::to_string(ArgCount) + ':' + |
| 597 | escapeSnippet(Chunk.Text) + '}'; |
| 598 | Item.label += Chunk.Text; |
| 599 | Item.insertTextFormat = InsertTextFormat::Snippet; |
| 600 | break; |
| 601 | case CodeCompletionString::CK_Informative: |
| 602 | // A piece of text that describes something about the result |
| 603 | // but should not be inserted into the buffer. |
| 604 | // For example, the word "const" for a const method, or the name of |
| 605 | // the base class for methods that are part of the base class. |
| 606 | Item.label += Chunk.Text; |
| 607 | // Don't put the informative chunks in the insertText. |
| 608 | break; |
| 609 | case CodeCompletionString::CK_ResultType: |
| 610 | // A piece of text that describes the type of an entity or, |
| 611 | // for functions and methods, the return type. |
| 612 | assert(Item.detail.empty() && "Unexpected extraneous CK_ResultType"); |
| 613 | Item.detail = Chunk.Text; |
| 614 | break; |
| 615 | case CodeCompletionString::CK_CurrentParameter: |
| 616 | // A piece of text that describes the parameter that corresponds to |
| 617 | // the code-completion location within a function call, message send, |
| 618 | // macro invocation, etc. |
| 619 | // |
| 620 | // This should never be present while collecting completion items, |
| 621 | // only while collecting overload candidates. |
| 622 | llvm_unreachable("Unexpected CK_CurrentParameter while collecting " |
| 623 | "CompletionItems"); |
| 624 | break; |
| 625 | case CodeCompletionString::CK_LeftParen: |
| 626 | // A left parenthesis ('('). |
| 627 | case CodeCompletionString::CK_RightParen: |
| 628 | // A right parenthesis (')'). |
| 629 | case CodeCompletionString::CK_LeftBracket: |
| 630 | // A left bracket ('['). |
| 631 | case CodeCompletionString::CK_RightBracket: |
| 632 | // A right bracket (']'). |
| 633 | case CodeCompletionString::CK_LeftBrace: |
| 634 | // A left brace ('{'). |
| 635 | case CodeCompletionString::CK_RightBrace: |
| 636 | // A right brace ('}'). |
| 637 | case CodeCompletionString::CK_LeftAngle: |
| 638 | // A left angle bracket ('<'). |
| 639 | case CodeCompletionString::CK_RightAngle: |
| 640 | // A right angle bracket ('>'). |
| 641 | case CodeCompletionString::CK_Comma: |
| 642 | // A comma separator (','). |
| 643 | case CodeCompletionString::CK_Colon: |
| 644 | // A colon (':'). |
| 645 | case CodeCompletionString::CK_SemiColon: |
| 646 | // A semicolon (';'). |
| 647 | case CodeCompletionString::CK_Equal: |
| 648 | // An '=' sign. |
| 649 | case CodeCompletionString::CK_HorizontalSpace: |
| 650 | // Horizontal whitespace (' '). |
| 651 | Item.insertText += Chunk.Text; |
| 652 | Item.label += Chunk.Text; |
| 653 | break; |
| 654 | case CodeCompletionString::CK_VerticalSpace: |
| 655 | // Vertical whitespace ('\n' or '\r\n', depending on the |
| 656 | // platform). |
| 657 | Item.insertText += Chunk.Text; |
| 658 | // Don't even add a space to the label. |
| 659 | break; |
| 660 | } |
| 661 | } |
| 662 | } |
| 663 | }; // SnippetCompletionItemsCollector |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 664 | |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 665 | class SignatureHelpCollector final : public CodeCompleteConsumer { |
| 666 | |
| 667 | public: |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 668 | SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts, |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 669 | SignatureHelp &SigHelp) |
| 670 | : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false), |
| 671 | SigHelp(SigHelp), |
| 672 | Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()), |
| 673 | CCTUInfo(Allocator) {} |
| 674 | |
| 675 | void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, |
| 676 | OverloadCandidate *Candidates, |
| 677 | unsigned NumCandidates) override { |
| 678 | SigHelp.signatures.reserve(NumCandidates); |
| 679 | // FIXME(rwols): How can we determine the "active overload candidate"? |
| 680 | // Right now the overloaded candidates seem to be provided in a "best fit" |
| 681 | // order, so I'm not too worried about this. |
| 682 | SigHelp.activeSignature = 0; |
Simon Pilgrim | a3aa724 | 2017-10-07 12:24:10 +0000 | [diff] [blame] | 683 | assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() && |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 684 | "too many arguments"); |
| 685 | SigHelp.activeParameter = static_cast<int>(CurrentArg); |
| 686 | for (unsigned I = 0; I < NumCandidates; ++I) { |
| 687 | const auto &Candidate = Candidates[I]; |
| 688 | const auto *CCS = Candidate.CreateSignatureString( |
| 689 | CurrentArg, S, *Allocator, CCTUInfo, true); |
| 690 | assert(CCS && "Expected the CodeCompletionString to be non-null"); |
| 691 | SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS)); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; } |
| 696 | |
| 697 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } |
| 698 | |
| 699 | private: |
| 700 | SignatureInformation |
| 701 | ProcessOverloadCandidate(const OverloadCandidate &Candidate, |
| 702 | const CodeCompletionString &CCS) const { |
| 703 | SignatureInformation Result; |
| 704 | const char *ReturnType = nullptr; |
| 705 | |
| 706 | Result.documentation = getDocumentation(CCS); |
| 707 | |
| 708 | for (const auto &Chunk : CCS) { |
| 709 | switch (Chunk.Kind) { |
| 710 | case CodeCompletionString::CK_ResultType: |
| 711 | // A piece of text that describes the type of an entity or, |
| 712 | // for functions and methods, the return type. |
| 713 | assert(!ReturnType && "Unexpected CK_ResultType"); |
| 714 | ReturnType = Chunk.Text; |
| 715 | break; |
| 716 | case CodeCompletionString::CK_Placeholder: |
| 717 | // A string that acts as a placeholder for, e.g., a function call |
| 718 | // argument. |
| 719 | // Intentional fallthrough here. |
| 720 | case CodeCompletionString::CK_CurrentParameter: { |
| 721 | // A piece of text that describes the parameter that corresponds to |
| 722 | // the code-completion location within a function call, message send, |
| 723 | // macro invocation, etc. |
| 724 | Result.label += Chunk.Text; |
| 725 | ParameterInformation Info; |
| 726 | Info.label = Chunk.Text; |
| 727 | Result.parameters.push_back(std::move(Info)); |
| 728 | break; |
| 729 | } |
| 730 | case CodeCompletionString::CK_Optional: { |
| 731 | // The rest of the parameters are defaulted/optional. |
| 732 | assert(Chunk.Optional && |
| 733 | "Expected the optional code completion string to be non-null."); |
| 734 | Result.label += |
| 735 | getOptionalParameters(*Chunk.Optional, Result.parameters); |
| 736 | break; |
| 737 | } |
| 738 | case CodeCompletionString::CK_VerticalSpace: |
| 739 | break; |
| 740 | default: |
| 741 | Result.label += Chunk.Text; |
| 742 | break; |
| 743 | } |
| 744 | } |
| 745 | if (ReturnType) { |
| 746 | Result.label += " -> "; |
| 747 | Result.label += ReturnType; |
| 748 | } |
| 749 | return Result; |
| 750 | } |
| 751 | |
| 752 | SignatureHelp &SigHelp; |
| 753 | std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator; |
| 754 | CodeCompletionTUInfo CCTUInfo; |
| 755 | |
| 756 | }; // SignatureHelpCollector |
| 757 | |
| 758 | bool invokeCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer, |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 759 | const clang::CodeCompleteOptions &Options, |
| 760 | PathRef FileName, |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 761 | const tooling::CompileCommand &Command, |
| 762 | PrecompiledPreamble const *Preamble, StringRef Contents, |
| 763 | Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 764 | std::shared_ptr<PCHContainerOperations> PCHs, |
| 765 | clangd::Logger &Logger) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 766 | std::vector<const char *> ArgStrs; |
| 767 | for (const auto &S : Command.CommandLine) |
| 768 | ArgStrs.push_back(S.c_str()); |
| 769 | |
Krasimir Georgiev | e4130d5 | 2017-07-25 11:37:43 +0000 | [diff] [blame] | 770 | VFS->setCurrentWorkingDirectory(Command.Directory); |
| 771 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 772 | std::unique_ptr<CompilerInvocation> CI; |
| 773 | EmptyDiagsConsumer DummyDiagsConsumer; |
| 774 | { |
| 775 | IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine = |
| 776 | CompilerInstance::createDiagnostics(new DiagnosticOptions, |
| 777 | &DummyDiagsConsumer, false); |
| 778 | CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS); |
| 779 | } |
| 780 | assert(CI && "Couldn't create CompilerInvocation"); |
| 781 | |
| 782 | std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = |
| 783 | llvm::MemoryBuffer::getMemBufferCopy(Contents, FileName); |
| 784 | |
| 785 | // Attempt to reuse the PCH from precompiled preamble, if it was built. |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 786 | if (Preamble) { |
| 787 | auto Bounds = |
| 788 | ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 789 | if (!Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds, VFS.get())) |
| 790 | Preamble = nullptr; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 791 | } |
| 792 | |
Benjamin Kramer | 5349eed | 2017-10-28 17:32:56 +0000 | [diff] [blame] | 793 | auto Clang = prepareCompilerInstance( |
| 794 | std::move(CI), Preamble, std::move(ContentsBuffer), std::move(PCHs), |
| 795 | std::move(VFS), DummyDiagsConsumer); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 796 | auto &DiagOpts = Clang->getDiagnosticOpts(); |
| 797 | DiagOpts.IgnoreWarnings = true; |
| 798 | |
| 799 | auto &FrontendOpts = Clang->getFrontendOpts(); |
| 800 | FrontendOpts.SkipFunctionBodies = true; |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 801 | FrontendOpts.CodeCompleteOpts = Options; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 802 | FrontendOpts.CodeCompletionAt.FileName = FileName; |
| 803 | FrontendOpts.CodeCompletionAt.Line = Pos.line + 1; |
| 804 | FrontendOpts.CodeCompletionAt.Column = Pos.character + 1; |
| 805 | |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 806 | Clang->setCodeCompletionConsumer(Consumer.release()); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 807 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 808 | SyntaxOnlyAction Action; |
| 809 | if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) { |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 810 | Logger.log("BeginSourceFile() failed when running codeComplete for " + |
| 811 | FileName); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 812 | return false; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 813 | } |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 814 | if (!Action.Execute()) { |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 815 | Logger.log("Execute() failed when running codeComplete for " + FileName); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 816 | return false; |
| 817 | } |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 818 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 819 | Action.EndSourceFile(); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 820 | |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 821 | return true; |
| 822 | } |
| 823 | |
| 824 | } // namespace |
| 825 | |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 826 | clang::CodeCompleteOptions |
| 827 | clangd::CodeCompleteOptions::getClangCompleteOpts() const { |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 828 | clang::CodeCompleteOptions Result; |
| 829 | Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns; |
| 830 | Result.IncludeMacros = IncludeMacros; |
| 831 | Result.IncludeGlobals = IncludeGlobals; |
| 832 | Result.IncludeBriefComments = IncludeBriefComments; |
| 833 | |
| 834 | return Result; |
| 835 | } |
| 836 | |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 837 | CompletionList |
Benjamin Kramer | 5349eed | 2017-10-28 17:32:56 +0000 | [diff] [blame] | 838 | clangd::codeComplete(PathRef FileName, const tooling::CompileCommand &Command, |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 839 | PrecompiledPreamble const *Preamble, StringRef Contents, |
| 840 | Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 841 | std::shared_ptr<PCHContainerOperations> PCHs, |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 842 | clangd::CodeCompleteOptions Opts, clangd::Logger &Logger) { |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 843 | CompletionList Results; |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 844 | std::unique_ptr<CodeCompleteConsumer> Consumer; |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 845 | if (Opts.EnableSnippets) { |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 846 | Consumer = |
| 847 | llvm::make_unique<SnippetCompletionItemsCollector>(Opts, Results); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 848 | } else { |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 849 | Consumer = |
| 850 | llvm::make_unique<PlainTextCompletionItemsCollector>(Opts, Results); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 851 | } |
Sam McCall | a40371b | 2017-11-15 09:16:29 +0000 | [diff] [blame] | 852 | invokeCodeComplete(std::move(Consumer), Opts.getClangCompleteOpts(), FileName, |
| 853 | Command, Preamble, Contents, Pos, std::move(VFS), |
| 854 | std::move(PCHs), Logger); |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 855 | return Results; |
| 856 | } |
| 857 | |
| 858 | SignatureHelp |
Benjamin Kramer | 5349eed | 2017-10-28 17:32:56 +0000 | [diff] [blame] | 859 | clangd::signatureHelp(PathRef FileName, const tooling::CompileCommand &Command, |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 860 | PrecompiledPreamble const *Preamble, StringRef Contents, |
| 861 | Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 862 | std::shared_ptr<PCHContainerOperations> PCHs, |
| 863 | clangd::Logger &Logger) { |
| 864 | SignatureHelp Result; |
Ilya Biryukov | b080cb1 | 2017-10-23 14:46:48 +0000 | [diff] [blame] | 865 | clang::CodeCompleteOptions Options; |
Ilya Biryukov | d9bdfe0 | 2017-10-06 11:54:17 +0000 | [diff] [blame] | 866 | Options.IncludeGlobals = false; |
| 867 | Options.IncludeMacros = false; |
| 868 | Options.IncludeCodePatterns = false; |
| 869 | Options.IncludeBriefComments = true; |
| 870 | invokeCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result), |
| 871 | Options, FileName, Command, Preamble, Contents, Pos, |
| 872 | std::move(VFS), std::move(PCHs), Logger); |
| 873 | return Result; |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 874 | } |
| 875 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 876 | void clangd::dumpAST(ParsedAST &AST, llvm::raw_ostream &OS) { |
| 877 | AST.getASTContext().getTranslationUnitDecl()->dump(OS, true); |
Ilya Biryukov | 38d7977 | 2017-05-16 09:38:59 +0000 | [diff] [blame] | 878 | } |
Ilya Biryukov | f01af68 | 2017-05-23 13:42:59 +0000 | [diff] [blame] | 879 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 880 | llvm::Optional<ParsedAST> |
| 881 | ParsedAST::Build(std::unique_ptr<clang::CompilerInvocation> CI, |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 882 | std::shared_ptr<const PreambleData> Preamble, |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 883 | std::unique_ptr<llvm::MemoryBuffer> Buffer, |
| 884 | std::shared_ptr<PCHContainerOperations> PCHs, |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 885 | IntrusiveRefCntPtr<vfs::FileSystem> VFS, |
| 886 | clangd::Logger &Logger) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 887 | |
| 888 | std::vector<DiagWithFixIts> ASTDiags; |
| 889 | StoreDiagsConsumer UnitDiagsConsumer(/*ref*/ ASTDiags); |
| 890 | |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 891 | const PrecompiledPreamble *PreamblePCH = |
| 892 | Preamble ? &Preamble->Preamble : nullptr; |
Benjamin Kramer | 5349eed | 2017-10-28 17:32:56 +0000 | [diff] [blame] | 893 | auto Clang = prepareCompilerInstance( |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 894 | std::move(CI), PreamblePCH, std::move(Buffer), std::move(PCHs), |
Benjamin Kramer | 5349eed | 2017-10-28 17:32:56 +0000 | [diff] [blame] | 895 | std::move(VFS), /*ref*/ UnitDiagsConsumer); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 896 | |
| 897 | // Recover resources if we crash before exiting this method. |
| 898 | llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup( |
| 899 | Clang.get()); |
| 900 | |
| 901 | auto Action = llvm::make_unique<ClangdFrontendAction>(); |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 902 | const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0]; |
| 903 | if (!Action->BeginSourceFile(*Clang, MainInput)) { |
| 904 | Logger.log("BeginSourceFile() failed when building AST for " + |
| 905 | MainInput.getFile()); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 906 | return llvm::None; |
| 907 | } |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 908 | if (!Action->Execute()) |
| 909 | Logger.log("Execute() failed when building AST for " + MainInput.getFile()); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 910 | |
| 911 | // UnitDiagsConsumer is local, we can not store it in CompilerInstance that |
| 912 | // has a longer lifetime. |
| 913 | Clang->getDiagnostics().setClient(new EmptyDiagsConsumer); |
| 914 | |
| 915 | std::vector<const Decl *> ParsedDecls = Action->takeTopLevelDecls(); |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 916 | return ParsedAST(std::move(Preamble), std::move(Clang), std::move(Action), |
| 917 | std::move(ParsedDecls), std::move(ASTDiags)); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 918 | } |
| 919 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 920 | namespace { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 921 | |
| 922 | SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr, |
| 923 | const FileEntry *FE, |
| 924 | unsigned Offset) { |
| 925 | SourceLocation FileLoc = Mgr.translateFileLineCol(FE, 1, 1); |
| 926 | return Mgr.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset)); |
| 927 | } |
| 928 | |
| 929 | SourceLocation getMacroArgExpandedLocation(const SourceManager &Mgr, |
| 930 | const FileEntry *FE, Position Pos) { |
| 931 | SourceLocation InputLoc = |
| 932 | Mgr.translateFileLineCol(FE, Pos.line + 1, Pos.character + 1); |
| 933 | return Mgr.getMacroArgExpandedLocation(InputLoc); |
| 934 | } |
| 935 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 936 | /// Finds declarations locations that a given source location refers to. |
| 937 | class DeclarationLocationsFinder : public index::IndexDataConsumer { |
| 938 | std::vector<Location> DeclarationLocations; |
| 939 | const SourceLocation &SearchedLocation; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 940 | const ASTContext &AST; |
| 941 | Preprocessor &PP; |
| 942 | |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 943 | public: |
| 944 | DeclarationLocationsFinder(raw_ostream &OS, |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 945 | const SourceLocation &SearchedLocation, |
| 946 | ASTContext &AST, Preprocessor &PP) |
| 947 | : SearchedLocation(SearchedLocation), AST(AST), PP(PP) {} |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 948 | |
| 949 | std::vector<Location> takeLocations() { |
| 950 | // Don't keep the same location multiple times. |
| 951 | // This can happen when nodes in the AST are visited twice. |
| 952 | std::sort(DeclarationLocations.begin(), DeclarationLocations.end()); |
Kirill Bobyrev | 4621387 | 2017-06-28 20:57:28 +0000 | [diff] [blame] | 953 | auto last = |
| 954 | std::unique(DeclarationLocations.begin(), DeclarationLocations.end()); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 955 | DeclarationLocations.erase(last, DeclarationLocations.end()); |
| 956 | return std::move(DeclarationLocations); |
| 957 | } |
| 958 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 959 | bool |
| 960 | handleDeclOccurence(const Decl *D, index::SymbolRoleSet Roles, |
| 961 | ArrayRef<index::SymbolRelation> Relations, FileID FID, |
| 962 | unsigned Offset, |
| 963 | index::IndexDataConsumer::ASTNodeInfo ASTNode) override { |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 964 | if (isSearchedLocation(FID, Offset)) { |
| 965 | addDeclarationLocation(D->getSourceRange()); |
| 966 | } |
| 967 | return true; |
| 968 | } |
| 969 | |
| 970 | private: |
| 971 | bool isSearchedLocation(FileID FID, unsigned Offset) const { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 972 | const SourceManager &SourceMgr = AST.getSourceManager(); |
| 973 | return SourceMgr.getFileOffset(SearchedLocation) == Offset && |
| 974 | SourceMgr.getFileID(SearchedLocation) == FID; |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 975 | } |
| 976 | |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 977 | void addDeclarationLocation(const SourceRange &ValSourceRange) { |
| 978 | const SourceManager &SourceMgr = AST.getSourceManager(); |
| 979 | const LangOptions &LangOpts = AST.getLangOpts(); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 980 | SourceLocation LocStart = ValSourceRange.getBegin(); |
| 981 | SourceLocation LocEnd = Lexer::getLocForEndOfToken(ValSourceRange.getEnd(), |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 982 | 0, SourceMgr, LangOpts); |
Kirill Bobyrev | 4621387 | 2017-06-28 20:57:28 +0000 | [diff] [blame] | 983 | Position Begin; |
| 984 | Begin.line = SourceMgr.getSpellingLineNumber(LocStart) - 1; |
| 985 | Begin.character = SourceMgr.getSpellingColumnNumber(LocStart) - 1; |
| 986 | Position End; |
| 987 | End.line = SourceMgr.getSpellingLineNumber(LocEnd) - 1; |
| 988 | End.character = SourceMgr.getSpellingColumnNumber(LocEnd) - 1; |
| 989 | Range R = {Begin, End}; |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 990 | Location L; |
Marc-Andre Laperle | ba07010 | 2017-11-07 16:16:45 +0000 | [diff] [blame] | 991 | if (const FileEntry *F = |
| 992 | SourceMgr.getFileEntryForID(SourceMgr.getFileID(LocStart))) { |
| 993 | StringRef FilePath = F->tryGetRealPathName(); |
| 994 | if (FilePath.empty()) |
| 995 | FilePath = F->getName(); |
| 996 | L.uri = URI::fromFile(FilePath); |
| 997 | L.range = R; |
| 998 | DeclarationLocations.push_back(L); |
| 999 | } |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1000 | } |
| 1001 | |
Kirill Bobyrev | 4621387 | 2017-06-28 20:57:28 +0000 | [diff] [blame] | 1002 | void finish() override { |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1003 | // Also handle possible macro at the searched location. |
| 1004 | Token Result; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1005 | if (!Lexer::getRawToken(SearchedLocation, Result, AST.getSourceManager(), |
| 1006 | AST.getLangOpts(), false)) { |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1007 | if (Result.is(tok::raw_identifier)) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1008 | PP.LookUpIdentifierInfo(Result); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1009 | } |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1010 | IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo(); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1011 | if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) { |
| 1012 | std::pair<FileID, unsigned int> DecLoc = |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1013 | AST.getSourceManager().getDecomposedExpansionLoc(SearchedLocation); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1014 | // Get the definition just before the searched location so that a macro |
| 1015 | // referenced in a '#undef MACRO' can still be found. |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1016 | SourceLocation BeforeSearchedLocation = getMacroArgExpandedLocation( |
| 1017 | AST.getSourceManager(), |
| 1018 | AST.getSourceManager().getFileEntryForID(DecLoc.first), |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1019 | DecLoc.second - 1); |
| 1020 | MacroDefinition MacroDef = |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1021 | PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation); |
| 1022 | MacroInfo *MacroInf = MacroDef.getMacroInfo(); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1023 | if (MacroInf) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1024 | addDeclarationLocation(SourceRange(MacroInf->getDefinitionLoc(), |
| 1025 | MacroInf->getDefinitionEndLoc())); |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1026 | } |
| 1027 | } |
| 1028 | } |
| 1029 | } |
| 1030 | }; |
Marc-Andre Laperle | 2cbf037 | 2017-06-28 16:12:10 +0000 | [diff] [blame] | 1031 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1032 | } // namespace |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1033 | |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 1034 | std::vector<Location> clangd::findDefinitions(ParsedAST &AST, Position Pos, |
| 1035 | clangd::Logger &Logger) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1036 | const SourceManager &SourceMgr = AST.getASTContext().getSourceManager(); |
| 1037 | const FileEntry *FE = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()); |
| 1038 | if (!FE) |
| 1039 | return {}; |
| 1040 | |
| 1041 | SourceLocation SourceLocationBeg = getBeginningOfIdentifier(AST, Pos, FE); |
| 1042 | |
| 1043 | auto DeclLocationsFinder = std::make_shared<DeclarationLocationsFinder>( |
| 1044 | llvm::errs(), SourceLocationBeg, AST.getASTContext(), |
| 1045 | AST.getPreprocessor()); |
| 1046 | index::IndexingOptions IndexOpts; |
| 1047 | IndexOpts.SystemSymbolFilter = |
| 1048 | index::IndexingOptions::SystemSymbolFilterKind::All; |
| 1049 | IndexOpts.IndexFunctionLocals = true; |
| 1050 | |
| 1051 | indexTopLevelDecls(AST.getASTContext(), AST.getTopLevelDecls(), |
| 1052 | DeclLocationsFinder, IndexOpts); |
| 1053 | |
| 1054 | return DeclLocationsFinder->takeLocations(); |
| 1055 | } |
| 1056 | |
| 1057 | void ParsedAST::ensurePreambleDeclsDeserialized() { |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 1058 | if (PreambleDeclsDeserialized || !Preamble) |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1059 | return; |
| 1060 | |
| 1061 | std::vector<const Decl *> Resolved; |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 1062 | Resolved.reserve(Preamble->TopLevelDeclIDs.size()); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1063 | |
| 1064 | ExternalASTSource &Source = *getASTContext().getExternalSource(); |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 1065 | for (serialization::DeclID TopLevelDecl : Preamble->TopLevelDeclIDs) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1066 | // Resolve the declaration ID to an actual declaration, possibly |
| 1067 | // deserializing the declaration in the process. |
| 1068 | if (Decl *D = Source.GetExternalDecl(TopLevelDecl)) |
| 1069 | Resolved.push_back(D); |
| 1070 | } |
| 1071 | |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 1072 | TopLevelDecls.reserve(TopLevelDecls.size() + |
| 1073 | Preamble->TopLevelDeclIDs.size()); |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1074 | TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); |
| 1075 | |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 1076 | PreambleDeclsDeserialized = true; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1077 | } |
| 1078 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1079 | ParsedAST::ParsedAST(ParsedAST &&Other) = default; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1080 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1081 | ParsedAST &ParsedAST::operator=(ParsedAST &&Other) = default; |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1082 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1083 | ParsedAST::~ParsedAST() { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1084 | if (Action) { |
| 1085 | Action->EndSourceFile(); |
| 1086 | } |
| 1087 | } |
| 1088 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1089 | ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); } |
| 1090 | |
| 1091 | const ASTContext &ParsedAST::getASTContext() const { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1092 | return Clang->getASTContext(); |
| 1093 | } |
| 1094 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1095 | Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); } |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1096 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1097 | const Preprocessor &ParsedAST::getPreprocessor() const { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1098 | return Clang->getPreprocessor(); |
| 1099 | } |
| 1100 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1101 | ArrayRef<const Decl *> ParsedAST::getTopLevelDecls() { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1102 | ensurePreambleDeclsDeserialized(); |
| 1103 | return TopLevelDecls; |
| 1104 | } |
| 1105 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1106 | const std::vector<DiagWithFixIts> &ParsedAST::getDiagnostics() const { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1107 | return Diags; |
| 1108 | } |
| 1109 | |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 1110 | PreambleData::PreambleData(PrecompiledPreamble Preamble, |
| 1111 | std::vector<serialization::DeclID> TopLevelDeclIDs, |
| 1112 | std::vector<DiagWithFixIts> Diags) |
| 1113 | : Preamble(std::move(Preamble)), |
| 1114 | TopLevelDeclIDs(std::move(TopLevelDeclIDs)), Diags(std::move(Diags)) {} |
| 1115 | |
| 1116 | ParsedAST::ParsedAST(std::shared_ptr<const PreambleData> Preamble, |
| 1117 | std::unique_ptr<CompilerInstance> Clang, |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1118 | std::unique_ptr<FrontendAction> Action, |
| 1119 | std::vector<const Decl *> TopLevelDecls, |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1120 | std::vector<DiagWithFixIts> Diags) |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 1121 | : Preamble(std::move(Preamble)), Clang(std::move(Clang)), |
| 1122 | Action(std::move(Action)), Diags(std::move(Diags)), |
| 1123 | TopLevelDecls(std::move(TopLevelDecls)), |
| 1124 | PreambleDeclsDeserialized(false) { |
Ilya Biryukov | 04db368 | 2017-07-21 13:29:29 +0000 | [diff] [blame] | 1125 | assert(this->Clang); |
| 1126 | assert(this->Action); |
| 1127 | } |
| 1128 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1129 | ParsedASTWrapper::ParsedASTWrapper(ParsedASTWrapper &&Wrapper) |
| 1130 | : AST(std::move(Wrapper.AST)) {} |
| 1131 | |
| 1132 | ParsedASTWrapper::ParsedASTWrapper(llvm::Optional<ParsedAST> AST) |
| 1133 | : AST(std::move(AST)) {} |
| 1134 | |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1135 | std::shared_ptr<CppFile> |
| 1136 | CppFile::Create(PathRef FileName, tooling::CompileCommand Command, |
Ilya Biryukov | e9eb7f0 | 2017-11-16 16:25:18 +0000 | [diff] [blame] | 1137 | bool StorePreamblesInMemory, |
Ilya Biryukov | 83ca8a2 | 2017-09-20 10:46:58 +0000 | [diff] [blame] | 1138 | std::shared_ptr<PCHContainerOperations> PCHs, |
| 1139 | clangd::Logger &Logger) { |
Ilya Biryukov | e9eb7f0 | 2017-11-16 16:25:18 +0000 | [diff] [blame] | 1140 | return std::shared_ptr<CppFile>(new CppFile(FileName, std::move(Command), |
| 1141 | StorePreamblesInMemory, |
| 1142 | std::move(PCHs), Logger)); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1143 | } |
| 1144 | |
| 1145 | CppFile::CppFile(PathRef FileName, tooling::CompileCommand Command, |
Ilya Biryukov | e9eb7f0 | 2017-11-16 16:25:18 +0000 | [diff] [blame] | 1146 | bool StorePreamblesInMemory, |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 1147 | std::shared_ptr<PCHContainerOperations> PCHs, |
| 1148 | clangd::Logger &Logger) |
Ilya Biryukov | e9eb7f0 | 2017-11-16 16:25:18 +0000 | [diff] [blame] | 1149 | : FileName(FileName), Command(std::move(Command)), |
| 1150 | StorePreamblesInMemory(StorePreamblesInMemory), RebuildCounter(0), |
Ilya Biryukov | e5128f7 | 2017-09-20 07:24:15 +0000 | [diff] [blame] | 1151 | RebuildInProgress(false), PCHs(std::move(PCHs)), Logger(Logger) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1152 | |
| 1153 | std::lock_guard<std::mutex> Lock(Mutex); |
| 1154 | LatestAvailablePreamble = nullptr; |
| 1155 | PreamblePromise.set_value(nullptr); |
| 1156 | PreambleFuture = PreamblePromise.get_future(); |
| 1157 | |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 1158 | ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None)); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1159 | ASTFuture = ASTPromise.get_future(); |
| 1160 | } |
| 1161 | |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 1162 | void CppFile::cancelRebuild() { deferCancelRebuild()(); } |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 1163 | |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 1164 | UniqueFunction<void()> CppFile::deferCancelRebuild() { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1165 | std::unique_lock<std::mutex> Lock(Mutex); |
| 1166 | // Cancel an ongoing rebuild, if any, and wait for it to finish. |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 1167 | unsigned RequestRebuildCounter = ++this->RebuildCounter; |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1168 | // Rebuild asserts that futures aren't ready if rebuild is cancelled. |
| 1169 | // We want to keep this invariant. |
| 1170 | if (futureIsReady(PreambleFuture)) { |
| 1171 | PreamblePromise = std::promise<std::shared_ptr<const PreambleData>>(); |
| 1172 | PreambleFuture = PreamblePromise.get_future(); |
| 1173 | } |
| 1174 | if (futureIsReady(ASTFuture)) { |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 1175 | ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>(); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1176 | ASTFuture = ASTPromise.get_future(); |
| 1177 | } |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1178 | |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 1179 | Lock.unlock(); |
| 1180 | // Notify about changes to RebuildCounter. |
| 1181 | RebuildCond.notify_all(); |
| 1182 | |
| 1183 | std::shared_ptr<CppFile> That = shared_from_this(); |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 1184 | return [That, RequestRebuildCounter]() { |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 1185 | std::unique_lock<std::mutex> Lock(That->Mutex); |
| 1186 | CppFile *This = &*That; |
| 1187 | This->RebuildCond.wait(Lock, [This, RequestRebuildCounter]() { |
| 1188 | return !This->RebuildInProgress || |
| 1189 | This->RebuildCounter != RequestRebuildCounter; |
| 1190 | }); |
| 1191 | |
| 1192 | // This computation got cancelled itself, do nothing. |
| 1193 | if (This->RebuildCounter != RequestRebuildCounter) |
| 1194 | return; |
| 1195 | |
| 1196 | // Set empty results for Promises. |
| 1197 | That->PreamblePromise.set_value(nullptr); |
| 1198 | That->ASTPromise.set_value(std::make_shared<ParsedASTWrapper>(llvm::None)); |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 1199 | }; |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1200 | } |
| 1201 | |
| 1202 | llvm::Optional<std::vector<DiagWithFixIts>> |
| 1203 | CppFile::rebuild(StringRef NewContents, |
| 1204 | IntrusiveRefCntPtr<vfs::FileSystem> VFS) { |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 1205 | return deferRebuild(NewContents, std::move(VFS))(); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1206 | } |
| 1207 | |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 1208 | UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>()> |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1209 | CppFile::deferRebuild(StringRef NewContents, |
| 1210 | IntrusiveRefCntPtr<vfs::FileSystem> VFS) { |
| 1211 | std::shared_ptr<const PreambleData> OldPreamble; |
| 1212 | std::shared_ptr<PCHContainerOperations> PCHs; |
| 1213 | unsigned RequestRebuildCounter; |
| 1214 | { |
| 1215 | std::unique_lock<std::mutex> Lock(Mutex); |
| 1216 | // Increase RebuildCounter to cancel all ongoing FinishRebuild operations. |
| 1217 | // They will try to exit as early as possible and won't call set_value on |
| 1218 | // our promises. |
| 1219 | RequestRebuildCounter = ++this->RebuildCounter; |
| 1220 | PCHs = this->PCHs; |
| 1221 | |
| 1222 | // Remember the preamble to be used during rebuild. |
| 1223 | OldPreamble = this->LatestAvailablePreamble; |
| 1224 | // Setup std::promises and std::futures for Preamble and AST. Corresponding |
| 1225 | // futures will wait until the rebuild process is finished. |
| 1226 | if (futureIsReady(this->PreambleFuture)) { |
| 1227 | this->PreamblePromise = |
| 1228 | std::promise<std::shared_ptr<const PreambleData>>(); |
| 1229 | this->PreambleFuture = this->PreamblePromise.get_future(); |
| 1230 | } |
| 1231 | if (futureIsReady(this->ASTFuture)) { |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 1232 | this->ASTPromise = std::promise<std::shared_ptr<ParsedASTWrapper>>(); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1233 | this->ASTFuture = this->ASTPromise.get_future(); |
| 1234 | } |
| 1235 | } // unlock Mutex. |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 1236 | // Notify about changes to RebuildCounter. |
| 1237 | RebuildCond.notify_all(); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1238 | |
| 1239 | // A helper to function to finish the rebuild. May be run on a different |
| 1240 | // thread. |
| 1241 | |
| 1242 | // Don't let this CppFile die before rebuild is finished. |
| 1243 | std::shared_ptr<CppFile> That = shared_from_this(); |
| 1244 | auto FinishRebuild = [OldPreamble, VFS, RequestRebuildCounter, PCHs, |
Ilya Biryukov | 11a0252 | 2017-11-17 19:05:56 +0000 | [diff] [blame] | 1245 | That](std::string NewContents) mutable // 'mutable' to |
| 1246 | // allow changing |
| 1247 | // OldPreamble. |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1248 | -> llvm::Optional<std::vector<DiagWithFixIts>> { |
| 1249 | // Only one execution of this method is possible at a time. |
| 1250 | // RebuildGuard will wait for any ongoing rebuilds to finish and will put us |
| 1251 | // into a state for doing a rebuild. |
| 1252 | RebuildGuard Rebuild(*That, RequestRebuildCounter); |
| 1253 | if (Rebuild.wasCancelledBeforeConstruction()) |
| 1254 | return llvm::None; |
| 1255 | |
| 1256 | std::vector<const char *> ArgStrs; |
| 1257 | for (const auto &S : That->Command.CommandLine) |
| 1258 | ArgStrs.push_back(S.c_str()); |
| 1259 | |
| 1260 | VFS->setCurrentWorkingDirectory(That->Command.Directory); |
| 1261 | |
| 1262 | std::unique_ptr<CompilerInvocation> CI; |
| 1263 | { |
| 1264 | // FIXME(ibiryukov): store diagnostics from CommandLine when we start |
| 1265 | // reporting them. |
| 1266 | EmptyDiagsConsumer CommandLineDiagsConsumer; |
| 1267 | IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine = |
| 1268 | CompilerInstance::createDiagnostics(new DiagnosticOptions, |
| 1269 | &CommandLineDiagsConsumer, false); |
| 1270 | CI = createCompilerInvocation(ArgStrs, CommandLineDiagsEngine, VFS); |
| 1271 | } |
| 1272 | assert(CI && "Couldn't create CompilerInvocation"); |
| 1273 | |
| 1274 | std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer = |
| 1275 | llvm::MemoryBuffer::getMemBufferCopy(NewContents, That->FileName); |
| 1276 | |
| 1277 | // A helper function to rebuild the preamble or reuse the existing one. Does |
Ilya Biryukov | 11a0252 | 2017-11-17 19:05:56 +0000 | [diff] [blame] | 1278 | // not mutate any fields of CppFile, only does the actual computation. |
| 1279 | // Lamdba is marked mutable to call reset() on OldPreamble. |
| 1280 | auto DoRebuildPreamble = |
| 1281 | [&]() mutable -> std::shared_ptr<const PreambleData> { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1282 | auto Bounds = |
| 1283 | ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0); |
| 1284 | if (OldPreamble && OldPreamble->Preamble.CanReuse( |
| 1285 | *CI, ContentsBuffer.get(), Bounds, VFS.get())) { |
| 1286 | return OldPreamble; |
| 1287 | } |
Ilya Biryukov | 11a0252 | 2017-11-17 19:05:56 +0000 | [diff] [blame] | 1288 | // We won't need the OldPreamble anymore, release it so it can be deleted |
| 1289 | // (if there are no other references to it). |
| 1290 | OldPreamble.reset(); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1291 | |
Sam McCall | 9cfd9c9 | 2017-11-23 17:12:04 +0000 | [diff] [blame] | 1292 | trace::Span Tracer("Preamble"); |
| 1293 | SPAN_ATTACH(Tracer, "File", That->FileName); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1294 | std::vector<DiagWithFixIts> PreambleDiags; |
| 1295 | StoreDiagsConsumer PreambleDiagnosticsConsumer(/*ref*/ PreambleDiags); |
| 1296 | IntrusiveRefCntPtr<DiagnosticsEngine> PreambleDiagsEngine = |
| 1297 | CompilerInstance::createDiagnostics( |
| 1298 | &CI->getDiagnosticOpts(), &PreambleDiagnosticsConsumer, false); |
| 1299 | CppFilePreambleCallbacks SerializedDeclsCollector; |
| 1300 | auto BuiltPreamble = PrecompiledPreamble::Build( |
| 1301 | *CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, VFS, PCHs, |
Ilya Biryukov | e9eb7f0 | 2017-11-16 16:25:18 +0000 | [diff] [blame] | 1302 | /*StoreInMemory=*/That->StorePreamblesInMemory, |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1303 | SerializedDeclsCollector); |
| 1304 | |
| 1305 | if (BuiltPreamble) { |
| 1306 | return std::make_shared<PreambleData>( |
| 1307 | std::move(*BuiltPreamble), |
| 1308 | SerializedDeclsCollector.takeTopLevelDeclIDs(), |
| 1309 | std::move(PreambleDiags)); |
| 1310 | } else { |
| 1311 | return nullptr; |
| 1312 | } |
| 1313 | }; |
| 1314 | |
| 1315 | // Compute updated Preamble. |
| 1316 | std::shared_ptr<const PreambleData> NewPreamble = DoRebuildPreamble(); |
| 1317 | // Publish the new Preamble. |
| 1318 | { |
| 1319 | std::lock_guard<std::mutex> Lock(That->Mutex); |
| 1320 | // We always set LatestAvailablePreamble to the new value, hoping that it |
| 1321 | // will still be usable in the further requests. |
| 1322 | That->LatestAvailablePreamble = NewPreamble; |
| 1323 | if (RequestRebuildCounter != That->RebuildCounter) |
| 1324 | return llvm::None; // Our rebuild request was cancelled, do nothing. |
| 1325 | That->PreamblePromise.set_value(NewPreamble); |
| 1326 | } // unlock Mutex |
| 1327 | |
| 1328 | // Prepare the Preamble and supplementary data for rebuilding AST. |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1329 | std::vector<DiagWithFixIts> Diagnostics; |
| 1330 | if (NewPreamble) { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1331 | Diagnostics.insert(Diagnostics.begin(), NewPreamble->Diags.begin(), |
| 1332 | NewPreamble->Diags.end()); |
| 1333 | } |
| 1334 | |
| 1335 | // Compute updated AST. |
Sam McCall | 8567cb3 | 2017-11-02 09:21:51 +0000 | [diff] [blame] | 1336 | llvm::Optional<ParsedAST> NewAST; |
| 1337 | { |
Sam McCall | 9cfd9c9 | 2017-11-23 17:12:04 +0000 | [diff] [blame] | 1338 | trace::Span Tracer("Build"); |
| 1339 | SPAN_ATTACH(Tracer, "File", That->FileName); |
Ilya Biryukov | 2660cc9 | 2017-11-24 13:04:21 +0000 | [diff] [blame^] | 1340 | NewAST = |
| 1341 | ParsedAST::Build(std::move(CI), std::move(NewPreamble), |
| 1342 | std::move(ContentsBuffer), PCHs, VFS, That->Logger); |
Sam McCall | 8567cb3 | 2017-11-02 09:21:51 +0000 | [diff] [blame] | 1343 | } |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1344 | |
| 1345 | if (NewAST) { |
| 1346 | Diagnostics.insert(Diagnostics.end(), NewAST->getDiagnostics().begin(), |
| 1347 | NewAST->getDiagnostics().end()); |
| 1348 | } else { |
| 1349 | // Don't report even Preamble diagnostics if we coulnd't build AST. |
| 1350 | Diagnostics.clear(); |
| 1351 | } |
| 1352 | |
| 1353 | // Publish the new AST. |
| 1354 | { |
| 1355 | std::lock_guard<std::mutex> Lock(That->Mutex); |
| 1356 | if (RequestRebuildCounter != That->RebuildCounter) |
| 1357 | return Diagnostics; // Our rebuild request was cancelled, don't set |
| 1358 | // ASTPromise. |
| 1359 | |
Ilya Biryukov | 574b753 | 2017-08-02 09:08:39 +0000 | [diff] [blame] | 1360 | That->ASTPromise.set_value( |
| 1361 | std::make_shared<ParsedASTWrapper>(std::move(NewAST))); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1362 | } // unlock Mutex |
| 1363 | |
| 1364 | return Diagnostics; |
| 1365 | }; |
| 1366 | |
Ilya Biryukov | 98a1fd7 | 2017-10-10 16:12:54 +0000 | [diff] [blame] | 1367 | return BindWithForward(FinishRebuild, NewContents.str()); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1368 | } |
| 1369 | |
| 1370 | std::shared_future<std::shared_ptr<const PreambleData>> |
| 1371 | CppFile::getPreamble() const { |
| 1372 | std::lock_guard<std::mutex> Lock(Mutex); |
| 1373 | return PreambleFuture; |
| 1374 | } |
| 1375 | |
| 1376 | std::shared_ptr<const PreambleData> CppFile::getPossiblyStalePreamble() const { |
| 1377 | std::lock_guard<std::mutex> Lock(Mutex); |
| 1378 | return LatestAvailablePreamble; |
| 1379 | } |
| 1380 | |
Ilya Biryukov | 6e1f3b1 | 2017-08-01 18:27:58 +0000 | [diff] [blame] | 1381 | std::shared_future<std::shared_ptr<ParsedASTWrapper>> CppFile::getAST() const { |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1382 | std::lock_guard<std::mutex> Lock(Mutex); |
| 1383 | return ASTFuture; |
| 1384 | } |
| 1385 | |
| 1386 | tooling::CompileCommand const &CppFile::getCompileCommand() const { |
| 1387 | return Command; |
| 1388 | } |
| 1389 | |
| 1390 | CppFile::RebuildGuard::RebuildGuard(CppFile &File, |
| 1391 | unsigned RequestRebuildCounter) |
| 1392 | : File(File), RequestRebuildCounter(RequestRebuildCounter) { |
| 1393 | std::unique_lock<std::mutex> Lock(File.Mutex); |
| 1394 | WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter; |
| 1395 | if (WasCancelledBeforeConstruction) |
| 1396 | return; |
| 1397 | |
Ilya Biryukov | c5ad35f | 2017-08-14 08:17:24 +0000 | [diff] [blame] | 1398 | File.RebuildCond.wait(Lock, [&File, RequestRebuildCounter]() { |
| 1399 | return !File.RebuildInProgress || |
| 1400 | File.RebuildCounter != RequestRebuildCounter; |
| 1401 | }); |
Ilya Biryukov | 02d5870 | 2017-08-01 15:51:38 +0000 | [diff] [blame] | 1402 | |
| 1403 | WasCancelledBeforeConstruction = File.RebuildCounter != RequestRebuildCounter; |
| 1404 | if (WasCancelledBeforeConstruction) |
| 1405 | return; |
| 1406 | |
| 1407 | File.RebuildInProgress = true; |
| 1408 | } |
| 1409 | |
| 1410 | bool CppFile::RebuildGuard::wasCancelledBeforeConstruction() const { |
| 1411 | return WasCancelledBeforeConstruction; |
| 1412 | } |
| 1413 | |
| 1414 | CppFile::RebuildGuard::~RebuildGuard() { |
| 1415 | if (WasCancelledBeforeConstruction) |
| 1416 | return; |
| 1417 | |
| 1418 | std::unique_lock<std::mutex> Lock(File.Mutex); |
| 1419 | assert(File.RebuildInProgress); |
| 1420 | File.RebuildInProgress = false; |
| 1421 | |
| 1422 | if (File.RebuildCounter == RequestRebuildCounter) { |
| 1423 | // Our rebuild request was successful. |
| 1424 | assert(futureIsReady(File.ASTFuture)); |
| 1425 | assert(futureIsReady(File.PreambleFuture)); |
| 1426 | } else { |
| 1427 | // Our rebuild request was cancelled, because further reparse was requested. |
| 1428 | assert(!futureIsReady(File.ASTFuture)); |
| 1429 | assert(!futureIsReady(File.PreambleFuture)); |
| 1430 | } |
| 1431 | |
| 1432 | Lock.unlock(); |
| 1433 | File.RebuildCond.notify_all(); |
| 1434 | } |
Haojian Wu | 345099c | 2017-11-09 11:30:04 +0000 | [diff] [blame] | 1435 | |
| 1436 | SourceLocation clangd::getBeginningOfIdentifier(ParsedAST &Unit, |
| 1437 | const Position &Pos, |
| 1438 | const FileEntry *FE) { |
| 1439 | // The language server protocol uses zero-based line and column numbers. |
| 1440 | // Clang uses one-based numbers. |
| 1441 | |
| 1442 | const ASTContext &AST = Unit.getASTContext(); |
| 1443 | const SourceManager &SourceMgr = AST.getSourceManager(); |
| 1444 | |
| 1445 | SourceLocation InputLocation = |
| 1446 | getMacroArgExpandedLocation(SourceMgr, FE, Pos); |
| 1447 | if (Pos.character == 0) { |
| 1448 | return InputLocation; |
| 1449 | } |
| 1450 | |
| 1451 | // This handle cases where the position is in the middle of a token or right |
| 1452 | // after the end of a token. In theory we could just use GetBeginningOfToken |
| 1453 | // to find the start of the token at the input position, but this doesn't |
| 1454 | // work when right after the end, i.e. foo|. |
| 1455 | // So try to go back by one and see if we're still inside the an identifier |
| 1456 | // token. If so, Take the beginning of this token. |
| 1457 | // (It should be the same identifier because you can't have two adjacent |
| 1458 | // identifiers without another token in between.) |
| 1459 | SourceLocation PeekBeforeLocation = getMacroArgExpandedLocation( |
| 1460 | SourceMgr, FE, Position{Pos.line, Pos.character - 1}); |
| 1461 | Token Result; |
| 1462 | if (Lexer::getRawToken(PeekBeforeLocation, Result, SourceMgr, |
| 1463 | AST.getLangOpts(), false)) { |
| 1464 | // getRawToken failed, just use InputLocation. |
| 1465 | return InputLocation; |
| 1466 | } |
| 1467 | |
| 1468 | if (Result.is(tok::raw_identifier)) { |
| 1469 | return Lexer::GetBeginningOfToken(PeekBeforeLocation, SourceMgr, |
| 1470 | AST.getLangOpts()); |
| 1471 | } |
| 1472 | |
| 1473 | return InputLocation; |
| 1474 | } |