clang-tools 20.0.0git
ConfigCompile.cpp
Go to the documentation of this file.
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 "Feature.h"
32#include "TidyProvider.h"
33#include "support/Logger.h"
34#include "support/Path.h"
35#include "support/Trace.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/ADT/StringRef.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/FormatVariadic.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/Regex.h"
44#include "llvm/Support/SMLoc.h"
45#include "llvm/Support/SourceMgr.h"
46#include <memory>
47#include <optional>
48#include <string>
49#include <vector>
50
51namespace clang {
52namespace clangd {
53namespace config {
54namespace {
55
56// Returns an empty stringref if Path is not under FragmentDir. Returns Path
57// as-is when FragmentDir is empty.
58llvm::StringRef configRelative(llvm::StringRef Path,
59 llvm::StringRef FragmentDir) {
60 if (FragmentDir.empty())
61 return Path;
62 if (!Path.consume_front(FragmentDir))
63 return llvm::StringRef();
64 return Path.empty() ? "." : Path;
65}
66
67struct CompiledFragmentImpl {
68 // The independent conditions to check before using settings from this config.
69 // The following fragment has *two* conditions:
70 // If: { Platform: [mac, linux], PathMatch: foo/.* }
71 // All of them must be satisfied: the platform and path conditions are ANDed.
72 // The OR logic for the platform condition is implemented inside the function.
73 std::vector<llvm::unique_function<bool(const Params &) const>> Conditions;
74 // Mutations that this fragment will apply to the configuration.
75 // These are invoked only if the conditions are satisfied.
76 std::vector<llvm::unique_function<void(const Params &, Config &) const>>
78
79 bool operator()(const Params &P, Config &C) const {
80 for (const auto &C : Conditions) {
81 if (!C(P)) {
82 dlog("Config fragment {0}: condition not met", this);
83 return false;
84 }
85 }
86 dlog("Config fragment {0}: applying {1} rules", this, Apply.size());
87 for (const auto &A : Apply)
88 A(P, C);
89 return true;
90 }
91};
92
93// Wrapper around condition compile() functions to reduce arg-passing.
94struct FragmentCompiler {
95 FragmentCompiler(CompiledFragmentImpl &Out, DiagnosticCallback D,
96 llvm::SourceMgr *SM)
97 : Out(Out), Diagnostic(D), SourceMgr(SM) {}
98 CompiledFragmentImpl &Out;
100 llvm::SourceMgr *SourceMgr;
101 // Normalized Fragment::SourceInfo::Directory.
102 std::string FragmentDirectory;
103 bool Trusted = false;
104
105 std::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 std::nullopt;
114 }
115 return std::move(Result);
116 }
117
118 std::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 std::nullopt;
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 std::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 std::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 std::nullopt and produces a diagnostic on failure.
174 //
175 // std::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 Trusted = F.Source.Trusted;
187 if (!F.Source.Directory.empty()) {
188 FragmentDirectory = llvm::sys::path::convert_to_slash(F.Source.Directory);
189 if (FragmentDirectory.back() != '/')
190 FragmentDirectory += '/';
191 }
192 compile(std::move(F.If));
193 compile(std::move(F.CompileFlags));
194 compile(std::move(F.Index));
195 compile(std::move(F.Diagnostics));
196 compile(std::move(F.Completion));
197 compile(std::move(F.Hover));
198 compile(std::move(F.InlayHints));
199 compile(std::move(F.SemanticTokens));
200 compile(std::move(F.Style));
201 }
202
203 void compile(Fragment::IfBlock &&F) {
204 if (F.HasUnrecognizedCondition)
205 Out.Conditions.push_back([&](const Params &) { return false; });
206
207#ifdef CLANGD_PATH_CASE_INSENSITIVE
208 llvm::Regex::RegexFlags Flags = llvm::Regex::IgnoreCase;
209#else
210 llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags;
211#endif
212
213 auto PathMatch = std::make_unique<std::vector<llvm::Regex>>();
214 for (auto &Entry : F.PathMatch) {
215 if (auto RE = compileRegex(Entry, Flags))
216 PathMatch->push_back(std::move(*RE));
217 }
218 if (!PathMatch->empty()) {
219 Out.Conditions.push_back(
220 [PathMatch(std::move(PathMatch)),
221 FragmentDir(FragmentDirectory)](const Params &P) {
222 if (P.Path.empty())
223 return false;
224 llvm::StringRef Path = configRelative(P.Path, FragmentDir);
225 // Ignore the file if it is not nested under Fragment.
226 if (Path.empty())
227 return false;
228 return llvm::any_of(*PathMatch, [&](const llvm::Regex &RE) {
229 return RE.match(Path);
230 });
231 });
232 }
233
234 auto PathExclude = std::make_unique<std::vector<llvm::Regex>>();
235 for (auto &Entry : F.PathExclude) {
236 if (auto RE = compileRegex(Entry, Flags))
237 PathExclude->push_back(std::move(*RE));
238 }
239 if (!PathExclude->empty()) {
240 Out.Conditions.push_back(
241 [PathExclude(std::move(PathExclude)),
242 FragmentDir(FragmentDirectory)](const Params &P) {
243 if (P.Path.empty())
244 return false;
245 llvm::StringRef Path = configRelative(P.Path, FragmentDir);
246 // Ignore the file if it is not nested under Fragment.
247 if (Path.empty())
248 return true;
249 return llvm::none_of(*PathExclude, [&](const llvm::Regex &RE) {
250 return RE.match(Path);
251 });
252 });
253 }
254 }
255
256 void compile(Fragment::CompileFlagsBlock &&F) {
257 if (F.Compiler)
258 Out.Apply.push_back(
259 [Compiler(std::move(**F.Compiler))](const Params &, Config &C) {
260 C.CompileFlags.Edits.push_back(
261 [Compiler](std::vector<std::string> &Args) {
262 if (!Args.empty())
263 Args.front() = Compiler;
264 });
265 });
266
267 if (!F.Remove.empty()) {
268 auto Remove = std::make_shared<ArgStripper>();
269 for (auto &A : F.Remove)
270 Remove->strip(*A);
271 Out.Apply.push_back([Remove(std::shared_ptr<const ArgStripper>(
272 std::move(Remove)))](const Params &, Config &C) {
273 C.CompileFlags.Edits.push_back(
274 [Remove](std::vector<std::string> &Args) {
275 Remove->process(Args);
276 });
277 });
278 }
279
280 if (!F.Add.empty()) {
281 std::vector<std::string> Add;
282 for (auto &A : F.Add)
283 Add.push_back(std::move(*A));
284 Out.Apply.push_back([Add(std::move(Add))](const Params &, Config &C) {
285 C.CompileFlags.Edits.push_back([Add](std::vector<std::string> &Args) {
286 // The point to insert at. Just append when `--` isn't present.
287 auto It = llvm::find(Args, "--");
288 Args.insert(It, Add.begin(), Add.end());
289 });
290 });
291 }
292
293 if (F.CompilationDatabase) {
294 std::optional<Config::CDBSearchSpec> Spec;
295 if (**F.CompilationDatabase == "Ancestors") {
296 Spec.emplace();
298 } else if (**F.CompilationDatabase == "None") {
299 Spec.emplace();
301 } else {
302 if (auto Path =
303 makeAbsolute(*F.CompilationDatabase, "CompilationDatabase",
304 llvm::sys::path::Style::native)) {
305 // Drop trailing slash to put the path in canonical form.
306 // Should makeAbsolute do this?
307 llvm::StringRef Rel = llvm::sys::path::relative_path(*Path);
308 if (!Rel.empty() && llvm::sys::path::is_separator(Rel.back()))
309 Path->pop_back();
310
311 Spec.emplace();
312 Spec->Policy = Config::CDBSearchSpec::FixedDir;
313 Spec->FixedCDBPath = std::move(Path);
314 }
315 }
316 if (Spec)
317 Out.Apply.push_back(
318 [Spec(std::move(*Spec))](const Params &, Config &C) {
319 C.CompileFlags.CDBSearch = Spec;
320 });
321 }
322 }
323
324 void compile(Fragment::IndexBlock &&F) {
325 if (F.Background) {
326 if (auto Val =
327 compileEnum<Config::BackgroundPolicy>("Background", *F.Background)
330 .value())
331 Out.Apply.push_back(
332 [Val](const Params &, Config &C) { C.Index.Background = *Val; });
333 }
334 if (F.External)
335 compile(std::move(**F.External), F.External->Range);
336 if (F.StandardLibrary)
337 Out.Apply.push_back(
338 [Val(**F.StandardLibrary)](const Params &, Config &C) {
339 C.Index.StandardLibrary = Val;
340 });
341 }
342
343 void compile(Fragment::IndexBlock::ExternalBlock &&External,
344 llvm::SMRange BlockRange) {
345 if (External.Server && !Trusted) {
346 diag(Error,
347 "Remote index may not be specified by untrusted configuration. "
348 "Copy this into user config to use it.",
349 External.Server->Range);
350 return;
351 }
352#ifndef CLANGD_ENABLE_REMOTE
353 if (External.Server) {
354 elog("Clangd isn't compiled with remote index support, ignoring Server: "
355 "{0}",
356 *External.Server);
357 External.Server.reset();
358 }
359#endif
360 // Make sure exactly one of the Sources is set.
361 unsigned SourceCount = External.File.has_value() +
362 External.Server.has_value() + *External.IsNone;
363 if (SourceCount != 1) {
364 diag(Error, "Exactly one of File, Server or None must be set.",
365 BlockRange);
366 return;
367 }
368 Config::ExternalIndexSpec Spec;
369 if (External.Server) {
371 Spec.Location = std::move(**External.Server);
372 } else if (External.File) {
374 auto AbsPath = makeAbsolute(std::move(*External.File), "File",
375 llvm::sys::path::Style::native);
376 if (!AbsPath)
377 return;
378 Spec.Location = std::move(*AbsPath);
379 } else {
380 assert(*External.IsNone);
382 }
383 if (Spec.Kind != Config::ExternalIndexSpec::None) {
384 // Make sure MountPoint is an absolute path with forward slashes.
385 if (!External.MountPoint)
386 External.MountPoint.emplace(FragmentDirectory);
387 if ((**External.MountPoint).empty()) {
388 diag(Error, "A mountpoint is required.", BlockRange);
389 return;
390 }
391 auto AbsPath = makeAbsolute(std::move(*External.MountPoint), "MountPoint",
392 llvm::sys::path::Style::posix);
393 if (!AbsPath)
394 return;
395 Spec.MountPoint = std::move(*AbsPath);
396 }
397 Out.Apply.push_back([Spec(std::move(Spec))](const Params &P, Config &C) {
398 if (Spec.Kind == Config::ExternalIndexSpec::None) {
399 C.Index.External = Spec;
400 return;
401 }
402 if (P.Path.empty() || !pathStartsWith(Spec.MountPoint, P.Path,
403 llvm::sys::path::Style::posix))
404 return;
405 C.Index.External = Spec;
406 // Disable background indexing for the files under the mountpoint.
407 // Note that this will overwrite statements in any previous fragments
408 // (including the current one).
409 C.Index.Background = Config::BackgroundPolicy::Skip;
410 });
411 }
412
413 void compile(Fragment::DiagnosticsBlock &&F) {
414 std::vector<std::string> Normalized;
415 for (const auto &Suppressed : F.Suppress) {
416 if (*Suppressed == "*") {
417 Out.Apply.push_back([&](const Params &, Config &C) {
418 C.Diagnostics.SuppressAll = true;
419 C.Diagnostics.Suppress.clear();
420 });
421 return;
422 }
423 Normalized.push_back(normalizeSuppressedCode(*Suppressed).str());
424 }
425 if (!Normalized.empty())
426 Out.Apply.push_back(
427 [Normalized(std::move(Normalized))](const Params &, Config &C) {
428 if (C.Diagnostics.SuppressAll)
429 return;
430 for (llvm::StringRef N : Normalized)
431 C.Diagnostics.Suppress.insert(N);
432 });
433
434 if (F.UnusedIncludes) {
435 auto Val = compileEnum<Config::IncludesPolicy>("UnusedIncludes",
436 **F.UnusedIncludes)
437 .map("Strict", Config::IncludesPolicy::Strict)
438 .map("None", Config::IncludesPolicy::None)
439 .value();
440 if (!Val && **F.UnusedIncludes == "Experiment") {
441 diag(Warning,
442 "Experiment is deprecated for UnusedIncludes, use Strict instead.",
443 F.UnusedIncludes->Range);
445 }
446 if (Val) {
447 Out.Apply.push_back([Val](const Params &, Config &C) {
448 C.Diagnostics.UnusedIncludes = *Val;
449 });
450 }
451 }
452
453 if (F.MissingIncludes)
454 if (auto Val = compileEnum<Config::IncludesPolicy>("MissingIncludes",
455 **F.MissingIncludes)
456 .map("Strict", Config::IncludesPolicy::Strict)
457 .map("None", Config::IncludesPolicy::None)
458 .value())
459 Out.Apply.push_back([Val](const Params &, Config &C) {
460 C.Diagnostics.MissingIncludes = *Val;
461 });
462
463 compile(std::move(F.Includes));
464 compile(std::move(F.ClangTidy));
465 }
466
467 void compile(Fragment::StyleBlock &&F) {
468 if (!F.FullyQualifiedNamespaces.empty()) {
469 std::vector<std::string> FullyQualifiedNamespaces;
470 for (auto &N : F.FullyQualifiedNamespaces) {
471 // Normalize the data by dropping both leading and trailing ::
472 StringRef Namespace(*N);
473 Namespace.consume_front("::");
474 Namespace.consume_back("::");
475 FullyQualifiedNamespaces.push_back(Namespace.str());
476 }
477 Out.Apply.push_back([FullyQualifiedNamespaces(
478 std::move(FullyQualifiedNamespaces))](
479 const Params &, Config &C) {
480 C.Style.FullyQualifiedNamespaces.insert(
481 C.Style.FullyQualifiedNamespaces.begin(),
482 FullyQualifiedNamespaces.begin(), FullyQualifiedNamespaces.end());
483 });
484 }
485 }
486
487 void appendTidyCheckSpec(std::string &CurSpec,
488 const Located<std::string> &Arg, bool IsPositive) {
489 StringRef Str = StringRef(*Arg).trim();
490 // Don't support negating here, its handled if the item is in the Add or
491 // Remove list.
492 if (Str.starts_with("-") || Str.contains(',')) {
493 diag(Error, "Invalid clang-tidy check name", Arg.Range);
494 return;
495 }
496 if (!Str.contains('*')) {
497 if (!isRegisteredTidyCheck(Str)) {
498 diag(Warning,
499 llvm::formatv("clang-tidy check '{0}' was not found", Str).str(),
500 Arg.Range);
501 return;
502 }
503 auto Fast = isFastTidyCheck(Str);
504 if (!Fast.has_value()) {
505 diag(Warning,
506 llvm::formatv(
507 "Latency of clang-tidy check '{0}' is not known. "
508 "It will only run if ClangTidy.FastCheckFilter is Loose or None",
509 Str)
510 .str(),
511 Arg.Range);
512 } else if (!*Fast) {
513 diag(Warning,
514 llvm::formatv(
515 "clang-tidy check '{0}' is slow. "
516 "It will only run if ClangTidy.FastCheckFilter is None",
517 Str)
518 .str(),
519 Arg.Range);
520 }
521 }
522 CurSpec += ',';
523 if (!IsPositive)
524 CurSpec += '-';
525 CurSpec += Str;
526 }
527
528 void compile(Fragment::DiagnosticsBlock::ClangTidyBlock &&F) {
529 std::string Checks;
530 for (auto &CheckGlob : F.Add)
531 appendTidyCheckSpec(Checks, CheckGlob, true);
532
533 for (auto &CheckGlob : F.Remove)
534 appendTidyCheckSpec(Checks, CheckGlob, false);
535
536 if (!Checks.empty())
537 Out.Apply.push_back(
538 [Checks = std::move(Checks)](const Params &, Config &C) {
539 C.Diagnostics.ClangTidy.Checks.append(
540 Checks,
541 C.Diagnostics.ClangTidy.Checks.empty() ? /*skip comma*/ 1 : 0,
542 std::string::npos);
543 });
544 if (!F.CheckOptions.empty()) {
545 std::vector<std::pair<std::string, std::string>> CheckOptions;
546 for (auto &Opt : F.CheckOptions)
547 CheckOptions.emplace_back(std::move(*Opt.first),
548 std::move(*Opt.second));
549 Out.Apply.push_back(
550 [CheckOptions = std::move(CheckOptions)](const Params &, Config &C) {
551 for (auto &StringPair : CheckOptions)
552 C.Diagnostics.ClangTidy.CheckOptions.insert_or_assign(
553 StringPair.first, StringPair.second);
554 });
555 }
556 if (F.FastCheckFilter.has_value())
557 if (auto Val = compileEnum<Config::FastCheckPolicy>("FastCheckFilter",
558 *F.FastCheckFilter)
559 .map("Strict", Config::FastCheckPolicy::Strict)
560 .map("Loose", Config::FastCheckPolicy::Loose)
562 .value())
563 Out.Apply.push_back([Val](const Params &, Config &C) {
564 C.Diagnostics.ClangTidy.FastCheckFilter = *Val;
565 });
566 }
567
568 void compile(Fragment::DiagnosticsBlock::IncludesBlock &&F) {
569#ifdef CLANGD_PATH_CASE_INSENSITIVE
570 static llvm::Regex::RegexFlags Flags = llvm::Regex::IgnoreCase;
571#else
572 static llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags;
573#endif
574 std::shared_ptr<std::vector<llvm::Regex>> Filters;
575 if (!F.IgnoreHeader.empty()) {
576 Filters = std::make_shared<std::vector<llvm::Regex>>();
577 for (auto &HeaderPattern : F.IgnoreHeader) {
578 // Anchor on the right.
579 std::string AnchoredPattern = "(" + *HeaderPattern + ")$";
580 llvm::Regex CompiledRegex(AnchoredPattern, Flags);
581 std::string RegexError;
582 if (!CompiledRegex.isValid(RegexError)) {
583 diag(Warning,
584 llvm::formatv("Invalid regular expression '{0}': {1}",
585 *HeaderPattern, RegexError)
586 .str(),
587 HeaderPattern.Range);
588 continue;
589 }
590 Filters->push_back(std::move(CompiledRegex));
591 }
592 }
593 // Optional to override the resulting AnalyzeAngledIncludes
594 // only if it's explicitly set in the current fragment.
595 // Otherwise it's inherited from parent fragment.
596 std::optional<bool> AnalyzeAngledIncludes;
597 if (F.AnalyzeAngledIncludes.has_value())
598 AnalyzeAngledIncludes = **F.AnalyzeAngledIncludes;
599 if (!Filters && !AnalyzeAngledIncludes.has_value())
600 return;
601 Out.Apply.push_back([Filters = std::move(Filters),
602 AnalyzeAngledIncludes](const Params &, Config &C) {
603 if (Filters) {
604 auto Filter = [Filters](llvm::StringRef Path) {
605 for (auto &Regex : *Filters)
606 if (Regex.match(Path))
607 return true;
608 return false;
609 };
610 C.Diagnostics.Includes.IgnoreHeader.emplace_back(std::move(Filter));
611 }
612 if (AnalyzeAngledIncludes.has_value())
613 C.Diagnostics.Includes.AnalyzeAngledIncludes = *AnalyzeAngledIncludes;
614 });
615 }
616
617 void compile(Fragment::CompletionBlock &&F) {
618 if (F.AllScopes) {
619 Out.Apply.push_back(
620 [AllScopes(**F.AllScopes)](const Params &, Config &C) {
621 C.Completion.AllScopes = AllScopes;
622 });
623 }
624 if (F.ArgumentLists) {
625 if (auto Val =
626 compileEnum<Config::ArgumentListsPolicy>("ArgumentLists",
627 *F.ArgumentLists)
629 .map("OpenDelimiter",
632 .map("FullPlaceholders",
634 .value())
635 Out.Apply.push_back([Val](const Params &, Config &C) {
636 C.Completion.ArgumentLists = *Val;
637 });
638 }
639 }
640
641 void compile(Fragment::HoverBlock &&F) {
642 if (F.ShowAKA) {
643 Out.Apply.push_back([ShowAKA(**F.ShowAKA)](const Params &, Config &C) {
644 C.Hover.ShowAKA = ShowAKA;
645 });
646 }
647 }
648
649 void compile(Fragment::InlayHintsBlock &&F) {
650 if (F.Enabled)
651 Out.Apply.push_back([Value(**F.Enabled)](const Params &, Config &C) {
652 C.InlayHints.Enabled = Value;
653 });
654 if (F.ParameterNames)
655 Out.Apply.push_back(
656 [Value(**F.ParameterNames)](const Params &, Config &C) {
657 C.InlayHints.Parameters = Value;
658 });
659 if (F.DeducedTypes)
660 Out.Apply.push_back([Value(**F.DeducedTypes)](const Params &, Config &C) {
661 C.InlayHints.DeducedTypes = Value;
662 });
663 if (F.Designators)
664 Out.Apply.push_back([Value(**F.Designators)](const Params &, Config &C) {
665 C.InlayHints.Designators = Value;
666 });
667 if (F.BlockEnd)
668 Out.Apply.push_back([Value(**F.BlockEnd)](const Params &, Config &C) {
669 C.InlayHints.BlockEnd = Value;
670 });
671 if (F.DefaultArguments)
672 Out.Apply.push_back(
673 [Value(**F.DefaultArguments)](const Params &, Config &C) {
674 C.InlayHints.DefaultArguments = Value;
675 });
676 if (F.TypeNameLimit)
677 Out.Apply.push_back(
678 [Value(**F.TypeNameLimit)](const Params &, Config &C) {
679 C.InlayHints.TypeNameLimit = Value;
680 });
681 }
682
683 void compile(Fragment::SemanticTokensBlock &&F) {
684 if (!F.DisabledKinds.empty()) {
685 std::vector<std::string> DisabledKinds;
686 for (auto &Kind : F.DisabledKinds)
687 DisabledKinds.push_back(std::move(*Kind));
688
689 Out.Apply.push_back(
690 [DisabledKinds(std::move(DisabledKinds))](const Params &, Config &C) {
691 for (auto &Kind : DisabledKinds) {
692 auto It = llvm::find(C.SemanticTokens.DisabledKinds, Kind);
693 if (It == C.SemanticTokens.DisabledKinds.end())
694 C.SemanticTokens.DisabledKinds.push_back(std::move(Kind));
695 }
696 });
697 }
698 if (!F.DisabledModifiers.empty()) {
699 std::vector<std::string> DisabledModifiers;
700 for (auto &Kind : F.DisabledModifiers)
701 DisabledModifiers.push_back(std::move(*Kind));
702
703 Out.Apply.push_back([DisabledModifiers(std::move(DisabledModifiers))](
704 const Params &, Config &C) {
705 for (auto &Kind : DisabledModifiers) {
706 auto It = llvm::find(C.SemanticTokens.DisabledModifiers, Kind);
707 if (It == C.SemanticTokens.DisabledModifiers.end())
708 C.SemanticTokens.DisabledModifiers.push_back(std::move(Kind));
709 }
710 });
711 }
712 }
713
714 constexpr static llvm::SourceMgr::DiagKind Error = llvm::SourceMgr::DK_Error;
715 constexpr static llvm::SourceMgr::DiagKind Warning =
716 llvm::SourceMgr::DK_Warning;
717 void diag(llvm::SourceMgr::DiagKind Kind, llvm::StringRef Message,
718 llvm::SMRange Range) {
719 if (Range.isValid() && SourceMgr != nullptr)
720 Diagnostic(SourceMgr->GetMessage(Range.Start, Kind, Message, Range));
721 else
722 Diagnostic(llvm::SMDiagnostic("", Kind, Message));
723 }
724};
725
726} // namespace
727
728CompiledFragment Fragment::compile(DiagnosticCallback D) && {
729 llvm::StringRef ConfigFile = "<unknown>";
730 std::pair<unsigned, unsigned> LineCol = {0, 0};
731 if (auto *SM = Source.Manager.get()) {
732 unsigned BufID = SM->getMainFileID();
733 LineCol = SM->getLineAndColumn(Source.Location, BufID);
734 ConfigFile = SM->getBufferInfo(BufID).Buffer->getBufferIdentifier();
735 }
736 trace::Span Tracer("ConfigCompile");
737 SPAN_ATTACH(Tracer, "ConfigFile", ConfigFile);
738 auto Result = std::make_shared<CompiledFragmentImpl>();
739 vlog("Config fragment: compiling {0}:{1} -> {2} (trusted={3})", ConfigFile,
740 LineCol.first, Result.get(), Source.Trusted);
741
742 FragmentCompiler{*Result, D, Source.Manager.get()}.compile(std::move(*this));
743 // Return as cheaply-copyable wrapper.
744 return [Result(std::move(Result))](const Params &P, Config &C) {
745 return (*Result)(P, C);
746 };
747}
748
749} // namespace config
750} // namespace clangd
751} // namespace clang
BindArgumentKind Kind
llvm::SmallString< 256U > Name
static cl::opt< std::string > ConfigFile("config-file", desc(R"( Specify the path of .clang-tidy or custom config file: e.g. --config-file=/some/path/myTidyConfigFile This option internally works exactly the same way as --config option after reading specified config file. Use either --config-file or --config, not both. )"), cl::init(""), cl::cat(ClangTidyCategory))
static constexpr llvm::SourceMgr::DiagKind Error
bool Trusted
CompiledFragmentImpl & Out
DiagnosticCallback Diagnostic
std::vector< llvm::unique_function< void(const Params &, Config &) const > > Apply
std::vector< llvm::unique_function< bool(const Params &) const > > Conditions
std::string FragmentDirectory
const Criteria C
CharSourceRange Range
SourceRange for the file name.
#define dlog(...)
Definition: Logger.h:101
llvm::json::Object Args
Definition: Trace.cpp:138
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition: Trace.h:164
Records an event whose duration is the lifetime of the Span object.
Definition: Trace.h:143
std::function< bool(const Params &, Config &)> CompiledFragment
A chunk of configuration that has been fully analyzed and is ready to apply.
llvm::function_ref< void(const llvm::SMDiagnostic &)> DiagnosticCallback
Used to report problems in parsing or interpreting a config.
@ Warning
A warning message.
@ Error
An error message.
std::string Path
A typedef to represent a file path.
Definition: Path.h:26
bool isRegisteredTidyCheck(llvm::StringRef Check)
Returns if Check is a registered clang-tidy check.
void vlog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:72
bool pathStartsWith(PathRef Ancestor, PathRef Path, llvm::sys::path::Style Style)
Checks if Ancestor is a proper ancestor of Path.
Definition: Path.cpp:36
std::optional< bool > isFastTidyCheck(llvm::StringRef Check)
Returns if Check is known-fast, known-slow, or its speed is unknown.
llvm::StringRef normalizeSuppressedCode(llvm::StringRef Code)
Take a user-specified diagnostic code, and convert it to a normalized form stored in the config and c...
void elog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:61
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Settings that express user/project preferences and control clangd behavior.
Definition: Config.h:44
@ None
nothing, no argument list and also NO Delimiters "()" or "<>".
@ Delimiters
empty pair of delimiters "()" or "<>".
@ OpenDelimiter
open, only opening delimiter "(" or "<".
@ FullPlaceholders
full name of both type and variable.
@ Strict
Diagnose missing and unused includes.
Describes the context used to evaluate configuration fragments.