├── CNAME ├── .gitattributes ├── .gitignore ├── favicon.png ├── screenshots ├── hover.png ├── errors.png ├── outline.png ├── rename.gif ├── apply_fix.gif ├── go_to_def.gif ├── navigation.gif ├── many_errors.png ├── code_completion.png ├── emacs_company.png ├── find_all_refs.gif ├── header_symbols.png ├── missing_include.png ├── signature_help.gif ├── symbol_header.png ├── unused_include.png ├── ycm_completion.png ├── basic_completion.png ├── emacs_diagnostics.png ├── format_selection.gif ├── include_fixer_fix.png ├── apply_clang_tidy_fix.gif ├── semantic_highlight.png ├── sublime_completion.png └── code_completion_insert_ns_qualifiers.gif ├── _includes └── toc.md ├── _config.yml ├── guides ├── index.md ├── remote-index.md ├── include-cleaner.md └── system-headers.md ├── scripts.js ├── index.md ├── README.md ├── _layouts └── default.html ├── _data └── navigation.yml ├── design ├── remote-index.md ├── index.md ├── threads.md ├── indexing.md ├── include-cleaner.md ├── compile-commands.md └── code.md ├── logo.svg ├── troubleshooting.md ├── styles.css ├── features.md ├── faq.md ├── LICENSE ├── installation.md ├── extensions.md └── config.md /CNAME: -------------------------------------------------------------------------------- 1 | clangd.llvm.org 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md linguist-detectable 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | _site/ 2 | .sass-cache/ 3 | .jekyll-cache/ 4 | -------------------------------------------------------------------------------- /favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/favicon.png -------------------------------------------------------------------------------- /screenshots/hover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/hover.png -------------------------------------------------------------------------------- /screenshots/errors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/errors.png -------------------------------------------------------------------------------- /screenshots/outline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/outline.png -------------------------------------------------------------------------------- /screenshots/rename.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/rename.gif -------------------------------------------------------------------------------- /screenshots/apply_fix.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/apply_fix.gif -------------------------------------------------------------------------------- /screenshots/go_to_def.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/go_to_def.gif -------------------------------------------------------------------------------- /screenshots/navigation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/navigation.gif -------------------------------------------------------------------------------- /screenshots/many_errors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/many_errors.png -------------------------------------------------------------------------------- /screenshots/code_completion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/code_completion.png -------------------------------------------------------------------------------- /screenshots/emacs_company.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/emacs_company.png -------------------------------------------------------------------------------- /screenshots/find_all_refs.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/find_all_refs.gif -------------------------------------------------------------------------------- /screenshots/header_symbols.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/header_symbols.png -------------------------------------------------------------------------------- /screenshots/missing_include.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/missing_include.png -------------------------------------------------------------------------------- /screenshots/signature_help.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/signature_help.gif -------------------------------------------------------------------------------- /screenshots/symbol_header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/symbol_header.png -------------------------------------------------------------------------------- /screenshots/unused_include.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/unused_include.png -------------------------------------------------------------------------------- /screenshots/ycm_completion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/ycm_completion.png -------------------------------------------------------------------------------- /screenshots/basic_completion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/basic_completion.png -------------------------------------------------------------------------------- /screenshots/emacs_diagnostics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/emacs_diagnostics.png -------------------------------------------------------------------------------- /screenshots/format_selection.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/format_selection.gif -------------------------------------------------------------------------------- /screenshots/include_fixer_fix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/include_fixer_fix.png -------------------------------------------------------------------------------- /_includes/toc.md: -------------------------------------------------------------------------------- 1 | ## Contents 2 | {:.no_toc} 3 | - Table of contents 4 | {::options toc_levels="2..5" /} 5 | {:toc} 6 | 7 | -------------------------------------------------------------------------------- /screenshots/apply_clang_tidy_fix.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/apply_clang_tidy_fix.gif -------------------------------------------------------------------------------- /screenshots/semantic_highlight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/semantic_highlight.png -------------------------------------------------------------------------------- /screenshots/sublime_completion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/sublime_completion.png -------------------------------------------------------------------------------- /screenshots/code_completion_insert_ns_qualifiers.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/llvm/clangd-www/HEAD/screenshots/code_completion_insert_ns_qualifiers.gif -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | title: clangd 2 | description: turn your editor into a C++ IDE 3 | plugins: 4 | - jekyll-optional-front-matter 5 | - jekyll-default-layout 6 | - jekyll-titles-from-headings 7 | - jekyll-redirect-from 8 | markdown: kramdown 9 | kramdown: 10 | parse_block_html: true 11 | -------------------------------------------------------------------------------- /guides/index.md: -------------------------------------------------------------------------------- 1 | # Guides 2 | 3 | These articles describe how certain features work. 4 | 5 | {% for entry in site.data.navigation %} 6 | {% if entry.url == '/guides/' %} 7 | {% for child in entry.children %} 8 | ## {{child.title}} 9 | 10 | {{child.description}} 11 | 12 | [{{child.title}}]({{child.url}}) 13 | {:.main-article} 14 | 15 | {% endfor %} 16 | {% endif %} 17 | {% endfor %} 18 | -------------------------------------------------------------------------------- /scripts.js: -------------------------------------------------------------------------------- 1 | // Inside each

, add #. 2 | document.querySelectorAll('h2[id], h3[id], h4[id]').forEach(header => { 3 | var link = document.createElement('a'); 4 | link.className = 'anchor-link'; 5 | link.href = '#' + header.id; 6 | link.textContent = '#'; 7 | var span = document.createElement('span'); 8 | span.textContent = header.id; 9 | link.appendChild(span); 10 | header.appendChild(link); 11 | }); 12 | -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | # What is clangd? 2 | 3 | clangd understands your C++ code and adds smart features to your editor: 4 | code completion, compile errors, go-to-definition and more. 5 | 6 | `clangd` is a _language server_ that can work with many editors via a plugin. 7 | Here's Visual Studio Code with the clangd plugin, demonstrating code completion: 8 | 9 | ![Code completion in VSCode](screenshots/basic_completion.png) 10 | 11 | clangd is based on the [Clang](https://clang.llvm.org) C++ compiler, and is part 12 | of the [LLVM](https://llvm.org) project. 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## [clangd.llvm.org](https://clangd.llvm.org/) 2 | 3 | This is the **source code** of clangd's website. 4 | 5 | The website itself can be found at https://clangd.llvm.org/. 6 | 7 | ## I'm in the right place, how do I build the docs? 8 | 9 | The docs are built and published by pushing to this repository (Github Pages). 10 | Usually you won't need more than GitHub's markdown preview feature. 11 | 12 | But if you're changing layout, and want to see exactly what it will look like, 13 | you can run jekyll locally. 14 | 15 | ``` 16 | apt-get install rubygems ruby-dev # or similar 17 | gem install github-pages 18 | jekyll serve 19 | ``` 20 | 21 | The instance at http://localhost:4000/ will refresh when you edit any file. 22 | -------------------------------------------------------------------------------- /_layouts/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | {{ page.title }} 10 | 11 | 12 | 18 | 19 | 20 | 41 |
42 | {{ content }} 43 | 44 | ✏️ 45 |
46 | 47 | -------------------------------------------------------------------------------- /_data/navigation.yml: -------------------------------------------------------------------------------- 1 | - title: Getting Started 2 | url: /installation 3 | icon: '▶' 4 | - title: Features 5 | url: /features 6 | icon: '✓' 7 | - title: Configuration 8 | url: /config 9 | icon: '⚙️' 10 | - title: Troubleshooting 11 | url: /troubleshooting 12 | icon: '💥' 13 | - title: Guides 14 | url: /guides/ 15 | icon: '📖' 16 | children: 17 | - title: Using a remote index 18 | description: > 19 | Avoid indexing a large project locally and share an index between 20 | developers in your team by running clangd index server. 21 | url: /guides/remote-index 22 | - title: System headers 23 | description: > 24 | Details about how system header detection in clangd works and how to fix 25 | issues with missing system headers. 26 | url: /guides/system-headers 27 | - title: 'Managing #includes' 28 | description: > 29 | Identify and #include the headers you actually use, and understand how 30 | clangd decides which headers are used. 31 | url: /guides/include-cleaner 32 | - title: FAQ 33 | url: /faq 34 | icon: '❓' 35 | - separator 36 | - title: Design 37 | url: /design/ 38 | icon: '✨' 39 | children: 40 | - title: Code walkthrough 41 | url: /design/code 42 | - title: Compile commands 43 | url: /design/compile-commands 44 | - title: Threads & requests 45 | url: /design/threads 46 | - title: The clangd index 47 | url: /design/indexing 48 | - title: Remote index 49 | url: /design/remote-index 50 | - title: Include Cleaner 51 | url: /design/include-cleaner 52 | - title: Protocol extensions 53 | url: /extensions 54 | icon: '⊕' 55 | - separator 56 | - title: Browse code 57 | url: https://github.com/llvm/llvm-project/tree/main/clang-tools-extra/clangd 58 | icon: '📄' 59 | - title: Bug tracker 60 | url: https://github.com/clangd/clangd/issues 61 | icon: '🐞' 62 | - title: Forum 63 | url: https://github.com/clangd/clangd/discussions 64 | icon: '💡' 65 | - title: Chat (#clangd) 66 | url: https://discord.gg/xS7Z362 67 | icon: '💬' 68 | -------------------------------------------------------------------------------- /design/remote-index.md: -------------------------------------------------------------------------------- 1 | # Remote index 2 | 3 | A [project-wide index](/design/indexing) can be slow to build, particularly 4 | for large projects on slower machines like laptops. A "remote index" allows 5 | a shared server to host the index instead. 6 | 7 | ## How it works 8 | 9 | The remote index has three components: 10 | 11 | - the **indexer** is a batch process that should run on a powerful machine. 12 | It parses all the code for your project, and produces an index file. 13 | - the **server** exposes the index over a network. It loads the index file into 14 | memory, and exposes a [gRPC](https://grpc.io) service to query it. 15 | - the **client** is part of clangd, which runs on the development machine. 16 | It connects to the server and requests information (such as the definition 17 | of a symbol) in real-time. 18 | 19 | Each of these components are open-source and part of 20 | [llvm/llvm-project/clang-tools-extra/clangd](https://github.com/llvm/llvm-project/tree/main/clang-tools-extra/clangd/). 21 | 22 | ## Indexer 23 | 24 | `clangd-indexer` collects public symbols from headers (functions, classes, 25 | types, etc). It's necessary to run the build system for your project first, 26 | to produce `compile_commands.json` and possibly generate source files. 27 | 28 | Running `clangd-indexer` is expensive and produced index is not incremental. 29 | Usually the index is produced periodically and so is always slightly stale. 30 | 31 | ## Server 32 | 33 | `clangd-index-server` is an RPC server that processes index requests. Clangd 34 | issues requests to the server whenever it uses its global index (e.g. find 35 | references request, index-based code completion). 36 | 37 | The source code lives under different paths on different machines. 38 | The `--project-root` flags specifies the source root on the indexer machine, 39 | this prefix will be stripped. The client will add its own prefix as appropriate. 40 | 41 | ## Client 42 | 43 | The client is compiled into clangd, and enabled when `Index.External.Server` is 44 | set in the [user config](/config). A "mount point" must also be specified to 45 | translate between local and remote paths. 46 | 47 | The remote index cannot be enabled from project config for privacy reasons 48 | (the client reveals information about the code being edited, and the project 49 | config from the source code repository isn't sufficiently trusted). 50 | 51 | ## Building/releases 52 | 53 | The client and server require the gRPC libraries. 54 | Because of this dependency, they are not enabled by default in CMake. 55 | 56 | To build remote-index-enabled `clangd` and `clangd-index-server`, you need: 57 | - gRPC libraries (e.g. `apt install libgrpc++-dev libprotobuf-dev 58 | protobuf-compiler-grpc` or `brew install grpc protobuf` or 59 | [build from source](https://github.com/grpc/grpc/blob/master/BUILDING.md)) 60 | - to set the `-DCLANGD_ENABLE_REMOTE=On` and possibly `-DGRPC_INSTALL_PATH` 61 | CMake flags 62 | 63 | The [clangd releases on GitHub](https://github.com/clangd/clangd/releases) 64 | include remote index support, but official LLVM releases do not (yet). 65 | -------------------------------------------------------------------------------- /design/index.md: -------------------------------------------------------------------------------- 1 | # Design of clangd 2 | 3 | A language server's main responsibilities are: 4 | 5 | - keeping track of open files and unsaved changes 6 | - providing the editor with up-to-date diagnostics (warnings/errors) 7 | - responding to requests from the editor (such as go-to-definition) 8 | 9 | Most of the design documentation focuses on the concepts, if you're interested 10 | in the implementation we try to keep the code well-documented. 11 | 12 | [code walkthrough](/design/code) 13 | {:.main-article} 14 | 15 | ## Compile commands 16 | 17 | Clangd needs to make choices about how to parse each open file, such as: 18 | - Is it C or C++? 19 | - Which version of C++? 20 | - Where are included headers found? 21 | 22 | clangd determines a virtual compiler command for each file 23 | (e.g. `clang foo.cc -Iheaders/`) and uses this to configure its parser. 24 | Ideally this command comes from the build system. 25 | 26 | Compile flags can control many subtle pieces of the clang parser, so compile 27 | commands are an important configuration point. 28 | 29 | [Compile commands](/design/compile-commands) 30 | {:.main-article} 31 | 32 | ## Request handling 33 | 34 | clangd is based on the `clang` compiler, and at its core runs the clang parser 35 | in a loop. The parser produces diagnostics as it encounters problems, and the 36 | end result is a [clang AST]. The AST is saved to answer queries like "what kind 37 | of symbol is under the cursor". 38 | 39 | [clang AST]: https://clang.llvm.org/docs/IntroductionToTheClangAST.html 40 | 41 | There is one such loop for each open file. The `TUScheduler` class manages a 42 | collection of `ASTWorker`s, each running on its own thread. Most operations run 43 | on these threads, though code completion is a notable exception. 44 | 45 | [threads and request handling](/design/threads) 46 | {:.main-article} 47 | 48 | ## Index 49 | 50 | C/C++/Objective-C are designed so that you can parse one source file at a time, 51 | without needing to see the whole program. This means that the resulting AST 52 | lacks certain information: 53 | 54 | - if you call a function, we can find a declaration for it, but we may not 55 | have seen its definition 56 | - there's no way to find all the references to a struct you defined 57 | - code completion can suggest variables that are in scope, but not those 58 | where you'd need to add an `#include` 59 | 60 | To solve this, clangd maintains a database of symbols found anywhere in the 61 | program, called the index. This is extracted from each open file as it is 62 | parsed, and also by parsing the whole project in the background. 63 | 64 | [the clangd index](/design/indexing) 65 | {:.main-article} 66 | 67 | ## Remote index 68 | 69 | The remote index system allows a codebase index to be built offline and shared 70 | across many clangd instances with an RPC server. 71 | 72 | [remote index](/design/remote-index) 73 | {:.main-article} 74 | 75 | ## Include Cleaner 76 | 77 | Issues diagnostics for unused includes and provides tools for keeping a minimal 78 | set of required includes. 79 | 80 | [include cleaner](/design/include-cleaner) 81 | {:.main-article} 82 | -------------------------------------------------------------------------------- /guides/remote-index.md: -------------------------------------------------------------------------------- 1 | --- 2 | redirect_from: /llvm-remote-index 3 | redirect_from: /llvm-remote-index.html 4 | redirect_from: /remote-index 5 | redirect_from: /remote-index.html 6 | --- 7 | # Using a remote index 8 | 9 | Usually clangd will build an [index](/design/indexing) of your project in the 10 | background. For large projects, this can be slow. 11 | 12 | If someone has set up a clangd index server for your project, then you can query 13 | this central index instead of building your own. 14 | 15 | ## Obtaining a suitable version of clangd 16 | 17 | You need a remote-index-enabled version (12 or later) of clangd, such as 18 | [the latest clangd release on github](https://github.com/clangd/clangd/releases/latest). 19 | 20 | The official LLVM releases and Debian etc packages of clangd 12 are not 21 | remote-index-enabled! 22 | 23 | (If building clangd from source, you need `-DCLANGD_ENABLE_REMOTE=On` in CMake). 24 | 25 | ## Configuring clangd to use the remote index 26 | 27 | You'll need the address of the server you want to connect to, and the local 28 | source code it matches. 29 | 30 | In your [user configuration](/config), add a section like: 31 | 32 | ```yaml 33 | If: 34 | PathMatch: /path/to/code/.* 35 | Index: 36 | External: 37 | Server: someserver:5900 38 | MountPoint: /path/to/code/ 39 | ``` 40 | 41 | ## What to expect 42 | 43 | After restarting clangd, it should no longer want to index your whole project, 44 | and you should get complete results for find-references etc. 45 | 46 | Results may not be entirely up-to-date. Index servers usually scan the 47 | project once a day, and if you're working on a branch you may get further skew. 48 | Files that you've had open will still be indexed locally and will be up-to-date. 49 | 50 | Queries to the index server may reveal information about the code you're editing 51 | (e.g. partial identifiers). Public servers should have a privacy policy. 52 | 53 | ## Public index servers 54 | 55 | Some open-source projects have public servers: 56 | 57 | - [LLVM](http://clangd-index.llvm.org/): `clangd-index.llvm.org:5900` 58 | - [Chromium](https://linux.clangd-index.chromium.org/): `linux.clangd-index.chromium.org:5900` (`linux` can instead be `chromeos`/`android`/`fuchsia`/`chromecast-linux`/`chromecast-android`) 59 | 60 | ## Running up an index server 61 | 62 | This is a little more involved, and you'll want to understand the 63 | [design of the remote index](/design/remote-index). In short: 64 | 65 | - you should periodically check out and index your project with a command like 66 | `clangd-indexer --executor=all-TUs /proj/compile_commands.json > proj.idx` 67 | - run the server as `clangd-index-server proj.idx /proj`. It listens on port 68 | 50051 by default, and reloads the index file when it is overwritten. 69 | 70 | The `clangd-indexer` and `clangd-index-server` tools can be found in 71 | `clangd_indexing_tools.zip` on the 72 | [release page](https://github.com/clangd/clangd/releases/latest). 73 | 74 | [clangd/llvm-remote-index](https://github.com/clangd/llvm-remote-index) is an 75 | example of a production-ready instance, with the indexing step running on 76 | GitHub Actions and the server running on Google Compute Engine. 77 | -------------------------------------------------------------------------------- /design/threads.md: -------------------------------------------------------------------------------- 1 | # Threads and request handling 2 | 3 | Our main goals in handling incoming requests are: 4 | 5 | - respond to requests as quickly as possible (don't block on unrelated work) 6 | - provide diagnostics as soon as possible once the user stops typing 7 | - handle requests using the expected version the of the file 8 | - use a predictable and bounded amount of CPU and RAM 9 | 10 | Some constraints are provided by clang: 11 | 12 | - Clang supports parsing the preamble (initial `#include`s) separately for 13 | better incremental performance. 14 | - Initial build of the preamble can be extremely slow - tens of seconds. 15 | Incremental AST builds (with an up-to-date preamble) are fast (sub-second). 16 | - Once built, the preamble is threadsafe (it's just immutable bytes). 17 | However ASTs are not threadsafe, even for read-only operations. 18 | 19 | ## Life of a request 20 | 21 | An LSP message like `textDocument/definition` or `textDocument/didChange` is 22 | decoded by `ClangdLSPServer` and dispatched to the appropriate function on 23 | `ClangdServer`. This happens on the main thread, ClangdServer is not threadsafe. 24 | Therefore, its methods should not block - that would block incoming messages 25 | which could be independent (code completion in a different file) or relevant 26 | (cancelling a slow request). 27 | 28 | Instead, they determine the affected file and place the action on `TUScheduler`. 29 | This class maintains a set of `ASTWorker`s, each is responsible for one file. 30 | The `ASTWorker` has a queue of operations, and a thread consuming them: 31 | 32 | - throwing away operations that are obsolete: 33 | - reads that have been cancelled 34 | - writes immediately followed by writes (e.g. two consecutive keystrokes) 35 | - executing the first operation that is still valid: 36 | - writes: rebuilding the AST (and preamble if needed), publishing diagnostics 37 | - reads: passing the AST to the action callback 38 | 39 | This ensures there's only one AST and one preamble per open file, operations on 40 | one file don't block another, and that reads see exactly the writes issued 41 | before them. 42 | 43 | ## Debouncing 44 | 45 | For files that rebuild relatively slowly, starting to build as soon as we see 46 | the first change isn't ideal. 47 | 48 | Suppose the user quickly types `foo();`. Building after the `f` is typed means: 49 | 50 | - we'll always see a diagnostic "unknown identifier `f`", which is annoying. 51 | - we'll never see the correct diagnostics until after 2 rebuilds 52 | 53 | To address this, writes are debounced: rebuilding doesn't start until either a 54 | read is received or a short deadline expires (user stopped typing). 55 | 56 | ## Code completion 57 | 58 | Unlike typical requests like go-to-definition, code completion does not use 59 | the pre-built AST. Clang doesn't do a great job of preserving the AST around 60 | incomplete code, and completion can make good use of transient parser state. 61 | We run a fresh parse with clang's completion API enabled, which injects a 62 | "code completion" token into the token stream, and invokes a callback once the 63 | parser hits it. 64 | 65 | As this doesn't reuse the AST, it can run on a separate thread rather than the 66 | ASTWorker. It does use the preamble, but we don't wait for it to be up-to-date. 67 | Since completion is extremely time sensitive, it just uses whichever is 68 | immediately available. 69 | -------------------------------------------------------------------------------- /design/indexing.md: -------------------------------------------------------------------------------- 1 | # The clangd index 2 | 3 | The index stores information about the whole codebase. It's used to provide LSP 4 | features where the AST of the current file doesn't have the information we need. 5 | 6 | ## Exposed data 7 | 8 | - `Symbol`s are the primary objects managed by the index. A function, variable, 9 | class, or macro is a Symbol, and each one has an opaque `SymbolID`. 10 | Two declarations of the same thing will produce the same `SymbolID` and thus 11 | be merged into one `Symbol`. 12 | 13 | Symbols have names, declaration/definition locations, documentation, and a 14 | bunch of attributes used for code completion. 15 | 16 | They can be looked up by ID, or fuzzy-searched by name. 17 | 18 | - `Ref`s are uses of a symbol in code, such as a call to a function. 19 | They are edges between a `Symbol` and a location in some file. 20 | 21 | They can be looked up by SymbolID. 22 | 23 | - `Relation`s describe related symbols, such as a class that inherits another. 24 | They are edges between two `Symbol`s, labeled with a relation kind. 25 | 26 | They are looked up using one of the `Symbols` and the kind. 27 | 28 | ## Implementations 29 | 30 | `SymbolIndex` is an interface, and clangd maintains several instances. 31 | These are stitched together using `MergedIndex`, which layers one index on top 32 | of another. Code implementing features sees only a single combined index. 33 | 34 | ### `FileIndex` ("dynamic index") 35 | 36 | This is the top layer, and includes symbols from the files that have been opened 37 | and the headers they include. This is used: 38 | 39 | - to provide code completions for symbols at global scope in header files. 40 | (This is more efficient than deserializing big parts of the preamble). 41 | - to ensure cross-references for the files you're working on are available, even 42 | if the background index hasn't finished yet 43 | - to ensure locations of definitions/references aren't stale despite actively 44 | editing the file 45 | 46 | The `FileIndex` class stores data from each file separately. When a file is 47 | parsed, the TUScheduler invokes a callback which adds the AST to the index. 48 | (In fact, there is a separate storage and callback for expensive-and-rare 49 | preamble rebuilds vs cheap-and-frequent main-file rebuilds). 50 | 51 | ### `BackgroundIndex` 52 | 53 | As the name suggests, this parses all files in the project in the background 54 | to build a complete index. This is used: 55 | 56 | - to ensure full coverage of the codebase 57 | - to capture references inside template instantiations, which are disabled 58 | elsewhere in clangd for performance reasons 59 | 60 | The `BackgroundIndex` maintains a thread-pool, and when a compilation database 61 | is found, the compile command for each source file is placed on a queue. 62 | 63 | Before indexing each file, the index checks for a cached `*.idx` file on disk. 64 | After indexing, it writes this file. This avoids reindexing on startup if 65 | nothing changed since last time. 66 | These files are located in `.cache/clangd/index/` next to `compile_commands.json`. 67 | For headers with no CDB, such as the standard library, they are in `clangd/index` 68 | under the user's cache directory (`$XDG_CACHE_HOME`, `DARWIN_USER_CACHE_DIR`, or 69 | `%LocalAppData%`). 70 | 71 | ### Static index 72 | 73 | The (optional) static index is built outside clangd. It would typically cover 74 | the whole codebase. This is used: 75 | 76 | - to avoid waiting for the background index to build 77 | - to allow the background index to be disabled for large projects, saving 78 | CPU/RAM/battery 79 | 80 | With the `-index-file` option, clangd will load an index produced by the 81 | `clangd-indexer` tool. 82 | 83 | ### Remote index 84 | 85 | For large codebases (e.g. LLVM and Chromium) global index can take a long 86 | time to build (multiple hours even on very powerful machines for Chrome-sized 87 | projects) and induces a large memory overhead (multiple GB of RAM) to serve 88 | within clangd. 89 | 90 | Remote index allows serving index on a separate machine and connecting to it 91 | from your device. This means you don't have to build the index yourself 92 | anymore and clangd will use significantly less memory. Hence developers can 93 | work from less powerful machines, while still using clangd to its fullest. 94 | For more details, see [remote index](/design/remote-index). 95 | -------------------------------------------------------------------------------- /logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 15 | 17 | 19 | 23 | 27 | 31 | 32 | 34 | 38 | 42 | 43 | 46 | 50 | 51 | 60 | 70 | 80 | 89 | 90 | 92 | 93 | 95 | image/svg+xml 96 | 98 | 99 | 100 | 101 | 102 | 106 | clangd 116 | 119 | 123 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /design/include-cleaner.md: -------------------------------------------------------------------------------- 1 | # Include Cleaner 2 | 3 | Manually managing includes in a C++ translation unit, especially in the face of 4 | transitive inclusions, requires a lot of effort. Include Cleaner aims to 5 | provide diagnostics to keep includes in an 6 | [IWYU](https://include-what-you-use.org/)-clean state. 7 | 8 | Include Cleaner is available in "preview" mode with an incomplete set of 9 | capabilities and can be enabled through [configuration 10 | file](/config#unusedincludes). If you experience any bugs, please submit a bug 11 | report in [clangd/issues](https://github.com/clangd/clangd/issues). 12 | 13 | {:.v14} 14 | 15 | ## How it works 16 | 17 | Include Cleaner issues diagnostics for includes that are present but not used 18 | in the main file. When you open a file, clangd will analyze the symbols the 19 | file uses and mark all headers defining these symbols as "used". The warnings 20 | will be issued for the headers that are included but not marked as "used". 21 | Example: 22 | 23 | ```c++ 24 | // foo.h 25 | #pragma once 26 | 27 | class Foo {}; 28 | ``` 29 | 30 | ```c++ 31 | // bar.h 32 | #pragma once 33 | 34 | class Bar {}; 35 | ``` 36 | 37 | ```c++ 38 | // main.cpp 39 | 40 | #include "foo.h" 41 | #include "bar.h" // <- Will be marked as unused and suggested to be removed. 42 | 43 | int main() { 44 | Foo f; 45 | } 46 | ``` 47 | 48 | Here, `main.cpp` only makes use of symbols from `foo.h` and removing `#include 49 | "bar.h"` prevents unnecessary parsing of `bar.h` and allows breaking the 50 | dependency on it. 51 | 52 | ### Deciding what headers are used 53 | 54 | Clangd relies on Clang AST to deduce which headers are used and which aren't, 55 | the whole Include Cleaner decision process is described below. 56 | 57 | #### Scanning the main file 58 | 59 | IncludeCleaner will traverse Clang AST of the main file. It will recursively 60 | visit AST nodes and collect locations of all referenced symbols (e.g. types, 61 | functions, global variables). Any declaration explicitly mentioned in the code, 62 | brought in via macro expansions, implicitly through type deductions or template 63 | instantiations will be marked as "used". Example: 64 | 65 | ```c++ 66 | // foo.h 67 | #pragma once 68 | 69 | // USED 70 | int foo(); 71 | 72 | // USED 73 | #define FOO foo 74 | 75 | // USED 76 | struct Bar { 77 | Bar(); 78 | } 79 | 80 | // USED 81 | struct Baz; 82 | 83 | // USED 84 | template Baz getBaz(); 85 | ``` 86 | 87 | ```c++ 88 | // main.cpp 89 | 90 | #include "foo.h" 91 | 92 | int main() { 93 | // Uses foo() and FOO 94 | FOO(); 95 | // Uses Baz, getBaz and Bar. 96 | auto baz = getBaz(); 97 | } 98 | ``` 99 | 100 | This means that Include Cleaner is conservatively treating symbols in the 101 | expanded code as usages as opposed to only explicitly spelled symbols. 102 | 103 | Include Cleaner will also traverse the macro names in the spelled code to 104 | collect used macros. 105 | 106 | After the process is complete, all declaration and definition locations will be 107 | collected and passed to the next stage. 108 | 109 | #### Marking the headers as used 110 | 111 | `SourceLocation` instances collected at the previous step will be converted to 112 | `FileID`s and deduplicated. 113 | 114 | This is achieved by looking at two hints in the code: 115 | 116 | - `IWYU pragma: private` directives, which explicitly tells a particular header 117 | should only be included through another. 118 | - Header being non-self contained (e.g. missing header guards or pragma once, 119 | having a `.inc` extension). In which case Include Cleaner uses the first 120 | self-contained header in the include stack as the public interface. 121 | 122 | After the responsible headers are collected, the only step left is producing 123 | diagnostics for unused headers. 124 | 125 | #### Issuing warnings 126 | 127 | After most of the work is done, Include Cleaner needs to decide which headers 128 | are not used in the main file. All inclusions are scanned and checked for 129 | containing `IWYU pragma: keep`; if they do not, they are not used and will be 130 | warned about. 131 | 132 | ### IWYU pragmas 133 | 134 | IWYU tool offers a set of 135 | [pragmas](https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/IWYUPragmas.md). 136 | Include Cleaner respects `keep`, `always_keep`, `private`, and 137 | `export`/`begin_exports`/`end_exports`. 138 | 139 | ## Future plans and Limitations 140 | 141 | ### Umbrella headers 142 | 143 | The "umbrella" headers are re-exporting the implementation headers for public 144 | use, which is a common practice in Open Source projects. A notable example of 145 | this is Googletest: the `gtest/gtest.h` top-level header does not contain any 146 | definitions: it includes a number of "internal" headers that are not 147 | recommended to users. The users should always write `#include 148 | "gtest/gtest.h"`. The way to propagate that information to Include Cleaner is 149 | using `// IWYU pragma: private, include "public.h"` in your `private.h` header 150 | that is being exported. 151 | 152 | ### Standard library (before clangd-17) 153 | 154 | By default, Include Cleaner will not diagnose headers from the Standard 155 | Library. Standard Library headers support is not complete yet (due to the 156 | macros and the fact that a symbol is allowed to come from multiple headers) but 157 | you can enable this unstable feature through passing `--include-cleaner-stdlib` 158 | flag to clangd invocation. 159 | 160 | Since clangd-17, Standard Library headers are always diagnosed and the flag is ignored. 161 | 162 | ### Inserting Includes 163 | 164 | The complete version of Include Cleaner will not only warn about unused 165 | headers, but also provide a way to include used headers directly, not through a 166 | chain of transitive includes. 167 | 168 | -------------------------------------------------------------------------------- /troubleshooting.md: -------------------------------------------------------------------------------- 1 | # Troubleshooting 2 | 3 | Sorry if things are going wrong! 4 | 5 | {% include toc.md %} 6 | 7 | ## Update clangd 8 | 9 | Every release fixes many bugs, works in more scenarios, and provides clearer 10 | logs for troubleshooting. 11 | 12 | Try to [install the latest major-version release][installation] or even a 13 | pre-release snapshot before you try anything else! 14 | 15 | ## Gathering logs 16 | 17 | Your editor should make clangd's `stderr` log available (see [installation][] 18 | for how). These describe the messages exchanged between the editor and `clangd`, 19 | and what clangd was thinking. 20 | 21 | Even if you don't understand the contents, it's tremendously useful to include 22 | this when filing a bug. If you add `--log=verbose` to the clangd arguments, this 23 | will include more detail (e.g. the full content of LSP messages). 24 | 25 | ## Lots of error diagnostics 26 | 27 | If your code builds OK but clangd shows lots of error diagnostics, it 28 | probably can't parse your code very well. Other features will work poorly too: 29 | 30 | ![Many errors](screenshots/many_errors.png) 31 | 32 | ### Can't find includes within your project 33 | 34 | This usually means that we don't have a compile command for this file. 35 | `compile_commands.json` should exist in some parent directory and should have 36 | a valid command. If this file has changed, you'll need to restart clangd to see 37 | the changes. 38 | 39 | The logs can tell you whether `compile_commands.json` was found and what compile 40 | command was ultimately used. 41 | 42 | ### Can't find standard library headers (``, `` etc) 43 | 44 | First, you'll need the standard library (and any other libraries you depend on) 45 | installed on your system! Even if you don't actually build on this machine, 46 | clangd needs to parse the headers. 47 | 48 | The standard library headers are often found relative to the compiler. 49 | Try to configure your project with an absolute path to the compiler 50 | (`/usr/bin/gcc`, not `gcc`). 51 | The logs (with `--log=verbose`) can tell you the `cc1` command, including which 52 | paths were searched for the standard library. You can compare this to the output 53 | of `clang -### `. 54 | 55 | If you're using an unusual compiler (e.g. a cross-compiler for a different 56 | platform, or MinGW on Windows) you may want to pass `--query-driver=/path/to/mygcc` 57 | or `--query-driver=/path/to/mygcc,/path/to/myg++` when using C++ to allow clangd 58 | to extract the include paths from it directly. 59 | 60 | It is recommended to use `--query-driver` over specifying system include paths 61 | manually using [configuration files](config#compileflags) as getting the latter right 62 | can be tricky (the order of include paths are important, for instance). 63 | Generally the value of `--query-driver` should match the command emitted by 64 | your build system in `compile_commands.json`, such as `/usr/bin/c++`. 65 | 66 | ### Can't find compiler built-in headers (`` etc) 67 | 68 | These headers are formally part of the standard library, but so closely coupled 69 | to the parser that they are installed with clangd. 70 | 71 | They must be found in `../lib/clang//include`. If you've built clangd 72 | from source or installed it from a package, these should be in the right place. 73 | If you've moved the binary around, move it back! 74 | 75 | ## Dealing with crashes 76 | 77 | If clangd is exiting unexpectedly, this is probably a crashing bug in clangd. 78 | Understanding it better will help you work around it, and if you can file an 79 | informative [bug report][] we'll try to fix it for the next release. 80 | 81 | The most helpful crash reports have a log including a (symbolic) stack trace, 82 | some idea of what the trigger is, and fairly compact example code that exhibits 83 | the problem. 84 | 85 | ### Crashes triggered by requests 86 | 87 | If clangd crashes when you go to a particular definition, or hover on a 88 | particular name, then the bug is probably in the code handling that request. 89 | You can sometimes just avoid doing this! 90 | 91 | If you can, try to work out the simplest program that will still exhibit the 92 | crash. This is a much more useful/fixable bug report. 93 | 94 | ### Crashes when opening a file 95 | 96 | If clangd triggers as soon as you open a particular file, it's likely a crash 97 | when parsing or indexing that file (or an included header). Again it's very 98 | useful to know what's in the file and minimize it as far as possible (especially 99 | include). 100 | 101 | A crash goes that goes away when disabling clang-tidy (`--clang-tidy=0`) is 102 | likely specific to a particular check and pattern of code. 103 | 104 | Note that a background-indexing crash can appear to trigger on file open. 105 | 106 | ### Crashes in background indexing 107 | 108 | Unfortunately a crash while background-indexing any file can take down the whole 109 | clangd process. When you start clangd again, it will pick up where it left off, 110 | and crash again. You can tell that this is happening if adding the clangd flag 111 | `--background-index=0` avoids the crash. 112 | 113 | Typically many files are indexed at once and it can be hard to tell which is 114 | crashing. Pass `-j=1 --log=verbose` to clangd to only index one file at a time 115 | and log its name. Once the file is identified, it can also be reduced to a 116 | simpler crashing example. 117 | 118 | ### Getting stacktraces from crashes 119 | 120 | `clangd` is likely writing a "stack trace" to the logs which helps explain 121 | why it crashed. It may look unhelpful, like this: 122 | 123 | ``` 124 | /home/me/bin/clangd[0x4f626c] 125 | /lib/x86_64-linux-gnu/libpthread.so.0(+0x13520)[0x7fb6b93c3520] 126 | /home/me/bin/clangd[0x12cc8d2] 127 | ... 128 | ``` 129 | 130 | It will be more useful if you have `llvm-symbolizer` on your PATH. 131 | 132 | ``` 133 | 0x00000000004f626c llvm::sys::RunSignalHandlers() 134 | 0x00007fe04358f520 __restore_rt 135 | 0x00000000012cc8d2 clang::Parser::ParseDirectDeclarator() 136 | ... 137 | ``` 138 | 139 | This is typically part of the `llvm` package. 140 | It may be installed as e.g. `llvm-symbolizer-10`, and you need to add a symlink. 141 | 142 | On Windows, debug symbols are stored in a separate PDB, and this file needs 143 | to be present in the same directory as clangd.exe to symbolize stack traces. 144 | For official releases, debug symbols can be downloaded as a separate package 145 | from https://github.com/clangd/clangd/releases. 146 | 147 | [installation]: /installation 148 | [bug report]: https://github.com/clangd/clangd/issues 149 | -------------------------------------------------------------------------------- /guides/include-cleaner.md: -------------------------------------------------------------------------------- 1 | # Managing `#include`s 2 | 3 | clangd has features to help you maintain the set of `#include` 4 | directives at the top of each file that are used to import dependencies. 5 | 6 | It follows the [include-what-you-use](https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/WhyIWYU.md) 7 | model: **each source file should `#include` headers that declare the symbols 8 | it references, and no others.** 9 | 10 | This means: 11 | - files should not rely on _transitive_ includes, only headers they include 12 | directly 13 | - `#include` directives describe direct dependencies between files, and it's 14 | possible to reason about them locally 15 | 16 | This is opinionated, and stricter than "will it compile". It implies adding 17 | `#includes` that the compiler does not strictly need. Some `#includes` that 18 | satisfy the compiler should be replaced with more specific ones. 19 | If your codebase broadly aims to follow this style, you should enable these 20 | features. 21 | 22 | ## Show which headers are used 23 | 24 | {:.v16} 25 | 26 | Hovering on a name will show you which header provides that symbol: 27 | ![Symbol hover showing provider in VSCode](../screenshots/symbol_header.png) 28 | 29 | Hovering on an `#include` will show which of its symbols are used in the file. 30 | ![#include hover showing symbols in VSCode](../screenshots/header_symbols.png) 31 | 32 | Using "find references" in your editor you can navigate to these uses. 33 | 34 | ## "Unused include" warning 35 | 36 | {:.v14} 37 | 38 | `#include`ing headers that are not used can confuse readers, slow down build 39 | times, and make code harder to refactor. clangd can warn about this: 40 | 41 | ![Unused include warning in VSCode](../screenshots/unused_include.png) 42 | 43 | Often, these `#include` directives have no effect and can simply be removed. 44 | This isn't always the case: the analysis makes assumptions about code style. 45 | 46 | ## "Missing include" warning 47 | 48 | {:.v17} 49 | 50 | Similarly, using symbols from a header without `#include`ing it is brittle and 51 | hides dependencies. clangd can show such uses: 52 | 53 | ![Missing include warning in VSCode](../screenshots/missing_include.png) 54 | 55 | Generally clangd can suggest a correct `#include` to add here. In some 56 | cases where multiple headers provide a symbol, you may prefer a different one. 57 | 58 | ## Scenarios and solutions 59 | 60 | **An included header X is marked unused, but it #includes Y, which I use** 61 | 62 | **clangd says I should include header Y, but I'm already including X, which 63 | includes Y** 64 | 65 | This is a transitive include. Generally you should avoid this, but there are 66 | times when it's needed, especially with external libraries. 67 | 68 | - Remove the `#include "X.h"` and add `#include "Y.h"` 69 | - If X **intends** to provide all the symbols of Y, indicate this in `X.h` with: 70 | `#include "Y.h" // IWYU pragma: export` 71 | - If X is an internal header that should not be included directly, add a comment 72 | `// IWYU pragma: private; include "Y.h"`. 73 | - Suppress unused-include warnings with `// IWYU pragma: keep`. 74 | - Suppress all warnings for `X.h` in your configuration. 75 | 76 | **A header is marked unused, but is needed by other headers I later include** 77 | 78 | The later headers are not self-contained; our idea of dependencies breaks down. 79 | 80 | - Suppress the warning with `// IWYU pragma: keep`. Document why! 81 | - Suppress all warnings for this header in your configuration. 82 | 83 | **I'm editing header X and `#include "Y.h"` is marked unused. I want X to 84 | provide all of Y's symbols** 85 | 86 | You are exporting a header: this makes dependencies less clear and 87 | coarser-grained, but is sometimes useful. 88 | 89 | - Indicate this with `#include "Y.h" // IWYU pragma: export`. 90 | - If Y is a private implementation detail, annotate it with 91 | `// IWYU pragma: private: include "X.h"`. 92 | 93 | **I'm using a symbol in a tricky way (e.g. through a template), but the header 94 | is marked as unused** 95 | 96 | There are some types of uses the analysis cannot find. 97 | 98 | - Suppress the warning with `// IWYU pragma: keep` 99 | 100 | **A header is marked unused, but removing it breaks my build!** 101 | 102 | clangd's definition of "unused" isn't the same as the compiler's (see above 103 | section). You may have to add missing includes too, or do other cleanups. 104 | 105 | - Identify which headers are **directly** used, and `#include` those instead. 106 | - Suppress the warning with `// IWYU pragma: keep`. 107 | 108 | **clangd suggests `#include "X"`, but the real header for the symbol is Y.** 109 | 110 | This is merely a suggestion: including `Y` should also hide the warning. 111 | 112 | clangd tries to pick the best header, preferring those that public, 113 | self-contained, provide full definitions (for classes and templates), and have 114 | a name matching the symbol's name. 115 | 116 | However, there are limitations. Most notably: only headers that are already 117 | transitively included are considered. You may have to insert the correct 118 | #include yourself. 119 | 120 | **clangd suggests `#include `, but we prefer e.g. ``** 121 | 122 | If the file is C++, then the C++ headers `` will be preferred. 123 | The C header names `<*.h>` will still be accepted as providing the symbol, but 124 | you'll have to `#include` them by hand - this behavior isn't customizable. 125 | 126 | If you're using namespaced symbols (`std::printf` rather than `::printf`) then 127 | only the `` header is acceptable. 128 | 129 | ## Adjusting behavior 130 | 131 | ### Configuration 132 | 133 | In your configuration file, set `Diagnostics.UnusedIncludes` and 134 | `Diagnostics.MissingIncludes` to `Strict` or `None`. 135 | You can also disable analysis of particular files (using `If` blocks), 136 | and suppress all warnings of certain headers. 137 | 138 | ``` 139 | If: 140 | PathMatch: .*/project1/.*\.cpp 141 | Diagnostics: 142 | UnusedIncludes: Strict 143 | MissingIncludes: Strict 144 | Includes: 145 | IgnoreHeader: Python\.h 146 | ``` 147 | 148 | ### IWYU pragmas 149 | 150 | These are magic comments [compatible with the include-what-you-use tool]( 151 | https://github.com/include-what-you-use/include-what-you-use/blob/master/docs/IWYUPragmas.md). 152 | clangd supports only a subset. 153 | 154 | * **keep** 155 | 156 | ``` 157 | #include "secretly-used.h" // IWYU pragma: keep 158 | ``` 159 | 160 | This avoids a particular `#include` being marked unused, without saying why. 161 | 162 | * **export** 163 | 164 | ``` 165 | // in "foo.h" 166 | #include "secretly-used.h" // IWYU pragma: export 167 | ``` 168 | 169 | Files can include `foo.h` to use symbols declared in `secretly-used.h`. 170 | The exported `#include` line itself will never be marked as unused. 171 | 172 | * **private** 173 | 174 | ``` 175 | // in "private.h" 176 | // IWYU pragma: private; include "public.h" 177 | ``` 178 | 179 | Files **must** include `public.h` to use symbols defined in `private.h`. 180 | -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | html { 2 | font-family: 'Helvetica', sans-serif; 3 | background-color: #eeeeee; 4 | margin: 0; 5 | min-height: 100%; 6 | overflow-x: hidden; 7 | overflow-y: overlay; 8 | display: flex; 9 | justify-content: center; 10 | } 11 | body { 12 | background-color: white; 13 | max-width: 1100px; 14 | margin: 0; 15 | box-shadow: 0 0 30px #888; 16 | display: flex; 17 | /* Avoid horizontal overflow. 18 | * Default (min-width: auto) prevents body from shrinking overwide content. */ 19 | min-width: 0; 20 | } 21 | h1, h2, h3, h4 { font-family: 'Nunito', sans-serif; } 22 | aside header { 23 | background-color: #3399dd; 24 | color: white; 25 | margin: 0; 26 | margin-bottom: 1em; 27 | padding: 1.5em 2em; 28 | } 29 | header h1 { 30 | font-size: 3em; 31 | margin: 0; 32 | } 33 | header h1 a { 34 | display: flex; 35 | white-space: nowrap; 36 | } 37 | header #logo-text { 38 | flex-grow: 1; 39 | } 40 | header #logo { 41 | height: 1em; 42 | align-self: center; 43 | margin-left: 0.2em; 44 | } 45 | header h2 { 46 | opacity: 0.7; 47 | font-size: 1em; 48 | margin: 0; 49 | } 50 | header a, nav a { 51 | text-decoration: none; 52 | color: inherit; 53 | } 54 | aside { 55 | background-color: rgba(50, 150, 220, 0.1); 56 | flex: 0 0 250px; 57 | } 58 | nav { 59 | display: flex; 60 | flex-direction: column; 61 | } 62 | nav a { 63 | padding: 0.8em 1.5em; 64 | /* text ------- [icon] */ 65 | display: flex; 66 | justify-content: space-between; 67 | align-items: center; 68 | /* use as a parent for absolute positioning */ 69 | position: relative; 70 | } 71 | nav a.selected { 72 | background-color: rgba(50, 150, 220, 0.3); 73 | } 74 | nav a.folder::before { 75 | content: "►"; 76 | color: #246; 77 | position: absolute; 78 | left: 0.2em; 79 | } 80 | nav a.folder.selected::before { 81 | content: "▼"; 82 | } 83 | nav a:hover:not(.selected) { 84 | background-color: rgba(50, 150, 220, 0.1); 85 | } 86 | nav a .icon { 87 | /* icons should be vertically and horizontally centered. */ 88 | display: inline-block; 89 | font-size: 180%; 90 | line-height: 1em; 91 | text-align: center; 92 | width: 1.2em; 93 | /* Get color emoji if we can */ 94 | font-family: "Noto Color Emoji", "Apple Color Emoji", "Segoe UI Emoji", Times, Symbola, Aegyptus, Code2000, Code2001, Code2002, Musica, serif, LastResort; 95 | order: 1; 96 | } 97 | nav a.child { 98 | font-weight: 600; 99 | padding: 0.4em 0.5em; 100 | display: block; 101 | color: #246; 102 | border-left: 2em solid rgba(0,0,0,0.1); 103 | } 104 | main { 105 | padding: 0 4em; 106 | flex: 1 1 700px; 107 | /* Avoid horizontal overflow. 108 | * Default (min-width: auto) prevents main from shrinking overwide content. */ 109 | min-width: 0; 110 | line-height: 150%; 111 | position: relative; 112 | } 113 | main img { 114 | max-width: 100%; 115 | } 116 | main h1, main h2 { 117 | color: rgb(0, 0, 128); 118 | border-bottom: 1px solid #def; 119 | } 120 | main h3 { 121 | color: rgb(64, 64, 64); 122 | } 123 | hr { 124 | border: none; 125 | height: 1px; 126 | background-color: rgba(0, 0, 0, 0.2); 127 | width: 100%; 128 | } 129 | details { 130 | background-color: rgba(50, 150, 220, 0.08); 131 | margin-bottom: 0.5em; 132 | padding: 0 1em; 133 | overflow-y: hidden; /* Suppress margin-collapsing */ 134 | } 135 | details[open] { 136 | border-bottom: 1px solid rgba(0, 0, 128, 0.2); 137 | margin-bottom: 1em; 138 | } 139 | details summary { 140 | font-weight: bold; 141 | background-color: rgba(50, 150, 220, 0.1); 142 | border-color: rgba(0, 0, 128, 0.2); 143 | border-width: 1px; 144 | border-style: solid none; 145 | padding: 0.2em; 146 | margin: 0 -1em; 147 | } 148 | details summary:hover { 149 | background-color: rgba(50, 150, 220, 0.2); 150 | cursor: pointer; 151 | } 152 | pre > code { 153 | display: block; 154 | overflow-x: auto; 155 | padding-left: 1em; 156 | } 157 | code { 158 | background-color: #ffe; 159 | border: 1px solid #feb; 160 | padding: 5px 1px; 161 | } 162 | a[href^="https://code.woboq.org/"] { 163 | font-family: monospace; 164 | } 165 | 166 | .tip { 167 | color: #00796b; 168 | } 169 | 170 | /* Version marker ornaments */ 171 | .v6::before, .v7::before, .v8::before, .v9::before, .v10::before, .v11::before, .v12::before, 172 | .v13::before, .v14::before, .v15::before, .v16::before, .v17::before, .v18::before, .v19::before, 173 | .v20::before, .v21::before, .v22::before { 174 | color: #008; 175 | border-radius: 3px; 176 | padding: 0.2em 0.6em; 177 | font-family: sans-serif; 178 | font-weight: 500; 179 | background-color: rgba(0, 128, 255, 0.2); 180 | float: right; 181 | line-height: 1.5em; 182 | text-align: center; 183 | font-size: x-small; 184 | } 185 | .v6::before { content: "clangd-6"; } 186 | .v7::before { content: "clangd-7"; } 187 | .v8::before { content: "clangd-8"; } 188 | .v9::before { content: "clangd-9"; } 189 | .v10::before { content: "clangd-10"; } 190 | .v11::before { content: "clangd-11"; } 191 | .v12::before { content: "clangd-12"; } 192 | .v13::before { content: "clangd-13"; } 193 | .v14::before { content: "clangd-14"; } 194 | .v15::before { content: "clangd-15"; } 195 | .v16::before { content: "clangd-16"; } 196 | .v17::before { content: "clangd-17"; } 197 | .v18::before { content: "clangd-18"; } 198 | .v19::before { content: "clangd-19"; } 199 | .v20::before { content: "clangd-20"; } 200 | .v21::before { content: "clangd-21"; } 201 | .v22::before { content: "clangd-22"; } 202 | #edit { 203 | text-decoration: none; 204 | position: absolute; 205 | top: 1em; 206 | right: 4em; 207 | } 208 | 209 | /* Heading anchors (added by JS) */ 210 | main h1, main h2, main h3, main h4 { 211 | overflow-x: clip; 212 | position: relative; 213 | } 214 | .anchor-link { 215 | opacity: 50%; 216 | margin-left: 0.25em; 217 | color: #666; 218 | text-decoration: none; 219 | position: absolute; 220 | } 221 | :hover > .anchor-link { opacity: 100%; } 222 | .anchor-link span { 223 | font-size: 60%; 224 | display: none; 225 | white-space: nowrap; 226 | vertical-align: top; 227 | } 228 | .anchor-link:hover span { display: initial; } 229 | 230 | .main-article { 231 | text-align: center; 232 | font-style: italic; 233 | background-color: rgba(0,0,0,0.05); 234 | padding: 0.3em 0; 235 | margin: -0.5em 0; 236 | text-decoration: none; 237 | } 238 | .main-article::before { 239 | content: "→ Main article: "; 240 | } 241 | 242 | /* Mini layout, for phones */ 243 | @media (max-width: 600px) { 244 | body { 245 | flex-direction: column; 246 | max-width: 100%; 247 | } 248 | main { padding: 0 1em; } 249 | #edit { right: 1em; } 250 | aside { 251 | font-size: 80%; 252 | flex: 0 1 auto; 253 | } 254 | aside header { 255 | margin-bottom: 0; 256 | padding: 1em; 257 | } 258 | aside header h2 { 259 | display: none; 260 | } 261 | nav { 262 | flex-direction: row; 263 | flex-wrap: wrap; 264 | } 265 | /* [Icon] Text ---- */ 266 | nav a { 267 | padding: 0.8em 1em; 268 | margin: 0; 269 | flex-direction: row; 270 | white-space: nowrap; 271 | justify-content: left; 272 | flex: 1 1 0; 273 | min-width: 115px; 274 | } 275 | nav a .icon { 276 | margin-right: 0.1em; 277 | order: -1; 278 | } 279 | nav hr { 280 | margin: 0; 281 | } 282 | /* Folders/children are not shown in mini layout */ 283 | nav a.folder::before { content: none ! important; } 284 | nav a.child { display: none; } 285 | pre { white-space: pre-wrap; } 286 | code { overflow-wrap: break-word; } 287 | } 288 | -------------------------------------------------------------------------------- /features.md: -------------------------------------------------------------------------------- 1 | # Features 2 | 3 | Here is what clangd can do for you. 4 | Screenshots show [VSCode](https://code.visualstudio.com/); the available 5 | features and UI will depend on your editor. 6 | 7 | {% include toc.md %} 8 | 9 | ## Errors and warnings 10 | 11 | clangd runs the clang compiler on your code as you type, and shows diagnostics 12 | of errors and warnings in-place. 13 | 14 | ![screenshot: clang errors](screenshots/errors.png) 15 | 16 | (Some errors are suppressed: diagnostics that require expanding templates in 17 | headers are disabled for performance reasons). 18 | 19 | ### Fixes 20 | 21 | The compiler can suggest fixes for many common problems automatically, and 22 | clangd can update the code for you. 23 | 24 | ![screenshot: apply fix](screenshots/apply_fix.gif) 25 | 26 | If a missing symbol was seen in a file you've edited recently, clangd will 27 | suggest inserting it. 28 | {:.v9} 29 | 30 | ![screenshot: include-fixer fix](screenshots/include_fixer_fix.png) 31 | 32 | ### clang-tidy checks 33 | {:.v9} 34 | 35 | clangd embeds [clang-tidy](https://clang.llvm.org/extra/clang-tidy/) which 36 | provides extra hints about code problems: bug-prone patterns, performance traps, 37 | and style issues. 38 | 39 | ![screenshot: apply clang-tidy fix](screenshots/apply_clang_tidy_fix.gif) 40 | 41 | clangd respects your project's `.clang-tidy` file which controls the checks to 42 | run. Not all checks work within clangd. 43 | 44 | 45 | ## Code completion 46 | 47 | You'll see suggestions as you type based on what methods, variables, etc are 48 | available in this context. 49 | 50 | ![screenshot: code completion](screenshots/code_completion.png) 51 | 52 | Abbreviating words may help you find the right result faster. If you type in 53 | `camelCase` but the function you're looking for is `snake_case`, that's OK. 54 | 55 | ### Namespace and include insertion 56 | {:.v8} 57 | 58 | clangd will sometimes suggest results from other files and namespaces. In this 59 | case the correct qualifier and `#include` directive will be inserted. 60 | 61 | ![screenshot: code completion insert ns](screenshots/code_completion_insert_ns_qualifiers.gif) 62 | 63 | ### Signature help 64 | 65 | Some editors will show you the parameters of the function you're calling, as 66 | you fill them in. 67 | 68 | ![screenshot: signature help](screenshots/signature_help.gif) 69 | 70 | ## Cross-references 71 | 72 | These features let you navigate your codebase. 73 | 74 | They work across the files you've opened. 75 | {:.v7} 76 | 77 | clangd will also automatically index your whole project. 78 | {:.v9} 79 | 80 | ### Find definition/declaration 81 | 82 | Jump to the definition or declaration of a symbol under the cursor. 83 | 84 | ![screenshot: go to def](screenshots/go_to_def.gif) 85 | 86 | (Some editors only expose "find definition" - hit it again to jump to the 87 | declaration). 88 | {:.v9} 89 | 90 | This also works on #include lines, to jump to the included file. 91 | 92 | ### Find references 93 | 94 | Show all references to a symbol under the cursor. 95 | 96 | ![screenshot: find references](screenshots/find_all_refs.gif) 97 | 98 | Some editors will automatically highlight local references to the selected 99 | symbol as you move around a file. 100 | 101 | ## Navigation 102 | 103 | clangd informs the editor of the code structure in the current file. 104 | Some editors use this to present an outline view: 105 | 106 | ![screenshot: outline](screenshots/outline.png) 107 | 108 | In VSCode, this also allows jumping to a symbol within the current file. 109 | 110 | Searching for symbols within the scope of the whole project is also possible. 111 | 112 | ![screenshot: navigation](screenshots/navigation.gif) 113 | 114 | ## Hover 115 | {:.v10} 116 | 117 | Hover over a symbol to see more information about it, such as its type, 118 | documentation, and definition. 119 | 120 | ![screenshot: hover](screenshots/hover.png) 121 | 122 | Hovering over `auto` will show the underlying type. 123 | 124 | ## Formatting 125 | 126 | clangd embeds [clang-format](https://clang.llvm.org/docs/ClangFormat.html), 127 | which can reformat your code: fixing indentation, breaking lines, and reflowing 128 | comments. 129 | 130 | ![screenshot: format selection](screenshots/format_selection.gif) 131 | 132 | clangd respects your project's `.clang-format` file which controls styling 133 | options. 134 | 135 | Format-as-you-type is experimental and doesn't work well yet. 136 | 137 | ## Refactoring 138 | 139 | ### Rename 140 | 141 | Rename a symbol under the cursor. All usages of the symbol will be renamed, 142 | including declaration, definition and references. 143 | 144 | ![screenshot: rename](screenshots/rename.gif) 145 | 146 | Most symbols are renameable, such as classes, variables, functions and methods. 147 | 148 | Renaming a symbol will affect usages of the name across the project. 149 | {:.v11} 150 | 151 | Known limitations 152 | 153 | - References in templates and macro bodies may not be renamed (difficult to 154 | analyze in general) 155 | - References in comments and disabled preprocessor sections are not yet renamed 156 | - Related symbols (e.g. overriden methods in a class hierarchy) are not yet renamed 157 | - Renaming symbols used in several files uses the [project index](design/indexing), and works best when it is up-to-date 158 | 159 | > TIP: the rename workflow highly depends on the editor you are using. Some 160 | > editors, e.g. VSCode, provide a way to preview the rename changes before 161 | > applying them; while some just apply the changes directly. 162 | {:.tip} 163 | 164 | ## Semantic Highlighting 165 | 166 | clangd computes semantic highlight tokens to enhance the source code theming. 167 | {:.v9} 168 | 169 | ![screenshot: highlight](screenshots/semantic_highlight.png) 170 | 171 | A token may be associated with one highlight kind and multiple highlight modifiers, as defined by the following section. 172 | 173 | ### Kinds 174 | 175 | clangd supports following standard LSP token kinds: 176 | 177 | | Kind | LSP Name | Since Version | Note 178 | |-------------------|---------------|---------------|-------------------------- 179 | | Variable | variable | 9 | 180 | | LocalVariable | variable | 9 | 181 | | StaticField | variable | 9 | 182 | | Parameter | parameter | 9 | 183 | | StaticMethod | function | 9 | 184 | | Function | function | 9 | 185 | | Method | method | 9 | 186 | | Field | property | 9 | 187 | | Class | class | 9 | 188 | | Interface | interface | 12 | Objective-C only 189 | | Enum | enum | 9 | 190 | | EnumConstant | enumMember | 9 | 191 | | Type | type | 12 | 192 | | Typedef | type | 9 | 193 | | Primitive | type | 9 | 194 | | TemplateParameter | typeParameter | 9 | 195 | | Namespace | namespace | 9 | 196 | | Macro | macro | 9 | 197 | | Modifier | modifier | 16 | `override`/`final` 198 | | Operator | operator | 15 | Including `new`/`delete` 199 | | Bracket | bracket | 15 | All `()[]{}` 200 | | Label | label | 15 | 201 | | InactiveCode | comment | 11 | Inactive preprocessor branches. Only enabled for clients that do not support [inactive regions extension](https://clangd.llvm.org/extensions#inactive-regions). 202 | 203 | On top of that, as an extension, clangd supports following additional token kinds: 204 | 205 | | Kind | LSP Name | Since Version | Note 206 | |--------------|--------------|---------------|-------------------------------- 207 | | Unknown | unknown | 12 | Dependent names 208 | | Concept | concept | 12 | 209 | 210 | ### Modifiers 211 | 212 | clangd supports following standard LSP token modifiers: 213 | 214 | | Modifier | LSP Name | Since Version | Note 215 | |----------------|----------------|---------------|---------------------- 216 | | Declaration | declaration | 12 | 217 | | Definition | definition | 16 | 218 | | Deprecated | deprecated | 12 | 219 | | Readonly | readonly | 12 | 220 | | Static | static | 12 | 221 | | Abstract | abstract | 12 | For abstract methods 222 | | DefaultLibrary | defaultLibrary | 13 | From standard library 223 | 224 | On top of that, as an extension, clangd supports following additional token modifiers: 225 | 226 | | Modifier | LSP Name | Since Version | Note 227 | |-------------------------|-------------------------|---------------|---------------------------- 228 | | Deduced | deduced | 12 | For `auto` 229 | | Virtual | virtual | 13 | 230 | | DependentName | dependentName | 12 | 231 | | UsedAsMutableReference | usedAsMutableReference | 14 | Mutable reference argument 232 | | UsedAsMutablePointer | usedAsMutablePointer | 15 | Mutable pointer argument 233 | | ConstructorOrDestructor | constructorOrDestructor | 15 | ctor/dtor name 234 | | UserDefined | userDefined | 15 | 235 | | FunctionScope | functionScope | 12 | 236 | | ClassScope | classScope | 12 | 237 | | FileScope | fileScope | 12 | 238 | | GlobalScope | globalScope | 12 | 239 | 240 | ## Experimental C++20 Modules Support 241 | {:.v19} 242 | 243 | Clangd supports C++20 modules experimentally. 244 | We can enable this support by `--experimental-modules-support` option. 245 | The feature is still in experimental stage. Feedback is welcome. 246 | -------------------------------------------------------------------------------- /faq.md: -------------------------------------------------------------------------------- 1 | # Frequently Asked Questions (FAQ) 2 | 3 | {% include toc.md %} 4 | 5 | ## How do I install clangd? 6 | 7 | Clangd is often distributed either within LLVM packages or in a separate 8 | Clang-related packages (e.g. 9 | [clang-tools](https://packages.ubuntu.com/search?keywords=clang-tools) on 10 | Ubuntu). These packages (mostly) follow official LLVM releases, which are 11 | released once every 6 months. 12 | 13 | If you want to use new versions of clangd, you have several options: 14 | 15 | - Download the binaries from our GitHub repository: 16 | - [Stable track](https://github.com/clangd/clangd/releases/latest) - follows 17 | the same release cycle as official LLVM releases and most distributions 18 | - [Weekly builds](https://github.com/clangd/clangd/releases) - not tested as 19 | thoroughly as official releases 20 | - [Compile from sources](#how-do-i-build-clangd-from-sources). 21 | 22 | ## How do I check the clangd version I am using? 23 | 24 | - Check the logs: clangd prints version on the first line. See your LSP client 25 | documentation on where to find them: e.g. VSCode has logs in the output panel, 26 | coc-clangd gives you the logs via `:CocCommand` into `workspace.showOutput` 27 | - Run `clangd --version`. Note: the binary in your `$PATH` might not be the one 28 | used within the editor, checking logs is preferred. 29 | 30 | ## Can you give an example configuration file for clangd? 31 | 32 | The [preferred way](https://clangd.llvm.org/config) to store clangd 33 | configuration is through YAML files. Here's an example config you could use: 34 | 35 | ```yaml 36 | CompileFlags: 37 | # Treat code as C++, use C++17 standard, enable more warnings. 38 | Add: [-xc++, -std=c++17, -Wall, -Wno-missing-prototypes] 39 | # Remove extra warnings specified in compile commands. 40 | # Single value is also acceptable, same as "Remove: [-mabi]" 41 | Remove: -mabi 42 | Diagnostics: 43 | # Tweak Clang-Tidy checks. 44 | ClangTidy: 45 | Add: [performance*, modernize*, readability*] 46 | Remove: [modernize-use-trailing-return-type] 47 | CheckOptions: 48 | readability-identifier-naming.VariableCase: CamelCase 49 | --- 50 | # Use Remote Index Service for LLVM. 51 | If: 52 | # Note: This is a regexp, notice '.*' at the end of PathMatch string. 53 | PathMatch: /path/to/llvm/.* 54 | Index: 55 | External: 56 | Server: clangd-index.llvm.org:5900 57 | MountPoint: /path/to/llvm/ 58 | ``` 59 | 60 | This can go in your project as `.clangd` or a global `clangd/config.yaml` file. 61 | 62 | ## How do I build clangd from sources? 63 | 64 | If you are a developer or downloading pre-built binaries is not an option, you 65 | can [compile 66 | clangd](https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clangd/README.md#building-and-testing-clangd) 67 | from [LLVM 68 | sources](https://github.com/llvm/llvm-project/tree/main/clang-tools-extra/clangd). 69 | Follow [Getting 70 | Started](https://llvm.org/docs/GettingStarted.html#getting-the-source-code-and-building-llvm) 71 | instructions and make sure `LLVM_ENABLE_PROJECTS` has `clang;clang-tools-extra` 72 | (e.g. `DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra"`). 73 | 74 | ## How do I stop clangd from indexing certain folders? 75 | 76 | ```yaml 77 | If: 78 | # Note: This is a regexp, notice '.*' at the end of PathMatch string. 79 | PathMatch: /my/project/large/dir/.* 80 | Index: 81 | # Disable slow background indexing of these files. 82 | Background: Skip 83 | ``` 84 | 85 | ## How do I make additional headers visible to clangd? 86 | 87 | If you have some headers outside of the visibility of clangd, you can either 88 | include individual headers (`--include=/headers/file.h`) or add 89 | directories to the include path (`-I/other/headers`). The easiest way to do 90 | that is through configuration file: 91 | 92 | ```yaml 93 | CompileFlags: 94 | Add: [--include=/headers/file.h, -I/other/headers] 95 | ``` 96 | 97 | ## How do I disable header insertion in code completion? 98 | 99 | You can disable this feature through your [configuration file](https://clangd.llvm.org/config#headerinsertion): 100 | 101 | ```yaml 102 | Completion: 103 | HeaderInsertion: Never 104 | ``` 105 | 106 | Alternatively, you can use the clangd CLI option `--header-insertion=never`. 107 | 108 | ## Why does clangd not return all references for a symbol? 109 | 110 | One of the potential reasons is that clangd has not indexed all the files in 111 | your project. Please make sure all files are visible to clangd through the 112 | project setup and `compile_commands.json`. 113 | 114 | If you are sure all files are indexed and can be accessed: clangd limits the 115 | number of returned results to prevent UI freezes by default. If you have more 116 | than a 1000 symbols and you would like to get through all of them, please pass 117 | `--limit-references=0` to clangd invocation. 118 | 119 | The same applies to the Remote Index Service but we are not respecting 120 | `--limit-references=0` on the server side to prevent DDoS attacks. 121 | 122 | ## How do I fix errors I get when opening headers outside of my project directory? 123 | 124 | Clangd might fail to find suitable compile flags for headers outside of your 125 | project directory (e.g. third party dependencies installed elsewhere -- for more 126 | details see [here](https://clangd.llvm.org/design/compile-commands#headers-outside-the-project-directory)). 127 | 128 | To work around this, you can instruct clangd to use your project's compilation 129 | database for all files, not just files in the project directory. 130 | 131 | This can be done by passing the path of the directory containing the compilation 132 | database as a `--compile-commands-dir=` command-line argument to clangd. 133 | 134 | ## What can I do if clangd chooses the wrong source file to infer commands for a header? 135 | 136 | A tool like 137 | [CompDB](https://github.com/Sarcasm/compdb#generate-a-compilation-database-with-header-files) 138 | can be used to post-process a `compile_commands.json` file to also contain 139 | entries for headers. 140 | 141 | In the absence of entries for headers, clangd will use 142 | [heuristics](https://clangd.llvm.org/design/compile-commands#commands-for-header-files) 143 | to choose a source file whose compile command to use when opening a header. 144 | The heuristics are currently based on filesystem paths and can sometimes 145 | choose the wrong source file, though 146 | [improvements](https://github.com/clangd/clangd/issues/123) are planned. 147 | 148 | ## Why does clangd produce false or missing diagnostics? 149 | 150 | To provide increased responsiveness, clangd skips parsing the bodies of 151 | functions defined in included headers. This optimization can result in: 152 | 153 | - False positive diagnotics, particularly around unused declarations 154 | (if the relevant uses are in the code that was skipped). This can be 155 | worked around by suppressing affected diagnostic categories in the 156 | [config file](https://clangd.llvm.org/config.html#suppress). 157 | 158 | - Missing diagnostics, if they occur in code that was skipped. See 159 | [this issue](https://github.com/clangd/clangd/issues/137) for some 160 | discussion. 161 | 162 | If you believe a false or missing diagnostic is not related to this (and 163 | also not configuration-related, i.e. resulting from clang using the wrong 164 | compile command for a file), please file a bug in the 165 | [issue tracker](https://github.com/clangd/clangd/issues). 166 | 167 | ## Does clangd support CUDA? 168 | 169 | There is some support, but it's not very polished or tested. 170 | clangd uses clang to parse code and [clang can understand CUDA code](https://llvm.org/docs/CompileCudaWithLLVM.html). 171 | 172 | Generally you'll need to: 173 | - ensure that your editor plugin is enabling clangd when CUDA files are open (e.g. enabling for extension `*.cu`) 174 | - make sure that clangd understands these are CUDA files (e.g. by extension `*.cu` or adding the clang flag `-xcuda`) 175 | - set the path to your cuda installation if it isn't detected, by adding the clang flag `--cuda-path=...` 176 | 177 | ## Error "Unable to handle compilation, expected exactly one compiler job" (macOS) 178 | 179 | If your project is configured to build for both ARM (M1) and Intel (x64), you'll see this error 180 | on clangd <= 13. 181 | 182 | [The problem](https://github.com/clangd/clangd/issues/827) 183 | is that the flags `arch x86_64 -arch arm64` tell clang to parse the code twice in 184 | different configurations, and we're not sure which to use. (clangd 14 will pick the first one). 185 | 186 | You can work around the problem by tweaking the compile flags in your clangd config file: 187 | 188 | ``` 189 | CompileFlags: 190 | Remove: [-arch] 191 | Add: [-arch, x86_64] 192 | ``` 193 | 194 | (In other cases, this error message indicates a compile command we don't understand. 195 | If you're not on a Mac it's more likely your compile flags are badly malformed.) 196 | 197 | ## How can I detect clangd in the preprocessor? 198 | 199 | clangd uses the clang parser, and defines preprocessor symbols like `__clang__`. 200 | Code that detects compilers will detect it as clang, which is usually good. 201 | If a library can't be parsed by clang, it generally can't be parsed by clangd either. 202 | 203 | Clangd does not define any extra symbols allowing you to detect it specifically. 204 | But you must write `#ifdef _CLANGD`, you can configure this: 205 | 206 | ``` 207 | CompileFlags: 208 | Add: [-D_CLANGD=1] 209 | ``` 210 | 211 | ## When will a recently added feature appear in a clangd release? 212 | 213 | Clangd follows LLVM's [release schedule](https://llvm.org/docs/HowToReleaseLLVM.html#release-timeline). 214 | 215 | Roughly speaking, LLVM release branches are created twice a year, in January and 216 | July, and stable releases are cut from them in March and September. 217 | 218 | So a clangd feature that lands on trunk between January and July will be available 219 | in a stable release the following September, and a clangd feature that lands on 220 | trunk between July and January will be available in a stable release the following 221 | March. 222 | 223 | For exact dates, you can check the [LLVM announcements forum](https://discourse.llvm.org/c/announce/46). 224 | 225 | You can also check what branches a commit is present on by checking the associated 226 | tags in GitHub. For example, you can tell 227 | [this commit](https://github.com/llvm/llvm-project/commit/85d60a441ab810e25605fb4555971b1d0a996e5c) 228 | is present on the 21 branch because it's labelled with a tag named `llvmorg-21.1.0`, while 229 | [this commit](https://github.com/llvm/llvm-project/commit/a3e2b64b0ddf42abf065377d77a9957edd142585) 230 | is not. 231 | 232 | If you'd like to use a new clangd feature before it appears in a stable release, you 233 | can obtain a weekly snapshot release from the project's 234 | [GitHub releases page](https://github.com/clangd/clangd/releases). In addition, 235 | for Debian-based operating systems, nightly packages are available from 236 | [apt.llvm.org](https://apt.llvm.org). 237 | -------------------------------------------------------------------------------- /design/compile-commands.md: -------------------------------------------------------------------------------- 1 | # Compile commands 2 | 3 | Interpreting source code requires a certain amount of context. 4 | 5 | ```c++ 6 | #include // which file is this, exactly? 7 | 8 | char data[sizeof(int)]; // how big is this array? 9 | 10 | @class Foo; // objective-C, or just a syntax error? 11 | ``` 12 | 13 | C++ compilers expect this context to be passed as command-line flags (and 14 | provide some defaults). A command might look like: 15 | `clang -x objective-c++ -I/path/headers --target=x86_64-pc-linux-gnu -DNDEBUG foo.mm`. 16 | Build systems are responsible for collecting the right flags for each file. 17 | 18 | Clangd also needs this bundle of hints for the files it operates on. 19 | It reuses the compiler's approach: first we determine a virtual 20 | **compile command** for each opened file (ideally by consulting the build 21 | system). Then we use this command to configure the parser. 22 | 23 | ## Compile command vs clangd flags 24 | 25 | These are easy to conflate, and important to distinguish! 26 | 27 | **`clangd` flags** are passed when the editor starts clangd. 28 | They appear in the clangd log at the very start, like 29 | ``` 30 | I[...] argv[1]: --log=verbose 31 | ``` 32 | 33 | The **compile command** (or compile flags) is a **virtual** command constructed, 34 | and interpreted within clangd. 35 | It is logged when a file is opened, e.g. 36 | ``` 37 | I[...] ASTWorker building file /path/test.cc version 1 with command [/path] 38 | /usr/bin/clang /path/test.cc -DNDEBUG -fsyntax-only -resource-dir=/usr/lib/clang/lib/12/ 39 | ``` 40 | 41 | ## What can be in a compile command? 42 | 43 | Because clangd embeds both clang's driver (used to interpret compile commands) 44 | and clang's parser (which is controlled by flags), most [flags that can be passed 45 | to `clang`](https://clang.llvm.org/docs/ClangCommandLineReference.html) 46 | will also work with clangd. The defaults are also similar to `clang` running on 47 | the same system. 48 | 49 | The most critical flags in practice are: 50 | 51 | - Setting the `#include` search path: `-I`, `-isystem`, and others. 52 | - Controlling the language variant used: `-x`, `-std` etc 53 | - Predefining preprocessor macros, `-D` and friends 54 | 55 | Without these flags, clangd will often spectacularly fail to parse source code, 56 | generating many spurious errors (e.g. #included files not being found). 57 | 58 | Many other flags are interesting though: 59 | 60 | - Warnings are controlled with compile flags (e.g. `-Wall`, `-Wswitch`, 61 | `-Wno-switch`, `-Werror`...) 62 | - Changing the target platform (e.g. `--target`) affects some builtins, like 63 | the size of `long`. 64 | 65 | As well as flags, the named program (`argv[0]`) affects parser behavior. 66 | `clang++` will parse as C++ by default, while `clang` will assume C. 67 | `/opt/llvm/bin/clang` will search for the standard library under `/opt/llvm` 68 | as well as the usual places. 69 | 70 | (The working directory is also considered part of the compile command, mostly 71 | it affects how relative paths within the compile command are interpreted). 72 | 73 | ## Where do compile commands come from? 74 | 75 | Generally, clangd first obtains a basic compile command from a compilation 76 | database and then applies some tweaks to it. 77 | 78 | ### Compilation databases 79 | 80 | A [compilation database](https://clang.llvm.org/docs/JSONCompilationDatabase.html) 81 | describes compile commands for a codebase. It can be: 82 | - a file named `compile_commands.json` listing commands for each file. 83 | Usually generated by a build system like CMake. 84 | - a file named `compile_flags.txt` listing flags to be used for all files. 85 | Typically hand-authored for simple projects. 86 | 87 | We first check for a compilation database in the directory containing the 88 | source file, and then walk up into parent directories until we find one. 89 | 90 | [GlobalCompilationDatabase] is responsible for discovering, caching and 91 | refreshing compilation databases. 92 | 93 | #### Commands for header files 94 | 95 | Clangd parses headers like any other source file (which is why it [only supports 96 | self-contained headers](https://github.com/clangd/clangd/issues/45)). However 97 | most build systems don't compile headers directly and therefore don't record 98 | compile commands for them. 99 | 100 | If no command is available for a header, but a file has been opened that 101 | transitively includes it, then that file's command will be used. To enable this 102 | [TUScheduler] keeps a `HeaderIncluderCache` to look up the relevant file. 103 | 104 | Otherwise when `compile_commands.json` is used, we'll pick some entry whose 105 | filename most closely matches that of the header. The idea is that `bar/foo.cc` 106 | is likely to include `bar/foo.h` and therefore have a compatible command. 107 | This is implemented in [InterpolatingCompilationDatabase]. As it's purely a 108 | filename-based heuristic it occasionally goes wrong. 109 | It can also provide a decent default command for newly created files the build 110 | system doesn't know about yet. 111 | 112 | If a command has been "borrowed" from another file, this is noted when the 113 | compile command is logged. (`... with command inferred from foo/bar.cc`). 114 | 115 | #### Fallback commands 116 | 117 | If no compilation database is found, a very simple command like `clang foo.cc` 118 | is used. For a real project this will often fail to find `#include`s, but it 119 | allows clangd to work on toy examples without configuration. 120 | 121 | ### Tweaks always applied 122 | 123 | - bare command names like `clang` are made absolute (by looking them up on the 124 | `$PATH`, querying `xcrun` on mac, or failing that guessing). 125 | This increases the chances of being able to find the standard library. 126 | - on mac, `-isysroot` is set to the default SDK (by querying `xcrun`). 127 | This more closely matches the behavior of Apple's `/usr/bin/clang` (which is 128 | really a script that invokes the real clang with extra flags). 129 | Without this, the standard library again will not be found. 130 | - `-fsyntax-only` is added because we're just parsing, not compiling. 131 | - `-resource-dir=...` is added, because built-in headers like `` must 132 | be the ones installed with clangd. 133 | - certain unsupported flags like `-plugin` are dropped. 134 | 135 | ### Query-driver 136 | 137 | If the compile command names a compiler that is present, then clangd can query 138 | it to understand its default configuration (header search paths and target), and 139 | then adjust the compile command to configure the clang parser to match. 140 | 141 | The compiler (e.g. `custom-gcc`) must be compatible enough with gcc to dump its 142 | configuration in response to this command: 143 | 144 | ``` 145 | $ custom-gcc -E -v -x c++ /dev/null 146 | Target: arm-linux-gnueabihf 147 | ... 148 | #include <...> search starts here: 149 | /opt/custom-gcc/include/c++/10 150 | ... 151 | End of search list. 152 | ``` 153 | 154 | This would cause clangd to add `--target=arm-linux-gnueabihf -isystem 155 | /opt/custom-gcc/include/c++/10` to the compile command, to better simulate this 156 | toolchain. This is often easier than configuring the correct search paths by 157 | hand when code is designed to build with a customized toolchain. 158 | 159 | The compiler queried is always the `argv[0]` of the compile command, but the 160 | clangd flag `--query-driver=/path/to/custom-gcc` must be passed to enable this. 161 | (This must be explicitly enabled as we're executing otherwise unknown binaries!) 162 | 163 | ### Customizing compile commands 164 | 165 | Users may want to modify the compile command used for various reasons. 166 | This is the preferred way to choose which warnings to show, and can sometimes 167 | be used to work around clangd bugs/limitations. 168 | 169 | Editing `compile_commands.json` is usually not a feasable option as it is 170 | a generated file and changes will be quickly overwritten (though writing tools 171 | to automate customizations is possible). 172 | 173 | The [configuration file](/config) is a simpler alternative, allowing compile 174 | flags to be added or removed. e.g. 175 | 176 | ``` 177 | CompileFlags: 178 | Add: '-Wswitch' 179 | Remove: '-Werror' 180 | ``` 181 | 182 | ## Compile command problems 183 | 184 | Incorrect compile commands can cause problems of different severity. 185 | In all cases, the log contains the compile command that was used, and it can be 186 | easiest to feed variations of that command to `clang` to try to understand 187 | the problem. 188 | 189 | ### Unusable command 190 | 191 | If a command is completely malformed, we won't run the parser. This produces 192 | some diagnostics which are attached to line 1 but other features on the file 193 | will not be available (will fail with "invalid AST"). 194 | 195 | (This isn't great, maybe we should recover with a fallback command instead?) 196 | 197 | This can be recognized by the diagnostics (often "expected exactly one compiler 198 | job") by subsequent "invalid AST" errors, and by the "Could not 199 | build CompilerInvocation" log message. 200 | 201 | ### Severe parsing problems 202 | 203 | If the command was unsuitable for the file, then then the parser may run but 204 | fail to understand much of the file. Typical causes: 205 | 206 | - couldn't find included headers because of missing `-I` flags 207 | - command is for parsing C but the code is C++ 208 | 209 | Usually diagnostics reported near the top of the file will make these problems 210 | obvious. 211 | 212 | ### Subtle parsing problems 213 | 214 | Sometimes only a few constructs do not get parsed correctly. For example if 215 | the code uses some C++20 constructs but the compile command doesn't specify 216 | the language version, or if some expected preprocessor symbols are missing. 217 | 218 | This may happens when compile commands from another compiler are used, and 219 | the defaults are different (e.g. GCC currently defaults to C++17, vs C++14 for 220 | clang). 221 | 222 | This will usually result in diagnostics that pinpoint the problem. 223 | 224 | ### Headers outside the project directory 225 | 226 | When opening a header outside the project directory (for example, a header from 227 | an external library that's included by a file in the project), clangd will 228 | typically fail to find a compilation database (which is usually located in the 229 | project directory), and fall back to a default command that may not include 230 | flags that are important for parsing the header's code (for example, include 231 | paths to locate the headers that _it_ includes). 232 | 233 | See [this FAQ question](https://clangd.llvm.org/faq#how-do-i-fix-errors-i-get-when-opening-headers-outside-of-my-project-directory) 234 | for a way to work around this. 235 | 236 | [GlobalCompilationDatabase]: https://code.woboq.org/llvm/clang-tools-extra/clangd/GlobalCompilationDatabase.h.html#clang::clangd::GlobalCompilationDatabase 237 | [InterpolatingCompilationDatabase]: https://code.woboq.org/llvm/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp.html#clang::tooling::(anonymousnamespace)::InterpolatingCompilationDatabase 238 | [TUScheduler]: https://code.woboq.org/llvm/clang-tools-extra/clangd/TUScheduler.h.html#clang::clangd::TUScheduler 239 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /guides/system-headers.md: -------------------------------------------------------------------------------- 1 | # System headers 2 | This guide tries to explain how clangd finds system headers while providing its 3 | functionality. It aims to provide users with enough understanding to resolve any 4 | issues around these headers being missing. 5 | 6 | {% include toc.md %} 7 | 8 | ## What are system headers ? 9 | 10 | In the context of this guide, any header a project depends on but doesn't exist 11 | in the repository is considered a system header. These usually include: 12 | 13 | - Standard library, e.g: `` 14 | - Third party libraries, e.g: `boost` 15 | - Posix, e.g: `` 16 | - Compiler's built-in headers, e.g: `` 17 | 18 | These headers are usually provided either by a custom toolchain, which might be 19 | part of the repository, or directly via system installed libraries. 20 | 21 | Clangd itself only ships with its own built-in headers, because they are tied to 22 | the version of clang embedded in clangd. The rest (including C++ STL) must be 23 | provided by your system. 24 | 25 | ## How clangd finds those headers 26 | 27 | `Clangd` comes with an embedded `clang` parser. Hence it makes use of all the 28 | mechanisms that exist in clang for lookups, while adding some extra spices to 29 | increase chances of discovery on Mac environments. Here follows some information 30 | about what clang does. 31 | 32 | ### Search directories mentioned with compile flags 33 | 34 | As most other compilers clang provides some command line flags to control system 35 | header search explicitly. Most important of these is `-isystem`, which adds a 36 | directory to system include search path. 37 | 38 | Best way to ensure clangd can find your system includes is by putting the 39 | directories to be searched into your compile flags via `-isystem`. You can 40 | achieve this with 41 | [compile\_flags.txt](https://clang.llvm.org/docs/JSONCompilationDatabase.html#alternatives), 42 | [compile\_commands.json](https://clang.llvm.org/docs/JSONCompilationDatabase.html) 43 | or a 44 | [clangd configuration file](http://clangd.llvm.org/config.html#compileflags). 45 | 46 | You might also want to take a look at 47 | [-isysroot](https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-isysroot-dir), 48 | [-system-header-prefix](https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-system-header-prefix) 49 | and 50 | [env variables](https://clang.llvm.org/docs/CommandGuide/clang.html#envvar-C_INCLUDE_PATH,OBJC_INCLUDE_PATH,CPLUS_INCLUDE_PATH,OBJCPLUS_INCLUDE_PATH) 51 | respected by clang. 52 | 53 | ### Heuristic search for system headers 54 | 55 | Clang performs some 56 | [toolchain specific searches](https://github.com/llvm/llvm-project/tree/main/clang/lib/Driver/ToolChains/) 57 | to find suitable directories for system header search. The heuristics used by 58 | most of these search algorithms primarily rely on the **directory containing the 59 | clang driver** and **the target triple**. 60 | 61 | You can investigate this search by invoking any clang with `-v`, for example 62 | `clang -v -c -xc++ /dev/null` (you can replace `/dev/null` with `nul` on 63 | windows). This prints out: 64 | 65 | ``` 66 | ... 67 | Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10 68 | Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/8 69 | Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9 70 | Selected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10 71 | ... 72 | ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include" 73 | ignoring nonexistent directory "/include" 74 | #include "..." search starts here: 75 | #include <...> search starts here: 76 | /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 77 | /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 78 | /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward 79 | /usr/lib/clang/13.0.0/include 80 | /usr/local/include 81 | /usr/include/x86_64-linux-gnu 82 | /usr/include 83 | End of search list. 84 | ``` 85 | 86 | Directories after `#include <...> search starts here` includes all the 87 | directories that will be used for system header search. 88 | 89 | #### Directory of the driver 90 | 91 | These heuristics often expect the standard library to be found near the 92 | compiler. Therefore clangd needs to know where the compiler is, especially when 93 | using a custom toolchain. 94 | 95 | Clangd makes use of the first argument of the compile flags as the driver's 96 | path. Ideally this argument should specify full path to the compiler. 97 | 98 | For example, for a `compile_commands.json` entry like: `{ "directory": 99 | "/home/user/llvm/build", "command": "/usr/bin/clang++ -c -o file.o file.cc", 100 | "file": "file.cc" },` first argument is `/usr/bin/clang++`. 101 | 102 | Note that, in case of a `compile_flags.txt` driver name defaults to `clang-tool` 103 | sitting next to `clangd` binary. 104 | 105 | #### Target Triple 106 | 107 | The second important factor is target triple, which specifies the architecture 108 | and OS to build for. It can be explicitly specified with `--target` compile flag 109 | or can be deduced implicitly from the driver name. 110 | 111 | This enables `clang` to try to locate appropriate headers for the target 112 | platform for example with `--target=x86_64-w64-mingw32` clang will look for 113 | mingw installed headers, which is one common toolchain for windows. You can see 114 | its effects on the header search dirs by executing `clang 115 | --target=x86_64-w64-mingw32 -xc++ -v -c /dev/null` (and without the target 116 | info). 117 | 118 | This can also be achieved by implicitly including target information in the 119 | driver name, but is a lot more subtle and less convenient. So this guide doesn't 120 | go into much details about it, but you can find more 121 | [here](https://github.com/llvm/llvm-project/blob/de79919e9ec9c5ca1aaec54ca0a5f959739d48da/clang/include/clang/Driver/ToolChain.h#L286). 122 | 123 | ### Query-driver 124 | 125 | Instead of trying to guess the header search paths, clangd can also try to query 126 | the actual compiler. For example if your compile flags has `/custom/compiler` as 127 | the driver name, clangd will run something similar to `/custom/compiler -E -xc++ 128 | -v /dev/null` and parse its output (this should work with variants of gcc, 129 | clang, and other compilers with compatible interfaces). 130 | 131 | Note that this is a mechanism that solely exists in clangd and has nothing to do 132 | with clang. 133 | 134 | It can be used as a last resort when clang's heuristics are not enough to detect 135 | standard library locations being used by your custom toolcahin. 136 | 137 | Since it implies executing arbitrary binaries, that might be checked-in with the 138 | project, clangd does not perform this inference automatically. You need to 139 | allowlist binaries you deem safe for execution using `--query-driver` **clangd** 140 | command line option. Please note that this option is just an allowlist and the 141 | real driver to be executed still comes from the compile command. It is a list of 142 | comma separated globs and a driver from a compile command needs to match at 143 | least one of these globs. For example to whitelist drivers in paths: 144 | 145 | - `/path/to/my/project/arm-gcc` 146 | - `/path/to/my/project/arm-g++` 147 | - `/path/to/other/project/gcc` 148 | 149 | You can pass 150 | `--query-driver="/path/to/my/project/arm-g*,/path/to/other/project/gcc"` into 151 | clangd. You can find details about changing clangd arguments used by your editor 152 | in [here](https://clangd.llvm.org/installation#editor-plugins), but it is always 153 | best to check your editor/LSP client's documents directly. 154 | 155 | ## Fixing missing system header issues 156 | 157 | Since we've established some basic understanding of how system header search 158 | works for clang and clangd. Now let's talk about how to fix missing system 159 | header issues. 160 | 161 | ### Headers not present in the system at all 162 | 163 | As mentioned above, clangd doesn't ship with its own standard library. If you 164 | can build the project you are working on the same machine you are using clangd, 165 | you probably have the headers you need on your system but clangd is failing to 166 | find them, so you can just skip this section. 167 | 168 | If you know your system lacks one, you should get it from some place suitable 169 | for your platform. Unfortunately this document is not the best place to talk 170 | about choices or how to get them but here are some choices: 171 | 172 | - `libc++-dev` or `libstdc++-dev` packages on debian-like systems, 173 | - `mingw` for windows, 174 | - `libc++` or `libstdc++` for mac, either through `brew` or `XCode`. 175 | 176 | After getting the headers clangd should hopefully be able to detect them, 177 | assuming they are not installed to a non-default location. 178 | 179 | ### You can build your project but clangd is complaining about missing headers 180 | 181 | In such a case you can start by checking your clangd logs to see compile flags 182 | being used by clangd. Easiest way to achieve this is by executing `clangd 183 | --check=/path/to/a/file/in/your/project.cc`. Outputs logs should contain 184 | something like: 185 | 186 | ``` 187 | I[17:11:57.203] Compile command from CDB is: ... 188 | I[17:11:57.206] internal (cc1) args are: -cc1 ... 189 | ``` 190 | 191 | Note that `--check` is only available starting from clangd-12. For earlier 192 | versions you can open the file in your editor and access clangd logs through 193 | your LSP plugin. 194 | 195 | If you are seeing a log line containing `Generic fallback command is` instead of 196 | the one above, it means clangd is not able to pick your compile commands. If you 197 | don't have any 198 | [compilation database](https://clangd.llvm.org/installation.html#project-setup), 199 | it is expected. But otherwise you should fix that first. 200 | 201 | 202 | You should first try executing the command from CDB to see if it can compile 203 | your file. If it can't, it means you have problems with your compile command 204 | again and probably there's a discrepancy between what your build system uses and 205 | what's being fed into clangd. 206 | 207 | ### Compile command provided to clangd works on its own 208 | 209 | There are usually two reasons for this failure. Either driver mentioned in the 210 | compile command is relative or it is employing custom heuristics unknown to 211 | clang. 212 | 213 | #### Relative driver name 214 | 215 | As mentioned above most of the clang's heuristics rely on the location of the 216 | driver. If clangd cannot figure out the absolute path for your driver, then all 217 | those relative search heuristics will fail. 218 | 219 | The best option here is changing the driver name in your CDB to use absolute 220 | path rather than relative paths. Other than that you can also try putting the 221 | directory containing your driver into `$PATH` so clangd can make it absolute 222 | itself. 223 | 224 | #### Your driver has heuristics unknown to clang 225 | 226 | This is the worst scenario to hit, and unfortunately is common for custom 227 | toolchains targetting embedded devices. 228 | 229 | You can execute the driver with `-v` option to see all the search directories it 230 | has found and the target triple being used. Afterwards there are a couple 231 | options: 232 | 233 | - Explicitly providing target triple in your compile flags and hope that 234 | clang's heuristics can work out the rest. 235 | - Add each system header search path to your compile flags via `-isystem` or 236 | env variables as mentioned above. Note that you might need to disable 237 | clang's search for system headers using 238 | [-nostdlibinc](https://clang.llvm.org/docs/CommandGuide/clang.html#cmdoption-nostdlibinc) 239 | and variants. 240 | - Using clangd's `--query-driver` option to let clangd infer target triple and 241 | system headers by executing the driver mentioned in the compile flags. 242 | - If it feels like your driver is actually performing a generic heuristic, 243 | send a patch to clang to improve it for all! 244 | -------------------------------------------------------------------------------- /installation.md: -------------------------------------------------------------------------------- 1 | # Getting started 2 | 3 | To use clangd, you need: 4 | 5 | - clangd installed 6 | - a plugin for your editor 7 | - to tell clangd how your project is built 8 | 9 | ## Installing clangd 10 | 11 | For best results, use the [most recent version](https://github.com/clangd/clangd/releases/latest) of clangd. 12 | 13 | You can check the version currently installed with `clangd --version`. 14 | 15 | (Version numbers are based on LLVM. clangd 7 was the first usable release). 16 | 17 | ### Installing with a package manager 18 | 19 |
20 | Mac OS X 21 | 22 | Clangd can be installed (along with LLVM) via [Homebrew](https://brew.sh): 23 | ``` 24 | brew install llvm 25 | ``` 26 | 27 | or with [MacPorts](https://www.macports.org/): 28 | 29 | ``` 30 | sudo port install clang-11 31 | ``` 32 | 33 |
34 | 35 |
36 | Windows 37 | Download the LLVM installer from [releases.llvm.org](http://releases.llvm.org/download.html) 38 |
39 | 40 |
41 | Debian/Ubuntu 42 | Installing the `clangd` package will usually give you a slightly older version. 43 | 44 | Try to install a packaged release (12.0): 45 | 46 | ```bash 47 | sudo apt-get install clangd-12 48 | ``` 49 | 50 | If that's not found, at least `clangd-9` or `clangd-8` should be available. 51 | Versions before 8 were part of the `clang-tools` package. 52 | 53 | This will install clangd as `/usr/bin/clangd-12`. Make it the default `clangd`: 54 | 55 | ```bash 56 | sudo update-alternatives --install /usr/bin/clangd clangd /usr/bin/clangd-12 100 57 | ``` 58 | 59 |
60 | 61 |
62 | Other systems 63 | Most distributions include clangd in a `clangd` package, in a `clang-tools` 64 | package, or in the full `llvm` distribution. 65 | 66 | For some platforms, binaries are also available at [releases.llvm.org](http://releases.llvm.org/download.html). 67 |
68 | 69 | ### Standalone .zip releases 70 | 71 | You can also download binaries directly for macOS, windows, and Linux (x86-64): 72 | [latest stable release](https://github.com/clangd/clangd/releases/latest). 73 | 74 | If you live on the bleeding edge, snapshot pre-releases are built weekly and 75 | available on the [github releases page](https://github.com/clangd/clangd/releases). 76 | 77 | ### Compiling from sources 78 | 79 | You can find instructions in 80 | [llvm-project](https://github.com/llvm/llvm-project/tree/main/clang-tools-extra/clangd#building-and-testing-clangd). 81 | 82 | ## Editor plugins 83 | 84 | clangd runs through [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), editors that 85 | support LSP can communicate with clangd to provide features like code completion, diagnostics, go-to-definition, etc. 86 | In principle clangd should work with any of them, though feature set and interface may vary. 87 | 88 | Here are some plugins we know work well with clangd: 89 | 90 |
91 | Vim/Neovim 92 | Vim and Neovim have several plugins that can communicate with clangd. 93 | 94 | ### YouCompleteMe 95 | 96 | Supports both Vim and Neovim. Note that clangd support is not enabled by default in [YouCompleteMe](https://github.com/ycm-core/YouCompleteMe), 97 | you must install it with `install.py --clangd-completer`. 98 | 99 | We recommend changing a couple of YCM's default settings. In `.vimrc` add: 100 | ``` 101 | " Let clangd fully control code completion 102 | let g:ycm_clangd_uses_ycmd_caching = 0 103 | " Use installed clangd, not YCM-bundled clangd which doesn't get updates. 104 | let g:ycm_clangd_binary_path = exepath("clangd") 105 | ``` 106 | 107 | You should see errors highlighted and completions as you type. 108 | 109 | ![Code completion in YouCompleteMe](screenshots/ycm_completion.png) 110 | 111 | YouCompleteMe supports many of clangd's features: 112 | 113 | - code completion 114 | - diagnostics and fixes (`:YcmCompleter FixIt`) 115 | - find declarations, references, and definitions (`:YcmCompleter GoTo` etc) 116 | - rename symbol (`:YcmCompleter RefactorRename`) 117 | 118 | Under the hood: 119 | 120 | - **Debug logs**: run `:YcmDebugInfo` to see clangd status, and `:YcmToggleLogs` 121 | to view clangd's debug logs. 122 | - **Command-line flags**: Set `g:ycm_clangd_args` in `.vimrc`, e.g.: 123 | 124 | ```vim 125 | let g:ycm_clangd_args = ['-log=verbose', '-pretty'] 126 | ``` 127 | 128 | - **Alternate clangd binary**: set `g:ycm_clangd_binary_path` in `.vimrc`. 129 | 130 | ### coc-clangd 131 | 132 | Supports both Vim and Neovim. [coc-clangd](https://github.com/clangd/coc-clangd) is an extension for 133 | [coc.nvim](https://github.com/neoclide/coc.nvim), you need to [install coc.nvim](https://github.com/neoclide/coc.nvim/wiki/Install-coc.nvim) first. 134 | 135 | `:CocInstall coc-clangd` in Vim/Neovim to install coc-clangd. coc-clangd will try to find clangd from your `$PATH`, 136 | if not found, run `:CocCommand clangd.install` to install the [latest release](https://github.com/clangd/clangd/releases/latest) 137 | from GitHub, or set `clangd.path` in `:CocConfig` to use custom clangd binary. 138 | 139 | coc-clangd provides configurations for clangd, you can set them in `:CocConfig`: 140 | 141 | ```json 142 | { 143 | "clangd.path": "/path/to/custom/clangd", 144 | "clangd.arguments": ["--background-index", "--clang-tidy"], 145 | "clangd.fallbackFlags": ["-std=c++23"] 146 | } 147 | ``` 148 | 149 | Check [coc-clangd's README](https://github.com/clangd/coc-clangd?tab=readme-ov-file#configurations) for more options. 150 | 151 | coc-clangd also provides commands to interact with clangd: 152 | 153 | - `:CocCommand clangd.switchSourceHeader`, switch between source/header files 154 | - `:CocCommand clangd.symbolInfo`, resolve symbol info under the cursor 155 | - `:CocCommand clangd.memoryUsage`, show memory usage 156 | - `:CocCommand clangd.install`, install latest release from GitHub 157 | - `:CocCommand clangd.update`, check and update clangd from GitHub 158 | 159 | There are two ways to get request/response logs from coc-clangd: 160 | 161 | 1. Set `"clangd.trace.server": "verbose"` in `:CocConfig`, and check the output in `:CocCommand workspace.showOutput clangd`. 162 | 2. Set `"clangd.trace.file": "/tmp/clangd.log"`, clangd will output logs to the file. 163 | 164 | ### Neovim built-in LSP client 165 | 166 | Neovim only. Neovim has a built-in LSP client, which can be configured to work with clangd. 167 | 168 | 1. install [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig) with your plugin manager 169 | 2. enable clangd in your init.lua: `require'lspconfig'.clangd.setup{}` 170 | 3. the `ClangdSwitchSourceHeader` and `ClangdShowSymbolInfo` commands will be enabled when you are in a C/C++ file 171 | 4. you can pass additional arguments to clangd to trace logs or enable more features: 172 | 173 | ```lua 174 | local lspconfig = require('lspconfig') 175 | lspconfig.clangd.setup({ 176 | cmd = {'clangd', '--background-index', '--clang-tidy', '--log=verbose'}, 177 | init_options = { 178 | fallbackFlags = { '-std=c++17' }, 179 | }, 180 | }) 181 | ``` 182 | 183 | You can also create your own LSP configuration by using the `vim.lsp.start` function. For more details, check `:help vim.lsp.start` 184 | or use [clangd_extensions.nvim](https://github.com/p00f/clangd_extensions.nvim) directly, with more off-spec features support. 185 |
186 | 187 |
188 | Emacs 189 | [eglot](https://github.com/joaotavora/eglot) can be configured to work with clangd. 190 | 191 | Install eglot with `M-x package-install RET eglot RET`. 192 | 193 | Add the following to `~/.emacs` to enable clangd: 194 | 195 | ```elisp 196 | (require 'eglot) 197 | (add-to-list 'eglot-server-programs '((c++-mode c-mode) "clangd")) 198 | (add-hook 'c-mode-hook 'eglot-ensure) 199 | (add-hook 'c++-mode-hook 'eglot-ensure) 200 | ``` 201 | 202 | After restarting you should see diagnostics for errors in your code, and `M-x 203 | completion-at-point` should work. 204 | 205 | ![Diagnostics in Emacs](screenshots/emacs_diagnostics.png) 206 | 207 | eglot supports many of clangd's features, with caveats: 208 | 209 | - code completion, enhanced by `company-mode`, see below 210 | - diagnostics and fixes 211 | - find definitions and references (`M-x xref-find-definitions` etc) 212 | - hover and highlights 213 | - code actions (`M-x eglot-code-actions`) 214 | 215 | ### company-mode 216 | 217 | eglot does have basic integration with company-mode, which provides a more 218 | fluent completion UI. 219 | 220 | You can install it with `M-x package-install RET company RET`, and enable it 221 | with `M-x company-mode`. 222 | 223 | ![Completion in company-mode](screenshots/emacs_company.png) 224 | 225 | ### Under the hood 226 | 227 | - **Debug logs**: available in the `EGLOT events` buffer. 228 | - **Command-line flags and alternate binary**: instead of adding `"clangd"` 229 | to `eglot-server-programs`, add `("/path/to/clangd" "-log=verbose")` etc. 230 |
231 | 232 |
233 | Visual Studio Code 234 | The official extension is 235 | [vscode-clangd](https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.vscode-clangd) 236 | and can be installed from within VSCode. 237 | 238 | Choose **View** --> **Extensions**, then search for "clangd". (Make sure 239 | the Microsoft C/C++ extension is **not** installed). 240 | 241 | After restarting, you should see red underlines underneath errors, and 242 | you should get rich code completions including e.g. function parameters. 243 | 244 | ![Code completion in VSCode](screenshots/basic_completion.png) 245 | 246 | vscode-clangd has excellent support for all clangd features, including: 247 | 248 | - code completion 249 | - diagnostics and fixes 250 | - find declarations, references, and definitions 251 | - find symbol in file (`Ctrl-P @foo`) or workspace (`Ctrl-P #foo`) 252 | - hover and highlights 253 | - code actions 254 | 255 | ### Under the hood 256 | 257 | - **Debug logs**: when clangd is running, you should see "Clang Language Server" 258 | in the dropdown of the Output panel (**View** -> **Output**). 259 | - **Command-line flags**: these can be passed in the `clangd.arguments` array 260 | in your `settings.json`. (**File** -> **Preferences** -> **Settings**). 261 | - **Alternate clangd binary**: set the `clangd.path` string in `settings.json`. 262 |
263 | 264 |
265 | Sublime Text 266 | [sublimelsp/LSP](https://github.com/sublimelsp/LSP) together with [sublimelsp/LSP-clangd](https://github.com/sublimelsp/LSP-clangd) works with clangd out of the box. 267 | 268 | Select **Tools**-->**Install Package Control** (if you haven't installed it yet). 269 | 270 | Press `Ctrl-Shift-P` and select **Package Control: Install Package**. Select 271 | **LSP**. 272 | 273 | Press `Ctrl-Shift-P` and select **Package Control: Install Package**. Select 274 | **LSP-clangd**. 275 | 276 | Open a C++ file, and you should see diagnostics and completion: 277 | 278 | ![Completion in Sublime Text](screenshots/sublime_completion.png) 279 | 280 | The LSP package has excellent support for all most clangd features, including: 281 | 282 | - code completion (a bit noisy due to how snippets are presented) 283 | - diagnostics and fixes 284 | - find definition and references 285 | - hover and highlights 286 | - code actions 287 | 288 | ### Under the hood 289 | 290 | Settings can be tweaked under **Preferences**-->**Package Settings**-->**LSP**-->**servers**-->**LSP-clangd** or from the Command Palette by selecting **Preferences: LSP-clangd Settings**. 291 | 292 | - **Command-line flags and alternate clangd binary**: check inside **Preferences: LSP-clangd Settings** for relevant option and documentation. 293 | 294 |
295 | 296 |
297 | Other editors 298 | There is a directory of LSP clients at [langserver.org](http://langserver.org). 299 | 300 | A generic client should be configured to run the command `clangd`, and 301 | communicate via the language server protocol on standard input/output. 302 |
303 | 304 | If you don't have strong feelings about an editor, we suggest you try out 305 | [VSCode](https://code.visualstudio.com/), it has excellent language server 306 | support and most faithfully demonstrates what clangd can do. 307 | 308 | ## Project setup 309 | 310 | To understand your source code, clangd needs to know your build flags. 311 | (This is just a fact of life in C++, source files are not self-contained). 312 | 313 | By default, clangd will assume your code is built as `clang some_file.cc`, 314 | and you'll probably get spurious errors about missing `#include`d files, etc. 315 | There are a couple of ways to fix this. 316 | 317 | ### `compile_commands.json` 318 | 319 | This file provides compile commands for every source file in a project. 320 | It is usually generated by tools. 321 | 322 | clangd will look in the parent directories of the files you edit looking for it, 323 | and also in subdirectories named `build/`. 324 | For example, if editing `$SRC/gui/window.cpp`, we search in `$SRC/gui/`, 325 | `$SRC/gui/build/`, `$SRC/`, `$SRC/build/`, ... 326 | 327 |
328 | CMake-based projects 329 | If your project builds with CMake, it can generate this file. You should enable 330 | it with: 331 | 332 | ```bash 333 | cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 334 | ``` 335 | 336 | `compile_commands.json` will be written to your build directory. 337 | If your build directory is `$SRC` or `$SRC/build`, clangd will find it. 338 | Otherwise, symlink or copy it to `$SRC`, the root of your source tree. 339 | 340 | ```bash 341 | ln -s ~/myproject-build/compile_commands.json ~/myproject/ 342 | ``` 343 |
344 | 345 |
346 | Bazel-based projects 347 | Bazel can generate this file via [this extractor extension](https://github.com/hedronvision/bazel-compile-commands-extractor). Refer to instructions in the project README; it is intended for use with clangd. 348 |
349 | 350 |
351 | Other build systems, using Bear 352 | [Bear](https://github.com/rizsotto/Bear) is a tool to generate a 353 | compile_commands.json file by recording a complete build. 354 | 355 | For a `make`-based build, you can run 356 | - `make clean; bear -- make` (for bear 3.0.x versions) 357 | - `make clean; bear make` (for bear 2.4.x versions) 358 | 359 | to generate the file (and run a clean build!). 360 | 361 | On Windows, a tool similar to Bear called [compiledb](https://github.com/nickdiego/compiledb) 362 | can be used. 363 |
364 | 365 | Other tools can also generate this file. See [the compile_commands.json 366 | specification](https://clang.llvm.org/docs/JSONCompilationDatabase.html). 367 | 368 | ### `compile_flags.txt` 369 | 370 | If all files in a project use the same build flags, you can put those 371 | flags one-per-line in `compile_flags.txt` in your source root. 372 | 373 | Clangd will assume the compile command is `clang $FLAGS some_file.cc`. 374 | 375 | Creating this file by hand is a reasonable place to start if your project is 376 | quite simple. However background-indexing will not work, as clangd can't be 377 | sure which of the files are project sources. 378 | 379 | This file will be ignored if `compile_commands.json` is present. 380 | -------------------------------------------------------------------------------- /extensions.md: -------------------------------------------------------------------------------- 1 | # Protocol extensions 2 | 3 | clangd supports some features that are not in the official 4 | [Language Server Protocol specification](https://microsoft.github.io/language-server-protocol/specification). 5 | 6 | We try to do this sparingly. The most important considerations are: 7 | 8 | - **Editor support**: How many users will the feature be available to? 9 | - **Standardization**: Is the feature stable? is it likely to be adopted by more 10 | editors over time? 11 | - **Utility**: Does the feature provide a lot of value? 12 | - **Complexity**: Is this hard to implement in clangd, or constrain future work? 13 | Is the protocol complicated? 14 | 15 | These extensions may evolve or disappear over time. If you use them, try to 16 | recover gracefully if the structures aren't what's expected. 17 | 18 | {% include toc.md %} 19 | 20 | ## Switch between source/header 21 | {:.v6} 22 | 23 | Lets editors switch between the main source file (`*.cpp`) and header (`*.h`). 24 | 25 | **New client->server request**: `textDocument/switchSourceHeader`. 26 | - Params: `TextDocumentIdentifier`: an open file. 27 | - Result: `string`: the URI of the corresponding header (if a source file was 28 | provided) or source file (if a header was provided). 29 | 30 | If the corresponding file can't be determined, `""` is returned. 31 | [bug?](https://github.com/clangd/clangd/issues/12) 32 | 33 | ## File status 34 | {:.v8} 35 | 36 | Provides information about activity on clangd's per-file worker thread. 37 | This can be relevant to users as building the AST blocks many other operations. 38 | 39 | **New server->client notification**: `textDocument/clangd.fileStatus` 40 | - Sent when the current activity for a file changes. Replaces previous 41 | activity for that file. 42 | - Params: `FileStatus` object with properties: 43 | - `uri : string`: the document whose status is being updated. 44 | - `state : string`: human-readable information about current activity. 45 | 46 | **New initialization option**: `initializationOptions.clangdFileStatus : bool` 47 | - Enables receiving `textDocument/clangd.fileStatus` notifications. 48 | 49 | ## Compilation commands 50 | {:.v8} 51 | 52 | clangd relies on having accurate compilation commands to correctly interpret a 53 | file. Typically these are discovered via a `compile_commands.json` file in 54 | a parent directory. These extensions allow editors to supply the commands over 55 | LSP instead. 56 | 57 | **New initialization option**: `initializationOptions.compilationDatabasePath : string` 58 | - Specifies the directory containing the compilation database (e.g. 59 | `compile_commands.json`). This path will be used for all files, instead of 60 | searching their ancestor directories. 61 | 62 | **New initialization option**: `initializationOptions.fallbackFlags : string[]` 63 | - Controls the flags used when no specific compile command is found. 64 | The compile command will be approximately `clang $FILE $fallbackFlags` in 65 | this case. 66 | 67 | **New configuration setting**: `settings.compilationDatabaseChanges : {string: CompileCommand}` 68 | - Provides compile commands for files. This can also be provided on startup as 69 | `initializationOptions.compilationDatabaseChanges`. 70 | - Keys are file paths (Not URIs! [bug?](https://github.com/clangd/clangd/issues/13)) 71 | - Values are `{workingDirectory: string, compilationCommand: string[]}` 72 | 73 | ## Force diagnostics generation 74 | {:.v7} 75 | 76 | Clangd does not regenerate diagnostics for every version of a file (e.g. after 77 | every keystroke), as that would be too slow. Its heuristics ensure: 78 | - diagnostics do not get too stale 79 | - if you stop editing, diagnostics will catch up 80 | 81 | This extension allows editors to force diagnostics to be generated/not generated 82 | at a particular revision. 83 | 84 | **New property of `textDocument/didChange` request**: `wantDiagnostics : bool` 85 | - if true, diagnostics will be produced for exactly this version. 86 | - if false, diagnostics will not be produced for this version, even if there 87 | are no further edits. 88 | - if unset, diagnostics will be produced for this version or some subsequent 89 | one in a bounded amount of time. 90 | 91 | ## Diagnostic categories 92 | {:.v8} 93 | 94 | Clang groups diagnostics into categories (e.g. "Inline Assembly Issue"). 95 | Clangd can emit these categories for interested editors. 96 | 97 | **New property of `Diagnostic` object**: `category : string`: 98 | - A human-readable name for a group of related diagnostics. 99 | Diagnostics with the same code will always have the same category. 100 | 101 | **New client capability**: `textDocument.publishDiagnostics.categorySupport`: 102 | - Requests that clangd send `Diagnostic.category`. 103 | 104 | ## Inline fixes for diagnostics 105 | {:.v8} 106 | 107 | LSP specifies that code actions for diagnostics (fixes) are retrieved 108 | asynchronously using `textDocument/codeAction`. However clangd always computes 109 | these eagerly, and providing them alongside diagnostics can improve the UX in 110 | editors. 111 | 112 | **New property of `Diagnostic` object**: `codeActions : CodeAction[]`: 113 | - All the code actions that address this diagnostic. 114 | 115 | **New client capability**: `textDocument.publishDiagnostics.codeActionsInline : bool` 116 | - Requests that clangd send `Diagnostic.codeActions`. 117 | 118 | ## Symbol info request 119 | {:.v8} 120 | 121 | This attempts to resolve the symbol under the cursor, without retrieving 122 | further information (like definition location, which may require consulting an 123 | index). This was added to support integration with indexes outside clangd. 124 | 125 | **New client->server request**: `textDocument/symbolInfo`: 126 | - Params: `TextDocumentPositionParams` 127 | - Response: `SymbolDetails`, an object with properties: 128 | - `name : string` the unqualified name of the symbol 129 | - `containerName : string` the enclosing namespace, class etc (without 130 | trailing `::`) 131 | - `usr : string`: the clang-specific "unified symbol resolution" identifier 132 | - `id : string?`: the clangd-specific opaque symbol ID 133 | 134 | ## UTF-8 offsets 135 | {:.v9} 136 | 137 | > **WARNING** 138 | > This extension has been deprecated with `clangd-21` in favor of the `positionEncoding` introduced in LSP 3.17. It'll go away with `clangd-23`. 139 | > See [the official LSP specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocuments) 140 | 141 | LSP specifies that offsets within lines are in UTF-16 code units (for `Position`s and also delta-encoded document updates). 142 | This choice of encoding is a legacy of VSCode's JavaScript implementation. 143 | 144 | clangd allows clients to use UTF-8 offsets instead. This allows clients that always speak UTF-8 (in violation of the protocol) to work correctly, and those that are UTF-8 native to avoid unnecessary transcoding (which may be slow if implemented in e.g. vimscript). 145 | 146 | **New client capability**: `offsetEncoding : string[]`: 147 | 148 | Lists the encodings the client supports, in preference order. It SHOULD include `"utf-16"`. If not present, it is assumed to be `["utf-16"]` 149 | 150 | Well-known encodings are: 151 | - `utf-8`: `character` counts bytes 152 | - `utf-16`: `character` counts code units 153 | - `utf-32`: `character` counts codepoints 154 | 155 | **New InitializeResponse property**: `offsetEncoding: string`: 156 | - Specifies the encoding that the server selected, which should be used. 157 | - This should be one of the requested encodings, or `"utf-16"` if none were supported. 158 | - Only sent if the client capability was specified (or otherwise negotiated, e.g. clangd flag `-offset-encoding=utf-8`). 159 | 160 | **Advice for clients using this extension**: 161 | - clients that only support UTF-8 should send `offsetEncoding: ["utf-8"]` in their client capabilities. 162 | This will cause the server to use UTF-8 if supported. 163 | - clients that prefer UTF-8 but can use UTF-16 should send `offsetEncoding: ["utf-8", "utf-16"]` and observe the selected encoding in the `InitializeResponse`, defaulting to UTF-16 if it's not present. 164 | This will negotiate UTF-8 with servers that support it. 165 | - clients that prefer UTF-16 may send `offsetEncoding: ["utf-16"]` or simply not use the extension. 166 | 167 | **Advice for servers using this extension**: 168 | - servers that only support UTF-8 should send `offsetEncoding: "utf-8"` in their InitializeResponse. 169 | This will enable UTF-8 in clients that support it. 170 | - servers that support both UTF-8 and UTF-16 should check whether the client capabilities mentions `"utf-8"` as supported, and use it if so. The selected encoding should be reported in the `InitializeResponse`. 171 | This allows UTF-8 to be used when the client prefers it. 172 | - servers that only support UTF-16 can add `offsetEncoding: "utf-16"` or simply not use the extension. 173 | 174 | ## Type hierarchy 175 | {:.v9} 176 | 177 | Clangd supports the type hierarchy extension proposed for LSP. 178 | 179 | Type hierarchy allows the server to provide the client with information about 180 | the subclasses (derived classes) and superclasses (base classes) of the class 181 | referenced at a provided document location. Clients typically use this to show 182 | a tree view of the class and its subclasses or superclasses (or sometimes, in 183 | languages with single inheritance, a single tree showing both). 184 | 185 | The version of the protocol currently implemented is the one in 186 | [this proposal](https://github.com/microsoft/vscode-languageserver-node/pull/426). 187 | 188 | ## Code completion scores 189 | {:.v10} 190 | 191 | LSP gives servers limited control over completion display order through the 192 | `sortText` attribute. Clangd uses several signals such as number of usages to 193 | ensure the most likely completions are near the top. 194 | 195 | However as the user continues to type, editors filter and re-rank the results 196 | on the client side. This re-ranking should take into account the signals from 197 | the server, but LSP does not expose them. 198 | 199 | **New CompletionItem property**: `score: number`: 200 | - The quality of the result, independent of how well it fuzzy-matches the word 201 | being completed. (Value is >= 0, higher is better). 202 | - Clients that fuzzy client-side filtering should multiply `score` by their 203 | fuzzy-match score and sort by the result. 204 | - Clients with non-fuzzy client-side filtering only should sort by `score`. 205 | - Clients that don't support client-side filtering should ignore this and 206 | use `sortText`, which incorporates `score` and fuzzy-matching. 207 | 208 | ## AST 209 | {:.v12} 210 | 211 | C++ has a complicated grammar and semantic structure that's not always obvious 212 | from the source. Inspecting the Clang AST can lend some insight. 213 | Despite the origin of the name (Abstract Syntax Tree), it captures semantics as 214 | well as syntax (e.g. implicit casts). 215 | 216 | **New client->server request**: `textDocument/ast`: 217 | - Params: `ASTParams` object with properties: 218 | - `textDocument : TextDocumentIdentifier`: the open file to inspect 219 | - `range : Range`: the region of the source code whose AST is fetched. 220 | The highest-level node that entirely contains the range is returned. 221 | - Result: `ASTNode` object with properties: 222 | - `role : string`: the general kind of node, such as "expression". 223 | Corresponds to clang's base AST node type, such as Expr. 224 | The most common are "expression", "statement", "type" and "declaration". 225 | - `kind : string`: the specific kind of node, such as "BinaryOperator". 226 | Corresponds to clang's concrete node class, with Expr etc suffix dropped. 227 | - `detail : string?`: brief additional details, such as '||'. 228 | Information present here depends on the node kind. 229 | - `arcana : string?`: one line dump of information, similar to that printed 230 | by `clang -Xclang -ast-dump`. Only available for certain types of nodes. 231 | - `range : Range`: the part of the code that produced this node. 232 | Missing for implicit nodes, nodes produced by macro expansion, etc. 233 | - `children : ASTNode[]?`: descendants describing the internal structure. 234 | The tree of nodes is similar to that printed by `clang -Xclang -ast-dump`, 235 | or that traversed by `clang::RecursiveASTVisitor`. 236 | 237 | **New server capability**: `astProvider : bool`: 238 | - Signals that the server supports `textDocument/ast` requests. 239 | 240 | ## Memory usage 241 | {:.v12} 242 | 243 | clangd can use a lot of memory. It can be valuable to understand where it goes. 244 | We expose a hierarchy where memory is associated with a tree of components. 245 | e.g. an AST may be stored under `clangd_server.tuscheduler."main.cpp".ast`. 246 | 247 | The actual component hierarchy is subject to change between versions, and 248 | the memory usage is only estimated (it mostly counts objects rather than 249 | tracking allocations directly). 250 | 251 | **New client->server request**: `$/memoryUsage`: 252 | - Params: none 253 | - Result: `MemoryTree` object with properties: 254 | - `_total : number`: number of bytes used, including child components 255 | - `_self : number`: number of bytes used, excluding child components 256 | - `[component] : MemoryTree`: memory usage of a named child component 257 | 258 | **New server capability**: `memoryUsageProvider : bool`: 259 | - Signals that the server supports `$/memoryUsage` requests. 260 | 261 | ## Reference Container 262 | {:.v16} 263 | 264 | When finding references to a symbol, it's often useful to know the name of the 265 | function or class in which the reference occurs. 266 | 267 | **New property of `Location` object**: `containerName : string?`: 268 | - Name of the function or class in which the reference occurs. Might be null, 269 | e.g. if the containing symbol is not indexed. Can also be an empty string, e.g. 270 | for declarations at global scope. 271 | 272 | **New client capability**: `textDocument.references.container`: 273 | - Requests that clangd adds the `containerName` property to the `Location` 274 | objects returned by `textDocument/references` 275 | 276 | ## Inlay hints 277 | {:.v14} 278 | 279 | Inlay hints are labels that are displayed by the editor in-line with the code. 280 | 281 | | **Without hints:** | memcpy(buf, data, n) | 282 | | **With hints:** | memcpy(_dest:_ buf, _src:_ data, _count:_ n) | 283 | 284 | clangd can provide several categories of hints. 285 | 286 | **New client->server request**: `clangd/inlayHints`: 287 | - Params: `InlayHintsParams` object with properties: 288 | - `textDocument : TextDocumentIdentifier`: the open file to inspect 289 | - `range : Range?`: the region of the source code to retrieve hints for. 290 | If not set, returns hints for the whole document. 291 | - Result: `InlayHints[]`, where `InlayHint` has properties: 292 | - `kind : string`: Type of hint being provided, e.g. `"parameter"`, `"type"`. 293 | - `label : string`: The label that should be displayed, e.g. `"dest:"`. 294 | - `position : Position`: The point between characters to show the hint. 295 | - `range : Range`: The range the hint is associated with, e.g. the argument. 296 | 297 | **New server capability**: `clangdInlayHintsProvider : bool`: 298 | - Signals that the server supports `clangd/inlayHints` requests. 299 | 300 | _Compatibility_: Several language servers support inlay hint extensions. 301 | This extension is mostly compatible with 302 | [rust-analyzer/inlayHints](https://github.com/kjeremy/vscode-languageserver-node/blob/5849e59afd9d598666426f2640dfbd173eace02d/protocol/src/protocol.inlayHints.proposed.md). 303 | typescript-language-server also supports a similar 304 | [typescript/inlayHints](https://github.com/typescript-language-server/typescript-language-server#inlay-hints-typescriptinlayhints-experimental). 305 | 306 | Our hope is that some version of inlay hints is standardized in LSP. Once 307 | standard inlay hints are implemented in clangd, we will deprecate this extension 308 | and eventually remove it. 309 | 310 | See LSP 311 | [bug 956](https://github.com/microsoft/language-server-protocol/issues/956), 312 | [PR 609](https://github.com/microsoft/vscode-languageserver-node/pull/609), 313 | [PR 772](https://github.com/microsoft/vscode-languageserver-node/pull/772). 314 | 315 | ## Inactive regions 316 | {:.v17} 317 | 318 | Source code can contain regions that are disabled by e.g. `#if 0` directives. 319 | Clangd can analyze the code to determine which regions are inactive. 320 | This allows the client to better highlight inactive code regions, for example by reducing their opacity. 321 | 322 | **New server->client notification**: `textDocument/inactiveRegions`. 323 | - Params: `InactiveRegions` object with properties: 324 | - `uri : string`: the document whose status is being updated. 325 | - `regions: Range[]`: an array of ranges that are inactive. 326 | 327 | **New client capability**: `textDocument.inactiveRegionsCapabilities.inactiveRegions : bool` 328 | - Enables receiving `textDocument/inactiveRegions` notifications. 329 | -------------------------------------------------------------------------------- /config.md: -------------------------------------------------------------------------------- 1 | # Configuration 2 | 3 | The configuration mechanism is new in clangd 11, and more options will be 4 | exposed in this way in future. 5 | {:.v11} 6 | 7 | {% include toc.md %} 8 | 9 | ## Files 10 | 11 | Configuration is stored in YAML files. These are either: 12 | 13 | - **project configuration**: a file named `.clangd` in the source tree. 14 | (clangd searches in all parent directories of the active file). 15 | 16 | Generally this should be used for shared and checked-in settings. 17 | 18 | (Existing _directories_ named `.clangd` can be deleted. 19 | These were used for temporary storage by clangd before version 11.) 20 | 21 | - **user configuration**: a `config.yaml` file in an OS-specific directory: 22 | - *Windows*: `%LocalAppData%\clangd\config.yaml`, typically 23 | `C:\Users\Bob\AppData\Local\clangd\config.yaml`. 24 | - *macOS*: `~/Library/Preferences/clangd/config.yaml` 25 | - *Linux and others*: `$XDG_CONFIG_HOME/clangd/config.yaml`, typically 26 | `~/.config/clangd/config.yaml`. 27 | 28 | Private settings go here, and can be scoped to projects using `If` conditions. 29 | 30 | Each file can contain multiple fragments separated by `---` lines. (This is 31 | only useful if the fragments have different `If` conditions). 32 | 33 | JSON is a subset of YAML, so you can use that syntax if you prefer. 34 | 35 | Changes should take effect immediately as you continue to edit code. 36 | 37 | ## Loading and combining fragments 38 | 39 | By default, user configuration applies to all files that are opened. 40 | Project configuration applies to files under its tree (`proj/.clangd` configures 41 | `proj/**`). 42 | 43 | `If` conditions can further limit this, e.g. to configure only header files. 44 | 45 | Configuration is combined when this is sensible. In case of conflicts, user 46 | config has the highest precedence, then inner project, then outer project. 47 | 48 | # Schema 49 | 50 | At the top-level, a fragment is a key-value mapping that divides the document 51 | into "blocks" of related options, each of which is a key-value mapping. 52 | 53 | In most places where an array of scalar values can be specified, a single value 54 | is also acceptable. e.g. `Add: -Wall` is equivalent to `Add: [-Wall]`. 55 | 56 | ## If 57 | 58 | Conditions in the `If` block restrict when a fragment applies. 59 | 60 | ```yaml 61 | If: # Apply this config conditionally 62 | PathMatch: .*\.h # to all headers... 63 | PathExclude: include/llvm-c/.* # except those under include/llvm-c/ 64 | ``` 65 | 66 | Each separate condition must match (combined with AND). 67 | When one condition has multiple values, any may match (combined with OR). 68 | e.g. `PathMatch: [foo/.*, bar/.*]` matches files in either directory. 69 | 70 | As a complete example this may look something like: 71 | 72 | ```yaml 73 | # ... Prior fragments 74 | --- 75 | If: # Apply this config conditionally 76 | PathMatch: [.*\.h, .*\.c] # to all headers OR c files 77 | PathExclude: internal/.* # except all files within "internal" 78 | CompileFlags: 79 | Add: [-DEXTERNAL] 80 | --- 81 | # ... Further fragments 82 | ``` 83 | 84 | Conditions based on a file's path use the following form: 85 | 86 | - if the fragment came from a project directory, the path is relative 87 | - if the fragment is global (e.g. user config), the path is absolute 88 | - paths always use forward-slashes (UNIX-style) 89 | 90 | If no file is being processed, these conditions will not match. 91 | 92 | ### PathMatch 93 | 94 | The file being processed must fully match a regular expression. 95 | 96 | ### PathExclude 97 | 98 | The file being processed must *not* fully match a regular expression. 99 | 100 | ## CompileFlags 101 | 102 | Affects how a source file is parsed. 103 | 104 | ```yaml 105 | CompileFlags: # Tweak the parse settings 106 | Add: [-xc++, -Wall] # treat all files as C++, enable more warnings 107 | Remove: [-W*] # strip all other warning-related flags 108 | Compiler: clang++ # Change argv[0] of compile flags to `clang++` 109 | ``` 110 | 111 | clangd emulates how clang would interpret a file. 112 | By default, it behaves roughly as `clang $FILENAME`, but real projects usually 113 | require setting the include path (with the `-I` flag), defining preprocessor 114 | symbols, configuring warnings etc. 115 | 116 | Often, a compilation database specifies these compile commands. clangd 117 | searches for `compile_commands.json` in parents of the source file. 118 | 119 | This section modifies how the compile command is constructed. 120 | 121 | ### Add 122 | 123 | List of flags to append to the compile command. 124 | 125 | ### Remove 126 | 127 | List of flags to remove from the compile command. 128 | 129 | - If the value is a recognized clang flag (like `-I`) then it will be 130 | removed along with any arguments. Synonyms like `--include-directory=` 131 | will also be removed. 132 | - Otherwise, if the value ends in `*` (like `-DFOO=*`) then any argument 133 | with the prefix will be removed. 134 | - Otherwise any argument exactly matching the value is removed. 135 | 136 | In all cases, `-Xclang` is also removed where needed. 137 | 138 | Example: 139 | 140 | - Command: `clang++ --include-directory=/usr/include -DFOO=42 foo.cc` 141 | - Configuration: `Remove: [-I, -DFOO=*]` 142 | - Result: `clang++ foo.cc` 143 | 144 | Flags added by the same CompileFlags entry will not be removed. 145 | 146 | ### CompilationDatabase 147 | {:.v12} 148 | 149 | Directory to search for compilation database (compile_commands.json etc). 150 | Valid values are: 151 | - A single path to a directory (absolute, or relative to the fragment) 152 | - Ancestors: search all parent directories (the default) 153 | - None: do not use a compilation database, just default flags. 154 | 155 | ### Compiler 156 | {:.v14} 157 | 158 | String to replace the executable name in the compile flags. The name controls 159 | flag parsing (clang vs clang-cl), target inference (gcc-arm-noneabi) etc. 160 | 161 | If the option matches a glob mentioned in `--query-driver`, then it'll be 162 | invoked for extraction of include paths. 163 | 164 | ### BuiltinHeaders 165 | {:.v21} 166 | 167 | Controls whether Clangd should include its own built-in headers (like 168 | stddef.h), or use the system header found from the query driver. 169 | 170 | Valid values are: 171 | - `Clangd`: Use builtin headers from `clangd`. This is the default. 172 | - `QueryDriver`: Use the headers extracted from the compiler via the 173 | `--query-driver` command line argument. If a query driver is not supplied or 174 | does not match the compiler, then the `Clangd` builtin headers will be the 175 | fallback. 176 | 177 | ```yaml 178 | CompileFlags: 179 | BuiltinHeaders: QueryDriver 180 | ``` 181 | 182 | **Note**: if the driver is not clang, `BuiltinHeaders: QueryDriver` will result 183 | in the clang frontend (embedded in clangd) processing the builtin headers of 184 | another compiler, which could lead to unexpected results such as false positive 185 | diagnostics. 186 | 187 | ## Index 188 | 189 | Controls how clangd understands code outside the current file. 190 | 191 | ```yaml 192 | Index: 193 | Background: Skip # Disable slow background indexing of these files. 194 | ``` 195 | 196 | clangd's indexes provide information about symbols that isn't available to 197 | clang's parser, such as incoming references. 198 | 199 | ### Background 200 | 201 | Whether files are built in the background to produce a project index. 202 | This is checked for translation units only, not headers they include. 203 | Legal values are `Build` (the default) or `Skip`. 204 | 205 | ### External 206 | {:.v12} 207 | 208 | Used to define an external index source: 209 | 210 | - On-disk monolithic index produced by `clangd-indexer` or 211 | - Address of a [remote-index-server](/guides/remote-index). 212 | 213 | `MountPoint` can be used to specify source root for the index. This is necessary 214 | to handle relative path conversions. Overall schema looks like this: 215 | 216 | ```yaml 217 | Index: 218 | External: 219 | File: /abs/path/to/an/index.idx 220 | # OR 221 | Server: my.index.server.com:50051 222 | MountPoint: /files/under/this/project/ 223 | ``` 224 | 225 | - Exactly one of `File` or `Server` needs to be specified. 226 | - `MountPoint` defaults to location of the config fragment if not provided, must 227 | be absolute in global config and relative in local config. 228 | - Declaring an `External` index disables background-indexing implicitly for 229 | files under the `MountPoint`. Users can turn it back on, by explicitly 230 | mentioning `Background: Build` in a later fragment. 231 | 232 | ### StandardLibrary 233 | {:.v15} 234 | 235 | Controls whether clangd eagerly indexes the standard library (to give 236 | code completions of standard library symbols on an empty file). Sample block 237 | (default). 238 | 239 | ``` 240 | Index: 241 | StandardLibrary: true 242 | ``` 243 | 244 | ## Style 245 | 246 | Describes the style of the codebase, beyond formatting. 247 | 248 | ### FullyQualifiedNamespaces 249 | 250 | Namespaces that should always be fully qualified, meaning no "using" 251 | declarations, always spell out the whole name (with or without leading::). 252 | All nested namespaces are affected as well. 253 | Affects availability of the AddUsing tweak. 254 | 255 | ### QuotedHeaders 256 | {:.v20} 257 | 258 | A list of regexes. Headers whose path matches one of these regexes are 259 | inserted using `""` syntax. 260 | 261 | ### AngledHeaders 262 | {:.v20} 263 | 264 | A list of regexes. Headers whose path matches one of these regexes are 265 | inserted using `<>` syntax. 266 | 267 | Example: 268 | 269 | ``` 270 | Style: 271 | QuotedHeaders: "src/.*" 272 | AngledHeaders: ["path/sdk/.*", "third-party/.*"] 273 | ``` 274 | 275 | ## Diagnostics 276 | {:.v12} 277 | 278 | ### Suppress 279 | 280 | Diagnostic codes that should be suppressed. 281 | 282 | Valid values are: 283 | 284 | - `'*'`, to disable all diagnostics 285 | - diagnostic codes exposed by clangd (e.g `unknown_type`, `-Wunused-result`) 286 | - clang internal diagnostic codes (e.g. `err_unknown_type`) 287 | - warning categories (e.g. `unused-result`) 288 | - clang-tidy check names (e.g. `bugprone-narrowing-conversions`) 289 | 290 | This is a simple filter. Diagnostics can be controlled in other ways 291 | (e.g. by disabling a clang-tidy check, or the `-Wunused` compile flag). 292 | This often has other advantages, such as skipping some analysis. 293 | 294 | ### ClangTidy 295 | 296 | Configure how clang-tidy runs over your files. 297 | 298 | The settings are merged with any settings found in .clang-tidy 299 | configuration files with the ones from clangd configs taking precedence. 300 | 301 | #### Add 302 | 303 | List of [checks](https://clang.llvm.org/extra/clang-tidy/checks/list.html). 304 | These can be globs, for example `Add: 'bugprone-*'`. 305 | 306 | #### Remove 307 | 308 | List of checks to disable, can be globs. 309 | 310 | This takes precedence over Add, this supports enabling all checks from a module apart from some specific checks. 311 | 312 | Example to use all modernize module checks apart from use trailing return type: 313 | 314 | ```yaml 315 | Diagnostics: 316 | ClangTidy: 317 | Add: modernize* 318 | Remove: modernize-use-trailing-return-type 319 | ``` 320 | 321 | #### CheckOptions 322 | 323 | Key-value pairs of options for clang-tidy checks. 324 | Available options for all checks can be found [here](https://clang.llvm.org/extra/clang-tidy/checks/list.html). 325 | 326 | Note the format here is slightly different to `.clang-tidy` configuration 327 | files as we don't specify `key: , value: `. Instead just use 328 | `: ` 329 | 330 | ```yaml 331 | Diagnostics: 332 | ClangTidy: 333 | CheckOptions: 334 | readability-identifier-naming.VariableCase: CamelCase 335 | ``` 336 | 337 | #### FastCheckFilter 338 | {:.v18} 339 | 340 | Whether to run clang-tidy checks that may slow down clangd. 341 | 342 | Valid values are: 343 | - `Strict`: Run only checks measured to be fast. This excludes recently-added 344 | checks that we have not timed yet. This is the default. 345 | - `Loose`: Run checks unless they are known to be slow. 346 | - `None`: Run checks regardless of their speed. 347 | 348 | ```yaml 349 | Diagnostics: 350 | ClangTidy: 351 | FastCheckFilter: Strict 352 | ``` 353 | 354 | ### UnusedIncludes 355 | {:.v14} 356 | 357 | Enables Include Cleaner's [unused includes 358 | diagnostics](/design/include-cleaner). Possible values: `None`, 359 | `Strict` (default since clangd 17). 360 | 361 | ```yaml 362 | Diagnostics: 363 | UnusedIncludes: Strict 364 | ``` 365 | 366 | ### Includes 367 | 368 | #### IgnoreHeader 369 | {:.v15} 370 | 371 | A list of regexes. Include Cleaner will not produce diagnostics for headers 372 | whose path is a suffix match for any of these. 373 | 374 | #### AnalyzeAngledIncludes 375 | {:.v19} 376 | 377 | A boolean that enables/disables detection of unused angled includes that are not from the Standard Library. 378 | Disabled by default to avoid false-positives caused by umbrella headers. 379 | 380 | ### MissingIncludes 381 | {:.v17} 382 | 383 | Enables Include Cleaner's [missing includes diagnostics](/design/include-cleaner). 384 | Possible values: `None` (default), `Strict`. 385 | 386 | ## Completion 387 | 388 | Configures code completion features. Sample block (default): 389 | 390 | ```yaml 391 | Completion: 392 | AllScopes: Yes 393 | ArgumentLists: FullPlaceholders 394 | HeaderInsertion: IWYU 395 | CodePatterns: All 396 | ``` 397 | 398 | ### AllScopes 399 | {:.v13} 400 | Whether code completion should include suggestions from scopes that are 401 | not visible. The required scope prefix will be inserted. The default is `Yes`. 402 | 403 | ### ArgumentLists 404 | {:.v20} 405 | 406 | Determines what is inserted in argument list position when completing a 407 | call to a function. Here are the valid values and examples of the 408 | corresponding behaviour, assuming a function `foo(int arg)` exists 409 | (`^` represents the cursor position): 410 | 411 | - `None`: `fo^` completes to `foo^` 412 | - `OpenDelimiter`: `fo^` completes to `foo(^` 413 | - `Delimiters`: `fo^` completes to `foo(^)` 414 | - `FullPlaceholders`: `fo^` completes to `foo(int arg)`, with `int arg` selected 415 | 416 | The default is `FullPlaceholders`. 417 | 418 | This option governs the completion of template names as well, where 419 | the delimiters are `<>`. 420 | 421 | ### HeaderInsertion 422 | {:.v21} 423 | 424 | Add `#include` directives when accepting code completions. Config 425 | equivalent of the CLI option `--header-insertion`. Valid values are: 426 | - `IWYU`: Include what you use. Insert the owning header for top-level 427 | symbols, unless the header is already directly included or the 428 | symbol is forward-declared. This is the default. 429 | - `Never`: Never insert headers. 430 | 431 | ### CodePatterns 432 | {:.v21} 433 | 434 | Completion will suggest code snippets and code patterns. 435 | Valid values are: 436 | - `All`: All the code snippets and patterns are suggested. 437 | - `None`: None of the code snippets and patterns are suggested. 438 | 439 | The default is `All`. 440 | 441 | ## InlayHints 442 | {:.v14} 443 | 444 | Configures the behaviour of the inlay-hints feature. Sample block (default): 445 | 446 | ```yaml 447 | InlayHints: 448 | BlockEnd: false 449 | Designators: true 450 | Enabled: true 451 | ParameterNames: true 452 | DeducedTypes: true 453 | DefaultArguments: false 454 | TypeNameLimit: 24 455 | ``` 456 | 457 | ### Enabled 458 | {:.v14} 459 | 460 | A boolean that enables/disables the inlay-hints feature for all kinds, when 461 | disabled, configuration for specific kinds are ignored. 462 | 463 | ### ParameterNames 464 | {:.v14} 465 | 466 | A boolean that enables/disables inlay-hints for parameter names in function 467 | calls. 468 | 469 | ### DeducedTypes 470 | {:.v14} 471 | 472 | A boolean that enables/disables inlay-hints for deduced types. 473 | 474 | ### Designators 475 | {:.v14} 476 | 477 | A boolean that enables/disables inlay-hints for designators in aggregate initialization. (eg: `Designators: true`: `std::vector arr = {[0]= 1, [1]= 2}` ; `Designators: false`: `std::vector arr = {1, 2}`) 478 | 479 | ### BlockEnd 480 | {:.v17} 481 | 482 | A boolean that enables/disables inlay-hints for block end comment. An example is shown below (comments are inlay hints): 483 | 484 | ```c++ 485 | void foo() { 486 | struct S { 487 | }; // struct S 488 | } // foo 489 | ``` 490 | 491 | ### DefaultArguments 492 | {:.v20} 493 | 494 | A boolean that enables/disables inlay hints for default arguments. Example: 495 | 496 | ```c++ 497 | void foo(int a, int b = 42); 498 | void bar() { 499 | // This line will be displayed as `foo(a: 41, b: 42);` 500 | // The `a:` is the usual parameter hint. 501 | // The `, b: 42` is a default argument hint. 502 | foo(41); 503 | } 504 | ``` 505 | 506 | ### TypeNameLimit 507 | {:.v17} 508 | 509 | Character limit for type hints. Hints that would be longer are not shown. 510 | 0 means no limit. 511 | 512 | ## Hover 513 | {:.v14} 514 | 515 | Configures contents of the hover cards. Sample block (default): 516 | 517 | ```yaml 518 | Hover: 519 | ShowAKA: false 520 | MacroContentsLimit: 2048 521 | ``` 522 | 523 | ### ShowAKA 524 | {:.v14} 525 | 526 | A boolean that controls printing of desugared types, e.g: 527 | `vector::value_type (aka int)` 528 | 529 | ### MacroContentsLimit 530 | {:.v22} 531 | 532 | Character limit for hovered macro expansions. Expansions that would be longer are not shown. 533 | 0 means no limit. 534 | 535 | The default is `2048`. 536 | 537 | ## Semantic Tokens 538 | {:.v17} 539 | 540 | Configure semantic highlighting. Sample block (default): 541 | 542 | ```yaml 543 | SemanticTokens: 544 | DisabledKinds: [] 545 | DisabledModifiers: [] 546 | ``` 547 | 548 | ### DisabledKinds 549 | {:.v17} 550 | 551 | Specify semantic token kinds that clangd should not send to client. 552 | 553 | Available kinds could be found [here](features#kinds) in the Kind column. 554 | 555 | ### DisabledModifiers 556 | {:.v17} 557 | 558 | Specify semantic token modifiers that clangd should not send to client. 559 | 560 | Available modifiers could be found [here](features#modifiers) in the Modifier column. 561 | 562 | ## Documentation 563 | {:.v22} 564 | 565 | Specify server side documentation code comment interpretation. 566 | Affects the format of the documentation string sent to the client for hover and code completions. 567 | Sample block (default): 568 | 569 | ```yaml 570 | Documentation: 571 | CommentFormat: Plaintext 572 | ``` 573 | 574 | ### CommentFormat 575 | 576 | Determines the comment format of code documentation. 577 | 578 | - `Plaintext`: interpret code documentation as plain text. Markdown specific syntax will be escaped. On clients supporting markdown, this will result in showing markdown syntax without rendering. E.g. using \*\*bold text\*\* in the documentation comment will be shown as \*\*bold text\*\* and not as **bold text** in the hover/code completion. 579 | - `Markdown`: interpret documentation comments as markdown. Markdown syntax will not be escaped, except for HTML tags. On clients supporting markdown, this will result in rendering all markdown syntax. 580 | - `Doxygen`: interpret code documentation as [doxygen](https://www.doxygen.nl/) comments. In addition to treating the documentation as markdown, this will parse the documentation with Clang's doxygen parser. It will highlight used doxygen commands, convert doxygen commands to markdown syntax and extend hover content with e.g. function parameter or return documentation. 581 | -------------------------------------------------------------------------------- /design/code.md: -------------------------------------------------------------------------------- 1 | # clangd code walkthrough 2 | 3 | This describes the critical parts of clangd and roughly what they do. 4 | It may get out of date from time to time, please 5 | [file a bug](https://github.com/llvm/clangd-www/issues)! 6 | It mostly starts at the outside and works it way inward. 7 | 8 | The clangd code lives in the [llvm-project] repository under 9 | [clang-tools-extra/clangd][clangd]. We'll also mention some dependencies in 10 | other parts of llvm-project (such as clang). 11 | 12 | Links below point to the [woboq] code browser. It has nice cross-referenced navigation, but may show 13 | a slightly outdated version of the code. 14 | 15 | {% include toc.md %} 16 | 17 | ## Starting up and managing files 18 | 19 | ### Entry point and JSON-RPC 20 | 21 | The `clangd` binary itself has its [main()] entrypoint in `tool/ClangdMain.cpp`. 22 | This mostly parses flags and hooks `ClangdLSPServer` up to its dependencies. 23 | 24 | One vital dependency is [JSONTransport] which speaks the JSON-RPC protocol 25 | over stdin/stdout. LSP is layered on top of this [Transport] abstraction. 26 | (There's also an Apple XPC transport in the [xpc/] directory). 27 | 28 | We call `ClangdLSPServer.run()` to start the loop, and it synchronously 29 | processes messages until the client disconnects. Calls to the large 30 | non-threadsafe singletons (`ClangdLSPServer`, `ClangdServer`, `TUScheduler`) 31 | all happen on the main thread. 32 | See [threads and request handling]. 33 | 34 | ### Language Server Protocol 35 | 36 | [ClangdLSPServer] handles the LSP protocol details. Incoming requests are routed 37 | to some method on this class using a lookup table, and then implemented 38 | by dispatching them to the contained `ClangdServer`. 39 | 40 | The incoming JSON requests are mapped onto structs defined in [Protocol.h]. 41 | In the simplest cases these are just forwarded to the appropriate method on 42 | `ClangdServer` - we use the LSP structs as vocabulary types for most things. 43 | 44 | In other cases there's some gap between LSP and what seems to be a sensible C++ 45 | API, so `ClangdLSPServer` has some real work to do. 46 | 47 | ### ClangdServer and TUScheduler 48 | 49 | The [ClangdServer] class is best thought of as the C++ API to clangd. 50 | Features tend to be implemented as stateless, synchronous functions ("give me 51 | hover information from this AST at offset 25"). ClangdServer exposes them as 52 | stateful, asynchronous functions ("compute hover information for the latest 53 | version of Foo.cpp at offset 25, call back when done") which is the LSP model. 54 | 55 | [TUScheduler] is responsible for keeping track of the latest version of each 56 | file, building and caching ASTs and preambles as inputs, and providing threads 57 | to run requests on in an appropriate sequence. (More details in 58 | [threads and request handling]). 59 | It also pushes certain events to `ClangdServer` via [ParsingCallbacks], to 60 | allow emitting diagnostics and indexing ASTs. 61 | 62 | `ClangdServer` is fairly mechanical for the most part. The features are 63 | implemented in various other files, and the scheduling and AST building is 64 | done by `TUScheduler`, so largely it just binds these together. 65 | `TUScheduler` doesn't know about particular features (except diagnostics). 66 | 67 | ### Compile commands 68 | 69 | Like other clang-based tools, clangd uses clang's command-line syntax as its 70 | interface to configure parse options (like include directories). 71 | The arguments are obtained from a [tooling::CompilationDatabase], typically 72 | built by reading `compile_commands.json` from a nearby directory. 73 | [GlobalCompilationDatabase] is responsible for finding and caching such 74 | databases, and for providing "fallback" commands when none are found. 75 | 76 | Various heuristic tweaks are applied to these commands to make them more likely 77 | to work, particularly on Mac. These live in [CommandMangler]. 78 | 79 | ## Features 80 | 81 | ### Diagnostics 82 | 83 | During parsing, clang emits diagnostics through a `DiagnosticConsumer` callback. 84 | clangd's [StoreDiags] implementation converts them into [Diag] objects, 85 | which capture the relationships between diagnostics, fixes, and notes. 86 | These are exposed in `ParsedAST`. 87 | (clang-tidy diagnostics are generated separately in `buildAST()`, but also end 88 | up captured by `StoreDiags` and exposed in the same way). 89 | 90 | [IncludeFixer] attempts to add automatic fixes to certain diagnostics by using 91 | the index to find headers that should be included. 92 | 93 | `TUScheduler` has a logic to determine when a `ParsedAST`'s diagnostics are 94 | "correct enough" to emit, and when a new build is needed for this purpose. 95 | It then triggers `ClangdServer::onMainAST`, which calls 96 | `ClangdLSPServer::onDiagnosticsReady`, which sends them to the client. 97 | 98 | ### AST-based features 99 | 100 | Most clangd requests are handled by inspecting a `ParsedAST`, and maybe the 101 | index. Examples are [locateSymbolAt()] (go-to-definition) and [getHover()]. 102 | 103 | These features are spread across various files, but are easy to find from their 104 | callsites in `ClangdServer`. 105 | 106 | ### Code completion (and signature help) 107 | 108 | Code completion does not follow the usual pattern for AST-based features. 109 | Instead there's a dedicated parse of the current file with a callback when the 110 | completion point is reached. 111 | The core completion logic is implemented in clang's [SemaCodeComplete.cpp] and 112 | has access to information not present in the AST, such as name-lookup structures 113 | and parser state. 114 | 115 | [CodeComplete.h] is mostly concerned with running clang in this mode, 116 | combining clang's results with index-based results, applying ranking, and 117 | converting to LSP's data model. 118 | 119 | The ranking is mostly implemented in [Quality.h], and the name-matching 120 | is done by [FuzzyMatcher]. 121 | 122 | ### Code actions 123 | 124 | Most code actions are provided by `Tweak`s. These are small plugins that 125 | implement the [Tweak] interface. They live in the [refactor/tweaks] directory 126 | and are registered through the linker. Given a selection, they can (quickly) 127 | determine whether they apply there and (maybe slowly) generate the actual edits. 128 | The LSP code-actions flow is built out of these primitives. 129 | 130 | ## Feature infrastructure 131 | 132 | ### Parsing and ASTs 133 | 134 | The representation of a parsed file in clangd is [ParsedAST]. 135 | As the name suggests this is mostly used to access Clang's AST 136 | (`clang::ASTContext`), but extends it by: 137 | 138 | - recording and exposing information gathered from callbacks (e.g. diagnostics) 139 | - encapsulating the other objects (e.g. SourceManager and Preprocessor) and 140 | keeps them alive with the correct lifetime 141 | 142 | `ParsedAST::build()` is where we run the clang parser. 143 | Some low-level bits (creating `CompilerInstance`) are in [Compiler.h] 144 | instead, and are reused when we run clang without retaining an AST (code 145 | completion, indexing, preambles). 146 | 147 | The [PreambleData] structure similarly extends Clang's `PrecompiledPreamble` 148 | class with extra recorded information. It contains the AST of included headers 149 | and is only rebuilt when those headers change. The preamble is large, it's kept 150 | on disk by default and parts are deserialized on demand. 151 | 152 | ### Abstractions over clang AST 153 | 154 | Several tasks come up in various features and we have reusable solutions: 155 | 156 | - [SelectionTree] identifies the AST nodes corresponding to a point or range 157 | in the source code. 158 | Used in go-to-definition, code actions, and many other features. 159 | - [targetDecl()] identifies the declaration an AST node refers to. 160 | Used e.g. in go-to-definition. 161 | - [findExplicitReferences()] traverses a chunk of AST and lists declarations 162 | referenced. Used e.g. in find-references and rename. Should be used for 163 | indexing, one day. 164 | 165 | ### Index 166 | 167 | Operations that need information outside the current file/AST make use of 168 | [the clangd index], which is in the [index/] directory. 169 | 170 | [SymbolIndex] is the index interface exposed to consuming features, and 171 | describes the data/queries they should provide. (`Symbol`, `Ref`, etc). 172 | It has several implementations used as building-blocks: 173 | 174 | - [MemIndex] is a simple in-memory implementation that's cheap to construct. 175 | - [Dex] is a more complex one with a scalable fuzzyFind search. 176 | - [MergedIndex] combines indexes, merging results. 177 | - [IndexClient] is a client for a remote index service over grpc. 178 | 179 | [SymbolCollector] extracts indexable data from a translation unit. 180 | [index/Serialization.h] defines a binary format to store/load index data. 181 | 182 | These building blocks are used to provide clangd's index data: 183 | 184 | - [BackgroundIndex] runs `SymbolCollector` over project files in background 185 | threads, periodically combining the results into an exposed `Dex` index. 186 | Index data is also written to disk and only reindexed when these are stale. 187 | - [FileIndex] stores the index information from all opened files and their 188 | preambles, running SymbolCollector on ASTs after they are rebuilt. It is a 189 | `MergedIndex` of a `Dex` of the preambles and a `MemIndex` of the main-file 190 | symbols. This is also known as the "dynamic index". 191 | - The "static index" is configured in `main` and may be a 192 | simple index file (generated by [indexer/IndexerMain.cpp]) loaded into `Dex`, 193 | a `RemoteIndex`, or nothing at all. 194 | 195 | ## Dependencies 196 | 197 | ### Clang libraries 198 | 199 | Clang code structure is a huge topic, but the most important pieces for clangd: 200 | 201 | - AST: [clang/AST/] defines the data structures that represent 202 | parsed C++ code, such the [Decl], [Stmt], and [Type] hierarchies. 203 | [RecursiveASTVisitor] is the generic mechanism to walk an AST. 204 | - Preambles: [PrecompiledPreamble] wraps a serialized partial AST that can be 205 | lazy-loaded from disk, clangd relies *heavily* on this optimization. 206 | - Preprocessor: at the token level, the [Preprocessor] handles directives and 207 | macro expansion, and we use [PPCallbacks] hooks to listen for events. 208 | 209 | ### Clang-tools libraries 210 | 211 | clangd shares code with other tools derived from the Clang compiler, these 212 | libraries live outside clangd. 213 | 214 | - [syntax::TokenBuffer] captures token-boundary and preprocessing information 215 | that clang itself doesn't preserve. 216 | - [clang/Index/] implements an indexing-oriented traversal of Clang ASTs, which 217 | is used in clangd's index. 218 | - [clang/Format/] is the clang-format logic used to satisfy formatting requests 219 | and also to format newly-inserted code. 220 | - [tooling::CompilationDatabase] is the foundation for clangd's integration 221 | with build systems. 222 | 223 | ### General support libraries 224 | 225 | Like most LLVM code, clangd heavily uses [llvm/ADT/] and [llvm/Support/] to 226 | supplement the standard library. We try to avoid other LLVM dependencies. 227 | 228 | clangd has its own [support/] library, conceptually similar to `llvm/Support`. 229 | It contains libraries that are general-purpose, but not a good fit for llvm as a 230 | whole (too opinionated, or focused on multithreading). The most prominent: 231 | 232 | - [ThreadsafeFS] addresses the problems with llvm's FileSystem abstraction for 233 | multithreaded programs. 234 | - [Context] is used to passing certain "ambient" data around within the current 235 | thread, and automatically propagating it when scheduling on another thread. 236 | (It is related to dynamically-scoped variables, and thread-local storage). 237 | It's used for certain settings like overriding LSP encoding, for tracking 238 | actions across threads, request cancellation and more. 239 | - [support/Logger.h] provides a concise, threadsafe logging API and lets 240 | embedders handle logs. 241 | - [support/Trace.h] allows instrumentation of clangd's implementation with 242 | events and metrics for performance analysis etc. 243 | 244 | ## Testing 245 | 246 | Most of the tests are in the [unittests/] directory (despite being a mix of unit 247 | and integration tests). Test files are mostly named after the file they're 248 | testing, and use the [googletest] framework. 249 | 250 | Some helpers are widely shared between tests: 251 | 252 | - [TestTU] lets tests tersely specify code for a test case, and can prepare 253 | `ParsedAST` and other structures needed for testing features on that code. 254 | - [Annotations] recognizes code examples with marked points and ranges. 255 | This is used e.g. to specify tests for "go to definition". 256 | 257 | clangd has a small number of black-box tests in [test/]. These use LLVM [lit] 258 | and [FileCheck] to drive the clangd binary and verify output. They smoke-test 259 | clangd as an LSP server, and test a few hard-to-isolate features. 260 | 261 | [FileCheck]: https://llvm.org/docs/CommandGuide/FileCheck.html 262 | [googletest]: https://github.com/google/googletest 263 | [lit]: https://llvm.org/docs/CommandGuide/lit.html 264 | [llvm-project]: https://github.com/llvm/llvm-project 265 | [woboq]: https://code.woboq.org/llvm/clang-tools-extra/clangd/ 266 | 267 | [threads and request handling]: /design/threads 268 | [the clangd index]: /design/indexing 269 | 270 | [clangd]: https://code.woboq.org/llvm/clang-tools-extra/clangd/ 271 | [index/]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/ 272 | [test/]: https://code.woboq.org/llvm/clang-tools-extra/clangd/test/ 273 | [refactor/tweaks/]: https://code.woboq.org/llvm/clang-tools-extra/clangd/refactor/tweaks/ 274 | [support/]: https://code.woboq.org/llvm/clang-tools-extra/clangd/support/ 275 | [unittests/]: https://code.woboq.org/llvm/clang-tools-extra/clangd/unittests/ 276 | [xpc/]: https://code.woboq.org/llvm/clang-tools-extra/clangd/xpc/ 277 | 278 | [llvm/ADT/]: https://code.woboq.org/llvm/llvm/include/llvm/ADT/ 279 | [llvm/Support/]: https://code.woboq.org/llvm/llvm/include/llvm/Support/ 280 | [clang/AST/]: https://code.woboq.org/llvm/clang/include/clang/AST/ 281 | [clang/Index/]: https://code.woboq.org/llvm/clang/include/clang/Index/ 282 | [clang/Format/]: https://code.woboq.org/llvm/clang/include/clang/Format/ 283 | 284 | [CodeComplete.h]: https://code.woboq.org/llvm/clang-tools-extra/clangd/CodeComplete.h.html 285 | [Compiler.h]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Compiler.h.html 286 | [Protocol.h]:https://code.woboq.org/llvm/clang-tools-extra/clangd/Protocol.h.html 287 | [Quality.h]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Quality.h.html 288 | [index/Serialization.h]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/Serialization.h.html 289 | [indexer/IndexerMain.cpp]: https://code.woboq.org/llvm/clang-tools-extra/clangd/indexer/IndexerMain.h.html 290 | [support/Logger.h]: https://code.woboq.org/llvm/clang-tools-extra/clangd/support/Logger.h.html 291 | [support/Trace.h]: https://code.woboq.org/llvm/clang-tools-extra/clangd/support/Trace.h.html 292 | 293 | [SemaCodeComplete.cpp]: https://code.woboq.org/llvm/clang/lib/Sema/SemaCodeComplete.cpp.html 294 | 295 | [Annotations]: https://code.woboq.org/llvm/clang-tools-extra/clangd/unittests/Annotations.h.html#clang::clangd::Annotations 296 | [BackgroundIndex]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/Background.h.html#clang::clangd::BackgroundIndex 297 | [ClangdLSPServer]: https://code.woboq.org/llvm/clang-tools-extra/clangd/ClangdLSPServer.h.html#clang::clangd::ClangdLSPServer 298 | [ClangdServer]: https://code.woboq.org/llvm/clang-tools-extra/clangd/ClangdServer.h.html#clang::clangd::ClangdServer 299 | [CommandMangler]: https://code.woboq.org/llvm/clang-tools-extra/clangd/CompileCommands.h.html#clang::clangd::CommandMangler 300 | [Context]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Context.h.html#clang::clangd::Context 301 | [Dex]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/dex/Dex.h.html#clang::clangd::dex::Dex 302 | [Diag]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Diagnostics.h.html#clang::clangd::Diag 303 | [FileIndex]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/FileIndex.h.html#clang::clangd::FileIndex 304 | [FuzzyMatcher]: https://code.woboq.org/llvm/clang-tools-extra/clangd/FuzzyMatch.h.html#clang::clangd::FuzzyMatcher 305 | [GlobalCompilationDatabase]: https://code.woboq.org/llvm/clang-tools-extra/clangd/GlobalCompilationDatabase.h.html#clang::clangd::GlobalCompilationDatabase 306 | [IncludeFixer]: https://code.woboq.org/llvm/clang-tools-extra/clangd/IncludeFixer.h.html#clang::clangd::IncludeFixer 307 | [IndexClient]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/remote/Client.cpp.html#clang::clangd::remote::(anonymousnamespace)::IndexClient 308 | [JSONTransport]: https://code.woboq.org/llvm/clang-tools-extra/clangd/JSONTransport.cpp.html#clang::clangd::(anonymousnamespace)::JSONTransport 309 | [MemIndex]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/MemIndex.h.html#clang::clangd::MemIndex 310 | [MergedIndex]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/Merge.h.html#clang::clangd::MergedIndex 311 | [ParsedAST]: https://code.woboq.org/llvm/clang-tools-extra/clangd/ParsedAST.h.html#clang::clangd::ParsedAST 312 | [ParsingCallbacks]: https://code.woboq.org/llvm/clang-tools-extra/clangd/TUScheduler.h.html#clang::clangd::ParsingCallbacks 313 | [PreambleData]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Preamble.h.html#clang::clangd::PreambleData 314 | [SelectionTree]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Selection.h.html#clang::clangd::SelectionTree 315 | [StoreDiags]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Diagnostics.h.html#clang::clangd::StoreDiags 316 | [SymbolCollector]: https://code.woboq.org/llvm/clang-tools-extra/clangd/index/SymbolCollector.h.html#clang::clangd::SymbolCollector 317 | [SymbolIndex]: https://code.woboq.org/llvm/clang-tools-extra/clang-include-fixer/SymbolIndex.h.html#clang::include_fixer::SymbolIndex 318 | [TUScheduler]: https://code.woboq.org/llvm/clang-tools-extra/clangd/TUScheduler.h.html#clang::clangd::TUScheduler 319 | [TestTU]: https://code.woboq.org/llvm/clang-tools-extra/clangd/unittests/TestTU.h.html#clang::clangd::TestTU 320 | [ThreadsafeFS]: https://code.woboq.org/llvm/clang-tools-extra/clangd/support/ThreadsafeFS.h.html#clang::clangd::ThreadsafeFS 321 | [Transport]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Transport.h.html#clang::clangd::Transport 322 | [Tweak]: https://code.woboq.org/llvm/clang-tools-extra/clangd/refactor/Tweak.h.html#clang::clangd::Tweak 323 | [findExplicitReferences()]: https://code.woboq.org/llvm/clang-tools-extra/clangd/FindTarget.h.html 324 | [getHover()]: https://code.woboq.org/llvm/clang-tools-extra/clangd/Hover.h.html 325 | [locateSymbolAt()]: https://code.woboq.org/llvm/clang-tools-extra/clangd/XRefs.h.html 326 | [main()]: https://code.woboq.org/llvm/clang-tools-extra/clangd/tool/ClangdMain.cpp.html#main 327 | [targetDecl()]: https://code.woboq.org/llvm/clang-tools-extra/clangd/FindTarget.h.html 328 | 329 | [Decl]: https://code.woboq.org/llvm/clang/include/clang/AST/DeclBase.h.html#clang::Decl 330 | [Stmt]: https://code.woboq.org/llvm/clang/include/clang/AST/Stmt.h.html#clang::Stmt 331 | [Type]: https://code.woboq.org/llvm/clang/include/clang/AST/Type.h.html#clang::Type 332 | [Preprocessor]: https://code.woboq.org/llvm/clang/include/clang/Lex/Preprocessor.h.html#clang::Preprocessor 333 | [PPCallbacks]: https://code.woboq.org/llvm/clang/include/clang/Lex/PPCallbacks.h.html#clang::PPCallbacks 334 | [RecursiveASTVisitor]: https://code.woboq.org/llvm/clang/include/clang/AST/RecursiveASTVisitor.h.html#clang::RecursiveASTVisitor 335 | [PrecompiledPreamble]: https://code.woboq.org/llvm/clang/include/clang/Frontend/PrecompiledPreamble.h.html#clang::PrecompiledPreamble 336 | [syntax::TokenBuffer]: https://code.woboq.org/llvm/clang/include/clang/Tooling/Syntax/Tokens.h.html#clang::syntax::TokenBuffer 337 | [tooling::CompilationDatabase]: https://code.woboq.org/llvm/clang/include/clang/Tooling/CompilationDatabase.h.html#clang::tooling::CompilationDatabase 338 | --------------------------------------------------------------------------------