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.handle("ExperimentalCustomChecks", [&](Node &N) {
178 if (auto Value = boolValue(N, "ExperimentalCustomChecks"))
179 F.ExperimentalCustomChecks = *Value;
180 });
181 Dict.parse(N);
182 }
183
184 void parse(Fragment::DiagnosticsBlock::IncludesBlock &F, Node &N) {
185 DictParser Dict("Includes", this);
186 Dict.handle("IgnoreHeader", [&](Node &N) {
187 if (auto Values = scalarValues(N))
188 F.IgnoreHeader = std::move(*Values);
189 });
190 Dict.handle("AnalyzeAngledIncludes", [&](Node &N) {
191 if (auto Value = boolValue(N, "AnalyzeAngledIncludes"))
192 F.AnalyzeAngledIncludes = *Value;
193 });
194 Dict.parse(N);
195 }
196
197 void parse(Fragment::IndexBlock &F, Node &N) {
198 DictParser Dict("Index", this);
199 Dict.handle("Background",
200 [&](Node &N) { F.Background = scalarValue(N, "Background"); });
201 Dict.handle("External", [&](Node &N) {
202 Fragment::IndexBlock::ExternalBlock External;
203 // External block can either be a mapping or a scalar value. Dispatch
204 // accordingly.
205 if (N.getType() == Node::NK_Mapping) {
206 parse(External, N);
207 } else if (N.getType() == Node::NK_Scalar ||
208 N.getType() == Node::NK_BlockScalar) {
209 parse(External, *scalarValue(N, "External"));
210 } else {
211 error("External must be either a scalar or a mapping.", N);
212 return;
213 }
214 F.External.emplace(std::move(External));
215 F.External->Range = N.getSourceRange();
216 });
217 Dict.handle("StandardLibrary", [&](Node &N) {
218 if (auto StandardLibrary = boolValue(N, "StandardLibrary"))
219 F.StandardLibrary = *StandardLibrary;
220 });
221 Dict.parse(N);
222 }
223
224 void parse(Fragment::IndexBlock::ExternalBlock &F,
225 Located<std::string> ExternalVal) {
226 if (!llvm::StringRef(*ExternalVal).equals_insensitive("none")) {
227 error("Only scalar value supported for External is 'None'",
228 ExternalVal.Range);
229 return;
230 }
231 F.IsNone = true;
232 F.IsNone.Range = ExternalVal.Range;
233 }
234
235 void parse(Fragment::IndexBlock::ExternalBlock &F, Node &N) {
236 DictParser Dict("External", this);
237 Dict.handle("File", [&](Node &N) { F.File = scalarValue(N, "File"); });
238 Dict.handle("Server",
239 [&](Node &N) { F.Server = scalarValue(N, "Server"); });
240 Dict.handle("MountPoint",
241 [&](Node &N) { F.MountPoint = scalarValue(N, "MountPoint"); });
242 Dict.parse(N);
243 }
244
245 void parse(Fragment::CompletionBlock &F, Node &N) {
246 DictParser Dict("Completion", this);
247 Dict.handle("AllScopes", [&](Node &N) {
248 if (auto AllScopes = boolValue(N, "AllScopes"))
249 F.AllScopes = *AllScopes;
250 });
251 Dict.handle("ArgumentLists", [&](Node &N) {
252 if (auto ArgumentLists = scalarValue(N, "ArgumentLists"))
253 F.ArgumentLists = *ArgumentLists;
254 });
255 Dict.handle("HeaderInsertion", [&](Node &N) {
256 if (auto HeaderInsertion = scalarValue(N, "HeaderInsertion"))
257 F.HeaderInsertion = *HeaderInsertion;
258 });
259 Dict.handle("CodePatterns", [&](Node &N) {
260 if (auto CodePatterns = scalarValue(N, "CodePatterns"))
261 F.CodePatterns = *CodePatterns;
262 });
263 Dict.handle("MacroFilter", [&](Node &N) {
264 if (auto MacroFilter = scalarValue(N, "MacroFilter"))
265 F.MacroFilter = *MacroFilter;
266 });
267 Dict.parse(N);
268 }
269
270 void parse(Fragment::HoverBlock &F, Node &N) {
271 DictParser Dict("Hover", this);
272 Dict.handle("ShowAKA", [&](Node &N) {
273 if (auto ShowAKA = boolValue(N, "ShowAKA"))
274 F.ShowAKA = *ShowAKA;
275 });
276 Dict.handle("MacroContentsLimit", [&](Node &N) {
277 if (auto MacroContentsLimit = uint32Value(N, "MacroContentsLimit"))
278 F.MacroContentsLimit = *MacroContentsLimit;
279 });
280 Dict.parse(N);
281 }
282
283 void parse(Fragment::InlayHintsBlock &F, Node &N) {
284 DictParser Dict("InlayHints", this);
285 Dict.handle("Enabled", [&](Node &N) {
286 if (auto Value = boolValue(N, "Enabled"))
287 F.Enabled = *Value;
288 });
289 Dict.handle("ParameterNames", [&](Node &N) {
290 if (auto Value = boolValue(N, "ParameterNames"))
291 F.ParameterNames = *Value;
292 });
293 Dict.handle("DeducedTypes", [&](Node &N) {
294 if (auto Value = boolValue(N, "DeducedTypes"))
295 F.DeducedTypes = *Value;
296 });
297 Dict.handle("Designators", [&](Node &N) {
298 if (auto Value = boolValue(N, "Designators"))
299 F.Designators = *Value;
300 });
301 Dict.handle("BlockEnd", [&](Node &N) {
302 if (auto Value = boolValue(N, "BlockEnd"))
303 F.BlockEnd = *Value;
304 });
305 Dict.handle("DefaultArguments", [&](Node &N) {
306 if (auto Value = boolValue(N, "DefaultArguments"))
307 F.DefaultArguments = *Value;
308 });
309 Dict.handle("TypeNameLimit", [&](Node &N) {
310 if (auto Value = uint32Value(N, "TypeNameLimit"))
311 F.TypeNameLimit = *Value;
312 });
313 Dict.parse(N);
314 }
315
316 void parse(Fragment::SemanticTokensBlock &F, Node &N) {
317 DictParser Dict("SemanticTokens", this);
318 Dict.handle("DisabledKinds", [&](Node &N) {
319 if (auto Values = scalarValues(N))
320 F.DisabledKinds = std::move(*Values);
321 });
322 Dict.handle("DisabledModifiers", [&](Node &N) {
323 if (auto Values = scalarValues(N))
324 F.DisabledModifiers = std::move(*Values);
325 });
326 Dict.parse(N);
327 }
328
329 void parse(Fragment::DocumentationBlock &F, Node &N) {
330 DictParser Dict("Documentation", this);
331 Dict.handle("CommentFormat", [&](Node &N) {
332 if (auto Value = scalarValue(N, "CommentFormat"))
333 F.CommentFormat = *Value;
334 });
335 Dict.parse(N);
336 }
337
338 // Helper for parsing mapping nodes (dictionaries).
339 // We don't use YamlIO as we want to control over unknown keys.
340 class DictParser {
341 llvm::StringRef Description;
342 std::vector<
343 std::pair<llvm::StringRef, llvm::unique_function<void(Node &) const>>>
344 Keys;
345 llvm::unique_function<bool(Located<std::string>, Node &) const>
346 UnknownHandler;
347 Parser *Outer;
348
349 public:
350 DictParser(llvm::StringRef Description, Parser *Outer)
351 : Description(Description), Outer(Outer) {}
352
353 // Parse is called when Key is encountered, and passed the associated value.
354 // It should emit diagnostics if the value is invalid (e.g. wrong type).
355 // If Key is seen twice, Parse runs only once and an error is reported.
356 void handle(llvm::StringLiteral Key,
357 llvm::unique_function<void(Node &) const> Parse) {
358 for (const auto &Entry : Keys) {
359 (void)Entry;
360 assert(Entry.first != Key && "duplicate key handler");
361 }
362 Keys.emplace_back(Key, std::move(Parse));
363 }
364
365 // Handler is called when a Key is not matched by any handle().
366 // If this is unset or the Handler returns true, a warning is emitted for
367 // the unknown key.
368 void
369 unrecognized(llvm::unique_function<bool(Located<std::string>, Node &) const>
370 Handler) {
371 UnknownHandler = std::move(Handler);
372 }
373
374 // Process a mapping node and call handlers for each key/value pair.
375 void parse(Node &N) const {
376 if (N.getType() != Node::NK_Mapping) {
377 Outer->error(Description + " should be a dictionary", N);
378 return;
379 }
380 llvm::SmallSet<std::string, 8> Seen;
381 llvm::SmallVector<Located<std::string>, 0> UnknownKeys;
382 // We *must* consume all items, even on error, or the parser will assert.
383 for (auto &KV : llvm::cast<MappingNode>(N)) {
384 auto *K = KV.getKey();
385 if (!K) // YAMLParser emitted an error.
386 continue;
387 auto Key = Outer->scalarValue(*K, "Dictionary key");
388 if (!Key)
389 continue;
390 if (!Seen.insert(**Key).second) {
391 Outer->warning("Duplicate key " + **Key + " is ignored", *K);
392 if (auto *Value = KV.getValue())
393 Value->skip();
394 continue;
395 }
396 auto *Value = KV.getValue();
397 if (!Value) // YAMLParser emitted an error.
398 continue;
399 bool Matched = false;
400 for (const auto &Handler : Keys) {
401 if (Handler.first == **Key) {
402 Matched = true;
403 Handler.second(*Value);
404 break;
405 }
406 }
407 if (!Matched) {
408 bool Warn = !UnknownHandler;
409 if (UnknownHandler)
410 Warn = UnknownHandler(
411 Located<std::string>(**Key, K->getSourceRange()), *Value);
412 if (Warn)
413 UnknownKeys.push_back(std::move(*Key));
414 }
415 }
416 if (!UnknownKeys.empty())
417 warnUnknownKeys(UnknownKeys, Seen);
418 }
419
420 private:
421 void warnUnknownKeys(llvm::ArrayRef<Located<std::string>> UnknownKeys,
422 const llvm::SmallSet<std::string, 8> &SeenKeys) const {
423 llvm::SmallVector<llvm::StringRef> UnseenKeys;
424 for (const auto &KeyAndHandler : Keys)
425 if (!SeenKeys.count(KeyAndHandler.first.str()))
426 UnseenKeys.push_back(KeyAndHandler.first);
427
428 for (const Located<std::string> &UnknownKey : UnknownKeys)
429 if (auto BestGuess = bestGuess(*UnknownKey, UnseenKeys))
430 Outer->warning("Unknown " + Description + " key '" + *UnknownKey +
431 "'; did you mean '" + *BestGuess + "'?",
432 UnknownKey.Range);
433 else
434 Outer->warning("Unknown " + Description + " key '" + *UnknownKey +
435 "'",
436 UnknownKey.Range);
437 }
438 };
439
440 // Try to parse a single scalar value from the node, warn on failure.
441 std::optional<Located<std::string>> scalarValue(Node &N,
442 llvm::StringRef Desc) {
443 llvm::SmallString<256> Buf;
444 if (auto *S = llvm::dyn_cast<ScalarNode>(&N))
445 return Located<std::string>(S->getValue(Buf).str(), N.getSourceRange());
446 if (auto *BS = llvm::dyn_cast<BlockScalarNode>(&N))
447 return Located<std::string>(BS->getValue().str(), N.getSourceRange());
448 warning(Desc + " should be scalar", N);
449 return std::nullopt;
450 }
451
452 std::optional<Located<bool>> boolValue(Node &N, llvm::StringRef Desc) {
453 if (auto Scalar = scalarValue(N, Desc)) {
454 if (auto Bool = llvm::yaml::parseBool(**Scalar))
455 return Located<bool>(*Bool, Scalar->Range);
456 warning(Desc + " should be a boolean", N);
457 }
458 return std::nullopt;
459 }
460
461 std::optional<Located<uint32_t>> uint32Value(Node &N, llvm::StringRef Desc) {
462 if (auto Scalar = scalarValue(N, Desc)) {
463 unsigned long long Num;
464 if (!llvm::getAsUnsignedInteger(**Scalar, 0, Num)) {
465 return Located<uint32_t>(Num, Scalar->Range);
466 }
467 }
468 warning(Desc + " invalid number", N);
469 return std::nullopt;
470 }
471
472 // Try to parse a list of single scalar values, or just a single value.
473 std::optional<std::vector<Located<std::string>>> scalarValues(Node &N) {
474 std::vector<Located<std::string>> Result;
475 if (auto *S = llvm::dyn_cast<ScalarNode>(&N)) {
476 llvm::SmallString<256> Buf;
477 Result.emplace_back(S->getValue(Buf).str(), N.getSourceRange());
478 } else if (auto *S = llvm::dyn_cast<BlockScalarNode>(&N)) {
479 Result.emplace_back(S->getValue().str(), N.getSourceRange());
480 } else if (auto *S = llvm::dyn_cast<SequenceNode>(&N)) {
481 // We *must* consume all items, even on error, or the parser will assert.
482 for (auto &Child : *S) {
483 if (auto Value = scalarValue(Child, "List item"))
484 Result.push_back(std::move(*Value));
485 }
486 } else {
487 warning("Expected scalar or list of scalars", N);
488 return std::nullopt;
489 }
490 return Result;
491 }
492
493 // Report a "hard" error, reflecting a config file that can never be valid.
494 void error(const llvm::Twine &Msg, llvm::SMRange Range) {
495 HadError = true;
496 SM.PrintMessage(Range.Start, llvm::SourceMgr::DK_Error, Msg, Range);
497 }
498 void error(const llvm::Twine &Msg, const Node &N) {
499 return error(Msg, N.getSourceRange());
500 }
501
502 // Report a "soft" error that could be caused by e.g. version skew.
503 void warning(const llvm::Twine &Msg, llvm::SMRange Range) {
504 SM.PrintMessage(Range.Start, llvm::SourceMgr::DK_Warning, Msg, Range);
505 }
506 void warning(const llvm::Twine &Msg, const Node &N) {
507 return warning(Msg, N.getSourceRange());
508 }
509};
510
511} // namespace
512
513std::vector<Fragment> Fragment::parseYAML(llvm::StringRef YAML,
514 llvm::StringRef BufferName,
515 DiagnosticCallback Diags) {
516 // The YAML document may contain multiple conditional fragments.
517 // The SourceManager is shared for all of them.
518 log("Loading config file at {0}", BufferName);
519 auto SM = std::make_shared<llvm::SourceMgr>();
520 auto Buf = llvm::MemoryBuffer::getMemBufferCopy(YAML, BufferName);
521 // Adapt DiagnosticCallback to function-pointer interface.
522 // Callback receives both errors we emit and those from the YAML parser.
523 SM->setDiagHandler(
524 [](const llvm::SMDiagnostic &Diag, void *Ctx) {
525 (*reinterpret_cast<DiagnosticCallback *>(Ctx))(Diag);
526 },
527 &Diags);
528 std::vector<Fragment> Result;
529 for (auto &Doc : llvm::yaml::Stream(*Buf, *SM)) {
530 if (Node *N = Doc.getRoot()) {
533 Fragment.Source.Location = N->getSourceRange().Start;
534 SM->PrintMessage(Fragment.Source.Location, llvm::SourceMgr::DK_Note,
535 "Parsing config fragment");
536 if (Parser(*SM).parse(Fragment, *N))
537 Result.push_back(std::move(Fragment));
538 }
539 }
540 SM->PrintMessage(SM->FindLocForLineAndColumn(SM->getMainFileID(), 0, 0),
541 llvm::SourceMgr::DK_Note,
542 "Parsed " + llvm::Twine(Result.size()) +
543 " fragments from file");
544 // Hack: stash the buffer in the SourceMgr to keep it alive.
545 // SM has two entries: "main" non-owning buffer, and ignored owning buffer.
546 SM->AddNewSourceBuffer(std::move(Buf), llvm::SMLoc());
547 return Result;
548}
549
550} // namespace config
551} // namespace clangd
552} // 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).