blob: 7e86e372124831ae9e79196ba7d345be28b83d8f [file] [log] [blame]
Sam McCalle9fb1502020-06-23 17:21:56 +02001//===--- 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
9#include "ConfigFragment.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
17namespace clang {
18namespace clangd {
19namespace config {
20namespace {
21using llvm::yaml::BlockScalarNode;
22using llvm::yaml::MappingNode;
23using llvm::yaml::Node;
24using llvm::yaml::ScalarNode;
25using llvm::yaml::SequenceNode;
26
27class Parser {
28 llvm::SourceMgr &SM;
Sam McCallf3651862020-07-09 00:13:54 +020029 bool HadError = false;
Sam McCalle9fb1502020-06-23 17:21:56 +020030
31public:
32 Parser(llvm::SourceMgr &SM) : SM(SM) {}
33
34 // Tries to parse N into F, returning false if it failed and we couldn't
Sam McCallf3651862020-07-09 00:13:54 +020035 // meaningfully recover (YAML syntax error, or hard semantic error).
Sam McCalle9fb1502020-06-23 17:21:56 +020036 bool parse(Fragment &F, Node &N) {
37 DictParser Dict("Config", this);
Sam McCallf3651862020-07-09 00:13:54 +020038 Dict.handle("If", [&](Node &N) { parse(F.If, N); });
39 Dict.handle("CompileFlags", [&](Node &N) { parse(F.CompileFlags, N); });
40 Dict.parse(N);
41 return !(N.failed() || HadError);
Sam McCalle9fb1502020-06-23 17:21:56 +020042 }
43
44private:
Sam McCallf3651862020-07-09 00:13:54 +020045 void parse(Fragment::IfBlock &F, Node &N) {
Sam McCallf12cd992020-06-26 01:49:53 +020046 DictParser Dict("If", this);
Sam McCalle9fb1502020-06-23 17:21:56 +020047 Dict.unrecognized(
48 [&](llvm::StringRef) { F.HasUnrecognizedCondition = true; });
49 Dict.handle("PathMatch", [&](Node &N) {
50 if (auto Values = scalarValues(N))
51 F.PathMatch = std::move(*Values);
Sam McCalle9fb1502020-06-23 17:21:56 +020052 });
Sam McCall86f13132020-07-09 23:33:46 +020053 Dict.handle("PathExclude", [&](Node &N) {
54 if (auto Values = scalarValues(N))
55 F.PathExclude = std::move(*Values);
56 });
Sam McCallf3651862020-07-09 00:13:54 +020057 Dict.parse(N);
Sam McCalle9fb1502020-06-23 17:21:56 +020058 }
59
Sam McCallf3651862020-07-09 00:13:54 +020060 void parse(Fragment::CompileFlagsBlock &F, Node &N) {
Sam McCalle9fb1502020-06-23 17:21:56 +020061 DictParser Dict("CompileFlags", this);
62 Dict.handle("Add", [&](Node &N) {
63 if (auto Values = scalarValues(N))
64 F.Add = std::move(*Values);
Sam McCalle9fb1502020-06-23 17:21:56 +020065 });
Sam McCall6c16fbd2020-07-13 20:37:54 +020066 Dict.handle("Remove", [&](Node &N) {
67 if (auto Values = scalarValues(N))
68 F.Remove = std::move(*Values);
69 });
Sam McCallf3651862020-07-09 00:13:54 +020070 Dict.parse(N);
Sam McCalle9fb1502020-06-23 17:21:56 +020071 }
72
73 // Helper for parsing mapping nodes (dictionaries).
74 // We don't use YamlIO as we want to control over unknown keys.
75 class DictParser {
76 llvm::StringRef Description;
Sam McCallf3651862020-07-09 00:13:54 +020077 std::vector<std::pair<llvm::StringRef, std::function<void(Node &)>>> Keys;
Sam McCalle9fb1502020-06-23 17:21:56 +020078 std::function<void(llvm::StringRef)> Unknown;
79 Parser *Outer;
80
81 public:
82 DictParser(llvm::StringRef Description, Parser *Outer)
83 : Description(Description), Outer(Outer) {}
84
85 // Parse is called when Key is encountered, and passed the associated value.
86 // It should emit diagnostics if the value is invalid (e.g. wrong type).
87 // If Key is seen twice, Parse runs only once and an error is reported.
Sam McCallf3651862020-07-09 00:13:54 +020088 void handle(llvm::StringLiteral Key, std::function<void(Node &)> Parse) {
Tres Popp1a30eab2020-06-26 10:12:04 +020089 for (const auto &Entry : Keys) {
90 (void) Entry;
Sam McCalle9fb1502020-06-23 17:21:56 +020091 assert(Entry.first != Key && "duplicate key handler");
Tres Popp1a30eab2020-06-26 10:12:04 +020092 }
Sam McCalle9fb1502020-06-23 17:21:56 +020093 Keys.emplace_back(Key, std::move(Parse));
94 }
95
96 // Fallback is called when a Key is not matched by any handle().
97 // A warning is also automatically emitted.
98 void unrecognized(std::function<void(llvm::StringRef)> Fallback) {
99 Unknown = std::move(Fallback);
100 }
101
102 // Process a mapping node and call handlers for each key/value pair.
Sam McCallf3651862020-07-09 00:13:54 +0200103 void parse(Node &N) const {
Sam McCalle9fb1502020-06-23 17:21:56 +0200104 if (N.getType() != Node::NK_Mapping) {
105 Outer->error(Description + " should be a dictionary", N);
Sam McCallf3651862020-07-09 00:13:54 +0200106 return;
Sam McCalle9fb1502020-06-23 17:21:56 +0200107 }
108 llvm::SmallSet<std::string, 8> Seen;
Sam McCallf3651862020-07-09 00:13:54 +0200109 // We *must* consume all items, even on error, or the parser will assert.
Sam McCalle9fb1502020-06-23 17:21:56 +0200110 for (auto &KV : llvm::cast<MappingNode>(N)) {
111 auto *K = KV.getKey();
112 if (!K) // YAMLParser emitted an error.
Sam McCallf3651862020-07-09 00:13:54 +0200113 continue;
Sam McCalle9fb1502020-06-23 17:21:56 +0200114 auto Key = Outer->scalarValue(*K, "Dictionary key");
115 if (!Key)
116 continue;
117 if (!Seen.insert(**Key).second) {
118 Outer->warning("Duplicate key " + **Key + " is ignored", *K);
119 continue;
120 }
121 auto *Value = KV.getValue();
122 if (!Value) // YAMLParser emitted an error.
Sam McCallf3651862020-07-09 00:13:54 +0200123 continue;
Sam McCalle9fb1502020-06-23 17:21:56 +0200124 bool Matched = false;
125 for (const auto &Handler : Keys) {
126 if (Handler.first == **Key) {
Sam McCalle9fb1502020-06-23 17:21:56 +0200127 Matched = true;
Sam McCallf3651862020-07-09 00:13:54 +0200128 Handler.second(*Value);
Sam McCalle9fb1502020-06-23 17:21:56 +0200129 break;
130 }
131 }
132 if (!Matched) {
133 Outer->warning("Unknown " + Description + " key " + **Key, *K);
134 if (Unknown)
135 Unknown(**Key);
136 }
137 }
Sam McCalle9fb1502020-06-23 17:21:56 +0200138 }
139 };
140
141 // Try to parse a single scalar value from the node, warn on failure.
142 llvm::Optional<Located<std::string>> scalarValue(Node &N,
143 llvm::StringRef Desc) {
144 llvm::SmallString<256> Buf;
145 if (auto *S = llvm::dyn_cast<ScalarNode>(&N))
146 return Located<std::string>(S->getValue(Buf).str(), N.getSourceRange());
147 if (auto *BS = llvm::dyn_cast<BlockScalarNode>(&N))
148 return Located<std::string>(BS->getValue().str(), N.getSourceRange());
149 warning(Desc + " should be scalar", N);
150 return llvm::None;
151 }
152
153 // Try to parse a list of single scalar values, or just a single value.
154 llvm::Optional<std::vector<Located<std::string>>> scalarValues(Node &N) {
155 std::vector<Located<std::string>> Result;
156 if (auto *S = llvm::dyn_cast<ScalarNode>(&N)) {
157 llvm::SmallString<256> Buf;
158 Result.emplace_back(S->getValue(Buf).str(), N.getSourceRange());
159 } else if (auto *S = llvm::dyn_cast<BlockScalarNode>(&N)) {
160 Result.emplace_back(S->getValue().str(), N.getSourceRange());
161 } else if (auto *S = llvm::dyn_cast<SequenceNode>(&N)) {
Sam McCallf3651862020-07-09 00:13:54 +0200162 // We *must* consume all items, even on error, or the parser will assert.
Sam McCalle9fb1502020-06-23 17:21:56 +0200163 for (auto &Child : *S) {
164 if (auto Value = scalarValue(Child, "List item"))
165 Result.push_back(std::move(*Value));
166 }
167 } else {
168 warning("Expected scalar or list of scalars", N);
169 return llvm::None;
170 }
171 return Result;
172 }
173
174 // Report a "hard" error, reflecting a config file that can never be valid.
175 void error(const llvm::Twine &Msg, const Node &N) {
Sam McCallf3651862020-07-09 00:13:54 +0200176 HadError = true;
Sam McCalle9fb1502020-06-23 17:21:56 +0200177 SM.PrintMessage(N.getSourceRange().Start, llvm::SourceMgr::DK_Error, Msg,
178 N.getSourceRange());
179 }
180
181 // Report a "soft" error that could be caused by e.g. version skew.
182 void warning(const llvm::Twine &Msg, const Node &N) {
183 SM.PrintMessage(N.getSourceRange().Start, llvm::SourceMgr::DK_Warning, Msg,
184 N.getSourceRange());
185 }
186};
187
188} // namespace
189
190std::vector<Fragment> Fragment::parseYAML(llvm::StringRef YAML,
191 llvm::StringRef BufferName,
192 DiagnosticCallback Diags) {
193 // The YAML document may contain multiple conditional fragments.
194 // The SourceManager is shared for all of them.
195 auto SM = std::make_shared<llvm::SourceMgr>();
196 auto Buf = llvm::MemoryBuffer::getMemBufferCopy(YAML, BufferName);
197 // Adapt DiagnosticCallback to function-pointer interface.
198 // Callback receives both errors we emit and those from the YAML parser.
199 SM->setDiagHandler(
200 [](const llvm::SMDiagnostic &Diag, void *Ctx) {
201 (*reinterpret_cast<DiagnosticCallback *>(Ctx))(Diag);
202 },
203 &Diags);
204 std::vector<Fragment> Result;
205 for (auto &Doc : llvm::yaml::Stream(*Buf, *SM)) {
Sam McCallf3651862020-07-09 00:13:54 +0200206 if (Node *N = Doc.getRoot()) {
Sam McCalle9fb1502020-06-23 17:21:56 +0200207 Fragment Fragment;
208 Fragment.Source.Manager = SM;
209 Fragment.Source.Location = N->getSourceRange().Start;
210 if (Parser(*SM).parse(Fragment, *N))
211 Result.push_back(std::move(Fragment));
212 }
213 }
214 // Hack: stash the buffer in the SourceMgr to keep it alive.
215 // SM has two entries: "main" non-owning buffer, and ignored owning buffer.
216 SM->AddNewSourceBuffer(std::move(Buf), llvm::SMLoc());
217 return Result;
218}
219
220} // namespace config
221} // namespace clangd
222} // namespace clang