1 //===--- Check.cpp - clangd self-diagnostics ------------------------------===//
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 // Many basic problems can occur processing a file in clangd, e.g.:
10 //  - system includes are not found
11 //  - crash when indexing its AST
12 // clangd --check provides a simplified, isolated way to reproduce these,
13 // with no editor, LSP, threads, background indexing etc to contend with.
14 //
15 // One important use case is gathering information for bug reports.
16 // Another is reproducing crashes, and checking which setting prevent them.
17 //
18 // It simulates opening a file (determining compile command, parsing, indexing)
19 // and then running features at many locations.
20 //
21 // Currently it adds some basic logging of progress and results.
22 // We should consider extending it to also recognize common symptoms and
23 // recommend solutions (e.g. standard library installation issues).
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "ClangdLSPServer.h"
28 #include "CodeComplete.h"
29 #include "CompileCommands.h"
30 #include "Config.h"
31 #include "GlobalCompilationDatabase.h"
32 #include "Hover.h"
33 #include "InlayHints.h"
34 #include "ParsedAST.h"
35 #include "Preamble.h"
36 #include "Protocol.h"
37 #include "SourceCode.h"
38 #include "XRefs.h"
39 #include "index/CanonicalIncludes.h"
40 #include "index/FileIndex.h"
41 #include "refactor/Tweak.h"
42 #include "support/ThreadsafeFS.h"
43 #include "support/Trace.h"
44 #include "clang/AST/ASTContext.h"
45 #include "clang/Format/Format.h"
46 #include "clang/Frontend/CompilerInvocation.h"
47 #include "clang/Tooling/CompilationDatabase.h"
48 #include "llvm/ADT/ArrayRef.h"
49 #include "llvm/ADT/Optional.h"
50 #include "llvm/Support/Path.h"
51 
52 namespace clang {
53 namespace clangd {
54 namespace {
55 
56 // Print (and count) the error-level diagnostics (warnings are ignored).
57 unsigned showErrors(llvm::ArrayRef<Diag> Diags) {
58   unsigned ErrCount = 0;
59   for (const auto &D : Diags) {
60     if (D.Severity >= DiagnosticsEngine::Error) {
61       elog("[{0}] Line {1}: {2}", D.Name, D.Range.start.line + 1, D.Message);
62       ++ErrCount;
63     }
64   }
65   return ErrCount;
66 }
67 
68 // This class is just a linear pipeline whose functions get called in sequence.
69 // Each exercises part of clangd's logic on our test file and logs results.
70 // Later steps depend on state built in earlier ones (such as the AST).
71 // Many steps can fatally fail (return false), then subsequent ones cannot run.
72 // Nonfatal failures are logged and tracked in ErrCount.
73 class Checker {
74   // from constructor
75   std::string File;
76   ClangdLSPServer::Options Opts;
77   // from buildCommand
78   tooling::CompileCommand Cmd;
79   // from buildInvocation
80   ParseInputs Inputs;
81   std::unique_ptr<CompilerInvocation> Invocation;
82   format::FormatStyle Style;
83   // from buildAST
84   std::shared_ptr<const PreambleData> Preamble;
85   llvm::Optional<ParsedAST> AST;
86   FileIndex Index;
87 
88 public:
89   // Number of non-fatal errors seen.
90   unsigned ErrCount = 0;
91 
92   Checker(llvm::StringRef File, const ClangdLSPServer::Options &Opts)
93       : File(File), Opts(Opts) {}
94 
95   // Read compilation database and choose a compile command for the file.
96   bool buildCommand(const ThreadsafeFS &TFS) {
97     log("Loading compilation database...");
98     DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS);
99     CDBOpts.CompileCommandsDir =
100         Config::current().CompileFlags.CDBSearch.FixedCDBPath;
101     std::unique_ptr<GlobalCompilationDatabase> BaseCDB =
102         std::make_unique<DirectoryBasedGlobalCompilationDatabase>(CDBOpts);
103     BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
104                                      std::move(BaseCDB));
105     auto Mangler = CommandMangler::detect();
106     if (Opts.ResourceDir)
107       Mangler.ResourceDir = *Opts.ResourceDir;
108     auto CDB = std::make_unique<OverlayCDB>(
109         BaseCDB.get(), std::vector<std::string>{},
110         tooling::ArgumentsAdjuster(std::move(Mangler)));
111 
112     if (auto TrueCmd = CDB->getCompileCommand(File)) {
113       Cmd = std::move(*TrueCmd);
114       log("Compile command from CDB is: {0}", printArgv(Cmd.CommandLine));
115     } else {
116       Cmd = CDB->getFallbackCommand(File);
117       log("Generic fallback command is: {0}", printArgv(Cmd.CommandLine));
118     }
119 
120     return true;
121   }
122 
123   // Prepare inputs and build CompilerInvocation (parsed compile command).
124   bool buildInvocation(const ThreadsafeFS &TFS,
125                        llvm::Optional<std::string> Contents) {
126     StoreDiags CaptureInvocationDiags;
127     std::vector<std::string> CC1Args;
128     Inputs.CompileCommand = Cmd;
129     Inputs.TFS = &TFS;
130     Inputs.ClangTidyProvider = Opts.ClangTidyProvider;
131     if (Contents.hasValue()) {
132       Inputs.Contents = *Contents;
133       log("Imaginary source file contents:\n{0}", Inputs.Contents);
134     } else {
135       if (auto Contents = TFS.view(llvm::None)->getBufferForFile(File)) {
136         Inputs.Contents = Contents->get()->getBuffer().str();
137       } else {
138         elog("Couldn't read {0}: {1}", File, Contents.getError().message());
139         return false;
140       }
141     }
142     log("Parsing command...");
143     Invocation =
144         buildCompilerInvocation(Inputs, CaptureInvocationDiags, &CC1Args);
145     auto InvocationDiags = CaptureInvocationDiags.take();
146     ErrCount += showErrors(InvocationDiags);
147     log("internal (cc1) args are: {0}", printArgv(CC1Args));
148     if (!Invocation) {
149       elog("Failed to parse command line");
150       return false;
151     }
152 
153     // FIXME: Check that resource-dir/built-in-headers exist?
154 
155     Style = getFormatStyleForFile(File, Inputs.Contents, TFS);
156 
157     return true;
158   }
159 
160   // Build preamble and AST, and index them.
161   bool buildAST() {
162     log("Building preamble...");
163     Preamble = buildPreamble(File, *Invocation, Inputs, /*StoreInMemory=*/true,
164                              [&](ASTContext &Ctx, Preprocessor &PP,
165                                  const CanonicalIncludes &Includes) {
166                                if (!Opts.BuildDynamicSymbolIndex)
167                                  return;
168                                log("Indexing headers...");
169                                Index.updatePreamble(File, /*Version=*/"null",
170                                                     Ctx, PP, Includes);
171                              });
172     if (!Preamble) {
173       elog("Failed to build preamble");
174       return false;
175     }
176     ErrCount += showErrors(Preamble->Diags);
177 
178     log("Building AST...");
179     AST = ParsedAST::build(File, Inputs, std::move(Invocation),
180                            /*InvocationDiags=*/std::vector<Diag>{}, Preamble);
181     if (!AST) {
182       elog("Failed to build AST");
183       return false;
184     }
185     ErrCount += showErrors(llvm::makeArrayRef(*AST->getDiagnostics())
186                                .drop_front(Preamble->Diags.size()));
187 
188     if (Opts.BuildDynamicSymbolIndex) {
189       log("Indexing AST...");
190       Index.updateMain(File, *AST);
191     }
192     return true;
193   }
194 
195   // Build Inlay Hints for the entire AST or the specified range
196   void buildInlayHints(llvm::Optional<Range> LineRange) {
197     log("Building inlay hints");
198     auto Hints = inlayHints(*AST, LineRange);
199 
200     for (const auto &Hint : Hints) {
201       vlog("  {0} {1} {2}", Hint.kind, Hint.position, Hint.label);
202     }
203   }
204 
205   // Run AST-based features at each token in the file.
206   void testLocationFeatures(llvm::Optional<Range> LineRange,
207                             const bool EnableCodeCompletion) {
208     trace::Span Trace("testLocationFeatures");
209     log("Testing features at each token (may be slow in large files)");
210     auto &SM = AST->getSourceManager();
211     auto SpelledTokens = AST->getTokens().spelledTokens(SM.getMainFileID());
212 
213     CodeCompleteOptions CCOpts = Opts.CodeComplete;
214     CCOpts.Index = &Index;
215 
216     for (const auto &Tok : SpelledTokens) {
217       unsigned Start = AST->getSourceManager().getFileOffset(Tok.location());
218       unsigned End = Start + Tok.length();
219       Position Pos = offsetToPosition(Inputs.Contents, Start);
220 
221       if (LineRange && !LineRange->contains(Pos))
222         continue;
223 
224       trace::Span Trace("Token");
225       SPAN_ATTACH(Trace, "pos", Pos);
226       SPAN_ATTACH(Trace, "text", Tok.text(AST->getSourceManager()));
227 
228       // FIXME: dumping the tokens may leak sensitive code into bug reports.
229       // Add an option to turn this off, once we decide how options work.
230       vlog("  {0} {1}", Pos, Tok.text(AST->getSourceManager()));
231       auto Tree = SelectionTree::createRight(AST->getASTContext(),
232                                              AST->getTokens(), Start, End);
233       Tweak::Selection Selection(&Index, *AST, Start, End, std::move(Tree),
234                                  nullptr);
235       // FS is only populated when applying a tweak, not during prepare as
236       // prepare should not do any I/O to be fast.
237       auto Tweaks =
238           prepareTweaks(Selection, Opts.TweakFilter, Opts.FeatureModules);
239       Selection.FS =
240           &AST->getSourceManager().getFileManager().getVirtualFileSystem();
241       for (const auto &T : Tweaks) {
242         auto Result = T->apply(Selection);
243         if (!Result) {
244           elog("    tweak: {0} ==> FAIL: {1}", T->id(), Result.takeError());
245           ++ErrCount;
246         } else {
247           vlog("    tweak: {0}", T->id());
248         }
249       }
250       unsigned Definitions = locateSymbolAt(*AST, Pos, &Index).size();
251       vlog("    definition: {0}", Definitions);
252 
253       auto Hover = getHover(*AST, Pos, Style, &Index);
254       vlog("    hover: {0}", Hover.hasValue());
255 
256       if (EnableCodeCompletion) {
257         Position EndPos = offsetToPosition(Inputs.Contents, End);
258         auto CC = codeComplete(File, EndPos, Preamble.get(), Inputs, CCOpts);
259         vlog("    code completion: {0}",
260              CC.Completions.empty() ? "<empty>" : CC.Completions[0].Name);
261       }
262     }
263   }
264 };
265 
266 } // namespace
267 
268 bool check(llvm::StringRef File, llvm::Optional<Range> LineRange,
269            const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts,
270            bool EnableCodeCompletion) {
271   llvm::SmallString<0> FakeFile;
272   llvm::Optional<std::string> Contents;
273   if (File.empty()) {
274     llvm::sys::path::system_temp_directory(false, FakeFile);
275     llvm::sys::path::append(FakeFile, "test.cc");
276     File = FakeFile;
277     Contents = R"cpp(
278       #include <stddef.h>
279       #include <string>
280 
281       size_t N = 50;
282       auto xxx = std::string(N, 'x');
283     )cpp";
284   }
285   log("Testing on source file {0}", File);
286 
287   auto ContextProvider = ClangdServer::createConfiguredContextProvider(
288       Opts.ConfigProvider, nullptr);
289   WithContext Ctx(ContextProvider(
290       FakeFile.empty()
291           ? File
292           : /*Don't turn on local configs for an arbitrary temp path.*/ ""));
293   Checker C(File, Opts);
294   if (!C.buildCommand(TFS) || !C.buildInvocation(TFS, Contents) ||
295       !C.buildAST())
296     return false;
297   C.buildInlayHints(LineRange);
298   C.testLocationFeatures(LineRange, EnableCodeCompletion);
299 
300   log("All checks completed, {0} errors", C.ErrCount);
301   return C.ErrCount == 0;
302 }
303 
304 } // namespace clangd
305 } // namespace clang
306