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