clang-tools  9.0.0
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 "TestFS.h"
11 #include "index/FileIndex.h"
12 #include "index/MemIndex.h"
13 #include "clang/AST/RecursiveASTVisitor.h"
14 #include "clang/Frontend/CompilerInvocation.h"
15 #include "clang/Frontend/Utils.h"
16 
17 namespace clang {
18 namespace clangd {
19 
21  std::string FullFilename = testPath(Filename),
22  FullHeaderName = testPath(HeaderFilename),
23  ImportThunk = testPath("import_thunk.h");
24  // We want to implicitly include HeaderFilename without messing up offsets.
25  // -include achieves this, but sometimes we want #import (to simulate a header
26  // guard without messing up offsets). In this case, use an intermediate file.
27  std::string ThunkContents = "#import \"" + FullHeaderName + "\"\n";
28 
29  llvm::StringMap<std::string> Files(AdditionalFiles);
30  Files[FullFilename] = Code;
31  Files[FullHeaderName] = HeaderCode;
32  Files[ImportThunk] = ThunkContents;
33 
34  std::vector<const char *> Cmd = {"clang"};
35  // FIXME: this shouldn't need to be conditional, but it breaks a
36  // GoToDefinition test for some reason (getMacroArgExpandedLocation fails).
37  if (!HeaderCode.empty()) {
38  Cmd.push_back("-include");
39  Cmd.push_back(ImplicitHeaderGuard ? ImportThunk.c_str()
40  : FullHeaderName.c_str());
41  // ms-compatibility changes the meaning of #import.
42  // The default is OS-dependent (on on windows), ensure it's off.
44  Cmd.push_back("-fno-ms-compatibility");
45  }
46  Cmd.insert(Cmd.end(), ExtraArgs.begin(), ExtraArgs.end());
47  // Put the file name at the end -- this allows the extra arg (-xc++) to
48  // override the language setting.
49  Cmd.push_back(FullFilename.c_str());
50  ParseInputs Inputs;
51  Inputs.CompileCommand.Filename = FullFilename;
52  Inputs.CompileCommand.CommandLine = {Cmd.begin(), Cmd.end()};
53  Inputs.CompileCommand.Directory = testRoot();
54  Inputs.Contents = Code;
55  Inputs.FS = buildTestFS(Files);
56  Inputs.Opts = ParseOptions();
59  Inputs.Index = ExternalIndex;
60  if (Inputs.Index)
61  Inputs.Opts.SuggestMissingIncludes = true;
62  auto CI = buildCompilerInvocation(Inputs);
63  assert(CI && "Failed to build compilation invocation.");
64  auto Preamble =
65  buildPreamble(FullFilename, *CI,
66  /*OldPreamble=*/nullptr,
67  /*OldCompileCommand=*/Inputs.CompileCommand, Inputs,
68  /*StoreInMemory=*/true, /*PreambleCallback=*/nullptr);
69  auto AST = buildAST(FullFilename, std::move(CI), Inputs, Preamble);
70  if (!AST.hasValue()) {
71  ADD_FAILURE() << "Failed to build code:\n" << Code;
72  llvm_unreachable("Failed to build TestTU!");
73  }
74  return std::move(*AST);
75 }
76 
78  auto AST = build();
79  return std::get<0>(indexHeaderSymbols(AST.getASTContext(),
80  AST.getPreprocessorPtr(),
81  AST.getCanonicalIncludes()));
82 }
83 
84 std::unique_ptr<SymbolIndex> TestTU::index() const {
85  auto AST = build();
86  auto Idx = llvm::make_unique<FileIndex>(/*UseDex=*/true);
87  Idx->updatePreamble(Filename, AST.getASTContext(), AST.getPreprocessorPtr(),
88  AST.getCanonicalIncludes());
89  Idx->updateMain(Filename, AST);
90  return std::move(Idx);
91 }
92 
93 const Symbol &findSymbol(const SymbolSlab &Slab, llvm::StringRef QName) {
94  const Symbol *Result = nullptr;
95  for (const Symbol &S : Slab) {
96  if (QName != (S.Scope + S.Name).str())
97  continue;
98  if (Result) {
99  ADD_FAILURE() << "Multiple symbols named " << QName << ":\n"
100  << *Result << "\n---\n"
101  << S;
102  assert(false && "QName is not unique");
103  }
104  Result = &S;
105  }
106  if (!Result) {
107  ADD_FAILURE() << "No symbol named " << QName << " in "
108  << ::testing::PrintToString(Slab);
109  assert(false && "No symbol with QName");
110  }
111  return *Result;
112 }
113 
114 const NamedDecl &findDecl(ParsedAST &AST, llvm::StringRef QName) {
115  llvm::SmallVector<llvm::StringRef, 4> Components;
116  QName.split(Components, "::");
117 
118  auto &Ctx = AST.getASTContext();
119  auto LookupDecl = [&Ctx](const DeclContext &Scope,
120  llvm::StringRef Name) -> const NamedDecl & {
121  auto LookupRes = Scope.lookup(DeclarationName(&Ctx.Idents.get(Name)));
122  assert(!LookupRes.empty() && "Lookup failed");
123  assert(LookupRes.size() == 1 && "Lookup returned multiple results");
124  return *LookupRes.front();
125  };
126 
127  const DeclContext *Scope = Ctx.getTranslationUnitDecl();
128  for (auto NameIt = Components.begin(), End = Components.end() - 1;
129  NameIt != End; ++NameIt) {
130  Scope = &cast<DeclContext>(LookupDecl(*Scope, *NameIt));
131  }
132  return LookupDecl(*Scope, Components.back());
133 }
134 
135 const NamedDecl &findDecl(ParsedAST &AST,
136  std::function<bool(const NamedDecl &)> Filter) {
137  struct Visitor : RecursiveASTVisitor<Visitor> {
138  decltype(Filter) F;
139  llvm::SmallVector<const NamedDecl *, 1> Decls;
140  bool VisitNamedDecl(const NamedDecl *ND) {
141  if (F(*ND))
142  Decls.push_back(ND);
143  return true;
144  }
145  } Visitor;
146  Visitor.F = Filter;
147  Visitor.TraverseDecl(AST.getASTContext().getTranslationUnitDecl());
148  if (Visitor.Decls.size() != 1) {
149  ADD_FAILURE() << Visitor.Decls.size() << " symbols matched.";
150  assert(Visitor.Decls.size() == 1);
151  }
152  return *Visitor.Decls.front();
153 }
154 
155 const NamedDecl &findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name) {
156  return findDecl(AST, [Name](const NamedDecl &ND) {
157  if (auto *ID = ND.getIdentifier())
158  if (ID->getName() == Name)
159  return true;
160  return false;
161  });
162 }
163 
164 } // namespace clangd
165 } // namespace clang
llvm::Optional< std::string > Checks
Checks filter.
ParsedAST build() const
Definition: TestTU.cpp:20
An immutable symbol container that stores a set of symbols.
Definition: Symbol.h:177
llvm::Optional< std::string > ClangTidyChecks
Definition: TestTU.h:59
std::string HeaderCode
Definition: TestTU.h:50
std::string Code
Definition: TestTU.h:46
tidy::ClangTidyOptions ClangTidyOpts
Definition: Compiler.h:39
const NamedDecl & findUnqualifiedDecl(ParsedAST &AST, llvm::StringRef Name)
Definition: TestTU.cpp:155
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
Definition: ClangdUnit.cpp:478
std::shared_ptr< const PreambleData > buildPreamble(PathRef FileName, CompilerInvocation &CI, std::shared_ptr< const PreambleData > OldPreamble, const tooling::CompileCommand &OldCompileCommand, const ParseInputs &Inputs, bool StoreInMemory, PreambleParsedCallback PreambleCallback)
Rebuild the preamble for the new inputs unless the old one can be reused.
Definition: ClangdUnit.cpp:567
std::vector< const char * > ExtraArgs
Definition: TestTU.h:57
Context Ctx
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > buildTestFS(llvm::StringMap< std::string > const &Files, llvm::StringMap< time_t > const &Timestamps)
Definition: TestFS.cpp:22
const SymbolIndex * ExternalIndex
Definition: TestTU.h:62
std::string QName
bool ImplicitHeaderGuard
Definition: TestTU.h:65
std::string testPath(PathRef File)
Definition: TestFS.cpp:82
llvm::Optional< std::string > ClangTidyWarningsAsErrors
Definition: TestTU.h:60
llvm::Optional< ParsedAST > buildAST(PathRef FileName, std::unique_ptr< CompilerInvocation > Invocation, const ParseInputs &Inputs, std::shared_ptr< const PreambleData > Preamble)
Build an AST from provided user inputs.
Definition: ClangdUnit.cpp:639
std::unique_ptr< CompilerInvocation > buildCompilerInvocation(const ParseInputs &Inputs)
Builds compiler invocation that could be used to build AST or preamble.
Definition: Compiler.cpp:44
tooling::CompileCommand CompileCommand
Definition: Compiler.h:45
static constexpr llvm::StringLiteral Name
const char * testRoot()
Definition: TestFS.cpp:74
llvm::Optional< std::string > WarningsAsErrors
WarningsAsErrors filter.
Stores and provides access to parsed AST.
Definition: ClangdUnit.h:73
const SymbolIndex * Index
Definition: Compiler.h:49
Information required to run clang, e.g. to parse AST or do code completion.
Definition: Compiler.h:44
SymbolSlab headerSymbols() const
Definition: TestTU.cpp:77
The class presents a C++ symbol, e.g.
Definition: Symbol.h:36
const PreambleData * Preamble
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
const Symbol & findSymbol(const SymbolSlab &Slab, llvm::StringRef QName)
Definition: TestTU.cpp:93
std::string Filename
Definition: TestTU.h:47
std::unique_ptr< SymbolIndex > index() const
Definition: TestTU.cpp:84
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: Rename.cpp:36
IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS
Definition: Compiler.h:46
std::string HeaderFilename
Definition: TestTU.h:51
llvm::StringMap< std::string > Files
llvm::StringMap< std::string > AdditionalFiles
Definition: TestTU.h:54
SlabTuple indexHeaderSymbols(ASTContext &AST, std::shared_ptr< Preprocessor > PP, const CanonicalIncludes &Includes)
Idex declarations from AST and macros from PP that are declared in included headers.
Definition: FileIndex.cpp:85
const NamedDecl & findDecl(ParsedAST &AST, llvm::StringRef QName)
Definition: TestTU.cpp:114