Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/c-index-test/core_main.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- core_main.cpp - Core Index Tool testbed ---------------------------===//
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 "clang/AST/Mangle.h"
10
#include "clang/Basic/LangOptions.h"
11
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
12
#include "clang/Frontend/ASTUnit.h"
13
#include "clang/Frontend/CompilerInstance.h"
14
#include "clang/Frontend/CompilerInvocation.h"
15
#include "clang/Frontend/FrontendAction.h"
16
#include "clang/Frontend/Utils.h"
17
#include "clang/Index/IndexDataConsumer.h"
18
#include "clang/Index/IndexingAction.h"
19
#include "clang/Index/USRGeneration.h"
20
#include "clang/Lex/Preprocessor.h"
21
#include "clang/Serialization/ASTReader.h"
22
#include "llvm/Support/CommandLine.h"
23
#include "llvm/Support/FileSystem.h"
24
#include "llvm/Support/PrettyStackTrace.h"
25
#include "llvm/Support/Program.h"
26
#include "llvm/Support/Signals.h"
27
#include "llvm/Support/StringSaver.h"
28
#include "llvm/Support/raw_ostream.h"
29
30
using namespace clang;
31
using namespace clang::index;
32
using namespace llvm;
33
34
extern "C" int indextest_core_main(int argc, const char **argv);
35
extern "C" int indextest_perform_shell_execution(const char *command_line);
36
37
namespace {
38
39
enum class ActionType {
40
  None,
41
  PrintSourceSymbols,
42
};
43
44
namespace options {
45
46
static cl::OptionCategory IndexTestCoreCategory("index-test-core options");
47
48
static cl::opt<ActionType>
49
Action(cl::desc("Action:"), cl::init(ActionType::None),
50
       cl::values(
51
          clEnumValN(ActionType::PrintSourceSymbols,
52
                     "print-source-symbols", "Print symbols from source")),
53
       cl::cat(IndexTestCoreCategory));
54
55
static cl::extrahelp MoreHelp(
56
  "\nAdd \"-- <compiler arguments>\" at the end to setup the compiler "
57
  "invocation\n"
58
);
59
60
static cl::opt<bool>
61
DumpModuleImports("dump-imported-module-files",
62
               cl::desc("Print symbols and input files from imported modules"));
63
64
static cl::opt<bool>
65
IncludeLocals("include-locals", cl::desc("Print local symbols"));
66
67
static cl::opt<bool> IgnoreMacros("ignore-macros",
68
                                  cl::desc("Skip indexing macros"));
69
70
static cl::opt<std::string>
71
ModuleFilePath("module-file",
72
               cl::desc("Path to module file to print symbols from"));
73
static cl::opt<std::string>
74
  ModuleFormat("fmodule-format", cl::init("raw"),
75
        cl::desc("Container format for clang modules and PCH, 'raw' or 'obj'"));
76
77
}
78
} // anonymous namespace
79
80
static void printSymbolInfo(SymbolInfo SymInfo, raw_ostream &OS);
81
static void printSymbolNameAndUSR(const Decl *D, ASTContext &Ctx,
82
                                  raw_ostream &OS);
83
static void printSymbolNameAndUSR(const clang::Module *Mod, raw_ostream &OS);
84
85
namespace {
86
87
class PrintIndexDataConsumer : public IndexDataConsumer {
88
  raw_ostream &OS;
89
  std::unique_ptr<ASTNameGenerator> ASTNameGen;
90
  std::shared_ptr<Preprocessor> PP;
91
92
public:
93
25
  PrintIndexDataConsumer(raw_ostream &OS) : OS(OS) {
94
25
  }
95
96
49
  void initialize(ASTContext &Ctx) override {
97
49
    ASTNameGen.reset(new ASTNameGenerator(Ctx));
98
49
  }
99
100
48
  void setPreprocessor(std::shared_ptr<Preprocessor> PP) override {
101
48
    this->PP = std::move(PP);
102
48
  }
103
104
  bool handleDeclOccurrence(const Decl *D, SymbolRoleSet Roles,
105
                            ArrayRef<SymbolRelation> Relations,
106
1.37k
                            SourceLocation Loc, ASTNodeInfo ASTNode) override {
107
1.37k
    ASTContext &Ctx = D->getASTContext();
108
1.37k
    SourceManager &SM = Ctx.getSourceManager();
109
110
1.37k
    Loc = SM.getFileLoc(Loc);
111
1.37k
    FileID FID = SM.getFileID(Loc);
112
1.37k
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
113
1.37k
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
114
1.37k
    OS << Line << ':' << Col << " | ";
115
116
1.37k
    printSymbolInfo(getSymbolInfo(D), OS);
117
1.37k
    OS << " | ";
118
119
1.37k
    printSymbolNameAndUSR(D, Ctx, OS);
120
1.37k
    OS << " | ";
121
122
1.37k
    if (ASTNameGen->writeName(D, OS))
123
856
      OS << "<no-cgname>";
124
1.37k
    OS << " | ";
125
126
1.37k
    printSymbolRoles(Roles, OS);
127
1.37k
    OS << " | ";
128
129
1.37k
    OS << "rel: " << Relations.size() << '\n';
130
131
1.37k
    for (auto &SymRel : Relations) {
132
1.16k
      OS << '\t';
133
1.16k
      printSymbolRoles(SymRel.Roles, OS);
134
1.16k
      OS << " | ";
135
1.16k
      printSymbolNameAndUSR(SymRel.RelatedSymbol, Ctx, OS);
136
1.16k
      OS << '\n';
137
1.16k
    }
138
139
1.37k
    return true;
140
1.37k
  }
141
142
  bool handleModuleOccurrence(const ImportDecl *ImportD,
143
                              const clang::Module *Mod, SymbolRoleSet Roles,
144
9
                              SourceLocation Loc) override {
145
9
    ASTContext &Ctx = ImportD->getASTContext();
146
9
    SourceManager &SM = Ctx.getSourceManager();
147
148
9
    Loc = SM.getFileLoc(Loc);
149
9
    FileID FID = SM.getFileID(Loc);
150
9
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
151
9
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
152
9
    OS << Line << ':' << Col << " | ";
153
154
9
    printSymbolInfo(getSymbolInfo(ImportD), OS);
155
9
    OS << " | ";
156
157
9
    printSymbolNameAndUSR(Mod, OS);
158
9
    OS << " | ";
159
160
9
    printSymbolRoles(Roles, OS);
161
9
    OS << " |\n";
162
163
9
    return true;
164
9
  }
165
166
  bool handleMacroOccurrence(const IdentifierInfo *Name, const MacroInfo *MI,
167
18.2k
                             SymbolRoleSet Roles, SourceLocation Loc) override {
168
18.2k
    assert(PP);
169
0
    SourceManager &SM = PP->getSourceManager();
170
171
18.2k
    Loc = SM.getFileLoc(Loc);
172
18.2k
    FileID FID = SM.getFileID(Loc);
173
18.2k
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
174
18.2k
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
175
18.2k
    OS << Line << ':' << Col << " | ";
176
177
18.2k
    printSymbolInfo(getSymbolInfoForMacro(*MI), OS);
178
18.2k
    OS << " | ";
179
180
18.2k
    OS << Name->getName();
181
18.2k
    OS << " | ";
182
183
18.2k
    SmallString<256> USRBuf;
184
18.2k
    if (generateUSRForMacro(Name->getName(), MI->getDefinitionLoc(), SM,
185
18.2k
                            USRBuf)) {
186
0
      OS << "<no-usr>";
187
18.2k
    } else {
188
18.2k
      OS << USRBuf;
189
18.2k
    }
190
18.2k
    OS << " | ";
191
192
18.2k
    printSymbolRoles(Roles, OS);
193
18.2k
    OS << " |\n";
194
18.2k
    return true;
195
18.2k
  }
196
};
197
198
} // anonymous namespace
199
200
//===----------------------------------------------------------------------===//
201
// Print Source Symbols
202
//===----------------------------------------------------------------------===//
203
204
static void dumpModuleFileInputs(serialization::ModuleFile &Mod,
205
                                 ASTReader &Reader,
206
1
                                 raw_ostream &OS) {
207
1
  OS << "---- Module Inputs ----\n";
208
1
  Reader.visitInputFiles(Mod, /*IncludeSystem=*/true, /*Complain=*/false,
209
4
                        [&](const serialization::InputFile &IF, bool isSystem) {
210
4
    OS << (isSystem ? 
"system"0
: "user") << " | ";
211
4
    OS << IF.getFile()->getName() << '\n';
212
4
  });
213
1
}
214
215
static bool printSourceSymbols(const char *Executable,
216
                               ArrayRef<const char *> Args,
217
                               bool dumpModuleImports, bool indexLocals,
218
23
                               bool ignoreMacros) {
219
23
  SmallVector<const char *, 4> ArgsWithProgName;
220
23
  ArgsWithProgName.push_back(Executable);
221
23
  ArgsWithProgName.append(Args.begin(), Args.end());
222
23
  IntrusiveRefCntPtr<DiagnosticsEngine>
223
23
    Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
224
23
  CreateInvocationOptions CIOpts;
225
23
  CIOpts.Diags = Diags;
226
23
  CIOpts.ProbePrecompiled = true; // FIXME: historical default. Needed?
227
23
  auto CInvok = createInvocation(ArgsWithProgName, std::move(CIOpts));
228
23
  if (!CInvok)
229
0
    return true;
230
231
23
  raw_ostream &OS = outs();
232
23
  auto DataConsumer = std::make_shared<PrintIndexDataConsumer>(OS);
233
23
  IndexingOptions IndexOpts;
234
23
  IndexOpts.IndexFunctionLocals = indexLocals;
235
23
  IndexOpts.IndexMacros = !ignoreMacros;
236
23
  IndexOpts.IndexMacrosInPreprocessor = !ignoreMacros;
237
23
  std::unique_ptr<FrontendAction> IndexAction =
238
23
      createIndexingAction(DataConsumer, IndexOpts);
239
240
23
  auto PCHContainerOps = std::make_shared<PCHContainerOperations>();
241
23
  std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCompilerInvocationAction(
242
23
      std::move(CInvok), PCHContainerOps, Diags, IndexAction.get()));
243
244
23
  if (!Unit)
245
0
    return true;
246
247
23
  if (dumpModuleImports) {
248
1
    if (auto Reader = Unit->getASTReader()) {
249
1
      Reader->getModuleManager().visit([&](serialization::ModuleFile &Mod) -> bool {
250
1
        OS << "==== Module " << Mod.ModuleName << " ====\n";
251
1
        indexModuleFile(Mod, *Reader, *DataConsumer, IndexOpts);
252
1
        dumpModuleFileInputs(Mod, *Reader, OS);
253
1
        return true; // skip module dependencies.
254
1
      });
255
1
    }
256
1
  }
257
258
23
  return false;
259
23
}
260
261
static bool printSourceSymbolsFromModule(StringRef modulePath,
262
2
                                         StringRef format) {
263
2
  FileSystemOptions FileSystemOpts;
264
2
  auto pchContOps = std::make_shared<PCHContainerOperations>();
265
  // Register the support for object-file-wrapped Clang modules.
266
2
  pchContOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
267
2
  auto pchRdr = pchContOps->getReaderOrNull(format);
268
2
  if (!pchRdr) {
269
0
    errs() << "unknown module format: " << format << '\n';
270
0
    return true;
271
0
  }
272
273
2
  IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
274
2
      CompilerInstance::createDiagnostics(new DiagnosticOptions());
275
2
  std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
276
2
      std::string(modulePath), *pchRdr, ASTUnit::LoadASTOnly, Diags,
277
2
      FileSystemOpts, /*UseDebugInfo=*/false,
278
2
      /*OnlyLocalDecls=*/true, CaptureDiagsKind::None,
279
2
      /*AllowASTWithCompilerErrors=*/true,
280
2
      /*UserFilesAreVolatile=*/false);
281
2
  if (!AU) {
282
0
    errs() << "failed to create TU for: " << modulePath << '\n';
283
0
    return true;
284
0
  }
285
286
2
  PrintIndexDataConsumer DataConsumer(outs());
287
2
  IndexingOptions IndexOpts;
288
2
  indexASTUnit(*AU, DataConsumer, IndexOpts);
289
290
2
  return false;
291
2
}
292
293
//===----------------------------------------------------------------------===//
294
// Helper Utils
295
//===----------------------------------------------------------------------===//
296
297
19.6k
static void printSymbolInfo(SymbolInfo SymInfo, raw_ostream &OS) {
298
19.6k
  OS << getSymbolKindString(SymInfo.Kind);
299
19.6k
  if (SymInfo.SubKind != SymbolSubKind::None)
300
113
    OS << '/' << getSymbolSubKindString(SymInfo.SubKind);
301
19.6k
  if (SymInfo.Properties) {
302
316
    OS << '(';
303
316
    printSymbolProperties(SymInfo.Properties, OS);
304
316
    OS << ')';
305
316
  }
306
19.6k
  OS << '/' << getSymbolLanguageString(SymInfo.Lang);
307
19.6k
}
308
309
static void printSymbolNameAndUSR(const Decl *D, ASTContext &Ctx,
310
2.54k
                                  raw_ostream &OS) {
311
2.54k
  if (printSymbolName(D, Ctx.getLangOpts(), OS)) {
312
8
    OS << "<no-name>";
313
8
  }
314
2.54k
  OS << " | ";
315
316
2.54k
  SmallString<256> USRBuf;
317
2.54k
  if (generateUSRForDecl(D, USRBuf)) {
318
0
    OS << "<no-usr>";
319
2.54k
  } else {
320
2.54k
    OS << USRBuf;
321
2.54k
  }
322
2.54k
}
323
324
9
static void printSymbolNameAndUSR(const clang::Module *Mod, raw_ostream &OS) {
325
9
  assert(Mod);
326
0
  OS << Mod->getFullModuleName() << " | ";
327
9
  generateFullUSRForModule(Mod, OS);
328
9
}
329
330
//===----------------------------------------------------------------------===//
331
// Command line processing.
332
//===----------------------------------------------------------------------===//
333
334
25
int indextest_core_main(int argc, const char **argv) {
335
25
  sys::PrintStackTraceOnErrorSignal(argv[0]);
336
25
  PrettyStackTraceProgram X(argc, argv);
337
25
  void *MainAddr = (void*) (intptr_t) indextest_core_main;
338
25
  std::string Executable = llvm::sys::fs::getMainExecutable(argv[0], MainAddr);
339
340
25
  assert(argv[1] == StringRef("core"));
341
0
  ++argv;
342
25
  --argc;
343
344
25
  std::vector<const char *> CompArgs;
345
25
  const char **DoubleDash = std::find(argv, argv + argc, StringRef("--"));
346
25
  if (DoubleDash != argv + argc) {
347
23
    CompArgs = std::vector<const char *>(DoubleDash + 1, argv + argc);
348
23
    argc = DoubleDash - argv;
349
23
  }
350
351
25
  cl::HideUnrelatedOptions(options::IndexTestCoreCategory);
352
25
  cl::ParseCommandLineOptions(argc, argv, "index-test-core");
353
354
25
  if (options::Action == ActionType::None) {
355
0
    errs() << "error: action required; pass '-help' for options\n";
356
0
    return 1;
357
0
  }
358
359
25
  if (options::Action == ActionType::PrintSourceSymbols) {
360
25
    if (!options::ModuleFilePath.empty()) {
361
2
      return printSourceSymbolsFromModule(options::ModuleFilePath,
362
2
                                          options::ModuleFormat);
363
2
    }
364
23
    if (CompArgs.empty()) {
365
0
      errs() << "error: missing compiler args; pass '-- <compiler arguments>'\n";
366
0
      return 1;
367
0
    }
368
23
    return printSourceSymbols(Executable.c_str(), CompArgs,
369
23
                              options::DumpModuleImports,
370
23
                              options::IncludeLocals, options::IgnoreMacros);
371
23
  }
372
373
0
  return 0;
374
25
}
375
376
//===----------------------------------------------------------------------===//
377
// Utility functions
378
//===----------------------------------------------------------------------===//
379
380
1
int indextest_perform_shell_execution(const char *command_line) {
381
1
  BumpPtrAllocator Alloc;
382
1
  llvm::StringSaver Saver(Alloc);
383
1
  SmallVector<const char *, 4> Args;
384
1
  llvm::cl::TokenizeGNUCommandLine(command_line, Saver, Args);
385
1
  auto Program = llvm::sys::findProgramByName(Args[0]);
386
1
  if (std::error_code ec = Program.getError()) {
387
0
    llvm::errs() << "command not found: " << Args[0] << "\n";
388
0
    return ec.value();
389
0
  }
390
1
  SmallVector<StringRef, 8> execArgs(Args.begin(), Args.end());
391
1
  return llvm::sys::ExecuteAndWait(*Program, execArgs);
392
1
}