LCOV - code coverage report
Current view: top level - clang/tools/extra/clangd - ClangdServer.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 0 6 0.0 %
Date: 2018-02-23 15:42:53 Functions: 0 8 0.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===--- ClangdServer.h - Main clangd server code ----------------*- 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             : #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_CLANGDSERVER_H
      11             : #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_CLANGDSERVER_H
      12             : 
      13             : #include "ClangdUnit.h"
      14             : #include "CodeComplete.h"
      15             : #include "CompileArgsCache.h"
      16             : #include "DraftStore.h"
      17             : #include "Function.h"
      18             : #include "GlobalCompilationDatabase.h"
      19             : #include "Protocol.h"
      20             : #include "TUScheduler.h"
      21             : #include "index/FileIndex.h"
      22             : #include "clang/Tooling/CompilationDatabase.h"
      23             : #include "clang/Tooling/Core/Replacement.h"
      24             : #include "llvm/ADT/IntrusiveRefCntPtr.h"
      25             : #include "llvm/ADT/Optional.h"
      26             : #include "llvm/ADT/StringRef.h"
      27             : #include <functional>
      28             : #include <future>
      29             : #include <string>
      30             : #include <type_traits>
      31             : #include <utility>
      32             : 
      33             : namespace clang {
      34             : class PCHContainerOperations;
      35             : 
      36             : namespace clangd {
      37             : 
      38             : /// A tag supplied by the FileSytemProvider.
      39             : typedef std::string VFSTag;
      40             : 
      41             : /// A value of an arbitrary type and VFSTag that was supplied by the
      42             : /// FileSystemProvider when this value was computed.
      43           0 : template <class T> class Tagged {
      44             : public:
      45             :   // MSVC requires future<> arguments to be default-constructible.
      46             :   Tagged() = default;
      47             : 
      48             :   template <class U>
      49           0 :   Tagged(U &&Value, VFSTag Tag)
      50           0 :       : Value(std::forward<U>(Value)), Tag(std::move(Tag)) {}
      51             : 
      52             :   template <class U>
      53             :   Tagged(const Tagged<U> &Other) : Value(Other.Value), Tag(Other.Tag) {}
      54             : 
      55             :   template <class U>
      56             :   Tagged(Tagged<U> &&Other)
      57             :       : Value(std::move(Other.Value)), Tag(std::move(Other.Tag)) {}
      58             : 
      59             :   T Value = T();
      60             :   VFSTag Tag = VFSTag();
      61             : };
      62             : 
      63             : template <class T>
      64           0 : Tagged<typename std::decay<T>::type> make_tagged(T &&Value, VFSTag Tag) {
      65           0 :   return Tagged<typename std::decay<T>::type>(std::forward<T>(Value), Tag);
      66             : }
      67             : 
      68             : class DiagnosticsConsumer {
      69             : public:
      70             :   virtual ~DiagnosticsConsumer() = default;
      71             : 
      72             :   /// Called by ClangdServer when \p Diagnostics for \p File are ready.
      73             :   virtual void
      74             :   onDiagnosticsReady(PathRef File,
      75             :                      Tagged<std::vector<DiagWithFixIts>> Diagnostics) = 0;
      76             : };
      77             : 
      78             : class FileSystemProvider {
      79             : public:
      80             :   virtual ~FileSystemProvider() = default;
      81             :   /// Called by ClangdServer to obtain a vfs::FileSystem to be used for parsing.
      82             :   /// Name of the file that will be parsed is passed in \p File.
      83             :   ///
      84             :   /// \return A filesystem that will be used for all file accesses in clangd.
      85             :   /// A Tag returned by this method will be propagated to all results of clangd
      86             :   /// that will use this filesystem.
      87             :   virtual Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
      88             :   getTaggedFileSystem(PathRef File) = 0;
      89             : };
      90             : 
      91             : class RealFileSystemProvider : public FileSystemProvider {
      92             : public:
      93             :   /// \return getRealFileSystem() tagged with default tag, i.e. VFSTag()
      94             :   Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
      95             :   getTaggedFileSystem(PathRef File) override;
      96             : };
      97             : 
      98             : /// Provides API to manage ASTs for a collection of C++ files and request
      99             : /// various language features.
     100             : /// Currently supports async diagnostics, code completion, formatting and goto
     101             : /// definition.
     102           0 : class ClangdServer {
     103             : public:
     104             :   /// Creates a new ClangdServer instance.
     105             :   /// To process parsing requests asynchronously, ClangdServer will spawn \p
     106             :   /// AsyncThreadsCount worker threads. However, if \p AsyncThreadsCount is 0,
     107             :   /// all requests will be processed on the calling thread.
     108             :   ///
     109             :   /// ClangdServer uses \p FSProvider to get an instance of vfs::FileSystem for
     110             :   /// each parsing request. Results of code completion and diagnostics also
     111             :   /// include a tag, that \p FSProvider returns along with the vfs::FileSystem.
     112             :   ///
     113             :   /// The value of \p ResourceDir will be used to search for internal headers
     114             :   /// (overriding defaults and -resource-dir compiler flag). If \p ResourceDir
     115             :   /// is None, ClangdServer will call CompilerInvocation::GetResourcePath() to
     116             :   /// obtain the standard resource directory.
     117             :   ///
     118             :   /// ClangdServer uses \p CDB to obtain compilation arguments for parsing. Note
     119             :   /// that ClangdServer only obtains compilation arguments once for each newly
     120             :   /// added file (i.e., when processing a first call to addDocument) and reuses
     121             :   /// those arguments for subsequent reparses. However, ClangdServer will check
     122             :   /// if compilation arguments changed on calls to forceReparse().
     123             :   ///
     124             :   /// After each parsing request finishes, ClangdServer reports diagnostics to
     125             :   /// \p DiagConsumer. Note that a callback to \p DiagConsumer happens on a
     126             :   /// worker thread. Therefore, instances of \p DiagConsumer must properly
     127             :   /// synchronize access to shared state.
     128             :   ///
     129             :   /// \p StorePreamblesInMemory defines whether the Preambles generated by
     130             :   /// clangd are stored in-memory or on disk.
     131             :   ///
     132             :   /// If \p BuildDynamicSymbolIndex is true, ClangdServer builds a dynamic
     133             :   /// in-memory index for symbols in all opened files and uses the index to
     134             :   /// augment code completion results.
     135             :   ///
     136             :   /// If \p StaticIdx is set, ClangdServer uses the index for global code
     137             :   /// completion.
     138             :   ClangdServer(GlobalCompilationDatabase &CDB,
     139             :                DiagnosticsConsumer &DiagConsumer,
     140             :                FileSystemProvider &FSProvider, unsigned AsyncThreadsCount,
     141             :                bool StorePreamblesInMemory,
     142             :                bool BuildDynamicSymbolIndex = false,
     143             :                SymbolIndex *StaticIdx = nullptr,
     144             :                llvm::Optional<StringRef> ResourceDir = llvm::None);
     145             : 
     146             :   /// Set the root path of the workspace.
     147             :   void setRootPath(PathRef RootPath);
     148             : 
     149             :   /// Add a \p File to the list of tracked C++ files or update the contents if
     150             :   /// \p File is already tracked. Also schedules parsing of the AST for it on a
     151             :   /// separate thread. When the parsing is complete, DiagConsumer passed in
     152             :   /// constructor will receive onDiagnosticsReady callback.
     153             :   void addDocument(PathRef File, StringRef Contents,
     154             :                    WantDiagnostics WD = WantDiagnostics::Auto);
     155             : 
     156             :   /// Remove \p File from list of tracked files, schedule a request to free
     157             :   /// resources associated with it.
     158             :   void removeDocument(PathRef File);
     159             : 
     160             :   /// Force \p File to be reparsed using the latest contents.
     161             :   /// Will also check if CompileCommand, provided by GlobalCompilationDatabase
     162             :   /// for \p File has changed. If it has, will remove currently stored Preamble
     163             :   /// and AST and rebuild them from scratch.
     164             :   void forceReparse(PathRef File);
     165             : 
     166             :   /// Calls forceReparse() on all currently opened files.
     167             :   /// As a result, this method may be very expensive.
     168             :   /// This method is normally called when the compilation database is changed.
     169             :   void reparseOpenedFiles();
     170             : 
     171             :   /// Run code completion for \p File at \p Pos.
     172             :   /// Request is processed asynchronously.
     173             :   ///
     174             :   /// If \p OverridenContents is not None, they will used only for code
     175             :   /// completion, i.e. no diagnostics update will be scheduled and a draft for
     176             :   /// \p File will not be updated. If \p OverridenContents is None, contents of
     177             :   /// the current draft for \p File will be used. If \p UsedFS is non-null, it
     178             :   /// will be overwritten by vfs::FileSystem used for completion.
     179             :   ///
     180             :   /// This method should only be called for currently tracked files. However, it
     181             :   /// is safe to call removeDocument for \p File after this method returns, even
     182             :   /// while returned future is not yet ready.
     183             :   /// A version of `codeComplete` that runs \p Callback on the processing thread
     184             :   /// when codeComplete results become available.
     185             :   void codeComplete(PathRef File, Position Pos,
     186             :                     const clangd::CodeCompleteOptions &Opts,
     187             :                     UniqueFunction<void(Tagged<CompletionList>)> Callback,
     188             :                     llvm::Optional<StringRef> OverridenContents = llvm::None,
     189             :                     IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS = nullptr);
     190             : 
     191             :   /// Provide signature help for \p File at \p Pos. If \p OverridenContents is
     192             :   /// not None, they will used only for signature help, i.e. no diagnostics
     193             :   /// update will be scheduled and a draft for \p File will not be updated. If
     194             :   /// \p OverridenContents is None, contents of the current draft for \p File
     195             :   /// will be used. If \p UsedFS is non-null, it will be overwritten by
     196             :   /// vfs::FileSystem used for signature help. This method should only be called
     197             :   /// for currently tracked files.
     198             :   void signatureHelp(
     199             :       PathRef File, Position Pos,
     200             :       UniqueFunction<void(llvm::Expected<Tagged<SignatureHelp>>)> Callback,
     201             :       llvm::Optional<StringRef> OverridenContents = llvm::None,
     202             :       IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS = nullptr);
     203             : 
     204             :   /// Get definition of symbol at a specified \p Line and \p Column in \p File.
     205             :   void findDefinitions(
     206             :       PathRef File, Position Pos,
     207             :       UniqueFunction<void(llvm::Expected<Tagged<std::vector<Location>>>)>
     208             :           Callback);
     209             : 
     210             :   /// Helper function that returns a path to the corresponding source file when
     211             :   /// given a header file and vice versa.
     212             :   llvm::Optional<Path> switchSourceHeader(PathRef Path);
     213             : 
     214             :   /// Get document highlights for a given position.
     215             :   void findDocumentHighlights(
     216             :       PathRef File, Position Pos,
     217             :       UniqueFunction<
     218             :           void(llvm::Expected<Tagged<std::vector<DocumentHighlight>>>)>
     219             :           Callback);
     220             : 
     221             :   /// Get code hover for a given position.
     222             :   void findHover(PathRef File, Position Pos,
     223             :                  UniqueFunction<void(llvm::Expected<Tagged<Hover>>)> Callback);
     224             : 
     225             :   /// Run formatting for \p Rng inside \p File with content \p Code.
     226             :   llvm::Expected<tooling::Replacements> formatRange(StringRef Code,
     227             :                                                     PathRef File, Range Rng);
     228             : 
     229             :   /// Run formatting for the whole \p File with content \p Code.
     230             :   llvm::Expected<tooling::Replacements> formatFile(StringRef Code,
     231             :                                                    PathRef File);
     232             : 
     233             :   /// Run formatting after a character was typed at \p Pos in \p File with
     234             :   /// content \p Code.
     235             :   llvm::Expected<tooling::Replacements>
     236             :   formatOnType(StringRef Code, PathRef File, Position Pos);
     237             : 
     238             :   /// Rename all occurrences of the symbol at the \p Pos in \p File to
     239             :   /// \p NewName.
     240             :   void rename(PathRef File, Position Pos, llvm::StringRef NewName,
     241             :               UniqueFunction<void(Expected<std::vector<tooling::Replacement>>)>
     242             :                   Callback);
     243             : 
     244             :   /// Inserts a new #include of \p Header into \p File, if it's not present.
     245             :   /// \p Header is either an URI that can be resolved to an #include path that
     246             :   /// is suitable to be inserted or a literal string quoted with <> or "" that
     247             :   /// can be #included directly.
     248             :   Expected<tooling::Replacements> insertInclude(PathRef File, StringRef Code,
     249             :                                                 StringRef Header);
     250             : 
     251             :   /// Gets current document contents for \p File. Returns None if \p File is not
     252             :   /// currently tracked.
     253             :   /// FIXME(ibiryukov): This function is here to allow offset-to-Position
     254             :   /// conversions in outside code, maybe there's a way to get rid of it.
     255             :   llvm::Optional<std::string> getDocument(PathRef File);
     256             : 
     257             :   /// Only for testing purposes.
     258             :   /// Waits until all requests to worker thread are finished and dumps AST for
     259             :   /// \p File. \p File must be in the list of added documents.
     260             :   void dumpAST(PathRef File, UniqueFunction<void(std::string)> Callback);
     261             :   /// Called when an event occurs for a watched file in the workspace.
     262             :   void onFileEvent(const DidChangeWatchedFilesParams &Params);
     263             : 
     264             :   /// Returns estimated memory usage for each of the currently open files.
     265             :   /// The order of results is unspecified.
     266             :   /// Overall memory usage of clangd may be significantly more than reported
     267             :   /// here, as this metric does not account (at least) for:
     268             :   ///   - memory occupied by static and dynamic index,
     269             :   ///   - memory required for in-flight requests,
     270             :   /// FIXME: those metrics might be useful too, we should add them.
     271             :   std::vector<std::pair<Path, std::size_t>> getUsedBytesPerFile() const;
     272             : 
     273             :   // Blocks the main thread until the server is idle. Only for use in tests.
     274             :   // Returns false if the timeout expires.
     275             :   LLVM_NODISCARD bool
     276             :   blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10);
     277             : 
     278             : private:
     279             :   /// FIXME: This stats several files to find a .clang-format file. I/O can be
     280             :   /// slow. Think of a way to cache this.
     281             :   llvm::Expected<tooling::Replacements>
     282             :   formatCode(llvm::StringRef Code, PathRef File,
     283             :              ArrayRef<tooling::Range> Ranges);
     284             : 
     285             :   void
     286             :   scheduleReparseAndDiags(PathRef File, VersionedDraft Contents,
     287             :                           WantDiagnostics WD,
     288             :                           Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS);
     289             : 
     290             :   CompileArgsCache CompileArgs;
     291             :   DiagnosticsConsumer &DiagConsumer;
     292             :   FileSystemProvider &FSProvider;
     293             :   DraftStore DraftMgr;
     294             :   // The index used to look up symbols. This could be:
     295             :   //   - null (all index functionality is optional)
     296             :   //   - the dynamic index owned by ClangdServer (FileIdx)
     297             :   //   - the static index passed to the constructor
     298             :   //   - a merged view of a static and dynamic index (MergedIndex)
     299             :   SymbolIndex *Index;
     300             :   // If present, an up-to-date of symbols in open files. Read via Index.
     301             :   std::unique_ptr<FileIndex> FileIdx;
     302             :   // If present, a merged view of FileIdx and an external index. Read via Index.
     303             :   std::unique_ptr<SymbolIndex> MergedIndex;
     304             :   // If set, this represents the workspace path.
     305             :   llvm::Optional<std::string> RootPath;
     306             :   std::shared_ptr<PCHContainerOperations> PCHs;
     307             :   /// Used to serialize diagnostic callbacks.
     308             :   /// FIXME(ibiryukov): get rid of an extra map and put all version counters
     309             :   /// into CppFile.
     310             :   std::mutex DiagnosticsMutex;
     311             :   /// Maps from a filename to the latest version of reported diagnostics.
     312             :   llvm::StringMap<DocVersion> ReportedDiagnosticVersions;
     313             :   // WorkScheduler has to be the last member, because its destructor has to be
     314             :   // called before all other members to stop the worker thread that references
     315             :   // ClangdServer.
     316             :   TUScheduler WorkScheduler;
     317             : };
     318             : 
     319             : } // namespace clangd
     320             : } // namespace clang
     321             : 
     322             : #endif

Generated by: LCOV version 1.13