clang-tools  14.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"
10 #include "CompileCommands.h"
11 #include "Compiler.h"
12 #include "Diagnostics.h"
13 #include "TestFS.h"
14 #include "index/FileIndex.h"
15 #include "index/MemIndex.h"
16 #include "clang/AST/RecursiveASTVisitor.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Frontend/CompilerInvocation.h"
19 #include "clang/Frontend/Utils.h"
20 #include "llvm/ADT/ScopeExit.h"
21 #include "llvm/Support/ScopedPrinter.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <cstdlib>
24 
25 namespace clang {
26 namespace 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 
37  FS.Files = AdditionalFiles;
38  FS.Files[FullFilename] = Code;
39  FS.Files[FullHeaderName] = HeaderCode;
40  FS.Files[ImportThunk] = ThunkContents;
41 
43  Inputs.FeatureModules = FeatureModules;
44  auto &Argv = Inputs.CompileCommand.CommandLine;
45  Argv = {"clang"};
46  // FIXME: this shouldn't need to be conditional, but it breaks a
47  // GoToDefinition test for some reason (getMacroArgExpandedLocation fails).
48  if (!HeaderCode.empty()) {
49  Argv.push_back("-include");
50  Argv.push_back(ImplicitHeaderGuard ? ImportThunk : FullHeaderName);
51  // ms-compatibility changes the meaning of #import.
52  // The default is OS-dependent (on on windows), ensure it's off.
54  Inputs.CompileCommand.CommandLine.push_back("-fno-ms-compatibility");
55  }
56  Argv.insert(Argv.end(), ExtraArgs.begin(), ExtraArgs.end());
57  // Put the file name at the end -- this allows the extra arg (-xc++) to
58  // override the language setting.
59  Argv.push_back(FullFilename);
60 
61  auto Mangler = CommandMangler::forTests();
62  Mangler.adjust(Inputs.CompileCommand.CommandLine, FullFilename);
63  Inputs.CompileCommand.Filename = FullFilename;
64  Inputs.CompileCommand.Directory = testRoot();
65  Inputs.Contents = Code;
67  FS.OverlayRealFileSystemForModules = true;
68  Inputs.TFS = &FS;
69  Inputs.Opts = ParseOptions();
71  Inputs.ClangTidyProvider = ClangTidyProvider;
72  Inputs.Index = ExternalIndex;
73  return Inputs;
74 }
75 
76 void initializeModuleCache(CompilerInvocation &CI) {
77  llvm::SmallString<128> ModuleCachePath;
78  if (llvm::sys::fs::createUniqueDirectory("module-cache", ModuleCachePath)) {
79  llvm::errs() << "Failed to create temp directory for module-cache";
80  std::abort();
81  }
82  CI.getHeaderSearchOpts().ModuleCachePath = ModuleCachePath.c_str();
83 }
84 
85 void deleteModuleCache(const std::string ModuleCachePath) {
86  if (!ModuleCachePath.empty()) {
87  if (llvm::sys::fs::remove_directories(ModuleCachePath)) {
88  llvm::errs() << "Failed to delete temp directory for module-cache";
89  std::abort();
90  }
91  }
92 }
93 
94 std::shared_ptr<const PreambleData>
95 TestTU::preamble(PreambleParsedCallback PreambleCallback) const {
96  MockFS FS;
97  auto Inputs = inputs(FS);
100  assert(CI && "Failed to build compilation invocation.");
103  auto ModuleCacheDeleter = llvm::make_scope_exit(
104  std::bind(deleteModuleCache, CI->getHeaderSearchOpts().ModuleCachePath));
106  /*StoreInMemory=*/true, PreambleCallback);
107 }
108 
110  MockFS FS;
111  auto Inputs = inputs(FS);
114  assert(CI && "Failed to build compilation invocation.");
117  auto ModuleCacheDeleter = llvm::make_scope_exit(
118  std::bind(deleteModuleCache, CI->getHeaderSearchOpts().ModuleCachePath));
119 
121  /*StoreInMemory=*/true,
122  /*PreambleCallback=*/nullptr);
123  auto AST = ParsedAST::build(testPath(Filename), Inputs, std::move(CI),
124  Diags.take(), Preamble);
125  if (!AST.hasValue()) {
126  llvm::errs() << "Failed to build code:\n" << Code;
127  std::abort();
128  }
129  assert(AST->getDiagnostics() &&
130  "TestTU should always build an AST with a fresh Preamble");
131  // Check for error diagnostics and report gtest failures (unless expected).
132  // This guards against accidental syntax errors silently subverting tests.
133  // error-ok is awfully primitive - using clang -verify would be nicer.
134  // Ownership and layering makes it pretty hard.
135  bool ErrorOk = [&, this] {
136  llvm::StringLiteral Marker = "error-ok";
137  if (llvm::StringRef(Code).contains(Marker) ||
138  llvm::StringRef(HeaderCode).contains(Marker))
139  return true;
140  for (const auto &KV : this->AdditionalFiles)
141  if (llvm::StringRef(KV.second).contains(Marker))
142  return true;
143  return false;
144  }();
145  if (!ErrorOk) {
146  // We always build AST with a fresh preamble in TestTU.
147  for (const auto &D : *AST->getDiagnostics())
148  if (D.Severity >= DiagnosticsEngine::Error) {
149  llvm::errs()
150  << "TestTU failed to build (suppress with /*error-ok*/): \n"
151  << D << "\n\nFor code:\n"
152  << Code;
153  std::abort(); // Stop after first error for simplicity.
154  }
155  }
156  return std::move(*AST);
157 }
158 
160  auto AST = build();
161  return std::get<0>(indexHeaderSymbols(/*Version=*/"null", AST.getASTContext(),
162  AST.getPreprocessorPtr(),
163  AST.getCanonicalIncludes()));
164 }
165 
167  auto AST = build();
168  return std::get<1>(indexMainDecls(AST));
169 }
170 
171 std::unique_ptr<SymbolIndex> TestTU::index() const {
172  auto AST = build();
173  auto Idx = std::make_unique<FileIndex>();
174  Idx->updatePreamble(testPath(Filename), /*Version=*/"null",
175  AST.getASTContext(), AST.getPreprocessorPtr(),
176  AST.getCanonicalIncludes());
177  Idx->updateMain(testPath(Filename), AST);
178  return std::move(Idx);
179 }
180 
181 const Symbol &findSymbol(const SymbolSlab &Slab, llvm::StringRef QName) {
182  const Symbol *Result = nullptr;
183  for (const Symbol &S : Slab) {
184  if (QName != (S.Scope + S.Name).str())
185  continue;
186  if (Result) {
187  llvm::errs() << "Multiple symbols named " << QName << ":\n"
188  << *Result << "\n---\n"
189  << S;
190  assert(false && "QName is not unique");
191  }
192  Result = &S;
193  }
194  if (!Result) {
195  llvm::errs() << "No symbol named " << QName << " in "
196  << llvm::to_string(Slab);
197  assert(false && "No symbol with QName");
198  }
199  return *Result;
200 }
201 
202 // RAII scoped class to disable TraversalScope for a ParsedAST.
204  ASTContext &Ctx;
205  std::vector<Decl *> ScopeToRestore;
206 
207 public:
209  : Ctx(AST.getASTContext()), ScopeToRestore(Ctx.getTraversalScope()) {
210  Ctx.setTraversalScope({Ctx.getTranslationUnitDecl()});
211  }
212  ~TraverseHeadersToo() { Ctx.setTraversalScope(std::move(ScopeToRestore)); }
213 };
214 
215 const NamedDecl &findDecl(ParsedAST &AST, llvm::StringRef QName) {
216  auto &Ctx = AST.getASTContext();
217  auto LookupDecl = [&Ctx](const DeclContext &Scope,
218  llvm::StringRef Name) -> const NamedDecl & {
219  auto LookupRes = Scope.lookup(DeclarationName(&Ctx.Idents.get(Name)));
220  assert(!LookupRes.empty() && "Lookup failed");
221  assert(LookupRes.isSingleResult() && "Lookup returned multiple results");
222  return *LookupRes.front();
223  };
224 
225  const DeclContext *Scope = Ctx.getTranslationUnitDecl();
226 
227  StringRef Cur, Rest;
228  for (std::tie(Cur, Rest) = QName.split("::"); !Rest.empty();
229  std::tie(Cur, Rest) = Rest.split("::")) {
230  Scope = &cast<DeclContext>(LookupDecl(*Scope, Cur));
231  }
232  return LookupDecl(*Scope, Cur);
233 }
234 
235 const NamedDecl &findDecl(ParsedAST &AST,
236  std::function<bool(const NamedDecl &)> Filter) {
237  TraverseHeadersToo Too(AST);
238  struct Visitor : RecursiveASTVisitor<Visitor> {
239  decltype(Filter) F;
240  llvm::SmallVector<const NamedDecl *, 1> Decls;
241  bool VisitNamedDecl(const NamedDecl *ND) {
242  if (F(*ND))
243  Decls.push_back(ND);
244  return true;
245  }
246  } Visitor;
247  Visitor.F = Filter;
248  Visitor.TraverseDecl(AST.getASTContext().getTranslationUnitDecl());
249  if (Visitor.Decls.size() != 1) {
250  llvm::errs() << Visitor.Decls.size() << " symbols matched.";
251  assert(Visitor.Decls.size() == 1);
252  }
253  return *Visitor.Decls.front();
254 }
255 
256 const NamedDecl &findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name) {
257  return findDecl(AST, [Name](const NamedDecl &ND) {
258  if (auto *ID = ND.getIdentifier())
259  if (ID->getName() == Name)
260  return true;
261  return false;
262  });
263 }
264 
265 } // namespace clangd
266 } // namespace clang
clang::clangd::TestTU::ExtraArgs
std::vector< std::string > ExtraArgs
Definition: TestTU.h:61
clang::clangd::TestTU::HeaderFilename
std::string HeaderFilename
Definition: TestTU.h:55
clang::clangd::findDecl
const NamedDecl & findDecl(ParsedAST &AST, llvm::StringRef QName)
Definition: TestTU.cpp:215
clang::clangd::TraverseHeadersToo::TraverseHeadersToo
TraverseHeadersToo(ParsedAST &AST)
Definition: TestTU.cpp:208
RecursiveASTVisitor
clang::clangd::deleteModuleCache
void deleteModuleCache(const std::string ModuleCachePath)
Definition: TestTU.cpp:85
clang::clangd::testPath
std::string testPath(PathRef File, llvm::sys::path::Style Style)
Definition: TestFS.cpp:82
clang::clangd::PreambleParsedCallback
std::function< void(ASTContext &, std::shared_ptr< clang::Preprocessor >, const CanonicalIncludes &)> PreambleParsedCallback
Definition: Preamble.h:75
clang::clangd::TestTU::build
ParsedAST build() const
Definition: TestTU.cpp:109
clang::clangd::TestTU::headerSymbols
SymbolSlab headerSymbols() const
Definition: TestTU.cpp:159
clang::clangd::initializeModuleCache
void initializeModuleCache(CompilerInvocation &CI)
Definition: TestTU.cpp:76
clang::clangd::TestTU::headerRefs
RefSlab headerRefs() const
Definition: TestTU.cpp:166
clang::clangd::Context::get
const Type * get(const Key< Type > &Key) const
Get data stored for a typed Key.
Definition: Context.h:98
clang::clangd::ParsedAST::getASTContext
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
Definition: ParsedAST.cpp:532
CI
std::unique_ptr< CompilerInvocation > CI
Definition: TUScheduler.cpp:450
TestTU.h
Ctx
Context Ctx
Definition: TUScheduler.cpp:454
clang::clangd::RefSlab
An efficient structure of storing large set of symbol references in memory.
Definition: Ref.h:110
clang::clangd::TestTU::preamble
std::shared_ptr< const PreambleData > preamble(PreambleParsedCallback PreambleCallback=nullptr) const
Definition: TestTU.cpp:95
clang::clangd::TraverseHeadersToo
Definition: TestTU.cpp:203
clang::clangd::TestTU::Code
std::string Code
Definition: TestTU.h:50
clang::clangd::findUnqualifiedDecl
const NamedDecl & findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name)
Definition: TestTU.cpp:256
Preamble
const PreambleData & Preamble
Definition: CodeComplete.cpp:1104
clang::clangd::TestTU::ExternalIndex
const SymbolIndex * ExternalIndex
Definition: TestTU.h:65
clang::clangd::ParsedAST::build
static llvm::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.
Definition: ParsedAST.cpp:248
clang::clangd::TestTU::inputs
ParseInputs inputs(MockFS &FS) const
Definition: TestTU.cpp:28
Error
constexpr static llvm::SourceMgr::DiagKind Error
Definition: ConfigCompile.cpp:500
Inputs
ParseInputs Inputs
Definition: TUScheduler.cpp:451
clang::clangd::TestTU::ClangTidyProvider
TidyProvider ClangTidyProvider
Definition: TestTU.h:63
clang::clangd::ParseInputs
Information required to run clang, e.g. to parse AST or do code completion.
Definition: Compiler.h:47
MemIndex.h
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
clang::clangd::testRoot
const char * testRoot()
Definition: TestFS.cpp:74
clang::clangd::MockFS
Definition: TestFS.h:34
CompileCommands.h
clang::clangd::TestTU::Filename
std::string Filename
Definition: TestTU.h:51
clang::clangd::buildPreamble
std::shared_ptr< const PreambleData > buildPreamble(PathRef FileName, CompilerInvocation CI, const ParseInputs &Inputs, bool StoreInMemory, PreambleParsedCallback PreambleCallback)
Build a preamble for the new inputs unless an old one can be reused.
Definition: Preamble.cpp:318
TestFS.h
clang::clangd::Symbol
The class presents a C++ symbol, e.g.
Definition: Symbol.h:36
if
if(CLANGD_ENABLE_REMOTE) generate_protos(RemoteIndexProto "Index.proto") generate_protos(MonitoringServiceProto "MonitoringService.proto" GRPC) generate_protos(RemoteIndexServiceProto "Service.proto" DEPENDS "Index.proto" GRPC) target_link_libraries(RemoteIndexServiceProto PRIVATE RemoteIndexProto MonitoringServiceProto) include_directories($
Definition: clangd/index/remote/CMakeLists.txt:1
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
clang::clangd::TestTU::OverlayRealFileSystemForModules
bool OverlayRealFileSystemForModules
Definition: TestTU.h:78
Diagnostics.h
clang::clangd::indexHeaderSymbols
SlabTuple indexHeaderSymbols(llvm::StringRef Version, ASTContext &AST, std::shared_ptr< Preprocessor > PP, const CanonicalIncludes &Includes)
Index declarations from AST and macros from PP that are declared in included headers.
Definition: FileIndex.cpp:227
FileIndex.h
clang::clangd::TraverseHeadersToo::~TraverseHeadersToo
~TraverseHeadersToo()
Definition: TestTU.cpp:212
clang::clangd::buildCompilerInvocation
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:84
clang::clangd::TestTU::ImplicitHeaderGuard
bool ImplicitHeaderGuard
Definition: TestTU.h:68
Compiler.h
ID
static char ID
Definition: Logger.cpp:74
clang::clangd::ParseOptions
Definition: Compiler.h:42
clang::clangd::TestTU::index
std::unique_ptr< SymbolIndex > index() const
Definition: TestTU.cpp:171
clang::clangd::TestTU::FeatureModules
FeatureModuleSet * FeatureModules
Definition: TestTU.h:80
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::clangd::StoreDiags
StoreDiags collects the diagnostics that can later be reported by clangd.
Definition: Diagnostics.h:135
Diags
CapturedDiags Diags
Definition: ConfigCompileTests.cpp:38
clang::clangd::ParsedAST
Stores and provides access to parsed AST.
Definition: ParsedAST.h:49
clang::clangd::CommandMangler::forTests
static CommandMangler forTests()
Definition: CompileCommands.cpp:196
clang::clangd::SymbolSlab
An immutable symbol container that stores a set of symbols.
Definition: Symbol.h:177
clang::clangd::TestTU::AdditionalFiles
llvm::StringMap< std::string > AdditionalFiles
Definition: TestTU.h:58
clang::clangd::findSymbol
const Symbol & findSymbol(const SymbolSlab &Slab, llvm::StringRef QName)
Definition: TestTU.cpp:181
clang::clangd::IgnoreDiagnostics
Definition: Compiler.h:32
clang::clangd::TestTU::HeaderCode
std::string HeaderCode
Definition: TestTU.h:54
contains
This directory contains
Definition: README.txt:6
clang::clangd::indexMainDecls
SlabTuple indexMainDecls(ParsedAST &AST)
Retrieves symbols and refs of local top level decls in AST (i.e.
Definition: FileIndex.cpp:220