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"
59llvm::StringRef configRelative(llvm::StringRef
Path,
60 llvm::StringRef FragmentDir) {
61 if (FragmentDir.empty())
63 if (!
Path.consume_front(FragmentDir))
64 return llvm::StringRef();
68struct CompiledFragmentImpl {
74 std::vector<llvm::unique_function<bool(
const Params &)
const>>
Conditions;
77 std::vector<llvm::unique_function<void(
const Params &, Config &)
const>>
80 bool operator()(
const Params &P, Config &
C)
const {
83 dlog(
"Config fragment {0}: condition not met",
this);
87 dlog(
"Config fragment {0}: applying {1} rules",
this,
Apply.size());
88 for (
const auto &A :
Apply)
95struct FragmentCompiler {
99 CompiledFragmentImpl &
Out;
101 llvm::SourceMgr *SourceMgr;
106 std::optional<llvm::Regex>
107 compileRegex(
const Located<std::string> &
Text,
108 llvm::Regex::RegexFlags
Flags = llvm::Regex::NoFlags) {
109 std::string Anchored =
"^(" + *
Text +
")$";
110 llvm::Regex Result(Anchored,
Flags);
111 std::string RegexError;
112 if (!Result.isValid(RegexError)) {
113 diag(
Error,
"Invalid regex " + Anchored +
": " + RegexError,
Text.Range);
116 return std::move(Result);
119 std::optional<std::string> makeAbsolute(Located<std::string>
Path,
120 llvm::StringLiteral Description,
121 llvm::sys::path::Style Style) {
122 if (llvm::sys::path::is_absolute(*
Path))
127 "{0} must be an absolute path, because this fragment is not "
128 "associated with any directory.",
134 llvm::SmallString<256> AbsPath = llvm::StringRef(*
Path);
135 llvm::sys::fs::make_absolute(FragmentDirectory, AbsPath);
136 llvm::sys::path::native(AbsPath, Style);
137 return AbsPath.str().str();
141 template <
typename T>
class EnumSwitch {
142 FragmentCompiler &Outer;
143 llvm::StringRef EnumName;
144 const Located<std::string> &Input;
145 std::optional<T> Result;
146 llvm::SmallVector<llvm::StringLiteral> ValidValues;
149 EnumSwitch(llvm::StringRef EnumName,
const Located<std::string> &In,
150 FragmentCompiler &Outer)
151 : Outer(Outer), EnumName(EnumName), Input(In) {}
153 EnumSwitch &map(llvm::StringLiteral
Name, T
Value) {
154 assert(!llvm::is_contained(ValidValues,
Name) &&
"Duplicate value!");
155 ValidValues.push_back(
Name);
156 if (!Result && *Input ==
Name)
161 std::optional<T> value() {
165 llvm::formatv(
"Invalid {0} value '{1}'. Valid values are {2}.",
166 EnumName, *Input, llvm::join(ValidValues,
", "))
180 template <
typename T>
181 EnumSwitch<T> compileEnum(llvm::StringRef EnumName,
182 const Located<std::string> &In) {
183 return EnumSwitch<T>(EnumName, In, *
this);
186 void compile(Fragment &&F) {
188 if (!F.Source.Directory.empty()) {
193 compile(std::move(F.If));
194 compile(std::move(F.CompileFlags));
195 compile(std::move(F.Index));
196 compile(std::move(F.Diagnostics));
197 compile(std::move(F.Completion));
198 compile(std::move(F.Hover));
199 compile(std::move(F.InlayHints));
200 compile(std::move(F.SemanticTokens));
201 compile(std::move(F.Style));
204 void compile(Fragment::IfBlock &&F) {
205 if (F.HasUnrecognizedCondition)
206 Out.Conditions.push_back([&](
const Params &) {
return false; });
208#ifdef CLANGD_PATH_CASE_INSENSITIVE
209 llvm::Regex::RegexFlags
Flags = llvm::Regex::IgnoreCase;
211 llvm::Regex::RegexFlags
Flags = llvm::Regex::NoFlags;
214 auto PathMatch = std::make_unique<std::vector<llvm::Regex>>();
215 for (
auto &
Entry : F.PathMatch) {
217 PathMatch->push_back(std::move(*RE));
219 if (!PathMatch->empty()) {
220 Out.Conditions.push_back(
221 [PathMatch(std::move(PathMatch)),
222 FragmentDir(FragmentDirectory)](
const Params &P) {
225 llvm::StringRef
Path = configRelative(P.Path, FragmentDir);
229 return llvm::any_of(*PathMatch, [&](
const llvm::Regex &RE) {
230 return RE.match(
Path);
235 auto PathExclude = std::make_unique<std::vector<llvm::Regex>>();
236 for (
auto &
Entry : F.PathExclude) {
238 PathExclude->push_back(std::move(*RE));
240 if (!PathExclude->empty()) {
241 Out.Conditions.push_back(
242 [PathExclude(std::move(PathExclude)),
243 FragmentDir(FragmentDirectory)](
const Params &P) {
246 llvm::StringRef
Path = configRelative(P.Path, FragmentDir);
250 return llvm::none_of(*PathExclude, [&](
const llvm::Regex &RE) {
251 return RE.match(
Path);
257 void compile(Fragment::CompileFlagsBlock &&F) {
260 [Compiler(std::move(**F.Compiler))](
const Params &, Config &
C) {
261 C.CompileFlags.Edits.push_back(
262 [Compiler](std::vector<std::string> &Args) {
264 Args.front() = Compiler;
268 if (!F.Remove.empty()) {
269 auto Remove = std::make_shared<ArgStripper>();
270 for (
auto &A : F.Remove)
272 Out.Apply.push_back([Remove(std::shared_ptr<const ArgStripper>(
273 std::move(Remove)))](
const Params &, Config &
C) {
274 C.CompileFlags.Edits.push_back(
275 [Remove](std::vector<std::string> &
Args) {
276 Remove->process(
Args);
281 if (!F.Add.empty()) {
282 std::vector<std::string> Add;
283 for (
auto &A : F.Add)
284 Add.push_back(std::move(*A));
285 Out.Apply.push_back([Add(std::move(Add))](
const Params &, Config &
C) {
286 C.CompileFlags.Edits.push_back([Add](std::vector<std::string> &
Args) {
288 auto It = llvm::find(
Args,
"--");
289 Args.insert(It, Add.begin(), Add.end());
294 if (F.CompilationDatabase) {
295 std::optional<Config::CDBSearchSpec> Spec;
296 if (**F.CompilationDatabase ==
"Ancestors") {
299 }
else if (**F.CompilationDatabase ==
"None") {
304 makeAbsolute(*F.CompilationDatabase,
"CompilationDatabase",
305 llvm::sys::path::Style::native)) {
308 llvm::StringRef Rel = llvm::sys::path::relative_path(*
Path);
309 if (!Rel.empty() && llvm::sys::path::is_separator(Rel.back()))
314 Spec->FixedCDBPath = std::move(
Path);
319 [Spec(std::move(*Spec))](
const Params &, Config &
C) {
320 C.CompileFlags.CDBSearch = Spec;
325 void compile(Fragment::IndexBlock &&F) {
328 compileEnum<Config::BackgroundPolicy>(
"Background", *F.Background)
333 [Val](
const Params &, Config &
C) {
C.Index.Background = *Val; });
336 compile(std::move(**F.External), F.External->Range);
337 if (F.StandardLibrary)
339 [Val(**F.StandardLibrary)](
const Params &, Config &
C) {
340 C.Index.StandardLibrary = Val;
344 void compile(Fragment::IndexBlock::ExternalBlock &&External,
345 llvm::SMRange BlockRange) {
346 if (External.Server && !
Trusted) {
348 "Remote index may not be specified by untrusted configuration. "
349 "Copy this into user config to use it.",
350 External.Server->Range);
353#ifndef CLANGD_ENABLE_REMOTE
354 if (External.Server) {
355 elog(
"Clangd isn't compiled with remote index support, ignoring Server: "
358 External.Server.reset();
362 unsigned SourceCount = External.File.has_value() +
363 External.Server.has_value() + *External.IsNone;
364 if (SourceCount != 1) {
365 diag(
Error,
"Exactly one of File, Server or None must be set.",
369 Config::ExternalIndexSpec Spec;
370 if (External.Server) {
372 Spec.Location = std::move(**External.Server);
373 }
else if (External.File) {
375 auto AbsPath = makeAbsolute(std::move(*External.File),
"File",
376 llvm::sys::path::Style::native);
379 Spec.Location = std::move(*AbsPath);
381 assert(*External.IsNone);
386 if (!External.MountPoint)
388 if ((**External.MountPoint).empty()) {
389 diag(
Error,
"A mountpoint is required.", BlockRange);
392 auto AbsPath = makeAbsolute(std::move(*External.MountPoint),
"MountPoint",
393 llvm::sys::path::Style::posix);
396 Spec.MountPoint = std::move(*AbsPath);
398 Out.Apply.push_back([Spec(std::move(Spec))](
const Params &P, Config &
C) {
400 C.Index.External = Spec;
404 llvm::sys::path::Style::posix))
406 C.Index.External = Spec;
414 void compile(Fragment::DiagnosticsBlock &&F) {
415 std::vector<std::string> Normalized;
416 for (
const auto &Suppressed : F.Suppress) {
417 if (*Suppressed ==
"*") {
418 Out.Apply.push_back([&](
const Params &, Config &
C) {
419 C.Diagnostics.SuppressAll =
true;
420 C.Diagnostics.Suppress.clear();
426 if (!Normalized.empty())
428 [Normalized(std::move(Normalized))](
const Params &, Config &
C) {
429 if (
C.Diagnostics.SuppressAll)
431 for (llvm::StringRef N : Normalized)
432 C.Diagnostics.Suppress.insert(N);
435 if (F.UnusedIncludes) {
436 auto Val = compileEnum<Config::IncludesPolicy>(
"UnusedIncludes",
441 if (!Val && **F.UnusedIncludes ==
"Experiment") {
443 "Experiment is deprecated for UnusedIncludes, use Strict instead.",
444 F.UnusedIncludes->Range);
448 Out.Apply.push_back([Val](
const Params &, Config &
C) {
449 C.Diagnostics.UnusedIncludes = *Val;
454 if (F.MissingIncludes)
455 if (
auto Val = compileEnum<Config::IncludesPolicy>(
"MissingIncludes",
460 Out.Apply.push_back([Val](
const Params &, Config &
C) {
461 C.Diagnostics.MissingIncludes = *Val;
464 compile(std::move(F.Includes));
465 compile(std::move(F.ClangTidy));
468 void compile(Fragment::StyleBlock &&F) {
469 if (!F.FullyQualifiedNamespaces.empty()) {
470 std::vector<std::string> FullyQualifiedNamespaces;
471 for (
auto &N : F.FullyQualifiedNamespaces) {
476 FullyQualifiedNamespaces.push_back(
Namespace.str());
478 Out.Apply.push_back([FullyQualifiedNamespaces(
479 std::move(FullyQualifiedNamespaces))](
480 const Params &, Config &
C) {
481 C.Style.FullyQualifiedNamespaces.insert(
482 C.Style.FullyQualifiedNamespaces.begin(),
483 FullyQualifiedNamespaces.begin(), FullyQualifiedNamespaces.end());
488 void appendTidyCheckSpec(std::string &CurSpec,
489 const Located<std::string> &Arg,
bool IsPositive) {
490 StringRef Str = StringRef(*Arg).trim();
493 if (Str.starts_with(
"-") || Str.contains(
',')) {
494 diag(
Error,
"Invalid clang-tidy check name", Arg.Range);
497 if (!Str.contains(
'*')) {
500 llvm::formatv(
"clang-tidy check '{0}' was not found", Str).str(),
505 if (!Fast.has_value()) {
508 "Latency of clang-tidy check '{0}' is not known. "
509 "It will only run if ClangTidy.FastCheckFilter is Loose or None",
516 "clang-tidy check '{0}' is slow. "
517 "It will only run if ClangTidy.FastCheckFilter is None",
529 void compile(Fragment::DiagnosticsBlock::ClangTidyBlock &&F) {
531 for (
auto &CheckGlob : F.Add)
532 appendTidyCheckSpec(Checks, CheckGlob,
true);
534 for (
auto &CheckGlob : F.Remove)
535 appendTidyCheckSpec(Checks, CheckGlob,
false);
539 [Checks = std::move(Checks)](
const Params &, Config &
C) {
540 C.Diagnostics.ClangTidy.Checks.append(
542 C.Diagnostics.ClangTidy.Checks.empty() ? 1 : 0,
545 if (!F.CheckOptions.empty()) {
546 std::vector<std::pair<std::string, std::string>> CheckOptions;
547 for (
auto &Opt : F.CheckOptions)
548 CheckOptions.emplace_back(std::move(*Opt.first),
549 std::move(*Opt.second));
551 [CheckOptions = std::move(CheckOptions)](
const Params &, Config &
C) {
552 for (
auto &StringPair : CheckOptions)
553 C.Diagnostics.ClangTidy.CheckOptions.insert_or_assign(
554 StringPair.first, StringPair.second);
557 if (F.FastCheckFilter.has_value())
558 if (
auto Val = compileEnum<Config::FastCheckPolicy>(
"FastCheckFilter",
564 Out.Apply.push_back([Val](
const Params &, Config &
C) {
565 C.Diagnostics.ClangTidy.FastCheckFilter = *Val;
569 void compile(Fragment::DiagnosticsBlock::IncludesBlock &&F) {
570#ifdef CLANGD_PATH_CASE_INSENSITIVE
571 static llvm::Regex::RegexFlags
Flags = llvm::Regex::IgnoreCase;
573 static llvm::Regex::RegexFlags
Flags = llvm::Regex::NoFlags;
575 std::shared_ptr<std::vector<llvm::Regex>> Filters;
576 if (!F.IgnoreHeader.empty()) {
577 Filters = std::make_shared<std::vector<llvm::Regex>>();
578 for (
auto &HeaderPattern : F.IgnoreHeader) {
580 std::string AnchoredPattern =
"(" + *HeaderPattern +
")$";
581 llvm::Regex CompiledRegex(AnchoredPattern,
Flags);
582 std::string RegexError;
583 if (!CompiledRegex.isValid(RegexError)) {
585 llvm::formatv(
"Invalid regular expression '{0}': {1}",
586 *HeaderPattern, RegexError)
588 HeaderPattern.Range);
591 Filters->push_back(std::move(CompiledRegex));
597 std::optional<bool> AnalyzeAngledIncludes;
598 if (F.AnalyzeAngledIncludes.has_value())
599 AnalyzeAngledIncludes = **F.AnalyzeAngledIncludes;
600 if (!Filters && !AnalyzeAngledIncludes.has_value())
602 Out.Apply.push_back([Filters = std::move(Filters),
603 AnalyzeAngledIncludes](
const Params &, Config &
C) {
605 auto Filter = [Filters](llvm::StringRef
Path) {
606 for (
auto &Regex : *Filters)
607 if (Regex.match(
Path))
611 C.Diagnostics.Includes.IgnoreHeader.emplace_back(std::move(Filter));
613 if (AnalyzeAngledIncludes.has_value())
614 C.Diagnostics.Includes.AnalyzeAngledIncludes = *AnalyzeAngledIncludes;
618 void compile(Fragment::CompletionBlock &&F) {
621 [AllScopes(**F.AllScopes)](
const Params &, Config &
C) {
622 C.Completion.AllScopes = AllScopes;
627 void compile(Fragment::HoverBlock &&F) {
629 Out.Apply.push_back([ShowAKA(**F.ShowAKA)](
const Params &, Config &
C) {
630 C.Hover.ShowAKA = ShowAKA;
635 void compile(Fragment::InlayHintsBlock &&F) {
637 Out.Apply.push_back([
Value(**F.Enabled)](
const Params &, Config &
C) {
638 C.InlayHints.Enabled = Value;
640 if (F.ParameterNames)
642 [
Value(**F.ParameterNames)](
const Params &, Config &
C) {
643 C.InlayHints.Parameters = Value;
646 Out.Apply.push_back([
Value(**F.DeducedTypes)](
const Params &, Config &
C) {
647 C.InlayHints.DeducedTypes = Value;
650 Out.Apply.push_back([
Value(**F.Designators)](
const Params &, Config &
C) {
651 C.InlayHints.Designators = Value;
654 Out.Apply.push_back([
Value(**F.BlockEnd)](
const Params &, Config &
C) {
655 C.InlayHints.BlockEnd = Value;
659 [
Value(**F.TypeNameLimit)](
const Params &, Config &
C) {
660 C.InlayHints.TypeNameLimit = Value;
664 void compile(Fragment::SemanticTokensBlock &&F) {
665 if (!F.DisabledKinds.empty()) {
666 std::vector<std::string> DisabledKinds;
667 for (
auto &
Kind : F.DisabledKinds)
668 DisabledKinds.push_back(std::move(*
Kind));
671 [DisabledKinds(std::move(DisabledKinds))](
const Params &, Config &
C) {
672 for (
auto &
Kind : DisabledKinds) {
673 auto It = llvm::find(
C.SemanticTokens.DisabledKinds,
Kind);
674 if (It ==
C.SemanticTokens.DisabledKinds.end())
675 C.SemanticTokens.DisabledKinds.push_back(std::move(
Kind));
679 if (!F.DisabledModifiers.empty()) {
680 std::vector<std::string> DisabledModifiers;
681 for (
auto &
Kind : F.DisabledModifiers)
682 DisabledModifiers.push_back(std::move(*
Kind));
684 Out.Apply.push_back([DisabledModifiers(std::move(DisabledModifiers))](
685 const Params &, Config &
C) {
686 for (
auto &
Kind : DisabledModifiers) {
687 auto It = llvm::find(
C.SemanticTokens.DisabledModifiers,
Kind);
688 if (It ==
C.SemanticTokens.DisabledModifiers.end())
689 C.SemanticTokens.DisabledModifiers.push_back(std::move(
Kind));
695 constexpr static llvm::SourceMgr::DiagKind
Error = llvm::SourceMgr::DK_Error;
696 constexpr static llvm::SourceMgr::DiagKind
Warning =
697 llvm::SourceMgr::DK_Warning;
698 void diag(llvm::SourceMgr::DiagKind
Kind, llvm::StringRef Message,
699 llvm::SMRange Range) {
700 if (
Range.isValid() && SourceMgr !=
nullptr)
711 std::pair<unsigned, unsigned> LineCol = {0, 0};
712 if (
auto *SM = Source.Manager.get()) {
713 unsigned BufID = SM->getMainFileID();
714 LineCol = SM->getLineAndColumn(Source.Location, BufID);
715 ConfigFile = SM->getBufferInfo(BufID).Buffer->getBufferIdentifier();
719 auto Result = std::make_shared<CompiledFragmentImpl>();
720 vlog(
"Config fragment: compiling {0}:{1} -> {2} (trusted={3})",
ConfigFile,
721 LineCol.first, Result.get(), Source.Trusted);
723 FragmentCompiler{*Result, D, Source.Manager.get()}.compile(std::move(*
this));
725 return [Result(std::move(Result))](
const Params &P,
Config &
C) {
726 return (*Result)(P,
C);
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
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
CharSourceRange Range
SourceRange for the file name.
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Records an event whose duration is the lifetime of the Span object.
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.
std::string Path
A typedef to represent a file path.
bool isRegisteredTidyCheck(llvm::StringRef Check)
Returns if Check is a registered clang-tidy check.
void vlog(const char *Fmt, Ts &&... Vals)
bool pathStartsWith(PathRef Ancestor, PathRef Path, llvm::sys::path::Style Style)
Checks if Ancestor is a proper ancestor of Path.
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)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Settings that express user/project preferences and control clangd behavior.
@ Strict
Diagnose missing and unused includes.
Describes the context used to evaluate configuration fragments.