clang-tools 24.0.0git
ConfigYAML.cpp
Go to the documentation of this file.
1//===--- ConfigYAML.cpp - Loading configuration fragments from YAML files -===//
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#include "ConfigFragment.h"
9#include "support/Logger.h"
10#include "llvm/ADT/FunctionExtras.h"
11#include "llvm/ADT/SmallSet.h"
12#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/Support/MemoryBuffer.h"
15#include "llvm/Support/SourceMgr.h"
16#include "llvm/Support/YAMLParser.h"
17#include <optional>
18#include <string>
19
20namespace clang {
21namespace clangd {
22namespace config {
23namespace {
24using llvm::yaml::BlockScalarNode;
25using llvm::yaml::MappingNode;
26using llvm::yaml::Node;
27using llvm::yaml::ScalarNode;
28using llvm::yaml::SequenceNode;
29
30std::optional<llvm::StringRef>
31bestGuess(llvm::StringRef Search,
32 llvm::ArrayRef<llvm::StringRef> AllowedValues) {
33 unsigned MaxEdit = (Search.size() + 1) / 3;
34 if (!MaxEdit)
35 return std::nullopt;
36 std::optional<llvm::StringRef> Result;
37 for (const auto &AllowedValue : AllowedValues) {
38 unsigned EditDistance = Search.edit_distance(AllowedValue, true, MaxEdit);
39 // We can't do better than an edit distance of 1, so just return this and
40 // save computing other values.
41 if (EditDistance == 1U)
42 return AllowedValue;
43 if (EditDistance == MaxEdit && !Result) {
44 Result = AllowedValue;
45 } else if (EditDistance < MaxEdit) {
46 Result = AllowedValue;
47 MaxEdit = EditDistance;
48 }
49 }
50 return Result;
51}
52
53class Parser {
54 llvm::SourceMgr &SM;
55 bool HadError = false;
56
57public:
58 Parser(llvm::SourceMgr &SM) : SM(SM) {}
59
60 // Tries to parse N into F, returning false if it failed and we couldn't
61 // meaningfully recover (YAML syntax error, or hard semantic error).
62 bool parse(Fragment &F, Node &N) {
63 DictParser Dict("Config", this);
64 Dict.handle("If", [&](Node &N) { parse(F.If, N); });
65 Dict.handle("CompileFlags", [&](Node &N) { parse(F.CompileFlags, N); });
66 Dict.handle("Index", [&](Node &N) { parse(F.Index, N); });
67 Dict.handle("Style", [&](Node &N) { parse(F.Style, N); });
68 Dict.handle("Diagnostics", [&](Node &N) { parse(F.Diagnostics, N); });
69 Dict.handle("Completion", [&](Node &N) { parse(F.Completion, N); });
70 Dict.handle("Hover", [&](Node &N) { parse(F.Hover, N); });
71 Dict.handle("InlayHints", [&](Node &N) { parse(F.InlayHints, N); });
72 Dict.handle("SemanticTokens", [&](Node &N) { parse(F.SemanticTokens, N); });
73 Dict.handle("Documentation", [&](Node &N) { parse(F.Documentation, N); });
74 Dict.parse(N);
75 return !(N.failed() || HadError);
76 }
77
78private:
79 void parse(Fragment::IfBlock &F, Node &N) {
80 DictParser Dict("If", this);
81 Dict.unrecognized([&](Located<std::string>, Node &) {
82 F.HasUnrecognizedCondition = true;
83 return true; // Emit a warning for the unrecognized key.
84 });
85 Dict.handle("PathMatch", [&](Node &N) {
86 if (auto Values = scalarValues(N))
87 F.PathMatch = std::move(*Values);
88 });
89 Dict.handle("PathExclude", [&](Node &N) {
90 if (auto Values = scalarValues(N))
91 F.PathExclude = std::move(*Values);
92 });
93 Dict.parse(N);
94 }
95
96 void parse(Fragment::CompileFlagsBlock &F, Node &N) {
97 DictParser Dict("CompileFlags", this);
98 Dict.handle("Compiler", [&](Node &N) {
99 if (auto Value = scalarValue(N, "Compiler"))
100 F.Compiler = std::move(*Value);
101 });
102 Dict.handle("Add", [&](Node &N) {
103 if (auto Values = scalarValues(N))
104 F.Add = std::move(*Values);
105 });
106 Dict.handle("Remove", [&](Node &N) {
107 if (auto Values = scalarValues(N))
108 F.Remove = std::move(*Values);
109 });
110 Dict.handle("BuiltinHeaders", [&](Node &N) {
111 if (auto BuiltinHeaders = scalarValue(N, "BuiltinHeaders"))
112 F.BuiltinHeaders = *BuiltinHeaders;
113 });
114 Dict.handle("CompilationDatabase", [&](Node &N) {
115 F.CompilationDatabase = scalarValue(N, "CompilationDatabase");
116 });
117 Dict.parse(N);
118 }
119
120 void parse(Fragment::StyleBlock &F, Node &N) {
121 DictParser Dict("Style", this);
122 Dict.handle("FullyQualifiedNamespaces", [&](Node &N) {
123 if (auto Values = scalarValues(N))
124 F.FullyQualifiedNamespaces = std::move(*Values);
125 });
126 Dict.handle("QuotedHeaders", [&](Node &N) {
127 if (auto Values = scalarValues(N))
128 F.QuotedHeaders = std::move(*Values);
129 });
130 Dict.handle("AngledHeaders", [&](Node &N) {
131 if (auto Values = scalarValues(N))
132 F.AngledHeaders = std::move(*Values);
133 });
134 Dict.parse(N);
135 }
136
137 void parse(Fragment::DiagnosticsBlock &F, Node &N) {
138 DictParser Dict("Diagnostics", this);
139 Dict.handle("Suppress", [&](Node &N) {
140 if (auto Values = scalarValues(N))
141 F.Suppress = std::move(*Values);
142 });
143 Dict.handle("UnusedIncludes", [&](Node &N) {
144 F.UnusedIncludes = scalarValue(N, "UnusedIncludes");
145 });
146 Dict.handle("MissingIncludes", [&](Node &N) {
147 F.MissingIncludes = scalarValue(N, "MissingIncludes");
148 });
149 Dict.handle("Includes", [&](Node &N) { parse(F.Includes, N); });
150 Dict.handle("ClangTidy", [&](Node &N) { parse(F.ClangTidy, N); });
151 Dict.parse(N);
152 }
153
154 void parse(Fragment::DiagnosticsBlock::ClangTidyBlock &F, Node &N) {
155 DictParser Dict("ClangTidy", this);
156 Dict.handle("Add", [&](Node &N) {
157 if (auto Values = scalarValues(N))
158 F.Add = std::move(*Values);
159 });
160 Dict.handle("Remove", [&](Node &N) {
161 if (auto Values = scalarValues(N))
162 F.Remove = std::move(*Values);
163 });
164 Dict.handle("CheckOptions", [&](Node &N) {
165 DictParser CheckOptDict("CheckOptions", this);
166 CheckOptDict.unrecognized([&](Located<std::string> &&Key, Node &Val) {
167 if (auto Value = scalarValue(Val, *Key))
168 F.CheckOptions.emplace_back(std::move(Key), std::move(*Value));
169 return false; // Don't emit a warning
170 });
171 CheckOptDict.parse(N);
172 });
173 Dict.handle("FastCheckFilter", [&](Node &N) {
174 if (auto FastCheckFilter = scalarValue(N, "FastCheckFilter"))
175 F.FastCheckFilter = *FastCheckFilter;
176 });
177 Dict.parse(N);
178 }
179
180 void parse(Fragment::DiagnosticsBlock::IncludesBlock &F, Node &N) {
181 DictParser Dict("Includes", this);
182 Dict.handle("IgnoreHeader", [&](Node &N) {
183 if (auto Values = scalarValues(N))
184 F.IgnoreHeader = std::move(*Values);
185 });
186 Dict.handle("AnalyzeAngledIncludes", [&](Node &N) {
187 if (auto Value = boolValue(N, "AnalyzeAngledIncludes"))
188 F.AnalyzeAngledIncludes = *Value;
189 });
190 Dict.parse(N);
191 }
192
193 void parse(Fragment::IndexBlock &F, Node &N) {
194 DictParser Dict("Index", this);
195 Dict.handle("Background",
196 [&](Node &N) { F.Background = scalarValue(N, "Background"); });
197 Dict.handle("External", [&](Node &N) {
198 Fragment::IndexBlock::ExternalBlock External;
199 // External block can either be a mapping or a scalar value. Dispatch
200 // accordingly.
201 if (N.getType() == Node::NK_Mapping) {
202 parse(External, N);
203 } else if (N.getType() == Node::NK_Scalar ||
204 N.getType() == Node::NK_BlockScalar) {
205 parse(External, *scalarValue(N, "External"));
206 } else {
207 error("External must be either a scalar or a mapping.", N);
208 return;
209 }
210 F.External.emplace(std::move(External));
211 F.External->Range = N.getSourceRange();
212 });
213 Dict.handle("StandardLibrary", [&](Node &N) {
214 if (auto StandardLibrary = boolValue(N, "StandardLibrary"))
215 F.StandardLibrary = *StandardLibrary;
216 });
217 Dict.parse(N);
218 }
219
220 void parse(Fragment::IndexBlock::ExternalBlock &F,
221 Located<std::string> ExternalVal) {
222 if (!llvm::StringRef(*ExternalVal).equals_insensitive("none")) {
223 error("Only scalar value supported for External is 'None'",
224 ExternalVal.Range);
225 return;
226 }
227 F.IsNone = true;
228 F.IsNone.Range = ExternalVal.Range;
229 }
230
231 void parse(Fragment::IndexBlock::ExternalBlock &F, Node &N) {
232 DictParser Dict("External", this);
233 Dict.handle("File", [&](Node &N) { F.File = scalarValue(N, "File"); });
234 Dict.handle("Server",
235 [&](Node &N) { F.Server = scalarValue(N, "Server"); });
236 Dict.handle("MountPoint",
237 [&](Node &N) { F.MountPoint = scalarValue(N, "MountPoint"); });
238 Dict.parse(N);
239 }
240
241 void parse(Fragment::CompletionBlock &F, Node &N) {
242 DictParser Dict("Completion", this);
243 Dict.handle("AllScopes", [&](Node &N) {
244 if (auto AllScopes = boolValue(N, "AllScopes"))
245 F.AllScopes = *AllScopes;
246 });
247 Dict.handle("ArgumentLists", [&](Node &N) {
248 if (auto ArgumentLists = scalarValue(N, "ArgumentLists"))
249 F.ArgumentLists = *ArgumentLists;
250 });
251 Dict.handle("HeaderInsertion", [&](Node &N) {
252 if (auto HeaderInsertion = scalarValue(N, "HeaderInsertion"))
253 F.HeaderInsertion = *HeaderInsertion;
254 });
255 Dict.handle("CodePatterns", [&](Node &N) {
256 if (auto CodePatterns = scalarValue(N, "CodePatterns"))
257 F.CodePatterns = *CodePatterns;
258 });
259 Dict.handle("MacroFilter", [&](Node &N) {
260 if (auto MacroFilter = scalarValue(N, "MacroFilter"))
261 F.MacroFilter = *MacroFilter;
262 });
263 Dict.parse(N);
264 }
265
266 void parse(Fragment::HoverBlock &F, Node &N) {
267 DictParser Dict("Hover", this);
268 Dict.handle("ShowAKA", [&](Node &N) {
269 if (auto ShowAKA = boolValue(N, "ShowAKA"))
270 F.ShowAKA = *ShowAKA;
271 });
272 Dict.handle("MacroContentsLimit", [&](Node &N) {
273 if (auto MacroContentsLimit = uint32Value(N, "MacroContentsLimit"))
274 F.MacroContentsLimit = *MacroContentsLimit;
275 });
276 Dict.parse(N);
277 }
278
279 void parse(Fragment::InlayHintsBlock &F, Node &N) {
280 DictParser Dict("InlayHints", this);
281 Dict.handle("Enabled", [&](Node &N) {
282 if (auto Value = boolValue(N, "Enabled"))
283 F.Enabled = *Value;
284 });
285 Dict.handle("ParameterNames", [&](Node &N) {
286 if (auto Value = boolValue(N, "ParameterNames"))
287 F.ParameterNames = *Value;
288 });
289 Dict.handle("DeducedTypes", [&](Node &N) {
290 if (auto Value = boolValue(N, "DeducedTypes"))
291 F.DeducedTypes = *Value;
292 });
293 Dict.handle("Designators", [&](Node &N) {
294 if (auto Value = boolValue(N, "Designators"))
295 F.Designators = *Value;
296 });
297 Dict.handle("BlockEnd", [&](Node &N) {
298 if (auto Value = boolValue(N, "BlockEnd"))
299 F.BlockEnd = *Value;
300 });
301 Dict.handle("DefaultArguments", [&](Node &N) {
302 if (auto Value = boolValue(N, "DefaultArguments"))
303 F.DefaultArguments = *Value;
304 });
305 Dict.handle("TypeNameLimit", [&](Node &N) {
306 if (auto Value = uint32Value(N, "TypeNameLimit"))
307 F.TypeNameLimit = *Value;
308 });
309 Dict.parse(N);
310 }
311
312 void parse(Fragment::SemanticTokensBlock &F, Node &N) {
313 DictParser Dict("SemanticTokens", this);
314 Dict.handle("DisabledKinds", [&](Node &N) {
315 if (auto Values = scalarValues(N))
316 F.DisabledKinds = std::move(*Values);
317 });
318 Dict.handle("DisabledModifiers", [&](Node &N) {
319 if (auto Values = scalarValues(N))
320 F.DisabledModifiers = std::move(*Values);
321 });
322 Dict.parse(N);
323 }
324
325 void parse(Fragment::DocumentationBlock &F, Node &N) {
326 DictParser Dict("Documentation", this);
327 Dict.handle("CommentFormat", [&](Node &N) {
328 if (auto Value = scalarValue(N, "CommentFormat"))
329 F.CommentFormat = *Value;
330 });
331 Dict.parse(N);
332 }
333
334 // Helper for parsing mapping nodes (dictionaries).
335 // We don't use YamlIO as we want to control over unknown keys.
336 class DictParser {
337 llvm::StringRef Description;
338 std::vector<
339 std::pair<llvm::StringRef, llvm::unique_function<void(Node &) const>>>
340 Keys;
341 llvm::unique_function<bool(Located<std::string>, Node &) const>
342 UnknownHandler;
343 Parser *Outer;
344
345 public:
346 DictParser(llvm::StringRef Description, Parser *Outer)
347 : Description(Description), Outer(Outer) {}
348
349 // Parse is called when Key is encountered, and passed the associated value.
350 // It should emit diagnostics if the value is invalid (e.g. wrong type).
351 // If Key is seen twice, Parse runs only once and an error is reported.
352 void handle(llvm::StringLiteral Key,
353 llvm::unique_function<void(Node &) const> Parse) {
354 for (const auto &Entry : Keys) {
355 (void)Entry;
356 assert(Entry.first != Key && "duplicate key handler");
357 }
358 Keys.emplace_back(Key, std::move(Parse));
359 }
360
361 // Handler is called when a Key is not matched by any handle().
362 // If this is unset or the Handler returns true, a warning is emitted for
363 // the unknown key.
364 void
365 unrecognized(llvm::unique_function<bool(Located<std::string>, Node &) const>
366 Handler) {
367 UnknownHandler = std::move(Handler);
368 }
369
370 // Process a mapping node and call handlers for each key/value pair.
371 void parse(Node &N) const {
372 if (N.getType() != Node::NK_Mapping) {
373 Outer->error(Description + " should be a dictionary", N);
374 return;
375 }
376 llvm::SmallSet<std::string, 8> Seen;
377 llvm::SmallVector<Located<std::string>, 0> UnknownKeys;
378 // We *must* consume all items, even on error, or the parser will assert.
379 for (auto &KV : llvm::cast<MappingNode>(N)) {
380 auto *K = KV.getKey();
381 if (!K) // YAMLParser emitted an error.
382 continue;
383 auto Key = Outer->scalarValue(*K, "Dictionary key");
384 if (!Key)
385 continue;
386 if (!Seen.insert(**Key).second) {
387 Outer->warning("Duplicate key " + **Key + " is ignored", *K);
388 if (auto *Value = KV.getValue())
389 Value->skip();
390 continue;
391 }
392 auto *Value = KV.getValue();
393 if (!Value) // YAMLParser emitted an error.
394 continue;
395 bool Matched = false;
396 for (const auto &Handler : Keys) {
397 if (Handler.first == **Key) {
398 Matched = true;
399 Handler.second(*Value);
400 break;
401 }
402 }
403 if (!Matched) {
404 bool Warn = !UnknownHandler;
405 if (UnknownHandler)
406 Warn = UnknownHandler(
407 Located<std::string>(**Key, K->getSourceRange()), *Value);
408 if (Warn)
409 UnknownKeys.push_back(std::move(*Key));
410 }
411 }
412 if (!UnknownKeys.empty())
413 warnUnknownKeys(UnknownKeys, Seen);
414 }
415
416 private:
417 void warnUnknownKeys(llvm::ArrayRef<Located<std::string>> UnknownKeys,
418 const llvm::SmallSet<std::string, 8> &SeenKeys) const {
419 llvm::SmallVector<llvm::StringRef> UnseenKeys;
420 for (const auto &KeyAndHandler : Keys)
421 if (!SeenKeys.count(KeyAndHandler.first.str()))
422 UnseenKeys.push_back(KeyAndHandler.first);
423
424 for (const Located<std::string> &UnknownKey : UnknownKeys)
425 if (auto BestGuess = bestGuess(*UnknownKey, UnseenKeys))
426 Outer->warning("Unknown " + Description + " key '" + *UnknownKey +
427 "'; did you mean '" + *BestGuess + "'?",
428 UnknownKey.Range);
429 else
430 Outer->warning("Unknown " + Description + " key '" + *UnknownKey +
431 "'",
432 UnknownKey.Range);
433 }
434 };
435
436 // Try to parse a single scalar value from the node, warn on failure.
437 std::optional<Located<std::string>> scalarValue(Node &N,
438 llvm::StringRef Desc) {
439 llvm::SmallString<256> Buf;
440 if (auto *S = llvm::dyn_cast<ScalarNode>(&N))
441 return Located<std::string>(S->getValue(Buf).str(), N.getSourceRange());
442 if (auto *BS = llvm::dyn_cast<BlockScalarNode>(&N))
443 return Located<std::string>(BS->getValue().str(), N.getSourceRange());
444 warning(Desc + " should be scalar", N);
445 return std::nullopt;
446 }
447
448 std::optional<Located<bool>> boolValue(Node &N, llvm::StringRef Desc) {
449 if (auto Scalar = scalarValue(N, Desc)) {
450 if (auto Bool = llvm::yaml::parseBool(**Scalar))
451 return Located<bool>(*Bool, Scalar->Range);
452 warning(Desc + " should be a boolean", N);
453 }
454 return std::nullopt;
455 }
456
457 std::optional<Located<uint32_t>> uint32Value(Node &N, llvm::StringRef Desc) {
458 if (auto Scalar = scalarValue(N, Desc)) {
459 unsigned long long Num;
460 if (!llvm::getAsUnsignedInteger(**Scalar, 0, Num)) {
461 return Located<uint32_t>(Num, Scalar->Range);
462 }
463 }
464 warning(Desc + " invalid number", N);
465 return std::nullopt;
466 }
467
468 // Try to parse a list of single scalar values, or just a single value.
469 std::optional<std::vector<Located<std::string>>> scalarValues(Node &N) {
470 std::vector<Located<std::string>> Result;
471 if (auto *S = llvm::dyn_cast<ScalarNode>(&N)) {
472 llvm::SmallString<256> Buf;
473 Result.emplace_back(S->getValue(Buf).str(), N.getSourceRange());
474 } else if (auto *S = llvm::dyn_cast<BlockScalarNode>(&N)) {
475 Result.emplace_back(S->getValue().str(), N.getSourceRange());
476 } else if (auto *S = llvm::dyn_cast<SequenceNode>(&N)) {
477 // We *must* consume all items, even on error, or the parser will assert.
478 for (auto &Child : *S) {
479 if (auto Value = scalarValue(Child, "List item"))
480 Result.push_back(std::move(*Value));
481 }
482 } else {
483 warning("Expected scalar or list of scalars", N);
484 return std::nullopt;
485 }
486 return Result;
487 }
488
489 // Report a "hard" error, reflecting a config file that can never be valid.
490 void error(const llvm::Twine &Msg, llvm::SMRange Range) {
491 HadError = true;
492 SM.PrintMessage(Range.Start, llvm::SourceMgr::DK_Error, Msg, Range);
493 }
494 void error(const llvm::Twine &Msg, const Node &N) {
495 return error(Msg, N.getSourceRange());
496 }
497
498 // Report a "soft" error that could be caused by e.g. version skew.
499 void warning(const llvm::Twine &Msg, llvm::SMRange Range) {
500 SM.PrintMessage(Range.Start, llvm::SourceMgr::DK_Warning, Msg, Range);
501 }
502 void warning(const llvm::Twine &Msg, const Node &N) {
503 return warning(Msg, N.getSourceRange());
504 }
505};
506
507} // namespace
508
509std::vector<Fragment> Fragment::parseYAML(llvm::StringRef YAML,
510 llvm::StringRef BufferName,
511 DiagnosticCallback Diags) {
512 // The YAML document may contain multiple conditional fragments.
513 // The SourceManager is shared for all of them.
514 log("Loading config file at {0}", BufferName);
515 auto SM = std::make_shared<llvm::SourceMgr>();
516 auto Buf = llvm::MemoryBuffer::getMemBufferCopy(YAML, BufferName);
517 // Adapt DiagnosticCallback to function-pointer interface.
518 // Callback receives both errors we emit and those from the YAML parser.
519 SM->setDiagHandler(
520 [](const llvm::SMDiagnostic &Diag, void *Ctx) {
521 (*reinterpret_cast<DiagnosticCallback *>(Ctx))(Diag);
522 },
523 &Diags);
524 std::vector<Fragment> Result;
525 for (auto &Doc : llvm::yaml::Stream(*Buf, *SM)) {
526 if (Node *N = Doc.getRoot()) {
529 Fragment.Source.Location = N->getSourceRange().Start;
530 SM->PrintMessage(Fragment.Source.Location, llvm::SourceMgr::DK_Note,
531 "Parsing config fragment");
532 if (Parser(*SM).parse(Fragment, *N))
533 Result.push_back(std::move(Fragment));
534 }
535 }
536 SM->PrintMessage(SM->FindLocForLineAndColumn(SM->getMainFileID(), 0, 0),
537 llvm::SourceMgr::DK_Note,
538 "Parsed " + llvm::Twine(Result.size()) +
539 " fragments from file");
540 // Hack: stash the buffer in the SourceMgr to keep it alive.
541 // SM has two entries: "main" non-owning buffer, and ignored owning buffer.
542 SM->AddNewSourceBuffer(std::move(Buf), llvm::SMLoc());
543 return Result;
544}
545
546} // namespace config
547} // namespace clangd
548} // namespace clang
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
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition Logger.h:79
void log(const char *Fmt, Ts &&... Vals)
Definition Logger.h:67
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
A top-level diagnostic that may have Notes and Fixes.
Definition Diagnostics.h:98
std::shared_ptr< llvm::SourceMgr > Manager
Retains a buffer of the original source this fragment was parsed from.
llvm::SMLoc Location
The start of the original source for this fragment.
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).