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