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 "GlobalCompilationDatabase.h"
30 #include "Hover.h"
31 #include "ParsedAST.h"
32 #include "Preamble.h"
33 #include "SourceCode.h"
34 #include "XRefs.h"
35 #include "index/CanonicalIncludes.h"
36 #include "index/FileIndex.h"
37 #include "refactor/Tweak.h"
38 #include "support/ThreadsafeFS.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/Basic/DiagnosticIDs.h"
41 #include "clang/Format/Format.h"
42 #include "clang/Frontend/CompilerInvocation.h"
43 #include "clang/Tooling/CompilationDatabase.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/Optional.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/Support/Path.h"
48 
49 namespace clang {
50 namespace clangd {
51 namespace {
52 
53 // Print (and count) the error-level diagnostics (warnings are ignored).
54 unsigned showErrors(llvm::ArrayRef<Diag> Diags) {
55   unsigned ErrCount = 0;
56   for (const auto &D : Diags) {
57     if (D.Severity >= DiagnosticsEngine::Error) {
58       elog("[{0}] Line {1}: {2}", D.Name, D.Range.start.line + 1, D.Message);
59       ++ErrCount;
60     }
61   }
62   return ErrCount;
63 }
64 
65 // This class is just a linear pipeline whose functions get called in sequence.
66 // Each exercises part of clangd's logic on our test file and logs results.
67 // Later steps depend on state built in earlier ones (such as the AST).
68 // Many steps can fatally fail (return false), then subsequent ones cannot run.
69 // Nonfatal failures are logged and tracked in ErrCount.
70 class Checker {
71   // from constructor
72   std::string File;
73   ClangdLSPServer::Options Opts;
74   // from buildCommand
75   tooling::CompileCommand Cmd;
76   // from buildInvocation
77   ParseInputs Inputs;
78   std::unique_ptr<CompilerInvocation> Invocation;
79   format::FormatStyle Style;
80   // from buildAST
81   std::shared_ptr<const PreambleData> Preamble;
82   llvm::Optional<ParsedAST> AST;
83   FileIndex Index;
84 
85 public:
86   // Number of non-fatal errors seen.
87   unsigned ErrCount = 0;
88 
89   Checker(llvm::StringRef File, const ClangdLSPServer::Options &Opts)
90       : File(File), Opts(Opts) {}
91 
92   // Read compilation database and choose a compile command for the file.
93   bool buildCommand(const ThreadsafeFS &TFS) {
94     log("Loading compilation database...");
95     DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS);
96     CDBOpts.CompileCommandsDir = Opts.CompileCommandsDir;
97     std::unique_ptr<GlobalCompilationDatabase> BaseCDB =
98         std::make_unique<DirectoryBasedGlobalCompilationDatabase>(CDBOpts);
99     BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
100                                      std::move(BaseCDB));
101     auto Mangler = CommandMangler::detect();
102     if (Opts.ResourceDir)
103       Mangler.ResourceDir = *Opts.ResourceDir;
104     auto CDB = std::make_unique<OverlayCDB>(
105         BaseCDB.get(), std::vector<std::string>{},
106         tooling::ArgumentsAdjuster(std::move(Mangler)));
107 
108     if (auto TrueCmd = CDB->getCompileCommand(File)) {
109       Cmd = std::move(*TrueCmd);
110       log("Compile command from CDB is: {0}", llvm::join(Cmd.CommandLine, " "));
111     } else {
112       Cmd = CDB->getFallbackCommand(File);
113       log("Generic fallback command is: {0}", llvm::join(Cmd.CommandLine, " "));
114     }
115 
116     return true;
117   }
118 
119   // Prepare inputs and build CompilerInvocation (parsed compile command).
120   bool buildInvocation(const ThreadsafeFS &TFS,
121                        llvm::Optional<std::string> Contents) {
122     StoreDiags CaptureInvocationDiags;
123     std::vector<std::string> CC1Args;
124     Inputs.CompileCommand = Cmd;
125     Inputs.TFS = &TFS;
126     if (Contents.hasValue()) {
127       Inputs.Contents = *Contents;
128       log("Imaginary source file contents:\n{0}", Inputs.Contents);
129     } else {
130       if (auto Contents = TFS.view(llvm::None)->getBufferForFile(File)) {
131         Inputs.Contents = Contents->get()->getBuffer().str();
132       } else {
133         elog("Couldn't read {0}: {1}", File, Contents.getError().message());
134         return false;
135       }
136     }
137     log("Parsing command...");
138     Invocation =
139         buildCompilerInvocation(Inputs, CaptureInvocationDiags, &CC1Args);
140     auto InvocationDiags = CaptureInvocationDiags.take();
141     ErrCount += showErrors(InvocationDiags);
142     log("internal (cc1) args are: {0}", llvm::join(CC1Args, " "));
143     if (!Invocation) {
144       elog("Failed to parse command line");
145       return false;
146     }
147 
148     // FIXME: Check that resource-dir/built-in-headers exist?
149 
150     Style = getFormatStyleForFile(File, Inputs.Contents, TFS);
151 
152     return true;
153   }
154 
155   // Build preamble and AST, and index them.
156   bool buildAST() {
157     log("Building preamble...");
158     Preamble =
159         buildPreamble(File, *Invocation, Inputs, /*StoreInMemory=*/true,
160                       [&](ASTContext &Ctx, std::shared_ptr<Preprocessor> PP,
161                           const CanonicalIncludes &Includes) {
162                         if (!Opts.BuildDynamicSymbolIndex)
163                           return;
164                         log("Indexing headers...");
165                         Index.updatePreamble(File, /*Version=*/"null", Ctx,
166                                              std::move(PP), Includes);
167                       });
168     if (!Preamble) {
169       elog("Failed to build preamble");
170       return false;
171     }
172     ErrCount += showErrors(Preamble->Diags);
173 
174     log("Building AST...");
175     AST = ParsedAST::build(File, Inputs, std::move(Invocation),
176                            /*InvocationDiags=*/std::vector<Diag>{}, Preamble);
177     if (!AST) {
178       elog("Failed to build AST");
179       return false;
180     }
181     ErrCount += showErrors(llvm::makeArrayRef(AST->getDiagnostics())
182                                .drop_front(Preamble->Diags.size()));
183 
184     if (Opts.BuildDynamicSymbolIndex) {
185       log("Indexing AST...");
186       Index.updateMain(File, *AST);
187     }
188     return true;
189   }
190 
191   // Run AST-based features at each token in the file.
192   void testLocationFeatures() {
193     log("Testing features at each token (may be slow in large files)");
194     auto SpelledTokens =
195         AST->getTokens().spelledTokens(AST->getSourceManager().getMainFileID());
196     for (const auto &Tok : SpelledTokens) {
197       unsigned Start = AST->getSourceManager().getFileOffset(Tok.location());
198       unsigned End = Start + Tok.length();
199       Position Pos = offsetToPosition(Inputs.Contents, Start);
200       // FIXME: dumping the tokens may leak sensitive code into bug reports.
201       // Add an option to turn this off, once we decide how options work.
202       vlog("  {0} {1}", Pos, Tok.text(AST->getSourceManager()));
203       auto Tree = SelectionTree::createRight(AST->getASTContext(),
204                                              AST->getTokens(), Start, End);
205       Tweak::Selection Selection(&Index, *AST, Start, End, std::move(Tree));
206       for (const auto &T : prepareTweaks(Selection, Opts.TweakFilter)) {
207         auto Result = T->apply(Selection);
208         if (!Result) {
209           elog("    tweak: {0} ==> FAIL: {1}", T->id(), Result.takeError());
210           ++ErrCount;
211         } else {
212           vlog("    tweak: {0}", T->id());
213         }
214       }
215       unsigned Definitions = locateSymbolAt(*AST, Pos, &Index).size();
216       vlog("    definition: {0}", Definitions);
217 
218       auto Hover = getHover(*AST, Pos, Style, &Index);
219       vlog("    hover: {0}", Hover.hasValue());
220 
221       // FIXME: it'd be nice to include code completion, but it's too slow.
222       // Maybe in combination with a line restriction?
223     }
224   }
225 };
226 
227 } // namespace
228 
229 bool check(llvm::StringRef File, const ThreadsafeFS &TFS,
230            const ClangdLSPServer::Options &Opts) {
231   llvm::SmallString<0> FakeFile;
232   llvm::Optional<std::string> Contents;
233   if (File.empty()) {
234     llvm::sys::path::system_temp_directory(false, FakeFile);
235     llvm::sys::path::append(FakeFile, "test.cc");
236     File = FakeFile;
237     Contents = R"cpp(
238       #include <stddef.h>
239       #include <string>
240 
241       size_t N = 50;
242       auto xxx = std::string(N, 'x');
243     )cpp";
244   }
245   log("Testing on source file {0}", File);
246 
247   Checker C(File, Opts);
248   if (!C.buildCommand(TFS) || !C.buildInvocation(TFS, Contents) ||
249       !C.buildAST())
250     return false;
251   C.testLocationFeatures();
252 
253   log("All checks completed, {0} errors", C.ErrCount);
254   return C.ErrCount == 0;
255 }
256 
257 } // namespace clangd
258 } // namespace clang
259