clang-tools 24.0.0git
TestTU.cpp
Go to the documentation of this file.
1//===--- TestTU.cpp - Scratch source files for testing --------------------===//
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#include "TestTU.h"
11#include "CompileCommands.h"
12#include "Compiler.h"
13#include "Diagnostics.h"
14#include "TestFS.h"
15#include "index/FileIndex.h"
16#include "index/SymbolOrigin.h"
17#include "clang/AST/RecursiveASTVisitor.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Frontend/CompilerInvocation.h"
20#include "llvm/ADT/ScopeExit.h"
21#include "llvm/Support/ScopedPrinter.h"
22#include "llvm/Support/raw_ostream.h"
23#include <cstdlib>
24
25namespace clang {
26namespace clangd {
27
29 std::string FullFilename = testPath(Filename),
30 FullHeaderName = testPath(HeaderFilename),
31 ImportThunk = testPath("import_thunk.h");
32 // We want to implicitly include HeaderFilename without messing up offsets.
33 // -include achieves this, but sometimes we want #import (to simulate a header
34 // guard without messing up offsets). In this case, use an intermediate file.
35 std::string ThunkContents = "#import \"" + FullHeaderName + "\"\n";
36
38 FS.Files[FullFilename] = Code;
39 FS.Files[FullHeaderName] = HeaderCode;
40 FS.Files[ImportThunk] = ThunkContents;
41
42 ParseInputs Inputs;
44 auto &Argv = Inputs.CompileCommand.CommandLine;
45 Argv = {"clang"};
46 // In tests, unless explicitly specified otherwise, omit predefined macros
47 // (__GNUC__ etc) for a 25% speedup. There are hundreds, and we'd generate,
48 // parse, serialize, and re-parse them!
49 if (!PredefineMacros) {
50 Argv.push_back("-Xclang");
51 Argv.push_back("-undef");
52 }
53 // FIXME: this shouldn't need to be conditional, but it breaks a
54 // GoToDefinition test for some reason (getMacroArgExpandedLocation fails).
55 if (!HeaderCode.empty()) {
56 Argv.push_back("-include");
57 Argv.push_back(ImplicitHeaderGuard ? ImportThunk : FullHeaderName);
58 // ms-compatibility changes the meaning of #import.
59 // The default is OS-dependent (on windows), ensure it's off.
61 Inputs.CompileCommand.CommandLine.push_back("-fno-ms-compatibility");
62 }
63 Argv.insert(Argv.end(), ExtraArgs.begin(), ExtraArgs.end());
64 // Put the file name at the end -- this allows the extra arg (-xc++) to
65 // override the language setting.
66 Argv.push_back(FullFilename);
67
68 auto Mangler = CommandMangler::forTests();
69 Mangler(Inputs.CompileCommand, FullFilename);
70 Inputs.CompileCommand.Filename = FullFilename;
71 Inputs.CompileCommand.Directory = testRoot();
72 Inputs.Contents = Code;
75 Inputs.TFS = &FS;
76 Inputs.Opts = ParseOptions();
77 Inputs.Index = ExternalIndex;
78 return Inputs;
79}
80
81void initializeModuleCache(CompilerInvocation &CI) {
82 llvm::SmallString<128> ModuleCachePath;
83 if (llvm::sys::fs::createUniqueDirectory("module-cache", ModuleCachePath)) {
84 llvm::errs() << "Failed to create temp directory for module-cache";
85 std::abort();
86 }
87 CI.getHeaderSearchOpts().ModuleCachePath = ModuleCachePath.c_str();
88}
89
90void deleteModuleCache(const std::string ModuleCachePath) {
91 if (!ModuleCachePath.empty()) {
92 if (llvm::sys::fs::remove_directories(ModuleCachePath)) {
93 llvm::errs() << "Failed to delete temp directory for module-cache";
94 std::abort();
95 }
96 }
97}
98
99std::shared_ptr<const PreambleData>
101 MockFS FS;
102 auto Inputs = inputs(FS);
103 IgnoreDiagnostics Diags;
104 auto CI = buildCompilerInvocation(Inputs, Diags);
105 assert(CI && "Failed to build compilation invocation.");
108 llvm::scope_exit ModuleCacheDeleter(
109 std::bind(deleteModuleCache, CI->getHeaderSearchOpts().ModuleCachePath));
111 /*StoreInMemory=*/true, PreambleCallback);
112}
113
116 llvm::errs() << "Use either ClangTidyProvider or FeatureModules\n";
117 std::abort();
118 }
119 MockFS FS;
120 auto Inputs = inputs(FS);
121 Inputs.Opts = ParseOpts;
122 FeatureModuleSet TidyModules;
123 if (ClangTidyProvider) {
124 TidyModules.add(std::make_unique<ClangTidyFeatureModule>(
125 [this](tidy::ClangTidyOptions &Opts, llvm::StringRef Filename) {
127 }));
128 Inputs.FeatureModules = &TidyModules;
129 }
130 StoreDiags Diags;
131 auto CI = buildCompilerInvocation(Inputs, Diags);
132 assert(CI && "Failed to build compilation invocation.");
135 llvm::scope_exit ModuleCacheDeleter(
136 std::bind(deleteModuleCache, CI->getHeaderSearchOpts().ModuleCachePath));
137
139 /*StoreInMemory=*/true,
140 /*PreambleCallback=*/nullptr);
141 auto AST = ParsedAST::build(testPath(Filename), Inputs, std::move(CI),
142 Diags.take(), Preamble);
143 if (!AST) {
144 llvm::errs() << "Failed to build code:\n" << Code;
145 std::abort();
146 }
147 // Check for error diagnostics and report gtest failures (unless expected).
148 // This guards against accidental syntax errors silently subverting tests.
149 // error-ok is awfully primitive - using clang -verify would be nicer.
150 // Ownership and layering makes it pretty hard.
151 bool ErrorOk = [&, this] {
152 llvm::StringLiteral Marker = "error-ok";
153 if (llvm::StringRef(Code).contains(Marker) ||
154 llvm::StringRef(HeaderCode).contains(Marker))
155 return true;
156 for (const auto &KV : this->AdditionalFiles)
157 if (llvm::StringRef(KV.second).contains(Marker))
158 return true;
159 return false;
160 }();
161 if (!ErrorOk) {
162 // We always build AST with a fresh preamble in TestTU.
163 for (const auto &D : AST->getDiagnostics())
164 if (D.Severity >= DiagnosticsEngine::Error) {
165 llvm::errs()
166 << "TestTU failed to build (suppress with /*error-ok*/): \n"
167 << D << "\n\nFor code:\n"
168 << Code;
169 std::abort(); // Stop after first error for simplicity.
170 }
171 }
172 return std::move(*AST);
173}
174
176 auto AST = build();
177 return std::get<0>(indexHeaderSymbols(
178 /*Version=*/"null", AST.getASTContext(), AST.getPreprocessor(),
179 AST.getPragmaIncludes(), SymbolOrigin::Preamble));
180}
181
183 auto AST = build();
184 return std::get<1>(indexMainDecls(AST));
185}
186
187std::unique_ptr<SymbolIndex> TestTU::index() const {
188 auto AST = build();
189 auto Idx = std::make_unique<FileIndex>(/*SupportContainedRefs=*/true);
190 Idx->updatePreamble(testPath(Filename), /*Version=*/"null",
191 AST.getASTContext(), AST.getPreprocessor(),
192 AST.getPragmaIncludes());
193 Idx->updateMain(testPath(Filename), AST);
194 return std::move(Idx);
195}
196
197const Symbol &findSymbol(const SymbolSlab &Slab, llvm::StringRef QName) {
198 const Symbol *Result = nullptr;
199 for (const Symbol &S : Slab) {
200 if (QName != (S.Scope + S.Name).str())
201 continue;
202 if (Result) {
203 llvm::errs() << "Multiple symbols named " << QName << ":\n"
204 << *Result << "\n---\n"
205 << S;
206 assert(false && "QName is not unique");
207 }
208 Result = &S;
209 }
210 if (!Result) {
211 llvm::errs() << "No symbol named " << QName << " in "
212 << llvm::to_string(Slab);
213 assert(false && "No symbol with QName");
214 }
215 return *Result;
216}
217
218// RAII scoped class to disable TraversalScope for a ParsedAST.
220 ASTContext &Ctx;
221 std::vector<Decl *> ScopeToRestore;
222
223public:
225 : Ctx(AST.getASTContext()), ScopeToRestore(Ctx.getTraversalScope()) {
226 Ctx.setTraversalScope({Ctx.getTranslationUnitDecl()});
227 }
228 ~TraverseHeadersToo() { Ctx.setTraversalScope(std::move(ScopeToRestore)); }
229};
230
231const NamedDecl &findDecl(ParsedAST &AST, llvm::StringRef QName) {
232 auto &Ctx = AST.getASTContext();
233 auto LookupDecl = [&Ctx](const DeclContext &Scope,
234 llvm::StringRef Name) -> const NamedDecl & {
235 auto LookupRes = Scope.lookup(DeclarationName(&Ctx.Idents.get(Name)));
236 assert(!LookupRes.empty() && "Lookup failed");
237 assert(LookupRes.isSingleResult() && "Lookup returned multiple results");
238 return *LookupRes.front();
239 };
240
241 const DeclContext *Scope = Ctx.getTranslationUnitDecl();
242
243 StringRef Cur, Rest;
244 for (std::tie(Cur, Rest) = QName.split("::"); !Rest.empty();
245 std::tie(Cur, Rest) = Rest.split("::")) {
246 Scope = &cast<DeclContext>(LookupDecl(*Scope, Cur));
247 }
248 return LookupDecl(*Scope, Cur);
249}
250
251const NamedDecl &findDecl(ParsedAST &AST,
252 std::function<bool(const NamedDecl &)> Filter) {
254 struct Visitor : RecursiveASTVisitor<Visitor> {
255 decltype(Filter) F;
256 llvm::SmallVector<const NamedDecl *, 1> Decls;
257 bool VisitNamedDecl(const NamedDecl *ND) {
258 if (F(*ND))
259 Decls.push_back(ND);
260 return true;
261 }
262 } Visitor;
263 Visitor.F = Filter;
264 Visitor.TraverseDecl(AST.getASTContext().getTranslationUnitDecl());
265 if (Visitor.Decls.size() != 1) {
266 llvm::errs() << Visitor.Decls.size() << " symbols matched.\n";
267 assert(Visitor.Decls.size() == 1);
268 }
269 return *Visitor.Decls.front();
270}
271
272const NamedDecl &findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name) {
273 return findDecl(AST, [Name](const NamedDecl &ND) {
274 if (auto *ID = ND.getIdentifier())
275 if (ID->getName() == Name)
276 return true;
277 return false;
278 });
279}
280
281} // namespace clangd
282} // namespace clang
A FeatureModuleSet is a collection of feature modules installed in clangd.
void add(std::unique_ptr< FeatureModule > M)
llvm::StringMap< std::string > Files
Definition TestFS.h:45
bool OverlayRealFileSystemForModules
Definition TestFS.h:49
Stores and provides access to parsed AST.
Definition ParsedAST.h:47
static std::optional< ParsedAST > build(llvm::StringRef Filename, const ParseInputs &Inputs, std::unique_ptr< clang::CompilerInvocation > CI, llvm::ArrayRef< Diag > CompilerInvocationDiags, std::shared_ptr< const PreambleData > Preamble)
Attempts to run Clang and store the parsed AST.
An efficient structure of storing large set of symbol references in memory.
Definition Ref.h:111
StoreDiags collects the diagnostics that can later be reported by clangd.
std::vector< Diag > take()
An immutable symbol container that stores a set of symbols.
Definition Symbol.h:215
TraverseHeadersToo(ParsedAST &AST)
Definition TestTU.cpp:224
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
const NamedDecl & findDecl(ParsedAST &AST, llvm::StringRef QName)
Definition TestTU.cpp:231
std::unique_ptr< CompilerInvocation > buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D, std::vector< std::string > *CC1Args)
Builds compiler invocation that could be used to build AST or preamble.
Definition Compiler.cpp:96
SlabTuple indexMainDecls(ParsedAST &AST)
Retrieves symbols and refs of local top level decls in AST (i.e.
std::string testPath(PathRef File, llvm::sys::path::Style Style)
Definition TestFS.cpp:94
std::shared_ptr< const PreambleData > buildPreamble(PathRef FileName, CompilerInvocation CI, const ParseInputs &Inputs, bool StoreInMemory, PreambleParsedCallback PreambleCallback, PreambleBuildStats *Stats)
Build a preamble for the new inputs unless an old one can be reused.
Definition Preamble.cpp:578
SlabTuple indexHeaderSymbols(llvm::StringRef Version, ASTContext &AST, Preprocessor &PP, const include_cleaner::PragmaIncludes &PI, SymbolOrigin Origin)
Index declarations from AST and macros from PP that are declared in included headers.
const NamedDecl & findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name)
Definition TestTU.cpp:272
void initializeModuleCache(CompilerInvocation &CI)
Definition TestTU.cpp:81
const Symbol & findSymbol(const SymbolSlab &Slab, llvm::StringRef QName)
Definition TestTU.cpp:197
void deleteModuleCache(const std::string ModuleCachePath)
Definition TestTU.cpp:90
std::function< void(CapturedASTCtx ASTCtx, std::shared_ptr< const include_cleaner::PragmaIncludes >)> PreambleParsedCallback
Definition Preamble.h:133
const char * testRoot()
Definition TestFS.cpp:85
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static CommandMangler forTests()
Information required to run clang, e.g. to parse AST or do code completion.
Definition Compiler.h:50
tooling::CompileCommand CompileCommand
Definition Compiler.h:51
const ThreadsafeFS * TFS
Definition Compiler.h:52
FeatureModuleSet * FeatureModules
Definition Compiler.h:63
const SymbolIndex * Index
Definition Compiler.h:60
Ensure we have enough bits to represent all SymbolTag values.
Definition Symbol.h:49
std::vector< std::string > ExtraArgs
Definition TestTU.h:60
TidyProvider ClangTidyProvider
Definition TestTU.h:65
std::string Code
Definition TestTU.h:49
ParsedAST build() const
Definition TestTU.cpp:114
std::string Filename
Definition TestTU.h:50
ParseInputs inputs(MockFS &FS) const
Definition TestTU.cpp:28
RefSlab headerRefs() const
Definition TestTU.cpp:182
ParseOptions ParseOpts
Definition TestTU.h:73
std::string HeaderFilename
Definition TestTU.h:54
SymbolSlab headerSymbols() const
Definition TestTU.cpp:175
std::shared_ptr< const PreambleData > preamble(PreambleParsedCallback PreambleCallback=nullptr) const
Definition TestTU.cpp:100
bool OverlayRealFileSystemForModules
Definition TestTU.h:83
const SymbolIndex * ExternalIndex
Definition TestTU.h:67
llvm::StringMap< std::string > AdditionalFiles
Definition TestTU.h:57
FeatureModuleSet * FeatureModules
Definition TestTU.h:85
std::string HeaderCode
Definition TestTU.h:53
std::unique_ptr< SymbolIndex > index() const
Definition TestTU.cpp:187
Contains options for clang-tidy.