clang-tools  15.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 "clang/AST/RecursiveASTVisitor.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Frontend/CompilerInvocation.h"
18 #include "llvm/ADT/ScopeExit.h"
19 #include "llvm/Support/ScopedPrinter.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <cstdlib>
22 
23 namespace clang {
24 namespace clangd {
25 
27  std::string FullFilename = testPath(Filename),
28  FullHeaderName = testPath(HeaderFilename),
29  ImportThunk = testPath("import_thunk.h");
30  // We want to implicitly include HeaderFilename without messing up offsets.
31  // -include achieves this, but sometimes we want #import (to simulate a header
32  // guard without messing up offsets). In this case, use an intermediate file.
33  std::string ThunkContents = "#import \"" + FullHeaderName + "\"\n";
34 
35  FS.Files = AdditionalFiles;
36  FS.Files[FullFilename] = Code;
37  FS.Files[FullHeaderName] = HeaderCode;
38  FS.Files[ImportThunk] = ThunkContents;
39 
41  Inputs.FeatureModules = FeatureModules;
42  auto &Argv = Inputs.CompileCommand.CommandLine;
43  // In tests, omit predefined macros (__GNUC__ etc) for a 25% speedup.
44  // There are hundreds, and we'd generate, parse, serialize, and re-parse them!
45  Argv = {"clang", "-Xclang", "-undef"};
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);
112  Inputs.Opts = ParseOpts;
115  assert(CI && "Failed to build compilation invocation.");
118  auto ModuleCacheDeleter = llvm::make_scope_exit(
119  std::bind(deleteModuleCache, CI->getHeaderSearchOpts().ModuleCachePath));
120 
122  /*StoreInMemory=*/true,
123  /*PreambleCallback=*/nullptr);
124  auto AST = ParsedAST::build(testPath(Filename), Inputs, std::move(CI),
125  Diags.take(), Preamble);
126  if (!AST.hasValue()) {
127  llvm::errs() << "Failed to build code:\n" << Code;
128  std::abort();
129  }
130  assert(AST->getDiagnostics() &&
131  "TestTU should always build an AST with a fresh Preamble");
132  // Check for error diagnostics and report gtest failures (unless expected).
133  // This guards against accidental syntax errors silently subverting tests.
134  // error-ok is awfully primitive - using clang -verify would be nicer.
135  // Ownership and layering makes it pretty hard.
136  bool ErrorOk = [&, this] {
137  llvm::StringLiteral Marker = "error-ok";
138  if (llvm::StringRef(Code).contains(Marker) ||
139  llvm::StringRef(HeaderCode).contains(Marker))
140  return true;
141  for (const auto &KV : this->AdditionalFiles)
142  if (llvm::StringRef(KV.second).contains(Marker))
143  return true;
144  return false;
145  }();
146  if (!ErrorOk) {
147  // We always build AST with a fresh preamble in TestTU.
148  for (const auto &D : *AST->getDiagnostics())
149  if (D.Severity >= DiagnosticsEngine::Error) {
150  llvm::errs()
151  << "TestTU failed to build (suppress with /*error-ok*/): \n"
152  << D << "\n\nFor code:\n"
153  << Code;
154  std::abort(); // Stop after first error for simplicity.
155  }
156  }
157  return std::move(*AST);
158 }
159 
161  auto AST = build();
162  return std::get<0>(indexHeaderSymbols(/*Version=*/"null", AST.getASTContext(),
163  AST.getPreprocessor(),
164  AST.getCanonicalIncludes()));
165 }
166 
168  auto AST = build();
169  return std::get<1>(indexMainDecls(AST));
170 }
171 
172 std::unique_ptr<SymbolIndex> TestTU::index() const {
173  auto AST = build();
174  auto Idx = std::make_unique<FileIndex>();
175  Idx->updatePreamble(testPath(Filename), /*Version=*/"null",
176  AST.getASTContext(), AST.getPreprocessor(),
177  AST.getCanonicalIncludes());
178  Idx->updateMain(testPath(Filename), AST);
179  return std::move(Idx);
180 }
181 
182 const Symbol &findSymbol(const SymbolSlab &Slab, llvm::StringRef QName) {
183  const Symbol *Result = nullptr;
184  for (const Symbol &S : Slab) {
185  if (QName != (S.Scope + S.Name).str())
186  continue;
187  if (Result) {
188  llvm::errs() << "Multiple symbols named " << QName << ":\n"
189  << *Result << "\n---\n"
190  << S;
191  assert(false && "QName is not unique");
192  }
193  Result = &S;
194  }
195  if (!Result) {
196  llvm::errs() << "No symbol named " << QName << " in "
197  << llvm::to_string(Slab);
198  assert(false && "No symbol with QName");
199  }
200  return *Result;
201 }
202 
203 // RAII scoped class to disable TraversalScope for a ParsedAST.
205  ASTContext &Ctx;
206  std::vector<Decl *> ScopeToRestore;
207 
208 public:
210  : Ctx(AST.getASTContext()), ScopeToRestore(Ctx.getTraversalScope()) {
211  Ctx.setTraversalScope({Ctx.getTranslationUnitDecl()});
212  }
213  ~TraverseHeadersToo() { Ctx.setTraversalScope(std::move(ScopeToRestore)); }
214 };
215 
216 const NamedDecl &findDecl(ParsedAST &AST, llvm::StringRef QName) {
217  auto &Ctx = AST.getASTContext();
218  auto LookupDecl = [&Ctx](const DeclContext &Scope,
219  llvm::StringRef Name) -> const NamedDecl & {
220  auto LookupRes = Scope.lookup(DeclarationName(&Ctx.Idents.get(Name)));
221  assert(!LookupRes.empty() && "Lookup failed");
222  assert(LookupRes.isSingleResult() && "Lookup returned multiple results");
223  return *LookupRes.front();
224  };
225 
226  const DeclContext *Scope = Ctx.getTranslationUnitDecl();
227 
228  StringRef Cur, Rest;
229  for (std::tie(Cur, Rest) = QName.split("::"); !Rest.empty();
230  std::tie(Cur, Rest) = Rest.split("::")) {
231  Scope = &cast<DeclContext>(LookupDecl(*Scope, Cur));
232  }
233  return LookupDecl(*Scope, Cur);
234 }
235 
236 const NamedDecl &findDecl(ParsedAST &AST,
237  std::function<bool(const NamedDecl &)> Filter) {
238  TraverseHeadersToo Too(AST);
239  struct Visitor : RecursiveASTVisitor<Visitor> {
240  decltype(Filter) F;
241  llvm::SmallVector<const NamedDecl *, 1> Decls;
242  bool VisitNamedDecl(const NamedDecl *ND) {
243  if (F(*ND))
244  Decls.push_back(ND);
245  return true;
246  }
247  } Visitor;
248  Visitor.F = Filter;
249  Visitor.TraverseDecl(AST.getASTContext().getTranslationUnitDecl());
250  if (Visitor.Decls.size() != 1) {
251  llvm::errs() << Visitor.Decls.size() << " symbols matched.\n";
252  assert(Visitor.Decls.size() == 1);
253  }
254  return *Visitor.Decls.front();
255 }
256 
257 const NamedDecl &findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name) {
258  return findDecl(AST, [Name](const NamedDecl &ND) {
259  if (auto *ID = ND.getIdentifier())
260  if (ID->getName() == Name)
261  return true;
262  return false;
263  });
264 }
265 
266 } // namespace clangd
267 } // namespace clang
clang::clangd::TestTU::ExtraArgs
std::vector< std::string > ExtraArgs
Definition: TestTU.h:60
clang::clangd::TestTU::HeaderFilename
std::string HeaderFilename
Definition: TestTU.h:54
clang::clangd::buildPreamble
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:466
clang::clangd::findDecl
const NamedDecl & findDecl(ParsedAST &AST, llvm::StringRef QName)
Definition: TestTU.cpp:216
clang::clangd::indexHeaderSymbols
SlabTuple indexHeaderSymbols(llvm::StringRef Version, ASTContext &AST, Preprocessor &PP, const CanonicalIncludes &Includes)
Index declarations from AST and macros from PP that are declared in included headers.
Definition: FileIndex.cpp:229
clang::clangd::TraverseHeadersToo::TraverseHeadersToo
TraverseHeadersToo(ParsedAST &AST)
Definition: TestTU.cpp:209
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:94
clang::clangd::TestTU::build
ParsedAST build() const
Definition: TestTU.cpp:109
clang::clangd::TestTU::headerSymbols
SymbolSlab headerSymbols() const
Definition: TestTU.cpp:160
clang::clangd::initializeModuleCache
void initializeModuleCache(CompilerInvocation &CI)
Definition: TestTU.cpp:76
clang::clangd::TestTU::headerRefs
RefSlab headerRefs() const
Definition: TestTU.cpp:167
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:697
CI
std::unique_ptr< CompilerInvocation > CI
Definition: TUScheduler.cpp:491
TestTU.h
Ctx
Context Ctx
Definition: TUScheduler.cpp:495
clang::clangd::RefSlab
An efficient structure of storing large set of symbol references in memory.
Definition: Ref.h:108
clang::clangd::TestTU::preamble
std::shared_ptr< const PreambleData > preamble(PreambleParsedCallback PreambleCallback=nullptr) const
Definition: TestTU.cpp:95
clang::clangd::TraverseHeadersToo
Definition: TestTU.cpp:204
clang::clangd::TestTU::Code
std::string Code
Definition: TestTU.h:49
clang::clangd::findUnqualifiedDecl
const NamedDecl & findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name)
Definition: TestTU.cpp:257
Preamble
const PreambleData & Preamble
Definition: CodeComplete.cpp:1204
clang::clangd::TestTU::ExternalIndex
const SymbolIndex * ExternalIndex
Definition: TestTU.h:64
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:342
clang::clangd::TestTU::inputs
ParseInputs inputs(MockFS &FS) const
Definition: TestTU.cpp:26
Error
constexpr static llvm::SourceMgr::DiagKind Error
Definition: ConfigCompile.cpp:591
Inputs
ParseInputs Inputs
Definition: TUScheduler.cpp:492
clang::clangd::TestTU::ClangTidyProvider
TidyProvider ClangTidyProvider
Definition: TestTU.h:62
clang::clangd::ParseInputs
Information required to run clang, e.g. to parse AST or do code completion.
Definition: Compiler.h:46
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
clang::clangd::testRoot
const char * testRoot()
Definition: TestFS.cpp:86
clang::clangd::MockFS
Definition: TestFS.h:32
CompileCommands.h
clang::clangd::TestTU::Filename
std::string Filename
Definition: TestTU.h:50
TestFS.h
clang::clangd::Symbol
The class presents a C++ symbol, e.g.
Definition: Symbol.h:36
clang::clangd::TestTU::OverlayRealFileSystemForModules
bool OverlayRealFileSystemForModules
Definition: TestTU.h:80
Diagnostics.h
Name
Token Name
Definition: MacroToEnumCheck.cpp:89
FileIndex.h
clang::clangd::TraverseHeadersToo::~TraverseHeadersToo
~TraverseHeadersToo()
Definition: TestTU.cpp:213
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:86
clang::clangd::TestTU::ImplicitHeaderGuard
bool ImplicitHeaderGuard
Definition: TestTU.h:67
Compiler.h
ID
static char ID
Definition: Logger.cpp:74
clang::clangd::ParseOptions
Definition: Compiler.h:41
clang::clangd::TestTU::ParseOpts
ParseOptions ParseOpts
Definition: TestTU.h:70
clang::clangd::TestTU::index
std::unique_ptr< SymbolIndex > index() const
Definition: TestTU.cpp:172
if
if(CLANG_PLUGIN_SUPPORT) export_executable_symbols_for_plugins(clang-tidy) endif() install(PROGRAMS clang-tidy-diff.py DESTINATION "$
Definition: clang-tidy/tool/CMakeLists.txt:59
clang::clangd::TestTU::FeatureModules
FeatureModuleSet * FeatureModules
Definition: TestTU.h:82
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:137
Diags
CapturedDiags Diags
Definition: ConfigCompileTests.cpp:39
clang::clangd::ParsedAST
Stores and provides access to parsed AST.
Definition: ParsedAST.h:45
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::PreambleParsedCallback
std::function< void(ASTContext &, Preprocessor &, const CanonicalIncludes &)> PreambleParsedCallback
Definition: Preamble.h:76
clang::clangd::TestTU::AdditionalFiles
llvm::StringMap< std::string > AdditionalFiles
Definition: TestTU.h:57
clang::clangd::findSymbol
const Symbol & findSymbol(const SymbolSlab &Slab, llvm::StringRef QName)
Definition: TestTU.cpp:182
clang::clangd::IgnoreDiagnostics
Definition: Compiler.h:31
clang::clangd::TestTU::HeaderCode
std::string HeaderCode
Definition: TestTU.h:53
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:222