1 //===--- ConfigCompile.cpp - Translating Fragments into Config ------------===//
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 // Fragments are applied to Configs in two steps:
10 //
11 // 1. (When the fragment is first loaded)
12 //    FragmentCompiler::compile() traverses the Fragment and creates
13 //    function objects that know how to apply the configuration.
14 // 2. (Every time a config is required)
15 //    CompiledFragment() executes these functions to populate the Config.
16 //
17 // Work could be split between these steps in different ways. We try to
18 // do as much work as possible in the first step. For example, regexes are
19 // compiled in stage 1 and captured by the apply function. This is because:
20 //
21 //  - it's more efficient, as the work done in stage 1 must only be done once
22 //  - problems can be reported in stage 1, in stage 2 we must silently recover
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "CompileCommands.h"
27 #include "Config.h"
28 #include "ConfigFragment.h"
29 #include "ConfigProvider.h"
30 #include "Diagnostics.h"
31 #include "Features.inc"
32 #include "TidyProvider.h"
33 #include "support/Logger.h"
34 #include "support/Path.h"
35 #include "support/Trace.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/FormatVariadic.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Regex.h"
48 #include "llvm/Support/SMLoc.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include <string>
51 
52 namespace clang {
53 namespace clangd {
54 namespace config {
55 namespace {
56 
57 // Returns an empty stringref if Path is not under FragmentDir. Returns Path
58 // as-is when FragmentDir is empty.
59 llvm::StringRef configRelative(llvm::StringRef Path,
60                                llvm::StringRef FragmentDir) {
61   if (FragmentDir.empty())
62     return Path;
63   if (!Path.consume_front(FragmentDir))
64     return llvm::StringRef();
65   return Path.empty() ? "." : Path;
66 }
67 
68 struct CompiledFragmentImpl {
69   // The independent conditions to check before using settings from this config.
70   // The following fragment has *two* conditions:
71   //   If: { Platform: [mac, linux], PathMatch: foo/.* }
72   // All of them must be satisfied: the platform and path conditions are ANDed.
73   // The OR logic for the platform condition is implemented inside the function.
74   std::vector<llvm::unique_function<bool(const Params &) const>> Conditions;
75   // Mutations that this fragment will apply to the configuration.
76   // These are invoked only if the conditions are satisfied.
77   std::vector<llvm::unique_function<void(const Params &, Config &) const>>
78       Apply;
79 
80   bool operator()(const Params &P, Config &C) const {
81     for (const auto &C : Conditions) {
82       if (!C(P)) {
83         dlog("Config fragment {0}: condition not met", this);
84         return false;
85       }
86     }
87     dlog("Config fragment {0}: applying {1} rules", this, Apply.size());
88     for (const auto &A : Apply)
89       A(P, C);
90     return true;
91   }
92 };
93 
94 // Wrapper around condition compile() functions to reduce arg-passing.
95 struct FragmentCompiler {
96   FragmentCompiler(CompiledFragmentImpl &Out, DiagnosticCallback D,
97                    llvm::SourceMgr *SM)
98       : Out(Out), Diagnostic(D), SourceMgr(SM) {}
99   CompiledFragmentImpl &Out;
100   DiagnosticCallback Diagnostic;
101   llvm::SourceMgr *SourceMgr;
102   // Normalized Fragment::SourceInfo::Directory.
103   std::string FragmentDirectory;
104 
105   llvm::Optional<llvm::Regex>
106   compileRegex(const Located<std::string> &Text,
107                llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags) {
108     std::string Anchored = "^(" + *Text + ")$";
109     llvm::Regex Result(Anchored, Flags);
110     std::string RegexError;
111     if (!Result.isValid(RegexError)) {
112       diag(Error, "Invalid regex " + Anchored + ": " + RegexError, Text.Range);
113       return llvm::None;
114     }
115     return Result;
116   }
117 
118   llvm::Optional<std::string> makeAbsolute(Located<std::string> Path,
119                                            llvm::StringLiteral Description,
120                                            llvm::sys::path::Style Style) {
121     if (llvm::sys::path::is_absolute(*Path))
122       return *Path;
123     if (FragmentDirectory.empty()) {
124       diag(Error,
125            llvm::formatv(
126                "{0} must be an absolute path, because this fragment is not "
127                "associated with any directory.",
128                Description)
129                .str(),
130            Path.Range);
131       return llvm::None;
132     }
133     llvm::SmallString<256> AbsPath = llvm::StringRef(*Path);
134     llvm::sys::fs::make_absolute(FragmentDirectory, AbsPath);
135     llvm::sys::path::native(AbsPath, Style);
136     return AbsPath.str().str();
137   }
138 
139   // Helper with similar API to StringSwitch, for parsing enum values.
140   template <typename T> class EnumSwitch {
141     FragmentCompiler &Outer;
142     llvm::StringRef EnumName;
143     const Located<std::string> &Input;
144     llvm::Optional<T> Result;
145     llvm::SmallVector<llvm::StringLiteral> ValidValues;
146 
147   public:
148     EnumSwitch(llvm::StringRef EnumName, const Located<std::string> &In,
149                FragmentCompiler &Outer)
150         : Outer(Outer), EnumName(EnumName), Input(In) {}
151 
152     EnumSwitch &map(llvm::StringLiteral Name, T Value) {
153       assert(!llvm::is_contained(ValidValues, Name) && "Duplicate value!");
154       ValidValues.push_back(Name);
155       if (!Result && *Input == Name)
156         Result = Value;
157       return *this;
158     }
159 
160     llvm::Optional<T> value() {
161       if (!Result)
162         Outer.diag(
163             Warning,
164             llvm::formatv("Invalid {0} value '{1}'. Valid values are {2}.",
165                           EnumName, *Input, llvm::join(ValidValues, ", "))
166                 .str(),
167             Input.Range);
168       return Result;
169     };
170   };
171 
172   // Attempt to parse a specified string into an enum.
173   // Yields llvm::None and produces a diagnostic on failure.
174   //
175   // Optional<T> Value = compileEnum<En>("Foo", Frag.Foo)
176   //    .map("Foo", Enum::Foo)
177   //    .map("Bar", Enum::Bar)
178   //    .value();
179   template <typename T>
180   EnumSwitch<T> compileEnum(llvm::StringRef EnumName,
181                             const Located<std::string> &In) {
182     return EnumSwitch<T>(EnumName, In, *this);
183   }
184 
185   void compile(Fragment &&F) {
186     if (!F.Source.Directory.empty()) {
187       FragmentDirectory = llvm::sys::path::convert_to_slash(F.Source.Directory);
188       if (FragmentDirectory.back() != '/')
189         FragmentDirectory += '/';
190     }
191     compile(std::move(F.If));
192     compile(std::move(F.CompileFlags));
193     compile(std::move(F.Index));
194     compile(std::move(F.Diagnostics));
195   }
196 
197   void compile(Fragment::IfBlock &&F) {
198     if (F.HasUnrecognizedCondition)
199       Out.Conditions.push_back([&](const Params &) { return false; });
200 
201 #ifdef CLANGD_PATH_CASE_INSENSITIVE
202     llvm::Regex::RegexFlags Flags = llvm::Regex::IgnoreCase;
203 #else
204     llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags;
205 #endif
206 
207     auto PathMatch = std::make_unique<std::vector<llvm::Regex>>();
208     for (auto &Entry : F.PathMatch) {
209       if (auto RE = compileRegex(Entry, Flags))
210         PathMatch->push_back(std::move(*RE));
211     }
212     if (!PathMatch->empty()) {
213       Out.Conditions.push_back(
214           [PathMatch(std::move(PathMatch)),
215            FragmentDir(FragmentDirectory)](const Params &P) {
216             if (P.Path.empty())
217               return false;
218             llvm::StringRef Path = configRelative(P.Path, FragmentDir);
219             // Ignore the file if it is not nested under Fragment.
220             if (Path.empty())
221               return false;
222             return llvm::any_of(*PathMatch, [&](const llvm::Regex &RE) {
223               return RE.match(Path);
224             });
225           });
226     }
227 
228     auto PathExclude = std::make_unique<std::vector<llvm::Regex>>();
229     for (auto &Entry : F.PathExclude) {
230       if (auto RE = compileRegex(Entry, Flags))
231         PathExclude->push_back(std::move(*RE));
232     }
233     if (!PathExclude->empty()) {
234       Out.Conditions.push_back(
235           [PathExclude(std::move(PathExclude)),
236            FragmentDir(FragmentDirectory)](const Params &P) {
237             if (P.Path.empty())
238               return false;
239             llvm::StringRef Path = configRelative(P.Path, FragmentDir);
240             // Ignore the file if it is not nested under Fragment.
241             if (Path.empty())
242               return true;
243             return llvm::none_of(*PathExclude, [&](const llvm::Regex &RE) {
244               return RE.match(Path);
245             });
246           });
247     }
248   }
249 
250   void compile(Fragment::CompileFlagsBlock &&F) {
251     if (!F.Remove.empty()) {
252       auto Remove = std::make_shared<ArgStripper>();
253       for (auto &A : F.Remove)
254         Remove->strip(*A);
255       Out.Apply.push_back([Remove(std::shared_ptr<const ArgStripper>(
256                               std::move(Remove)))](const Params &, Config &C) {
257         C.CompileFlags.Edits.push_back(
258             [Remove](std::vector<std::string> &Args) {
259               Remove->process(Args);
260             });
261       });
262     }
263 
264     if (!F.Add.empty()) {
265       std::vector<std::string> Add;
266       for (auto &A : F.Add)
267         Add.push_back(std::move(*A));
268       Out.Apply.push_back([Add(std::move(Add))](const Params &, Config &C) {
269         C.CompileFlags.Edits.push_back([Add](std::vector<std::string> &Args) {
270           Args.insert(Args.end(), Add.begin(), Add.end());
271         });
272       });
273     }
274 
275     if (F.CompilationDatabase) {
276       llvm::Optional<Config::CDBSearchSpec> Spec;
277       if (**F.CompilationDatabase == "Ancestors") {
278         Spec.emplace();
279         Spec->Policy = Config::CDBSearchSpec::Ancestors;
280       } else if (**F.CompilationDatabase == "None") {
281         Spec.emplace();
282         Spec->Policy = Config::CDBSearchSpec::NoCDBSearch;
283       } else {
284         if (auto Path =
285                 makeAbsolute(*F.CompilationDatabase, "CompilationDatabase",
286                              llvm::sys::path::Style::native)) {
287           // Drop trailing slash to put the path in canonical form.
288           // Should makeAbsolute do this?
289           llvm::StringRef Rel = llvm::sys::path::relative_path(*Path);
290           if (!Rel.empty() && llvm::sys::path::is_separator(Rel.back()))
291             Path->pop_back();
292 
293           Spec.emplace();
294           Spec->Policy = Config::CDBSearchSpec::FixedDir;
295           Spec->FixedCDBPath = std::move(Path);
296         }
297       }
298       if (Spec)
299         Out.Apply.push_back(
300             [Spec(std::move(*Spec))](const Params &, Config &C) {
301               C.CompileFlags.CDBSearch = Spec;
302             });
303     }
304   }
305 
306   void compile(Fragment::IndexBlock &&F) {
307     if (F.Background) {
308       if (auto Val = compileEnum<Config::BackgroundPolicy>("Background",
309                                                            **F.Background)
310                          .map("Build", Config::BackgroundPolicy::Build)
311                          .map("Skip", Config::BackgroundPolicy::Skip)
312                          .value())
313         Out.Apply.push_back(
314             [Val](const Params &, Config &C) { C.Index.Background = *Val; });
315     }
316     if (F.External)
317       compile(std::move(**F.External), F.External->Range);
318   }
319 
320   void compile(Fragment::IndexBlock::ExternalBlock &&External,
321                llvm::SMRange BlockRange) {
322 #ifndef CLANGD_ENABLE_REMOTE
323     if (External.Server) {
324       diag(Error, "Clangd isn't compiled with remote index support, ignoring "
325                   "Server." External.Server->Range);
326       External.Server.reset();
327     }
328 #endif
329     // Make sure exactly one of the Sources is set.
330     unsigned SourceCount =
331         External.File.hasValue() + External.Server.hasValue();
332     if (SourceCount != 1) {
333       diag(Error, "Exactly one of File or Server must be set.", BlockRange);
334       return;
335     }
336     Config::ExternalIndexSpec Spec;
337     if (External.Server) {
338       Spec.Kind = Config::ExternalIndexSpec::Server;
339       Spec.Location = std::move(**External.Server);
340     } else if (External.File) {
341       Spec.Kind = Config::ExternalIndexSpec::File;
342       auto AbsPath = makeAbsolute(std::move(*External.File), "File",
343                                   llvm::sys::path::Style::native);
344       if (!AbsPath)
345         return;
346       Spec.Location = std::move(*AbsPath);
347     }
348     // Make sure MountPoint is an absolute path with forward slashes.
349     if (!External.MountPoint)
350       External.MountPoint.emplace(FragmentDirectory);
351     if ((**External.MountPoint).empty()) {
352       diag(Error, "A mountpoint is required.", BlockRange);
353       return;
354     }
355     auto AbsPath = makeAbsolute(std::move(*External.MountPoint), "MountPoint",
356                                 llvm::sys::path::Style::posix);
357     if (!AbsPath)
358       return;
359     Spec.MountPoint = std::move(*AbsPath);
360     Out.Apply.push_back([Spec(std::move(Spec))](const Params &P, Config &C) {
361       if (P.Path.empty() || !pathStartsWith(Spec.MountPoint, P.Path,
362                                             llvm::sys::path::Style::posix))
363         return;
364       C.Index.External = Spec;
365       // Disable background indexing for the files under the mountpoint.
366       // Note that this will overwrite statements in any previous fragments
367       // (including the current one).
368       C.Index.Background = Config::BackgroundPolicy::Skip;
369     });
370   }
371 
372   void compile(Fragment::DiagnosticsBlock &&F) {
373     std::vector<llvm::StringRef> Normalized;
374     for (const auto &Suppressed : F.Suppress) {
375       if (*Suppressed == "*") {
376         Out.Apply.push_back([&](const Params &, Config &C) {
377           C.Diagnostics.SuppressAll = true;
378           C.Diagnostics.Suppress.clear();
379         });
380         return;
381       }
382       Normalized.push_back(normalizeSuppressedCode(*Suppressed));
383     }
384     if (!Normalized.empty())
385       Out.Apply.push_back([Normalized](const Params &, Config &C) {
386         if (C.Diagnostics.SuppressAll)
387           return;
388         for (llvm::StringRef N : Normalized)
389           C.Diagnostics.Suppress.insert(N);
390       });
391 
392     compile(std::move(F.ClangTidy));
393   }
394 
395   void compile(Fragment::StyleBlock &&F) {
396     if (!F.FullyQualifiedNamespaces.empty()) {
397       std::vector<std::string> FullyQualifiedNamespaces;
398       for (auto &N : F.FullyQualifiedNamespaces) {
399         // Normalize the data by dropping both leading and trailing ::
400         StringRef Namespace(*N);
401         Namespace.consume_front("::");
402         Namespace.consume_back("::");
403         FullyQualifiedNamespaces.push_back(Namespace.str());
404       }
405       Out.Apply.push_back([FullyQualifiedNamespaces(
406                               std::move(FullyQualifiedNamespaces))](
407                               const Params &, Config &C) {
408         C.Style.FullyQualifiedNamespaces.insert(
409             C.Style.FullyQualifiedNamespaces.begin(),
410             FullyQualifiedNamespaces.begin(), FullyQualifiedNamespaces.end());
411       });
412     }
413   }
414 
415   void appendTidyCheckSpec(std::string &CurSpec,
416                            const Located<std::string> &Arg, bool IsPositive) {
417     StringRef Str = StringRef(*Arg).trim();
418     // Don't support negating here, its handled if the item is in the Add or
419     // Remove list.
420     if (Str.startswith("-") || Str.contains(',')) {
421       diag(Error, "Invalid clang-tidy check name", Arg.Range);
422       return;
423     }
424     if (!Str.contains('*') && !isRegisteredTidyCheck(Str)) {
425       diag(Warning,
426            llvm::formatv("clang-tidy check '{0}' was not found", Str).str(),
427            Arg.Range);
428       return;
429     }
430     CurSpec += ',';
431     if (!IsPositive)
432       CurSpec += '-';
433     CurSpec += Str;
434   }
435 
436   void compile(Fragment::DiagnosticsBlock::ClangTidyBlock &&F) {
437     std::string Checks;
438     for (auto &CheckGlob : F.Add)
439       appendTidyCheckSpec(Checks, CheckGlob, true);
440 
441     for (auto &CheckGlob : F.Remove)
442       appendTidyCheckSpec(Checks, CheckGlob, false);
443 
444     if (!Checks.empty())
445       Out.Apply.push_back(
446           [Checks = std::move(Checks)](const Params &, Config &C) {
447             C.Diagnostics.ClangTidy.Checks.append(
448                 Checks,
449                 C.Diagnostics.ClangTidy.Checks.empty() ? /*skip comma*/ 1 : 0,
450                 std::string::npos);
451           });
452     if (!F.CheckOptions.empty()) {
453       std::vector<std::pair<std::string, std::string>> CheckOptions;
454       for (auto &Opt : F.CheckOptions)
455         CheckOptions.emplace_back(std::move(*Opt.first),
456                                   std::move(*Opt.second));
457       Out.Apply.push_back(
458           [CheckOptions = std::move(CheckOptions)](const Params &, Config &C) {
459             for (auto &StringPair : CheckOptions)
460               C.Diagnostics.ClangTidy.CheckOptions.insert_or_assign(
461                   StringPair.first, StringPair.second);
462           });
463     }
464   }
465 
466   constexpr static llvm::SourceMgr::DiagKind Error = llvm::SourceMgr::DK_Error;
467   constexpr static llvm::SourceMgr::DiagKind Warning =
468       llvm::SourceMgr::DK_Warning;
469   void diag(llvm::SourceMgr::DiagKind Kind, llvm::StringRef Message,
470             llvm::SMRange Range) {
471     if (Range.isValid() && SourceMgr != nullptr)
472       Diagnostic(SourceMgr->GetMessage(Range.Start, Kind, Message, Range));
473     else
474       Diagnostic(llvm::SMDiagnostic("", Kind, Message));
475   }
476 };
477 
478 } // namespace
479 
480 CompiledFragment Fragment::compile(DiagnosticCallback D) && {
481   llvm::StringRef ConfigFile = "<unknown>";
482   std::pair<unsigned, unsigned> LineCol = {0, 0};
483   if (auto *SM = Source.Manager.get()) {
484     unsigned BufID = SM->getMainFileID();
485     LineCol = SM->getLineAndColumn(Source.Location, BufID);
486     ConfigFile = SM->getBufferInfo(BufID).Buffer->getBufferIdentifier();
487   }
488   trace::Span Tracer("ConfigCompile");
489   SPAN_ATTACH(Tracer, "ConfigFile", ConfigFile);
490   auto Result = std::make_shared<CompiledFragmentImpl>();
491   vlog("Config fragment: compiling {0}:{1} -> {2}", ConfigFile, LineCol.first,
492        Result.get());
493 
494   FragmentCompiler{*Result, D, Source.Manager.get()}.compile(std::move(*this));
495   // Return as cheaply-copyable wrapper.
496   return [Result(std::move(Result))](const Params &P, Config &C) {
497     return (*Result)(P, C);
498   };
499 }
500 
501 } // namespace config
502 } // namespace clangd
503 } // namespace clang
504