clang-tools 24.0.0git
ConfigProvider.cpp
Go to the documentation of this file.
1//===--- ConfigProvider.cpp - Loading of user configuration ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ConfigProvider.h"
10#include "Config.h"
11#include "ConfigFragment.h"
12#include "support/FileCache.h"
13#include "support/Logger.h"
14#include "support/Path.h"
16#include "support/Trace.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/StringMap.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/Support/Path.h"
22#include <chrono>
23#include <mutex>
24#include <optional>
25#include <string>
26
27namespace clang {
28namespace clangd {
29namespace config {
30
31// Threadsafe cache around reading a YAML config file from disk.
32class FileConfigCache : public FileCache {
33 mutable llvm::SmallVector<CompiledFragment, 1> CachedValue;
34 std::string Directory;
35
36public:
37 FileConfigCache(llvm::StringRef Path, llvm::StringRef Directory)
38 : FileCache(Path), Directory(Directory) {}
39
40 void get(const ThreadsafeFS &TFS, DiagnosticCallback DC,
41 std::chrono::steady_clock::time_point FreshTime, bool Trusted,
42 std::vector<CompiledFragment> &Out) const {
43 read(
44 TFS, FreshTime,
45 [&](std::optional<llvm::StringRef> Data) {
46 CachedValue.clear();
47 if (Data)
48 for (auto &Fragment : Fragment::parseYAML(*Data, path(), DC)) {
49 Fragment.Source.Directory = Directory;
50 Fragment.Source.Trusted = Trusted;
51 CachedValue.push_back(std::move(Fragment).compile(DC));
52 }
53 },
54 [&]() { llvm::copy(CachedValue, std::back_inserter(Out)); });
55 }
56};
57
58std::unique_ptr<Provider> Provider::fromYAMLFile(llvm::StringRef AbsPath,
59 llvm::StringRef Directory,
60 const ThreadsafeFS &FS,
61 bool Trusted) {
62 class AbsFileProvider : public Provider {
63 mutable FileConfigCache Cache; // threadsafe
64 const ThreadsafeFS &FS;
65 bool Trusted;
66
67 std::vector<CompiledFragment>
68 getFragments(const Params &P, DiagnosticCallback DC) const override {
69 std::vector<CompiledFragment> Result;
70 Cache.get(FS, DC, P.FreshTime, Trusted, Result);
71 return Result;
72 };
73
74 public:
75 AbsFileProvider(llvm::StringRef Path, llvm::StringRef Directory,
76 const ThreadsafeFS &FS, bool Trusted)
77 : Cache(Path, Directory), FS(FS), Trusted(Trusted) {
78 assert(llvm::sys::path::is_absolute(Path));
79 }
80 };
81
82 return std::make_unique<AbsFileProvider>(AbsPath, Directory, FS, Trusted);
83}
84
85std::unique_ptr<Provider>
87 const ThreadsafeFS &FS, bool Trusted) {
88 class RelFileProvider : public Provider {
89 std::string RelPath;
90 const ThreadsafeFS &FS;
91 bool Trusted;
92
93 mutable std::mutex Mu;
94 // Keys are the (posix-style) ancestor directory, not the config within it.
95 // We only insert into this map, so pointers to values are stable forever.
96 // Mutex guards the map itself, not the values (which are threadsafe).
97 mutable llvm::StringMap<FileConfigCache> Cache;
98
99 std::vector<CompiledFragment>
100 getFragments(const Params &P, DiagnosticCallback DC) const override {
101 namespace path = llvm::sys::path;
102
103 if (P.Path.empty())
104 return {};
105
106 // Compute absolute paths to all ancestors (substrings of P.Path).
107 llvm::SmallVector<llvm::StringRef, 8> Ancestors;
108 for (auto Ancestor = absoluteParent(P.Path); !Ancestor.empty();
109 Ancestor = absoluteParent(Ancestor)) {
110 Ancestors.emplace_back(Ancestor);
111 }
112 // Ensure corresponding cache entries exist in the map.
113 llvm::SmallVector<FileConfigCache *, 8> Caches;
114 {
115 std::lock_guard<std::mutex> Lock(Mu);
116 for (llvm::StringRef Ancestor : Ancestors) {
117 auto It = Cache.find(Ancestor);
118 // Assemble the actual config file path only once.
119 if (It == Cache.end()) {
120 llvm::SmallString<256> ConfigPath = Ancestor;
121 path::append(ConfigPath, RelPath);
122 // Use native slashes for reading the file, affects diagnostics.
123 llvm::sys::path::native(ConfigPath);
124 It = Cache.try_emplace(Ancestor, ConfigPath.str(), Ancestor).first;
125 }
126 Caches.push_back(&It->second);
127 }
128 }
129 // Finally query each individual file.
130 // This will take a (per-file) lock for each file that actually exists.
131 std::vector<CompiledFragment> Result;
132 for (FileConfigCache *Cache : llvm::reverse(Caches))
133 Cache->get(FS, DC, P.FreshTime, Trusted, Result);
134 return Result;
135 };
136
137 public:
138 RelFileProvider(llvm::StringRef RelPath, const ThreadsafeFS &FS,
139 bool Trusted)
140 : RelPath(RelPath), FS(FS), Trusted(Trusted) {
141 assert(llvm::sys::path::is_relative(RelPath));
142 }
143 };
144
145 return std::make_unique<RelFileProvider>(RelPath, FS, Trusted);
146}
147
148std::unique_ptr<Provider>
149Provider::combine(std::vector<std::unique_ptr<Provider>> Providers) {
150 class CombinedProvider : public Provider {
151 std::vector<std::unique_ptr<Provider>> Providers;
152
153 std::vector<CompiledFragment>
154 getFragments(const Params &P, DiagnosticCallback DC) const override {
155 std::vector<CompiledFragment> Result;
156 for (const auto &Provider : Providers) {
157 for (auto &Fragment : Provider->getFragments(P, DC))
158 Result.push_back(std::move(Fragment));
159 }
160 return Result;
161 }
162
163 public:
164 CombinedProvider(std::vector<std::unique_ptr<Provider>> Providers)
165 : Providers(std::move(Providers)) {}
166 };
167
168 return std::make_unique<CombinedProvider>(std::move(Providers));
169}
170
171std::vector<std::unique_ptr<Provider>>
173 std::vector<std::unique_ptr<Provider>> Providers;
174 Providers.push_back(fromAncestorRelativeYAMLFiles(".clangd", TFS));
175 llvm::SmallString<256> UserConfig;
176 if (llvm::sys::path::user_config_directory(UserConfig)) {
177 llvm::sys::path::append(UserConfig, "clangd", "config.yaml");
178 vlog("User config file is {0}", UserConfig);
179 Providers.push_back(
180 fromYAMLFile(UserConfig, /*Directory=*/"", TFS, /*Trusted=*/true));
181 } else {
182 elog("Couldn't determine user config file, not loading");
183 }
184 return Providers;
185}
186
187const char *const Provider::EnableConfigFlagDesc =
188 "Read user and project configuration from YAML files.\n"
189 "Project config is from a .clangd file in the project directory.\n"
190 "User config is from clangd/config.yaml in the following directories:\n"
191 "\tWindows: %USERPROFILE%\\AppData\\Local\n"
192 "\tMac OS: ~/Library/Preferences/\n"
193 "\tOthers: $XDG_CONFIG_HOME, usually ~/.config\n"
194 "Configuration is documented at https://clangd.llvm.org/config.html";
195
197 trace::Span Tracer("getConfig");
198 if (!P.Path.empty())
199 SPAN_ATTACH(Tracer, "path", P.Path);
200 Config C;
201 for (const auto &Fragment : getFragments(P, DC))
202 Fragment(P, C);
203 return C;
204}
205
206} // namespace config
207} // namespace clangd
208} // namespace clang
static cl::opt< std::string > Directory(cl::Positional, cl::Required, cl::desc("<Search Root Directory>"))
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition Trace.h:164
FileCache(PathRef Path)
Definition FileCache.cpp:25
PathRef path() const
Definition FileCache.h:63
void read(const ThreadsafeFS &TFS, std::chrono::steady_clock::time_point FreshTime, llvm::function_ref< void(std::optional< llvm::StringRef >)> Parse, llvm::function_ref< void()> Read) const
Definition FileCache.cpp:31
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
void get(const ThreadsafeFS &TFS, DiagnosticCallback DC, std::chrono::steady_clock::time_point FreshTime, bool Trusted, std::vector< CompiledFragment > &Out) const
FileConfigCache(llvm::StringRef Path, llvm::StringRef Directory)
A source of configuration fragments.
static const char *const EnableConfigFlagDesc
Help text for the –enable-config flag, shared by clangd tools that expose createDefaultProviders() on...
static std::vector< std::unique_ptr< Provider > > createDefaultProviders(const ThreadsafeFS &)
Returns providers for the configuration files that clangd tools read by default: project config (ance...
static std::unique_ptr< Provider > fromYAMLFile(llvm::StringRef AbsPath, llvm::StringRef Directory, const ThreadsafeFS &, bool Trusted=false)
Reads fragments from a single YAML file with a fixed path.
Config getConfig(const Params &, DiagnosticCallback) const
Build a config based on this provider.
static std::unique_ptr< Provider > fromAncestorRelativeYAMLFiles(llvm::StringRef RelPath, const ThreadsafeFS &, bool Trusted=false)
static std::unique_ptr< Provider > combine(std::vector< std::unique_ptr< Provider > >)
A provider that includes fragments from all the supplied providers.
Records an event whose duration is the lifetime of the Span object.
Definition Trace.h:143
llvm::function_ref< void(const llvm::SMDiagnostic &)> DiagnosticCallback
Used to report problems in parsing or interpreting a config.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
void vlog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:72
PathRef absoluteParent(PathRef Path)
Variant of parent_path that operates only on absolute paths.
Definition Path.cpp:22
std::string Path
A typedef to represent a file path.
Definition Path.h:26
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Settings that express user/project preferences and control clangd behavior.
Definition Config.h:45
bool Trusted
Whether this fragment is allowed to make critical security/privacy decisions.
std::string Directory
Absolute path to directory the fragment is associated with.
A chunk of configuration obtained from a config file, LSP, or elsewhere.
static std::vector< Fragment > parseYAML(llvm::StringRef YAML, llvm::StringRef BufferName, DiagnosticCallback)
Parses fragments from a YAML file (one from each — delimited document).
Describes the context used to evaluate configuration fragments.