blob: ee3331df8694fc9095a4774ed2ef201f19d34d8c [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;
29
30public:
31 Parser(llvm::SourceMgr &SM) : SM(SM) {}
32
33 // Tries to parse N into F, returning false if it failed and we couldn't
34 // meaningfully recover (e.g. YAML syntax error broke the stream).
35 // The private parse() helpers follow the same pattern.
36 bool parse(Fragment &F, Node &N) {
37 DictParser Dict("Config", this);
38 Dict.handle("If", [&](Node &N) { return parse(F.Condition, N); });
39 Dict.handle("CompileFlags",
40 [&](Node &N) { return parse(F.CompileFlags, N); });
41 return Dict.parse(N);
42 }
43
44private:
45 bool parse(Fragment::ConditionBlock &F, Node &N) {
46 DictParser Dict("Condition", this);
47 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);
52 return !N.failed();
53 });
54 return Dict.parse(N);
55 }
56
57 bool parse(Fragment::CompileFlagsBlock &F, Node &N) {
58 DictParser Dict("CompileFlags", this);
59 Dict.handle("Add", [&](Node &N) {
60 if (auto Values = scalarValues(N))
61 F.Add = std::move(*Values);
62 return !N.failed();
63 });
64 return Dict.parse(N);
65 }
66
67 // Helper for parsing mapping nodes (dictionaries).
68 // We don't use YamlIO as we want to control over unknown keys.
69 class DictParser {
70 llvm::StringRef Description;
71 std::vector<std::pair<llvm::StringRef, std::function<bool(Node &)>>> Keys;
72 std::function<void(llvm::StringRef)> Unknown;
73 Parser *Outer;
74
75 public:
76 DictParser(llvm::StringRef Description, Parser *Outer)
77 : Description(Description), Outer(Outer) {}
78
79 // Parse is called when Key is encountered, and passed the associated value.
80 // It should emit diagnostics if the value is invalid (e.g. wrong type).
81 // If Key is seen twice, Parse runs only once and an error is reported.
82 void handle(llvm::StringLiteral Key, std::function<bool(Node &)> Parse) {
83 for (const auto &Entry : Keys)
84 assert(Entry.first != Key && "duplicate key handler");
85 Keys.emplace_back(Key, std::move(Parse));
86 }
87
88 // Fallback is called when a Key is not matched by any handle().
89 // A warning is also automatically emitted.
90 void unrecognized(std::function<void(llvm::StringRef)> Fallback) {
91 Unknown = std::move(Fallback);
92 }
93
94 // Process a mapping node and call handlers for each key/value pair.
95 bool parse(Node &N) const {
96 if (N.getType() != Node::NK_Mapping) {
97 Outer->error(Description + " should be a dictionary", N);
98 return false;
99 }
100 llvm::SmallSet<std::string, 8> Seen;
101 for (auto &KV : llvm::cast<MappingNode>(N)) {
102 auto *K = KV.getKey();
103 if (!K) // YAMLParser emitted an error.
104 return false;
105 auto Key = Outer->scalarValue(*K, "Dictionary key");
106 if (!Key)
107 continue;
108 if (!Seen.insert(**Key).second) {
109 Outer->warning("Duplicate key " + **Key + " is ignored", *K);
110 continue;
111 }
112 auto *Value = KV.getValue();
113 if (!Value) // YAMLParser emitted an error.
114 return false;
115 bool Matched = false;
116 for (const auto &Handler : Keys) {
117 if (Handler.first == **Key) {
118 if (!Handler.second(*Value))
119 return false;
120 Matched = true;
121 break;
122 }
123 }
124 if (!Matched) {
125 Outer->warning("Unknown " + Description + " key " + **Key, *K);
126 if (Unknown)
127 Unknown(**Key);
128 }
129 }
130 return true;
131 }
132 };
133
134 // Try to parse a single scalar value from the node, warn on failure.
135 llvm::Optional<Located<std::string>> scalarValue(Node &N,
136 llvm::StringRef Desc) {
137 llvm::SmallString<256> Buf;
138 if (auto *S = llvm::dyn_cast<ScalarNode>(&N))
139 return Located<std::string>(S->getValue(Buf).str(), N.getSourceRange());
140 if (auto *BS = llvm::dyn_cast<BlockScalarNode>(&N))
141 return Located<std::string>(BS->getValue().str(), N.getSourceRange());
142 warning(Desc + " should be scalar", N);
143 return llvm::None;
144 }
145
146 // Try to parse a list of single scalar values, or just a single value.
147 llvm::Optional<std::vector<Located<std::string>>> scalarValues(Node &N) {
148 std::vector<Located<std::string>> Result;
149 if (auto *S = llvm::dyn_cast<ScalarNode>(&N)) {
150 llvm::SmallString<256> Buf;
151 Result.emplace_back(S->getValue(Buf).str(), N.getSourceRange());
152 } else if (auto *S = llvm::dyn_cast<BlockScalarNode>(&N)) {
153 Result.emplace_back(S->getValue().str(), N.getSourceRange());
154 } else if (auto *S = llvm::dyn_cast<SequenceNode>(&N)) {
155 for (auto &Child : *S) {
156 if (auto Value = scalarValue(Child, "List item"))
157 Result.push_back(std::move(*Value));
158 }
159 } else {
160 warning("Expected scalar or list of scalars", N);
161 return llvm::None;
162 }
163 return Result;
164 }
165
166 // Report a "hard" error, reflecting a config file that can never be valid.
167 void error(const llvm::Twine &Msg, const Node &N) {
168 SM.PrintMessage(N.getSourceRange().Start, llvm::SourceMgr::DK_Error, Msg,
169 N.getSourceRange());
170 }
171
172 // Report a "soft" error that could be caused by e.g. version skew.
173 void warning(const llvm::Twine &Msg, const Node &N) {
174 SM.PrintMessage(N.getSourceRange().Start, llvm::SourceMgr::DK_Warning, Msg,
175 N.getSourceRange());
176 }
177};
178
179} // namespace
180
181std::vector<Fragment> Fragment::parseYAML(llvm::StringRef YAML,
182 llvm::StringRef BufferName,
183 DiagnosticCallback Diags) {
184 // The YAML document may contain multiple conditional fragments.
185 // The SourceManager is shared for all of them.
186 auto SM = std::make_shared<llvm::SourceMgr>();
187 auto Buf = llvm::MemoryBuffer::getMemBufferCopy(YAML, BufferName);
188 // Adapt DiagnosticCallback to function-pointer interface.
189 // Callback receives both errors we emit and those from the YAML parser.
190 SM->setDiagHandler(
191 [](const llvm::SMDiagnostic &Diag, void *Ctx) {
192 (*reinterpret_cast<DiagnosticCallback *>(Ctx))(Diag);
193 },
194 &Diags);
195 std::vector<Fragment> Result;
196 for (auto &Doc : llvm::yaml::Stream(*Buf, *SM)) {
197 if (Node *N = Doc.parseBlockNode()) {
198 Fragment Fragment;
199 Fragment.Source.Manager = SM;
200 Fragment.Source.Location = N->getSourceRange().Start;
201 if (Parser(*SM).parse(Fragment, *N))
202 Result.push_back(std::move(Fragment));
203 }
204 }
205 // Hack: stash the buffer in the SourceMgr to keep it alive.
206 // SM has two entries: "main" non-owning buffer, and ignored owning buffer.
207 SM->AddNewSourceBuffer(std::move(Buf), llvm::SMLoc());
208 return Result;
209}
210
211} // namespace config
212} // namespace clangd
213} // namespace clang