Skip to content

Latest commit

 

History

History
496 lines (396 loc) · 30.3 KB

configuration.md

File metadata and controls

496 lines (396 loc) · 30.3 KB

Configuration and limits

This is the reference for how the server is configured and what it deliberately does not do. The language features themselves are in c-support.md and cpp-support.md.

1. Two inputs, and no third

compile_commands.json     the build, as it ran                    — every build system can export it
build_database.json       the same, for a build with C++ modules — CMake 3.31's CMAKE_EXPORT_BUILD_DATABASE
.cppls.toml               what a person knows and a build cannot  — this file

A server that also read this build system's cache and that one's project file would have to be taught every build system in turn, and would still be wrong about the one nobody wrote an adapter for. The database is what they all agree on; .cppls.toml is where a project says what no database can. There is no CMake support, on purpose — CMake's job is to produce a compilation database, and -DCMAKE_EXPORT_COMPILE_COMMANDS=ON (or set(CMAKE_EXPORT_COMPILE_COMMANDS ON)) is how you ask it to.

When there is no database, three fallbacks apply in this order, each weaker than the last:

The two database formats

Both describe one command per translation unit — its source file and the flags it was compiled with — and both are read into the same structure; only the JSON layout differs.

compile_commands.json   [ { "file": "src/a.cpp", "directory": "…", "arguments": [...] | "command": "…" } ]
                        written by CMake (…_COMPILE_COMMANDS=ON), Ninja, Meson, Bazel, Bear, intercept-build, …
build_database.json     { "sets": [ { "translation-units": [ { "source": "src/a.cpp",
                          "work-directory": "…", "arguments": [...] | baseline+local, … } ] } ] }
                        written by CMake 3.31+ (CMAKE_EXPORT_BUILD_DATABASE=ON, Ninja generators), for C++ modules
  • Discovery. Either name in the project root, or up to three directories below it (build/, out/build/linux/, …). A directory that has both is read as compile_commands.json: it describes the build that actually ran, while a build database exists only when a build has module information to export. The build_database_<CONFIG>.json, build_database_<LANG>.json and build_database_<LANG>_<CONFIG>.json variants are found the same way.
  • What is read is the same from either: the per-file arguments — include paths, defines, standard, target. In a build database an entry's command may be split into baseline-arguments + local-arguments (the format's way of sharing flags inside a set); that is read as the concatenation, and a relative source is resolved against its work-directory, which is how CMake writes it.
  • What is not read (yet): the module metadata a build database carries — provides/requires, BMI paths, visible-sets. Modules are resolved from their interface sources instead, which needs no build output; see cpp-support.md.
  • Response files are followed either way: CMake writes a target's include paths into @CMakeFiles/<target>.dir/includes_CXX.rsp and names that file in the command, so a reader that did not expand them would see a project with no include paths at all.
  • [compile] database in .cppls.toml may name either format explicitly, which is how a project with several build directories picks the one to use.
1. .cppls.toml says                a person wrote the compilation down — it wins outright
2. compile_commands.json says      found beside the root, or up to three directories down (build/, out/build/linux/);
   or build_database.json says     the same search, when the build wrote the module-aware database instead
3. fuzzy include matching          an #include whose directory no search path could place, matched by the tail
                                   of its path against the files that are actually in the tree

Fallback 3 is on exactly when there is no database (the key below overrides it either way). It runs only after every exact candidate has failed, refuses a target with no directory in it (#include <vector> is spelled that way because the search path is supposed to find it), and matches the tail of the path component by component, backwards.

2. .cppls.toml

Read from the workspace root (or the file named by --config). Every key is optional; a section that is absent is a section at its defaults.

[workspace] — what to read at all

[workspace]
exclude = ["**/build/**", "third_party/**"]   # globs the analysis must not read
source_extensions = ["cuh", "cppm"]           # extensions *added* to the engine's own list
native_watch = false                          # no OS watcher of the server's own (see below)

exclude is the same list an editor uses to hide files. source_extensions is additive: the engine's own list is what a C/C++ project is made of, and writing this says "and also these" — a CUDA .cuh, a module .cppm. To read fewer files, use exclude.

native_watch turns off the watcher the server starts. It only starts at all for a client that does not watch for itself (no workspace.didChangeWatchedFiles dynamic registration — Neovim's configuration), and on a very large tree it is the part with the least to offer and the most to cost: a Linux kernel checkout produced 332 lost-event reports in fifty seconds from a tree a build was writing to, and each one used to re-open the whole workspace. That is bounded now — a lost-event report reconciles with the disk (one stat per project file, Session::reconcile) and a directory appearing in the tree does the same — but a checkout whose events are noise (a build directory inside the tree, a network mount) can turn the watcher off here. Absent means "watch".

The engine's own list: c cc cpp cxx c++ h hh hpp hxx h++ ipp inl tpp tcc cppm ixx, plus def mpp cuh for headers reached through an #include.

[compile] — how the project is built

[compile]
database = "build/compile_commands.json"   # where the database is, when discovery would not find it
                                           # (either format: `build/build_database.json` works here too)
compiler = "clang++"                       # a name on PATH or a path; "auto" (or absent) leaves it to discovery
standard = "c++20"                         # the project-wide language standard, as `-std=` spells it
args = ["-std=c++20", "-Iinclude"]         # the project's **whole** command line, instead of the database's
extra_args = ["-DFEATURE=1"]               # added on top of whichever flags won
remove_args = ["-Werror"]                  # dropped from whichever flags won, matched by whole spelling
fuzzy_includes = true                      # force the tail-matching fallback on (or false to forbid it)
  • args wins outright. When it is present the database's flags are ignored entirely: a project that writes args has said what its compilation is, and merging two sets of flags would make the result depend on their order in a way nobody can predict by reading the file. Use extra_args to add to whichever set won.
  • remove_args is applied before extra_args, which is what makes "drop the database's -std=c++17, add -std=c++20" work.
  • compiler decides whose headers are read. "auto" and absence are the same thing.
  • standard is also what decides whether the file is C or C++ — see §5.

[compile.include] — extra include directories for a subtree

[compile.include]
"src/legacy" = ["legacy/include"]
"*" = ["include"]

A directory and the include paths it needs. Longest matching prefix wins, and "*" applies everywhere — both can be true at once, and the nearer rule's directories are added first, because the resolver searches include paths in order. The names may be relative to the workspace root, and absolute paths are reported as a problem.

[[compile.target]] — one compilation, when the project is several

A real project is not one compilation: it is several, each with its own include directories and its own defines, and a single args list cannot describe them. Writing every target's -I into one list is not a simplification but a wrong answer.

[[compile.target]]
name     = "CodeFormatServer"
sources  = ["CodeFormatServer/**", "CodeFormatServer/*/src/**"]
includes = ["CodeFormatServer/include", "CodeFormatServer/src", "Util/include"]
defines  = ["URI_STATIC_BUILD", "WIN32_LEAN_AND_MEAN"]
standard = "c++20"

[[compile.target]]
name     = "LuaParser"
sources  = ["LuaParser/**"]
includes = ["LuaParser/include", "LuaParser/src"]
defines  = ["LUA_COMPAT_5_3"]
.cppls.toml CMake meaning
name the target's name what to call it in a message
sources add_executable/add_library sources which files it describes, as patterns
includes target_include_directories its include directories, relative to the root
defines target_compile_definitions its preprocessor definitions — "NAME" or "NAME=value", no -D
standard CXX_STANDARD its standard; the project's [compile].standard is used when absent
args, extra_args, remove_args — the same three keys as [compile], for these files
depends target_link_libraries the [[library]] names this target uses — see below

It is not a build system: there are no sources to compile and no commands to run. It describes compilations, which is all an analysis needs — plus depends, which is not a build dependency but a visibility one: it puts a library's include directories and defines on the search path of the files this target describes, and nowhere else.

Patterns. Matched against the file's path relative to the workspace root, component by component:

"CodeFormatServer/**"     the subtree, at any depth
"*/src/**"                any target's src tree
"Util/*.cpp"              direct children only

** stands for any number of components (including none), * for any run of characters within one component, and everything else is literal. A pattern must consume the whole path unless its last component is **. Matching is case-insensitive.

Which target describes a file. The most specific match wins — the one fixing the most literal components — and ties go to the one written first. Every target that describes the file contributes, nearest first. A file no target describes is compiled exactly as [compile] says. A target with no sources describes nothing.

[compile.ascend] — an Ascend C project

[compile.ascend]
enable = true                                   # read it as Ascend C without an `ccec` in the database
toolkit = "C:/Ascend/ascend-toolkit/latest"
include = ["src/kernels/include"]               # extra include directories for AICore units
args = ["-DASCENDC_CPU_DEBUG"]                 # extra flags, appended to whatever won

Ascend C is C++ plus Huawei's AICore kernel vocabulary: __aicore__, __global__, __gm__, __ubuf__, __cbuf__, __fbuf__, __ca__, __cb__, __cc__, and the AscendC::TPipe / GlobalTensor / LocalTensor names from kernel_operator.h. .cce and .asc are the Ascend compiler's kernel suffixes and join the project scan in this family. enable is the escape hatch for a project with no compile database; toolkit adds the installation's compiler/tikcpp/tikcfw and interface header directories, which is what makes #include "kernel_operator.h" resolve.

The family also turns on three AI Core restrictions — ascend-dynamic-allocation, ascend-exception and ascend-std-type — which are reported only inside a function carrying __aicore__/__global__.

A project belongs to exactly one family. [compile.cuda], [unreal] and [compile.ascend] are mutually exclusive: enabling two is a configuration error and none of them is applied until only one is on. The analysis holds the family as one enum (ProjectLanguage: Cpp, Cuda, Unreal, AscendC) rather than three independent flags, so the impossible combination cannot be represented internally.

[compile.cuda] — a CUDA project

[compile.cuda]
enable = true                                   # read it as CUDA even without an `nvcc` in the database
toolkit = "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.4"
host_compiler = "cl"                            # the host dialect: cl (MSVC) or g++/clang++ (GNU)
include = ["third_party/cutlass/include"]       # extra include directories for CUDA units
args = ["-arch=sm_80"]                          # extra flags, appended to whatever won

The analysis reads a project as CUDA when its toolchain is nvcc (__CUDACC__ in the macro table, or the compiler's name); enable is the escape hatch for a project that has .cu files but no compile database. toolkit is what makes #include <cuda_runtime.h> resolve — the toolkit installs its headers under <toolkit>/include (and, from CUDA 12.8, a CCCL include beside it), and nothing on the system path knows that. host_compiler decides the dialect, which is a different question from the CUDA flag: on Windows nvcc drives cl.exe, on Linux g++.

[index] — what is read and remembered

[index]
cache_dir = ".cppls"     # one component, relative to the root; where cooked readings are cached
max_files = 20000        # how many files the project scan may list
modules = true           # read the interface unit of a module a file imports (`import std;`)
cooked_budget_mb = 256   # memory for cooked readings; evicted readings are re-cooked on demand

modules = false is the switch for a project that would rather not pay for import std;: the read is a whole program (223 files, a 1.99 MB rendering) and costs minutes on a cold cache, where the cached result serves in 264 ms. A project that never imports a module pays nothing either way; one that does pays that cost after every cache invalidation, and while it runs the machine is busy. With the key off, std is simply not read.

cooked_budget_mb bounds the cooked readings — the compiler's view of a file, which is where a macro-declared type such as typedef kvec_t(Object) Array; exists. The default is 256 MB; an evicted reading is marked unread and re-cooked when a query needs it, so this key trades memory for the latency of that re-cook rather than changing any answer. 0 is rejected with a warning because it would leave every type query to a re-cook.

[[library]] — a dependency outside the workspace

[[library]]
name         = "widgets"
path         = "E:/SDK/widgets"      # absolute, or relative to the workspace root — either may be outside it
includes     = ["include"]           # searched for headers; on the search path of a target that depends on it
modules      = ["src"]               # searched for `.cppm`
defines      = ["WIDGETS_STATIC"]
headers_only = true                  # the default

[[compile.target]]
name    = "app"
sources = ["src/**"]
depends = ["widgets"]                # the inclusion of `includes`/`defines`, and a module by name

A library is read through what it exports: its headers and its .cppm files join the index, its .cpp files do not. That is the whole cost model — a dependency's implementation is not part of what the depending project compiles, and indexing it would multiply the index by every dependency's sources on every cold start. The price is stated where a reader will meet it: Go to Definition from a call into a library lands on its declaration or an inline body in a header, never in its .cpp.

depends is what makes #include "widgets/widget.h" resolve for a file of that target — and not for a file of a target that did not ask for it, which is the difference between a project with several targets and a project with one search path for all of them.

Read by the language server

[diagnostics]
on_change_ms = 300       # debounce for push diagnostics; pull requests remain client-driven
enable = []              # start from this list only (an empty list means "everything")
disable = []             # never report these — wins over `enable`, and over the defaults
                         # e.g. disable = ["missing-include", "unused"] — the rule names are the codes below

[hover]
enable = true            # whether hover answers at all

[inlay]                  # what the editor draws inside the code
enable = true            # the whole feature; `false` answers an empty list without querying
parameter_names = true   # `scale(count: 3, factor: 0.5)`
types = true             # `auto n: int`, structured bindings, deduced returns
template_arguments = true  # `make_pair<T = int, U = double>(…)`
enum_values = true       # `enum Color { Red = 0, Green = 5 }`
max_length = 0           # truncate a rendered label; 0 means no limit

[code_lens]
enable = true            # the `N references` a function gets, and its price: a reference query per function
                         # (measured at 5 ms a lens), paid when a file is opened or saved. `false` answers no lens
                         # at all, without running the query.

[completion]
max_items = 1000         # how many items one completion may carry; clamped to 1..20000
suggest_unincluded = true  # offer names from a nearby header, with the `#include` that makes them usable

[format]                 # how this project's files are formatted
formatter = "clang-format"   # the default: found on PATH. Or "cpp_formatter" for the built-in one, or a path

[format_strings]         # where this project's format strings are
enable = true            # the colouring, the popup and the completion — `false` is all three at once
std = true               # `{…}` — std::format / std::print / fmt::format, fmt::print
printf = true            # `%…` — printf, fprintf, snprintf, fmt::printf, fmt::sprintf
scanf = true             # `%…` with scansets — scanf, sscanf

[format_strings.functions]   # your own, keyed by the name the analysis RESOLVES them to
"mylib::logf" = "printf"                                 # printf's syntax, format string first
"mylib::log" = "std"
"mylib::trace" = { syntax = "printf", argument = 1 }     # `trace(level, fmt, …)`

[format] formatter names the program textDocument/formatting runs, and it is one of two things: the built-in formatter's name, or a program — a bare name looked up in PATH, or a path run as written.

formatter = "clang-format"        # the default — a bare name, looked up in PATH
formatter = "clang-format-18"     # a versioned install is the same kind of value
formatter = "D:/LLVM/bin/clang-format.exe"   # a path is run as written
formatter = "cpp_formatter"       # this repository's own formatter: a library call, no child process

cpp_formatter (also spelled cpp_format and cppfmt) is the built-in one — it claims clang-format's configuration surface and reads .clang-format, but it does not yet reflow lines the way clang-format does (crates/cpp_formatter/tests/suite/against_clang_format.rs measures the gap). Anything else is a program run the way clang-format documents for a filter: the text on stdin, the formatted text on stdout, --assume-filename for the style lookup, and --lines for a range format — and the answer of a range request is then clamped to the requested lines, because --lines alone was measured to reformat the line beside the range (clang-format 19.1.7), and a range that edits outside itself is the one thing this server promises not to do.

A program that is not on the machine is a warning, not a failure. The server says so once — at startup, and again only if the request finds it gone — and answers the request with the built-in formatter, so format-on-save keeps working. A project that does not want clang-format at all should say formatter = "cpp_formatter" and hear nothing.

Format strings are a different question and have their own section: [format_strings] decides which literals are format strings and what is inside them — the colouring, the hover and the completion inside a literal. It was called [format] until the formatter needed that name; the old keys are still read from [format] with a warning naming the move, and a [format_strings] section wins over them.

For clients without pull-diagnostics support, on_change_ms sets the debounce in milliseconds before publishing diagnostics for open files; the default is 300 ms. Pull-capable clients request diagnostics themselves, so this setting does not delay or schedule their pull requests. Where supported, inter-file changes also trigger a coalesced pull refresh.

A wrapper has a position: mylib::trace(level, fmt, …) puts the format string second, which { syntax = "printf", argument = 1 } says and a list of names cannot. A bare string means the common case — that syntax, the first argument. Either form is matched against the resolved qualified name, so using mylib::logf; works and a local logf that is something else is not read as the wrapper.

Why [completion] max_items is a payload bound, and why the list is still exact

std holds 12 867 declarations once import std; is read, and sending all of them is megabytes of JSON per keystroke. So a completion carries at most max_items — and says so: a cut list answers isIncomplete: true, the client then asks again on the next keystroke, and the prefix filter runs in the index, before anything is cloned. Measured on a project that imports the standard module:

`std::`          1000 items, truncated true,  53 ms
`std::s`          167 items, truncated false,  7 ms
`std::st`          55 items, truncated false,  6 ms
`std::str`         38 items, truncated false,  6 ms
`std::string`       6 items, truncated false,  6 ms

From the first typed character on, the answer is complete — the budget only decides how much the empty-prefix list carries. Raising it makes that first list longer (and slower); lowering it costs a few more round trips. The scope collection itself is capped at 4 096 names per namespace, so a max_items above that adds nothing for one scope.

missing-include and [completion] suggest_unincluded — the same rule, twice

missing-include reports a type a declaration uses when some file declares it and this file neither includes nor reaches that file — the finding a reader turns into an #include. It is a rule like any other: it can be turned off with [diagnostics] disable = ["missing-include"].

suggest_unincluded is the completion's half of the same idea: a name from a strongly related header this file does not include is offered in the list, and accepting it inserts the name and the #include in one accept. Only three kinds of file are candidates — one in the same directory, one under a [[library]] the project names, one under this file's include directories — so the list stays a suggestion and not a dump of the project.

Both exclude the standard library mechanically: a candidate must be under the workspace root or under a library's own path, so a toolchain header, a module unit read for import std; and a vendored tree are never suggested. Neither needs the standard library's index, which is the reason the rule can run at all.

The whole set, in one place

[workspace]  exclude = []  source_extensions = []

[compile]    database  compiler  standard  args  extra_args  remove_args  fuzzy_includes
             include  cuda  unreal
[[compile.target]]  name  sources  includes  defines  standard  args  extra_args  remove_args  depends

[[library]]  name  path  includes  modules  defines  headers_only

[index]      cache_dir  max_files  modules  cooked_budget_mb

[diagnostics] on_change_ms  enable  disable
[hover]      enable
[inlay]      enable  parameter_names  types  template_arguments  enum_values  max_length
[completion] max_items  suggest_unincluded
[format]     formatter
[format_strings] enable  std  printf  scanf      + [format_strings.functions]

[unreal]     enable  engine
[compile.cuda] enable toolkit host_compiler include args
[compile.ascend] enable toolkit include args
locale       "zh-CN"

3. When a key is wrong

Unknown keys fail their whole section, with a message, and the section keeps its defaults:

[compile] could not be read, so that section keeps its defaults: unknown field `standrad`

A rule name in [diagnostics] that this build does not have is logged the same way. Silently ignoring an unknown name is the failure mode the analysis is written against — a rule the user believes is on, that never runs.

[unreal] — Unreal Engine conventions

[unreal]
enable = true
engine = "C:/Program Files/Epic Games/UE_5.4"   # optional: the installation, or its Engine directory

A UE project writes C++ that is not readable as ordinary C++: UCLASS(), GENERATED_BODY() and UPROPERTY(…) come from the engine's headers and expand to nothing, and the engine's naming rules are conventions no ordinary C++ project follows. Either key turns the engine reading on; engine also makes the engine's headers resolve:

engine    every `Engine/Source/Runtime/<Module>/{Public,Classes}` becomes an include directory, so
          `#include "CoreMinimal.h"` and `#include "GameFramework/Actor.h"` resolve as in a build. A path that is not
          an installation is used as a plain include root, which is what a header-only simulation needs.
          Without the key, an `Engine/Source/Runtime` beside (or one level above) the workspace is used when it exists.
generated the project's own generated headers are found either way: every
          `Intermediate/Build/<Platform>/<Config>/Inc/<Module>/UHT` directory is on the include path, which is where
          UHT writes `*.generated.h` and where a built project takes `Super`, `ThisClass` and `StaticClass()` from.
          A project that has never been built has none of these, and the analysis falls back to the macro's own half.
macros    WITH_EDITOR, WITH_EDITORONLY_DATA, WITH_ENGINE, UE_BUILD_DEVELOPMENT, UE_SERVER, IS_PROGRAM and the host's
          PLATFORM_* — the engine's build configuration. A define the project states itself (compile database,
          `[compile] args`, `[compile] extra_args`) wins: a guess must not override a build that exists.
API       one `<MODULE>_API` per module the project's `*.uproject` names, defined as nothing. `MyGame` gives
          `MYGAME_API`: the build tool turns it into a visibility attribute, and to a reader it is empty.

The two rules that judge the conventions:

ue-naming          a UCLASS/USTRUCT/UENUM name without its engine prefix, a boolean member without `b`
ue-generate-body   a UCLASS/USTRUCT whose body writes no GENERATED_BODY()
ue-generated-header  a file with annotations and no `*.generated.h`, or one that is not the last include
ue-macro-scope     a UPROPERTY/UFUNCTION on a local or a file-scope declaration, which the build tool never reads
ue-specifier       a specifier the engine does not know, which the build tool silently ignores

Both judge style and engine semantics rather than the language, which is why they are in the list of C++-only rules and why they are off for a project that does not say it is Unreal: class Widget would otherwise be reported as a missing A/U/F.

Without an engine installed, a simulated tree of the same shape is enough — CoreMinimal.h with the reflection macros expanded to nothing and int32/TArray/FString spelled the way a module uses them, plus a *.uproject naming the module. C:\Users\zc\Desktop\UE_SOURCE is such a tree and C:\Users\zc\Desktop\UE-like a project over it: a clean module, and the same code with one violation of each rule.

4. What is not supported

Not supported Why
Build-system integration (CMake, Meson, …) the database is the interface; compile_commands.json is what they export
textDocument/onTypeFormatting the trigger is unreliable in practice; formatting on save and on demand covers it
clang-format's line breaking, in the built-in formatter cpp_formatter reads a common subset of .clang-format and computes spacing and indentation; the line breaks are the source's. [format] formatter = "clang-format" is the default for exactly that reason
C++26 #embed not implemented (C23's #embed neither). The C++26 language features — static reflection and contracts — are read, without a feature bit: no earlier standard gives their tokens a meaning, so they are parsed whatever -std= says. See cpp-support.md §2
C23 #embed not implemented
references / rename of ordinary names answering them means parsing every candidate file; the server refuses rather than editing half a name's uses (macros are answered exactly)
Module linking modules are parsed, indexed and resolved by name; nothing is linked or built
Dataflow analysis the checks are local to the file's facts plus the index
Macro-expanded source mapping hover and completion are answered from the macro environment, not from expanded text

5. C and C++ in one project

The language of a file is decided by its -std= first (-std=c17 → C, -std=c++20 → C++), then by its extension; .h belongs to whichever language includes it, and C++ is the wider list. A project that states no language is read as "not told", which is not the same as C.

Fourteen rules are C++ only, and are switched off for a file compiled as C — use-nullptr, use-auto, use-override, c-style-cast, access-invisible, concept-not-satisfied, module-note, implicit-bool-conversion, dangling-field, and the five Unreal rules ue-naming, ue-generate-body, ue-generated-header, ue-macro-scope and ue-specifier. Six of them name grammar C does not have (use-override, access-invisible, concept-not-satisfied, module-note, use-auto, use-nullptr); the other two name C++ style that C's own idiom contradicts — a C-style cast is the only cast C has, and an int in a condition is the language's idiom rather than a mistake. Measured before the gate existed: a C corpus configured with -std=c17 answered 14 c-style-cast findings telling the program to write static_cast.

The other twenty rules are about both languages. The gate is not a configuration key: a file compiled as C is read as C, and the eight rules are not opinions about it. [diagnostics].disable turns any rule off; nothing turns a C++-only rule on for C.