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"
24using llvm::yaml::BlockScalarNode;
25using llvm::yaml::MappingNode;
26using llvm::yaml::Node;
27using llvm::yaml::ScalarNode;
28using llvm::yaml::SequenceNode;
30std::optional<llvm::StringRef>
31bestGuess(llvm::StringRef Search,
32 llvm::ArrayRef<llvm::StringRef> AllowedValues) {
33 unsigned MaxEdit = (Search.size() + 1) / 3;
36 std::optional<llvm::StringRef> Result;
37 for (
const auto &AllowedValue : AllowedValues) {
38 unsigned EditDistance = Search.edit_distance(AllowedValue,
true, MaxEdit);
41 if (EditDistance == 1U)
43 if (EditDistance == MaxEdit && !Result) {
44 Result = AllowedValue;
45 }
else if (EditDistance < MaxEdit) {
46 Result = AllowedValue;
47 MaxEdit = EditDistance;
55 bool HadError =
false;
58 Parser(llvm::SourceMgr &SM) : SM(SM) {}
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); });
75 return !(N.failed() || HadError);
79 void parse(Fragment::IfBlock &F, Node &N) {
80 DictParser Dict(
"If",
this);
81 Dict.unrecognized([&](Located<std::string>, Node &) {
82 F.HasUnrecognizedCondition =
true;
85 Dict.handle(
"PathMatch", [&](Node &N) {
86 if (
auto Values = scalarValues(N))
87 F.PathMatch = std::move(*Values);
89 Dict.handle(
"PathExclude", [&](Node &N) {
90 if (
auto Values = scalarValues(N))
91 F.PathExclude = std::move(*Values);
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);
102 Dict.handle(
"Add", [&](Node &N) {
103 if (
auto Values = scalarValues(N))
104 F.Add = std::move(*Values);
106 Dict.handle(
"Remove", [&](Node &N) {
107 if (
auto Values = scalarValues(N))
108 F.Remove = std::move(*Values);
110 Dict.handle(
"BuiltinHeaders", [&](Node &N) {
111 if (
auto BuiltinHeaders = scalarValue(N,
"BuiltinHeaders"))
112 F.BuiltinHeaders = *BuiltinHeaders;
114 Dict.handle(
"CompilationDatabase", [&](Node &N) {
115 F.CompilationDatabase = scalarValue(N,
"CompilationDatabase");
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);
126 Dict.handle(
"QuotedHeaders", [&](Node &N) {
127 if (
auto Values = scalarValues(N))
128 F.QuotedHeaders = std::move(*Values);
130 Dict.handle(
"AngledHeaders", [&](Node &N) {
131 if (
auto Values = scalarValues(N))
132 F.AngledHeaders = std::move(*Values);
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);
143 Dict.handle(
"UnusedIncludes", [&](Node &N) {
144 F.UnusedIncludes = scalarValue(N,
"UnusedIncludes");
146 Dict.handle(
"MissingIncludes", [&](Node &N) {
147 F.MissingIncludes = scalarValue(N,
"MissingIncludes");
149 Dict.handle(
"Includes", [&](Node &N) { parse(F.Includes, N); });
150 Dict.handle(
"ClangTidy", [&](Node &N) { parse(F.ClangTidy, N); });
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);
160 Dict.handle(
"Remove", [&](Node &N) {
161 if (
auto Values = scalarValues(N))
162 F.Remove = std::move(*Values);
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));
171 CheckOptDict.parse(N);
173 Dict.handle(
"FastCheckFilter", [&](Node &N) {
174 if (
auto FastCheckFilter = scalarValue(N,
"FastCheckFilter"))
175 F.FastCheckFilter = *FastCheckFilter;
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);
186 Dict.handle(
"AnalyzeAngledIncludes", [&](Node &N) {
187 if (
auto Value = boolValue(N,
"AnalyzeAngledIncludes"))
188 F.AnalyzeAngledIncludes = *
Value;
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;
201 if (N.getType() == Node::NK_Mapping) {
203 }
else if (N.getType() == Node::NK_Scalar ||
204 N.getType() == Node::NK_BlockScalar) {
205 parse(External, *scalarValue(N,
"External"));
207 error(
"External must be either a scalar or a mapping.", N);
210 F.External.emplace(std::move(External));
211 F.External->Range = N.getSourceRange();
213 Dict.handle(
"StandardLibrary", [&](Node &N) {
214 if (
auto StandardLibrary = boolValue(N,
"StandardLibrary"))
215 F.StandardLibrary = *StandardLibrary;
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'",
228 F.IsNone.Range = ExternalVal.Range;
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"); });
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;
247 Dict.handle(
"ArgumentLists", [&](Node &N) {
248 if (
auto ArgumentLists = scalarValue(N,
"ArgumentLists"))
249 F.ArgumentLists = *ArgumentLists;
251 Dict.handle(
"HeaderInsertion", [&](Node &N) {
252 if (
auto HeaderInsertion = scalarValue(N,
"HeaderInsertion"))
253 F.HeaderInsertion = *HeaderInsertion;
255 Dict.handle(
"CodePatterns", [&](Node &N) {
256 if (
auto CodePatterns = scalarValue(N,
"CodePatterns"))
257 F.CodePatterns = *CodePatterns;
259 Dict.handle(
"MacroFilter", [&](Node &N) {
260 if (
auto MacroFilter = scalarValue(N,
"MacroFilter"))
261 F.MacroFilter = *MacroFilter;
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;
272 Dict.handle(
"MacroContentsLimit", [&](Node &N) {
273 if (
auto MacroContentsLimit = uint32Value(N,
"MacroContentsLimit"))
274 F.MacroContentsLimit = *MacroContentsLimit;
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"))
285 Dict.handle(
"ParameterNames", [&](Node &N) {
286 if (
auto Value = boolValue(N,
"ParameterNames"))
287 F.ParameterNames = *
Value;
289 Dict.handle(
"DeducedTypes", [&](Node &N) {
290 if (
auto Value = boolValue(N,
"DeducedTypes"))
291 F.DeducedTypes = *
Value;
293 Dict.handle(
"Designators", [&](Node &N) {
294 if (
auto Value = boolValue(N,
"Designators"))
295 F.Designators = *
Value;
297 Dict.handle(
"BlockEnd", [&](Node &N) {
298 if (
auto Value = boolValue(N,
"BlockEnd"))
301 Dict.handle(
"DefaultArguments", [&](Node &N) {
302 if (
auto Value = boolValue(N,
"DefaultArguments"))
303 F.DefaultArguments = *
Value;
305 Dict.handle(
"TypeNameLimit", [&](Node &N) {
306 if (
auto Value = uint32Value(N,
"TypeNameLimit"))
307 F.TypeNameLimit = *
Value;
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);
318 Dict.handle(
"DisabledModifiers", [&](Node &N) {
319 if (
auto Values = scalarValues(N))
320 F.DisabledModifiers = std::move(*Values);
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;
337 llvm::StringRef Description;
339 std::pair<llvm::StringRef, llvm::unique_function<void(Node &)
const>>>
341 llvm::unique_function<bool(Located<std::string>, Node &)
const>
346 DictParser(llvm::StringRef Description, Parser *Outer)
347 : Description(Description), Outer(Outer) {}
352 void handle(llvm::StringLiteral
Key,
353 llvm::unique_function<
void(Node &)
const> Parse) {
354 for (
const auto &Entry : Keys) {
356 assert(Entry.first !=
Key &&
"duplicate key handler");
358 Keys.emplace_back(
Key, std::move(Parse));
365 unrecognized(llvm::unique_function<
bool(Located<std::string>, Node &)
const>
367 UnknownHandler = std::move(Handler);
371 void parse(Node &N)
const {
372 if (N.getType() != Node::NK_Mapping) {
373 Outer->error(Description +
" should be a dictionary", N);
376 llvm::SmallSet<std::string, 8> Seen;
377 llvm::SmallVector<Located<std::string>, 0> UnknownKeys;
379 for (
auto &KV : llvm::cast<MappingNode>(N)) {
380 auto *K = KV.getKey();
383 auto Key = Outer->scalarValue(*K,
"Dictionary key");
386 if (!Seen.insert(**Key).second) {
387 Outer->warning(
"Duplicate key " + **
Key +
" is ignored", *K);
388 if (
auto *
Value = KV.getValue())
392 auto *
Value = KV.getValue();
395 bool Matched =
false;
396 for (
const auto &Handler : Keys) {
397 if (Handler.first == **
Key) {
399 Handler.second(*
Value);
404 bool Warn = !UnknownHandler;
406 Warn = UnknownHandler(
407 Located<std::string>(**
Key, K->getSourceRange()), *
Value);
409 UnknownKeys.push_back(std::move(*
Key));
412 if (!UnknownKeys.empty())
413 warnUnknownKeys(UnknownKeys, Seen);
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);
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 +
"'?",
430 Outer->warning(
"Unknown " + Description +
" key '" + *UnknownKey +
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);
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);
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);
464 warning(Desc +
" invalid number", N);
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)) {
478 for (
auto &Child : *S) {
479 if (
auto Value = scalarValue(Child,
"List item"))
480 Result.push_back(std::move(*
Value));
483 warning(
"Expected scalar or list of scalars", N);
490 void error(
const llvm::Twine &Msg, llvm::SMRange Range) {
492 SM.PrintMessage(Range.Start, llvm::SourceMgr::DK_Error, Msg, Range);
494 void error(
const llvm::Twine &Msg,
const Node &N) {
495 return error(Msg, N.getSourceRange());
499 void warning(
const llvm::Twine &Msg, llvm::SMRange Range) {
500 SM.PrintMessage(Range.Start, llvm::SourceMgr::DK_Warning, Msg, Range);
502 void warning(
const llvm::Twine &Msg,
const Node &N) {
503 return warning(Msg, N.getSourceRange());
510 llvm::StringRef BufferName,
514 log(
"Loading config file at {0}", BufferName);
515 auto SM = std::make_shared<llvm::SourceMgr>();
516 auto Buf = llvm::MemoryBuffer::getMemBufferCopy(
YAML, BufferName);
520 [](
const llvm::SMDiagnostic &
Diag,
void *Ctx) {
524 std::vector<Fragment> Result;
525 for (
auto &Doc : llvm::yaml::Stream(*Buf, *SM)) {
526 if (Node *N = Doc.getRoot()) {
531 "Parsing config fragment");
532 if (Parser(*SM).parse(
Fragment, *N))
533 Result.push_back(std::move(
Fragment));
536 SM->PrintMessage(SM->FindLocForLineAndColumn(SM->getMainFileID(), 0, 0),
537 llvm::SourceMgr::DK_Note,
538 "Parsed " + llvm::Twine(Result.size()) +
539 " fragments from file");
542 SM->AddNewSourceBuffer(std::move(Buf), llvm::SMLoc());
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.
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
void log(const char *Fmt, Ts &&... Vals)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
A top-level diagnostic that may have Notes and Fixes.
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).