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