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;
177 Dict.handle(
"ExperimentalCustomChecks", [&](Node &N) {
178 if (
auto Value = boolValue(N,
"ExperimentalCustomChecks"))
179 F.ExperimentalCustomChecks = *
Value;
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);
190 Dict.handle(
"AnalyzeAngledIncludes", [&](Node &N) {
191 if (
auto Value = boolValue(N,
"AnalyzeAngledIncludes"))
192 F.AnalyzeAngledIncludes = *
Value;
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;
205 if (N.getType() == Node::NK_Mapping) {
207 }
else if (N.getType() == Node::NK_Scalar ||
208 N.getType() == Node::NK_BlockScalar) {
209 parse(External, *scalarValue(N,
"External"));
211 error(
"External must be either a scalar or a mapping.", N);
214 F.External.emplace(std::move(External));
215 F.External->Range = N.getSourceRange();
217 Dict.handle(
"StandardLibrary", [&](Node &N) {
218 if (
auto StandardLibrary = boolValue(N,
"StandardLibrary"))
219 F.StandardLibrary = *StandardLibrary;
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'",
232 F.IsNone.Range = ExternalVal.Range;
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"); });
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;
251 Dict.handle(
"ArgumentLists", [&](Node &N) {
252 if (
auto ArgumentLists = scalarValue(N,
"ArgumentLists"))
253 F.ArgumentLists = *ArgumentLists;
255 Dict.handle(
"HeaderInsertion", [&](Node &N) {
256 if (
auto HeaderInsertion = scalarValue(N,
"HeaderInsertion"))
257 F.HeaderInsertion = *HeaderInsertion;
259 Dict.handle(
"CodePatterns", [&](Node &N) {
260 if (
auto CodePatterns = scalarValue(N,
"CodePatterns"))
261 F.CodePatterns = *CodePatterns;
263 Dict.handle(
"MacroFilter", [&](Node &N) {
264 if (
auto MacroFilter = scalarValue(N,
"MacroFilter"))
265 F.MacroFilter = *MacroFilter;
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;
276 Dict.handle(
"MacroContentsLimit", [&](Node &N) {
277 if (
auto MacroContentsLimit = uint32Value(N,
"MacroContentsLimit"))
278 F.MacroContentsLimit = *MacroContentsLimit;
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"))
289 Dict.handle(
"ParameterNames", [&](Node &N) {
290 if (
auto Value = boolValue(N,
"ParameterNames"))
291 F.ParameterNames = *
Value;
293 Dict.handle(
"DeducedTypes", [&](Node &N) {
294 if (
auto Value = boolValue(N,
"DeducedTypes"))
295 F.DeducedTypes = *
Value;
297 Dict.handle(
"Designators", [&](Node &N) {
298 if (
auto Value = boolValue(N,
"Designators"))
299 F.Designators = *
Value;
301 Dict.handle(
"BlockEnd", [&](Node &N) {
302 if (
auto Value = boolValue(N,
"BlockEnd"))
305 Dict.handle(
"DefaultArguments", [&](Node &N) {
306 if (
auto Value = boolValue(N,
"DefaultArguments"))
307 F.DefaultArguments = *
Value;
309 Dict.handle(
"TypeNameLimit", [&](Node &N) {
310 if (
auto Value = uint32Value(N,
"TypeNameLimit"))
311 F.TypeNameLimit = *
Value;
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);
322 Dict.handle(
"DisabledModifiers", [&](Node &N) {
323 if (
auto Values = scalarValues(N))
324 F.DisabledModifiers = std::move(*Values);
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;
341 llvm::StringRef Description;
343 std::pair<llvm::StringRef, llvm::unique_function<void(Node &)
const>>>
345 llvm::unique_function<bool(Located<std::string>, Node &)
const>
350 DictParser(llvm::StringRef Description, Parser *Outer)
351 : Description(Description), Outer(Outer) {}
356 void handle(llvm::StringLiteral
Key,
357 llvm::unique_function<
void(Node &)
const> Parse) {
358 for (
const auto &Entry : Keys) {
360 assert(Entry.first !=
Key &&
"duplicate key handler");
362 Keys.emplace_back(
Key, std::move(Parse));
369 unrecognized(llvm::unique_function<
bool(Located<std::string>, Node &)
const>
371 UnknownHandler = std::move(Handler);
375 void parse(Node &N)
const {
376 if (N.getType() != Node::NK_Mapping) {
377 Outer->error(Description +
" should be a dictionary", N);
380 llvm::SmallSet<std::string, 8> Seen;
381 llvm::SmallVector<Located<std::string>, 0> UnknownKeys;
383 for (
auto &KV : llvm::cast<MappingNode>(N)) {
384 auto *K = KV.getKey();
387 auto Key = Outer->scalarValue(*K,
"Dictionary key");
390 if (!Seen.insert(**Key).second) {
391 Outer->warning(
"Duplicate key " + **
Key +
" is ignored", *K);
392 if (
auto *
Value = KV.getValue())
396 auto *
Value = KV.getValue();
399 bool Matched =
false;
400 for (
const auto &Handler : Keys) {
401 if (Handler.first == **
Key) {
403 Handler.second(*
Value);
408 bool Warn = !UnknownHandler;
410 Warn = UnknownHandler(
411 Located<std::string>(**
Key, K->getSourceRange()), *
Value);
413 UnknownKeys.push_back(std::move(*
Key));
416 if (!UnknownKeys.empty())
417 warnUnknownKeys(UnknownKeys, Seen);
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);
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 +
"'?",
434 Outer->warning(
"Unknown " + Description +
" key '" + *UnknownKey +
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);
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);
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);
468 warning(Desc +
" invalid number", N);
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)) {
482 for (
auto &Child : *S) {
483 if (
auto Value = scalarValue(Child,
"List item"))
484 Result.push_back(std::move(*
Value));
487 warning(
"Expected scalar or list of scalars", N);
494 void error(
const llvm::Twine &Msg, llvm::SMRange Range) {
496 SM.PrintMessage(Range.Start, llvm::SourceMgr::DK_Error, Msg, Range);
498 void error(
const llvm::Twine &Msg,
const Node &N) {
499 return error(Msg, N.getSourceRange());
503 void warning(
const llvm::Twine &Msg, llvm::SMRange Range) {
504 SM.PrintMessage(Range.Start, llvm::SourceMgr::DK_Warning, Msg, Range);
506 void warning(
const llvm::Twine &Msg,
const Node &N) {
507 return warning(Msg, N.getSourceRange());
514 llvm::StringRef BufferName,
518 log(
"Loading config file at {0}", BufferName);
519 auto SM = std::make_shared<llvm::SourceMgr>();
520 auto Buf = llvm::MemoryBuffer::getMemBufferCopy(
YAML, BufferName);
524 [](
const llvm::SMDiagnostic &
Diag,
void *Ctx) {
528 std::vector<Fragment> Result;
529 for (
auto &Doc : llvm::yaml::Stream(*Buf, *SM)) {
530 if (Node *N = Doc.getRoot()) {
535 "Parsing config fragment");
536 if (Parser(*SM).parse(
Fragment, *N))
537 Result.push_back(std::move(
Fragment));
540 SM->PrintMessage(SM->FindLocForLineAndColumn(SM->getMainFileID(), 0, 0),
541 llvm::SourceMgr::DK_Note,
542 "Parsed " + llvm::Twine(Result.size()) +
543 " fragments from file");
546 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).