Debian Codegraph @

build/clang-plugin/mozsearch-plugin/MozsearchIndexer.cpp

raw
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 #include "clang/AST/AST.h"
7 #include "clang/AST/ASTConsumer.h"
8 #include "clang/AST/ASTContext.h"
9 #include "clang/AST/Expr.h"
10 #include "clang/AST/ExprCXX.h"
11 #include "clang/AST/Mangle.h"
12 #include "clang/AST/RecordLayout.h"
13 #include "clang/AST/RecursiveASTVisitor.h"
14 #include "clang/Basic/FileManager.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Format/Format.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "clang/Frontend/FrontendPluginRegistry.h"
20 #include "clang/Lex/Lexer.h"
21 #include "clang/Lex/PPCallbacks.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/TokenConcatenation.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Support/JSON.h"
26 #include "llvm/Support/raw_ostream.h"
27
28 #include <algorithm>
29 #include <fstream>
30 #include <iostream>
31 #include <map>
32 #include <memory>
33 #include <sstream>
34 #include <stack>
35 #include <string>
36 #include <tuple>
37 #include <unordered_set>
38
39 #include <stdio.h>
40 #include <stdlib.h>
41
42 #include "BindingOperations.h"
43 #include "FileOperations.h"
44 #include "StringOperations.h"
45 #include "from-clangd/HeuristicResolver.h"
46
47 #if CLANG_VERSION_MAJOR < 8
48 // Starting with Clang 8.0 some basic functions have been renamed
49 #define getBeginLoc getLocStart
50 #define getEndLoc getLocEnd
51 #endif
52 // We want std::make_unique, but that's only available in c++14. In versions
53 // prior to that, we need to fall back to llvm's make_unique. It's also the
54 // case that we expect clang 10 to build with c++14 and clang 9 and earlier to
55 // build with c++11, at least as suggested by the llvm-config --cxxflags on
56 // non-windows platforms. mozilla-central seems to build with -std=c++17 on
57 // windows so we need to make this decision based on __cplusplus instead of
58 // the CLANG_VERSION_MAJOR.
59 #if __cplusplus < 201402L
60 using llvm::make_unique;
61 #else
62 using std::make_unique;
63 #endif
64
65 using namespace clang;
66
67 const std::string GENERATED("__GENERATED__" PATHSEP_STRING);
68
69 // Absolute path to directory containing source code.
70 std::string Srcdir;
71
72 // Absolute path to objdir (including generated code).
73 std::string Objdir;
74
75 // Absolute path where analysis JSON output will be stored.
76 std::string Outdir;
77
78 enum class FileType {
79 // The file was either in the source tree nor objdir. It might be a system
80 // include, for example.
81 Unknown,
82 // A file from the source tree.
83 Source,
84 // A file from the objdir.
85 Generated,
86 };
87
88 // Takes an absolute path to a file, and returns the type of file it is. If
89 // it's a Source or Generated file, the provided inout path argument is modified
90 // in-place so that it is relative to the source dir or objdir, respectively.
91 FileType relativizePath(std::string &path) {
92 if (path.compare(0, Objdir.length(), Objdir) == 0) {
93 path.replace(0, Objdir.length(), GENERATED);
94 return FileType::Generated;
95 }
96 // Empty filenames can get turned into Srcdir when they are resolved as
97 // absolute paths, so we should exclude files that are exactly equal to
98 // Srcdir or anything outside Srcdir.
99 if (path.length() > Srcdir.length() &&
100 path.compare(0, Srcdir.length(), Srcdir) == 0) {
101 // Remove the trailing `/' as well.
102 path.erase(0, Srcdir.length() + 1);
103 return FileType::Source;
104 }
105 return FileType::Unknown;
106 }
107
108 #if !defined(_WIN32) && !defined(_WIN64)
109 #include <sys/time.h>
110
111 static double time() {
112 struct timeval Tv;
113 gettimeofday(&Tv, nullptr);
114 return double(Tv.tv_sec) + double(Tv.tv_usec) / 1000000.;
115 }
116 #endif
117
118 // Return true if |input| is a valid C++ identifier. We don't want to generate
119 // analysis information for operators, string literals, etc. by accident since
120 // it trips up consumers of the data.
121 static bool isValidIdentifier(std::string Input) {
122 for (char C : Input) {
123 if (!(isalpha(C) || isdigit(C) || C == '_')) {
124 return false;
125 }
126 }
127 return true;
128 }
129
130 template <size_t N>
131 static bool stringStartsWith(const std::string &Input,
132 const char (&Prefix)[N]) {
133 return Input.length() > N - 1 && memcmp(Input.c_str(), Prefix, N - 1) == 0;
134 }
135
136 static bool isASCII(const std::string &Input) {
137 for (char C : Input) {
138 if (C & 0x80) {
139 return false;
140 }
141 }
142 return true;
143 }
144
145 struct RAIITracer {
146 RAIITracer(const char *log) : mLog(log) { printf("<%s>\n", mLog); }
147
148 ~RAIITracer() { printf("</%s>\n", mLog); }
149
150 const char *mLog;
151 };
152
153 #define TRACEFUNC RAIITracer tracer(__FUNCTION__);
154
155 // Sets variable to value on creation then resets variable to its original
156 // value on destruction
157 template <typename T> class ValueRollback {
158 public:
159 template <typename U = T>
160 ValueRollback(T &variable, U &&value)
161 : mVariable{&variable},
162 mSavedValue{std::exchange(variable, std::forward<U>(value))} {}
163
164 ValueRollback(ValueRollback &&other) noexcept
165 : mVariable{std::exchange(other.mVariable, nullptr)},
166 mSavedValue{std::move(other.mSavedValue)} {}
167
168 ValueRollback(const ValueRollback &) = delete;
169 ValueRollback &operator=(ValueRollback &&) = delete;
170 ValueRollback &operator=(const ValueRollback &) = delete;
171
172 ~ValueRollback() {
173 if (mVariable)
174 *mVariable = std::move(mSavedValue);
175 }
176
177 private:
178 T *mVariable;
179 T mSavedValue;
180 };
181
182 class IndexConsumer;
183
184 bool isPure(FunctionDecl *D) {
185 #if CLANG_VERSION_MAJOR >= 18
186 return D->isPureVirtual();
187 #else
188 return D->isPure();
189 #endif
190 }
191
192 // For each C++ file seen by the analysis (.cpp or .h), we track a
193 // FileInfo. This object tracks whether the file is "interesting" (i.e., whether
194 // it's in the source dir or the objdir). We also store the analysis output
195 // here.
196 struct FileInfo {
197 FileInfo(std::string &Rname) : Realname(Rname) {
198 switch (relativizePath(Realname)) {
199 case FileType::Generated:
200 Interesting = true;
201 Generated = true;
202 break;
203 case FileType::Source:
204 Interesting = true;
205 Generated = false;
206 break;
207 case FileType::Unknown:
208 Interesting = false;
209 Generated = false;
210 break;
211 }
212 }
213 std::string Realname;
214 std::vector<std::string> Output;
215 bool Interesting;
216 bool Generated;
217 };
218
219 struct MacroExpansionState {
220 Token MacroNameToken;
221 const MacroInfo *MacroInfo = nullptr;
222 // other macro symbols this expansion depends on
223 std::vector<std::string> Dependencies;
224 std::string Expansion;
225 std::map<SourceLocation, unsigned> TokenLocations;
226 SourceRange Range;
227 Token PrevPrevTok;
228 Token PrevTok;
229 };
230
231 struct ExpandedMacro {
232 std::string Symbol;
233 std::string Key; // "{Symbol}(,{Dependencies})..."
234 std::string Expansion;
235 std::map<SourceLocation, unsigned> TokenLocations;
236 };
237
238 class IndexConsumer;
239
240 class PreprocessorHook : public PPCallbacks {
241 IndexConsumer *Indexer;
242
243 public:
244 PreprocessorHook(IndexConsumer *C) : Indexer(C) {}
245
246 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
247 SrcMgr::CharacteristicKind FileType,
248 FileID PrevFID) override;
249
250 virtual void InclusionDirective(SourceLocation HashLoc,
251 const Token &IncludeTok, StringRef FileName,
252 bool IsAngled, CharSourceRange FileNameRange,
253 #if CLANG_VERSION_MAJOR >= 16
254 OptionalFileEntryRef File,
255 #elif CLANG_VERSION_MAJOR >= 15
256 Optional<FileEntryRef> File,
257 #else
258 const FileEntry *File,
259 #endif
260 StringRef SearchPath, StringRef RelativePath,
261 #if CLANG_VERSION_MAJOR >= 19
262 const Module *SuggestedModule,
263 bool ModuleImported,
264 #else
265 const Module *Imported,
266 #endif
267 SrcMgr::CharacteristicKind FileType) override;
268
269 virtual void MacroDefined(const Token &Tok,
270 const MacroDirective *Md) override;
271
272 virtual void MacroExpands(const Token &Tok, const MacroDefinition &Md,
273 SourceRange Range, const MacroArgs *Ma) override;
274 virtual void MacroUndefined(const Token &Tok, const MacroDefinition &Md,
275 const MacroDirective *Undef) override;
276 virtual void Defined(const Token &Tok, const MacroDefinition &Md,
277 SourceRange Range) override;
278 virtual void Ifdef(SourceLocation Loc, const Token &Tok,
279 const MacroDefinition &Md) override;
280 virtual void Ifndef(SourceLocation Loc, const Token &Tok,
281 const MacroDefinition &Md) override;
282 };
283
284 class IndexConsumer : public ASTConsumer,
285 public RecursiveASTVisitor<IndexConsumer>,
286 public DiagnosticConsumer {
287 private:
288 CompilerInstance &CI;
289 SourceManager &SM;
290 LangOptions &LO;
291 std::map<FileID, std::unique_ptr<FileInfo>> FileMap;
292 MangleContext *CurMangleContext;
293 ASTContext *AstContext;
294 std::unique_ptr<clangd::HeuristicResolver> Resolver;
295
296 // Used during a macro expansion to build the expanded string
297 TokenConcatenation ConcatInfo;
298 std::optional<MacroExpansionState> MacroExpansionState;
299 // Keeps track of the positions of tokens inside each expanded macro
300 std::map<SourceLocation, ExpandedMacro> MacroMaps;
301
302 typedef RecursiveASTVisitor<IndexConsumer> Super;
303
304 // Tracks the set of declarations that the current expression/statement is
305 // nested inside of.
306 struct AutoSetContext {
307 AutoSetContext(IndexConsumer *Self, NamedDecl *Context,
308 bool VisitImplicit = false)
309 : Self(Self), Prev(Self->CurDeclContext), Decl(Context) {
310 this->VisitImplicit =
311 VisitImplicit || (Prev ? Prev->VisitImplicit : false);
312 Self->CurDeclContext = this;
313 }
314
315 ~AutoSetContext() { Self->CurDeclContext = Prev; }
316
317 IndexConsumer *Self;
318 AutoSetContext *Prev;
319 NamedDecl *Decl;
320 bool VisitImplicit;
321 };
322 AutoSetContext *CurDeclContext;
323
324 FileInfo *getFileInfo(SourceLocation Loc) {
325 FileID Id = SM.getFileID(Loc);
326
327 std::map<FileID, std::unique_ptr<FileInfo>>::iterator It;
328 It = FileMap.find(Id);
329 if (It == FileMap.end()) {
330 // We haven't seen this file before. We need to make the FileInfo
331 // structure information ourselves
332 std::string Filename = std::string(SM.getFilename(Loc));
333 std::string Absolute;
334 // If Loc is a macro id rather than a file id, it Filename might be
335 // empty. Also for some types of file locations that are clang-internal
336 // like "<scratch>" it can return an empty Filename. In these cases we
337 // want to leave Absolute as empty.
338 if (!Filename.empty()) {
339 Absolute = getAbsolutePath(Filename);
340 if (Absolute.empty()) {
341 Absolute = Filename;
342 }
343 }
344 std::unique_ptr<FileInfo> Info = make_unique<FileInfo>(Absolute);
345 It = FileMap.insert(std::make_pair(Id, std::move(Info))).first;
346 }
347 return It->second.get();
348 }
349
350 // Helpers for processing declarations
351 // Should we ignore this location?
352 bool isInterestingLocation(SourceLocation Loc) {
353 if (SM.isMacroBodyExpansion(Loc)) {
354 Loc = SM.getFileLoc(Loc);
355 }
356
357 normalizeLocation(&Loc);
358 if (Loc.isInvalid()) {
359 return false;
360 }
361
362 return getFileInfo(Loc)->Interesting;
363 }
364
365 // Convert location to "line:column" or "line:column-column" given length.
366 // In resulting string rep, line is 1-based and zero-padded to 5 digits, while
367 // column is 0-based and unpadded.
368 std::string locationToString(SourceLocation Loc, size_t Length = 0) {
369 std::pair<FileID, unsigned> Pair = SM.getDecomposedLoc(Loc);
370
371 bool IsInvalid;
372 unsigned Line = SM.getLineNumber(Pair.first, Pair.second, &IsInvalid);
373 if (IsInvalid) {
374 return "";
375 }
376 unsigned Column = SM.getColumnNumber(Pair.first, Pair.second, &IsInvalid);
377 if (IsInvalid) {
378 return "";
379 }
380
381 if (Length) {
382 return stringFormat("%05d:%d-%d", Line, Column - 1, Column - 1 + Length);
383 } else {
384 return stringFormat("%05d:%d", Line, Column - 1);
385 }
386 }
387
388 // Convert SourceRange to "line-line" or "line".
389 // In the resulting string rep, line is 1-based.
390 std::string lineRangeToString(SourceRange Range, bool omitEnd = false) {
391 std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(Range.getBegin());
392 std::pair<FileID, unsigned> End = SM.getDecomposedLoc(Range.getEnd());
393
394 bool IsInvalid;
395 unsigned Line1 = SM.getLineNumber(Begin.first, Begin.second, &IsInvalid);
396 if (IsInvalid) {
397 return "";
398 }
399 unsigned Line2 = SM.getLineNumber(End.first, End.second, &IsInvalid);
400 if (IsInvalid) {
401 return "";
402 }
403
404 if (omitEnd && Line1 == Line2) {
405 return stringFormat("%d", Line1);
406 }
407
408 return stringFormat("%d-%d", Line1, Line2);
409 }
410
411 // Convert SourceRange to "PATH#line-line" or "PATH#line".
412 // If Range's file is same as fromFileID, PATH is omitted.
413 std::string pathAndLineRangeToString(FileID fromFileID, SourceRange Range) {
414 FileInfo *toFile = getFileInfo(Range.getBegin());
415 FileInfo *fromFile = FileMap.find(fromFileID)->second.get();
416
417 auto lineRange = lineRangeToString(Range, true);
418
419 if (lineRange.empty()) {
420 return "";
421 }
422
423 if (toFile == fromFile) {
424 return "#" + lineRange;
425 }
426
427 if (toFile->Realname.empty()) {
428 return "#" + lineRange;
429 }
430
431 std::string result = toFile->Realname;
432 result += "#";
433 result += lineRange;
434 return result;
435 }
436
437 // Convert SourceRange to "line:column-line:column".
438 // In the resulting string rep, line is 1-based, column is 0-based.
439 std::string fullRangeToString(SourceRange Range) {
440 std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(Range.getBegin());
441 std::pair<FileID, unsigned> End = SM.getDecomposedLoc(Range.getEnd());
442
443 bool IsInvalid;
444 unsigned Line1 = SM.getLineNumber(Begin.first, Begin.second, &IsInvalid);
445 if (IsInvalid) {
446 return "";
447 }
448 unsigned Column1 =
449 SM.getColumnNumber(Begin.first, Begin.second, &IsInvalid);
450 if (IsInvalid) {
451 return "";
452 }
453 unsigned Line2 = SM.getLineNumber(End.first, End.second, &IsInvalid);
454 if (IsInvalid) {
455 return "";
456 }
457 unsigned Column2 = SM.getColumnNumber(End.first, End.second, &IsInvalid);
458 if (IsInvalid) {
459 return "";
460 }
461
462 return stringFormat("%d:%d-%d:%d", Line1, Column1 - 1, Line2, Column2 - 1);
463 }
464
465 // Returns the qualified name of `d` without considering template parameters.
466 std::string getQualifiedName(const NamedDecl *D) {
467 const DeclContext *Ctx = D->getDeclContext();
468 if (Ctx->isFunctionOrMethod()) {
469 return D->getQualifiedNameAsString();
470 }
471
472 std::vector<const DeclContext *> Contexts;
473
474 // Collect contexts.
475 while (Ctx && isa<NamedDecl>(Ctx)) {
476 Contexts.push_back(Ctx);
477 Ctx = Ctx->getParent();
478 }
479
480 std::string Result;
481
482 std::reverse(Contexts.begin(), Contexts.end());
483
484 for (const DeclContext *DC : Contexts) {
485 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
486 Result += Spec->getNameAsString();
487
488 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
489 std::string Backing;
490 llvm::raw_string_ostream Stream(Backing);
491 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
492 printTemplateArgumentList(Stream, TemplateArgs.asArray(),
493 PrintingPolicy(CI.getLangOpts()));
494 Result += Stream.str();
495 }
496 } else if (const auto *Nd = dyn_cast<NamespaceDecl>(DC)) {
497 if (Nd->isAnonymousNamespace() || Nd->isInline()) {
498 continue;
499 }
500 Result += Nd->getNameAsString();
501 } else if (const auto *Rd = dyn_cast<RecordDecl>(DC)) {
502 if (!Rd->getIdentifier()) {
503 Result += "(anonymous)";
504 } else {
505 Result += Rd->getNameAsString();
506 }
507 } else if (const auto *Fd = dyn_cast<FunctionDecl>(DC)) {
508 Result += Fd->getNameAsString();
509 } else if (const auto *Ed = dyn_cast<EnumDecl>(DC)) {
510 // C++ [dcl.enum]p10: Each enum-name and each unscoped
511 // enumerator is declared in the scope that immediately contains
512 // the enum-specifier. Each scoped enumerator is declared in the
513 // scope of the enumeration.
514 if (Ed->isScoped() || Ed->getIdentifier())
515 Result += Ed->getNameAsString();
516 else
517 continue;
518 } else {
519 Result += cast<NamedDecl>(DC)->getNameAsString();
520 }
521 Result += "::";
522 }
523
524 if (D->getDeclName())
525 Result += D->getNameAsString();
526 else
527 Result += "(anonymous)";
528
529 return Result;
530 }
531
532 std::string mangleLocation(SourceLocation Loc,
533 std::string Backup = std::string()) {
534 FileInfo *F = getFileInfo(Loc);
535 std::string Filename = F->Realname;
536 if (Filename.length() == 0 && Backup.length() != 0) {
537 return Backup;
538 }
539 if (F->Generated) {
540 // Since generated files may be different on different platforms,
541 // we need to include a platform-specific thing in the hash. Otherwise
542 // we can end up with hash collisions where different symbols from
543 // different platforms map to the same thing.
544 char *Platform = getenv("MOZSEARCH_PLATFORM");
545 Filename =
546 std::string(Platform ? Platform : "") + std::string("@") + Filename;
547 }
548 return hash(Filename + std::string("@") + locationToString(Loc));
549 }
550
551 bool isAcceptableSymbolChar(char c) {
552 return isalpha(c) || isdigit(c) || c == '_' || c == '/';
553 }
554
555 std::string mangleFile(std::string Filename, FileType Type) {
556 // "Mangle" the file path, such that:
557 // 1. The majority of paths will still be mostly human-readable.
558 // 2. The sanitization algorithm doesn't produce collisions where two
559 // different unsanitized paths can result in the same sanitized paths.
560 // 3. The produced symbol doesn't cause problems with downstream consumers.
561 // In order to accomplish this, we keep alphanumeric chars, underscores,
562 // and slashes, and replace everything else with an "@xx" hex encoding.
563 // The majority of path characters are letters and slashes which don't get
564 // encoded, so that satisfies (1). Since "@" characters in the unsanitized
565 // path get encoded, there should be no "@" characters in the sanitized path
566 // that got preserved from the unsanitized input, so that should satisfy
567 // (2). And (3) was done by trial-and-error. Note in particular the dot (.)
568 // character needs to be encoded, or the symbol-search feature of mozsearch
569 // doesn't work correctly, as all dot characters in the symbol query get
570 // replaced by #.
571 for (size_t i = 0; i < Filename.length(); i++) {
572 char c = Filename[i];
573 if (isAcceptableSymbolChar(c)) {
574 continue;
575 }
576 char hex[4];
577 sprintf(hex, "@%02X", ((int)c) & 0xFF);
578 Filename.replace(i, 1, hex);
579 i += 2;
580 }
581
582 if (Type == FileType::Generated) {
583 // Since generated files may be different on different platforms,
584 // we need to include a platform-specific thing in the hash. Otherwise
585 // we can end up with hash collisions where different symbols from
586 // different platforms map to the same thing.
587 char *Platform = getenv("MOZSEARCH_PLATFORM");
588 Filename =
589 std::string(Platform ? Platform : "") + std::string("@") + Filename;
590 }
591 return Filename;
592 }
593
594 std::string mangleURL(std::string Url) {
595 return mangleFile(Url, FileType::Source);
596 }
597
598 std::string mangleQualifiedName(std::string Name) {
599 std::replace(Name.begin(), Name.end(), ' ', '_');
600 return Name;
601 }
602
603 std::string getMangledName(clang::MangleContext *Ctx,
604 const clang::NamedDecl *Decl) {
605 // Main functions will tend to collide because they inherently have similar
606 // signatures, so let's provide a custom location-based signature.
607 if (isa<FunctionDecl>(Decl) && cast<FunctionDecl>(Decl)->isMain()) {
608 return std::string("MF_") + mangleLocation(Decl->getLocation());
609 }
610
611 if (isa<FunctionDecl>(Decl) && cast<FunctionDecl>(Decl)->isExternC()) {
612 return cast<FunctionDecl>(Decl)->getNameAsString();
613 }
614
615 if (isa<FunctionDecl>(Decl) || isa<VarDecl>(Decl)) {
616 const DeclContext *DC = Decl->getDeclContext();
617 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
618 isa<LinkageSpecDecl>(DC) ||
619 // isa<ExternCContextDecl>(DC) ||
620 isa<TagDecl>(DC)) {
621 llvm::SmallVector<char, 512> Output;
622 llvm::raw_svector_ostream Out(Output);
623 #if CLANG_VERSION_MAJOR >= 11
624 // This code changed upstream in version 11:
625 // https://github.com/llvm/llvm-project/commit/29e1a16be8216066d1ed733a763a749aed13ff47
626 GlobalDecl GD;
627 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(Decl)) {
628 GD = GlobalDecl(D, Ctor_Complete);
629 } else if (const CXXDestructorDecl *D =
630 dyn_cast<CXXDestructorDecl>(Decl)) {
631 GD = GlobalDecl(D, Dtor_Complete);
632 } else {
633 GD = GlobalDecl(Decl);
634 }
635 Ctx->mangleName(GD, Out);
636 #else
637 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(Decl)) {
638 Ctx->mangleCXXCtor(D, CXXCtorType::Ctor_Complete, Out);
639 } else if (const CXXDestructorDecl *D =
640 dyn_cast<CXXDestructorDecl>(Decl)) {
641 Ctx->mangleCXXDtor(D, CXXDtorType::Dtor_Complete, Out);
642 } else {
643 Ctx->mangleName(Decl, Out);
644 }
645 #endif
646 return Out.str().str();
647 } else {
648 return std::string("V_") + mangleLocation(Decl->getLocation()) +
649 std::string("_") + hash(std::string(Decl->getName()));
650 }
651 } else if (isa<TagDecl>(Decl) || isa<ObjCInterfaceDecl>(Decl)) {
652 if (!Decl->getIdentifier()) {
653 // Anonymous.
654 return std::string("T_") + mangleLocation(Decl->getLocation());
655 }
656
657 return std::string("T_") + mangleQualifiedName(getQualifiedName(Decl));
658 } else if (isa<TypedefNameDecl>(Decl)) {
659 if (!Decl->getIdentifier()) {
660 // Anonymous.
661 return std::string("TA_") + mangleLocation(Decl->getLocation());
662 }
663
664 return std::string("TA_") + mangleQualifiedName(getQualifiedName(Decl));
665 } else if (isa<NamespaceDecl>(Decl) || isa<NamespaceAliasDecl>(Decl)) {
666 if (!Decl->getIdentifier()) {
667 // Anonymous.
668 return std::string("NS_") + mangleLocation(Decl->getLocation());
669 }
670
671 return std::string("NS_") + mangleQualifiedName(getQualifiedName(Decl));
672 } else if (const ObjCIvarDecl *D2 = dyn_cast<ObjCIvarDecl>(Decl)) {
673 const ObjCInterfaceDecl *Iface = D2->getContainingInterface();
674 return std::string("F_<") + getMangledName(Ctx, Iface) + ">_" +
675 D2->getNameAsString();
676 } else if (const FieldDecl *D2 = dyn_cast<FieldDecl>(Decl)) {
677 const RecordDecl *Record = D2->getParent();
678 return std::string("F_<") + getMangledName(Ctx, Record) + ">_" +
679 D2->getNameAsString();
680 } else if (const EnumConstantDecl *D2 = dyn_cast<EnumConstantDecl>(Decl)) {
681 const DeclContext *DC = Decl->getDeclContext();
682 if (const NamedDecl *Named = dyn_cast<NamedDecl>(DC)) {
683 return std::string("E_<") + getMangledName(Ctx, Named) + ">_" +
684 D2->getNameAsString();
685 }
686 }
687
688 assert(false);
689 return std::string("");
690 }
691
692 void debugLocation(SourceLocation Loc) {
693 std::string S = locationToString(Loc);
694 StringRef Filename = SM.getFilename(Loc);
695 printf("--> %s %s\n", std::string(Filename).c_str(), S.c_str());
696 }
697
698 void debugRange(SourceRange Range) {
699 printf("Range\n");
700 debugLocation(Range.getBegin());
701 debugLocation(Range.getEnd());
702 }
703
704 public:
705 IndexConsumer(CompilerInstance &CI)
706 : CI(CI), SM(CI.getSourceManager()), LO(CI.getLangOpts()),
707 CurMangleContext(nullptr), AstContext(nullptr),
708 ConcatInfo(CI.getPreprocessor()), CurDeclContext(nullptr),
709 TemplateStack(nullptr) {
710 CI.getPreprocessor().addPPCallbacks(make_unique<PreprocessorHook>(this));
711 CI.getPreprocessor().setTokenWatcher(
712 [this](const auto &token) { onTokenLexed(token); });
713 }
714
715 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
716 return new IndexConsumer(CI);
717 }
718
719 #if !defined(_WIN32) && !defined(_WIN64)
720 struct AutoTime {
721 AutoTime(double *Counter) : Counter(Counter), Start(time()) {}
722 ~AutoTime() {
723 if (Start) {
724 *Counter += time() - Start;
725 }
726 }
727 void stop() {
728 *Counter += time() - Start;
729 Start = 0;
730 }
731 double *Counter;
732 double Start;
733 };
734 #endif
735
736 // All we need is to follow the final declaration.
737 virtual void HandleTranslationUnit(ASTContext &Ctx) {
738 CurMangleContext =
739 clang::ItaniumMangleContext::create(Ctx, CI.getDiagnostics());
740
741 AstContext = &Ctx;
742 Resolver = std::make_unique<clangd::HeuristicResolver>(Ctx);
743 TraverseDecl(Ctx.getTranslationUnitDecl());
744
745 // Emit the JSON data for all files now.
746 std::map<FileID, std::unique_ptr<FileInfo>>::iterator It;
747 for (It = FileMap.begin(); It != FileMap.end(); It++) {
748 if (!It->second->Interesting) {
749 continue;
750 }
751
752 FileInfo &Info = *It->second;
753
754 std::string Filename = Outdir + Info.Realname;
755 std::string SrcFilename =
756 Info.Generated ? Objdir + Info.Realname.substr(GENERATED.length())
757 : Srcdir + PATHSEP_STRING + Info.Realname;
758
759 ensurePath(Filename);
760
761 // We lock the output file in case some other clang process is trying to
762 // write to it at the same time.
763 AutoLockFile Lock(SrcFilename, Filename);
764
765 if (!Lock.success()) {
766 fprintf(stderr, "Unable to lock file %s\n", Filename.c_str());
767 exit(1);
768 }
769
770 // Merge our results with the existing lines from the output file.
771 // This ensures that header files that are included multiple times
772 // in different ways are analyzed completely.
773 std::ifstream Fin(Filename.c_str(), std::ios::in | std::ios::binary);
774 FILE *OutFp = Lock.openTmp();
775 if (!OutFp) {
776 fprintf(stderr, "Unable to open tmp out file for %s\n",
777 Filename.c_str());
778 exit(1);
779 }
780
781 // Sort our new results and get an iterator to them
782 std::sort(Info.Output.begin(), Info.Output.end());
783 std::vector<std::string>::const_iterator NewLinesIter =
784 Info.Output.begin();
785 std::string LastNewWritten;
786
787 // Loop over the existing (sorted) lines in the analysis output file.
788 // (The good() check also handles the case where Fin did not exist when we
789 // went to open it.)
790 while (Fin.good()) {
791 std::string OldLine;
792 std::getline(Fin, OldLine);
793 // Skip blank lines.
794 if (OldLine.length() == 0) {
795 continue;
796 }
797 // We need to put the newlines back that getline() eats.
798 OldLine.push_back('\n');
799
800 // Write any results from Info.Output that are lexicographically
801 // smaller than OldLine (read from the existing file), but make sure
802 // to skip duplicates. Keep advancing NewLinesIter until we reach an
803 // entry that is lexicographically greater than OldLine.
804 for (; NewLinesIter != Info.Output.end(); NewLinesIter++) {
805 if (*NewLinesIter > OldLine) {
806 break;
807 }
808 if (*NewLinesIter == OldLine) {
809 continue;
810 }
811 if (*NewLinesIter == LastNewWritten) {
812 // dedupe the new entries being written
813 continue;
814 }
815 if (fwrite(NewLinesIter->c_str(), NewLinesIter->length(), 1, OutFp) !=
816 1) {
817 fprintf(stderr,
818 "Unable to write %zu bytes[1] to tmp output file for %s\n",
819 NewLinesIter->length(), Filename.c_str());
820 exit(1);
821 }
822 LastNewWritten = *NewLinesIter;
823 }
824
825 // Write the entry read from the existing file.
826 if (fwrite(OldLine.c_str(), OldLine.length(), 1, OutFp) != 1) {
827 fprintf(stderr,
828 "Unable to write %zu bytes[2] to tmp output file for %s\n",
829 OldLine.length(), Filename.c_str());
830 exit(1);
831 }
832 }
833
834 // We finished reading from Fin
835 Fin.close();
836
837 // Finish iterating our new results, discarding duplicates
838 for (; NewLinesIter != Info.Output.end(); NewLinesIter++) {
839 if (*NewLinesIter == LastNewWritten) {
840 continue;
841 }
842 if (fwrite(NewLinesIter->c_str(), NewLinesIter->length(), 1, OutFp) !=
843 1) {
844 fprintf(stderr,
845 "Unable to write %zu bytes[3] to tmp output file for %s\n",
846 NewLinesIter->length(), Filename.c_str());
847 exit(1);
848 }
849 LastNewWritten = *NewLinesIter;
850 }
851
852 // Done writing all the things, close it and replace the old output file
853 // with the new one.
854 fclose(OutFp);
855 if (!Lock.moveTmp()) {
856 fprintf(stderr,
857 "Unable to move tmp output file into place for %s (err %d)\n",
858 Filename.c_str(), errno);
859 exit(1);
860 }
861 }
862 }
863
864 // Unfortunately, we have to override all these methods in order to track the
865 // context we're inside.
866
867 bool TraverseEnumDecl(EnumDecl *D) {
868 AutoSetContext Asc(this, D);
869 return Super::TraverseEnumDecl(D);
870 }
871 bool TraverseRecordDecl(RecordDecl *D) {
872 AutoSetContext Asc(this, D);
873 return Super::TraverseRecordDecl(D);
874 }
875 bool TraverseCXXRecordDecl(CXXRecordDecl *D) {
876 AutoSetContext Asc(this, D);
877 return Super::TraverseCXXRecordDecl(D);
878 }
879 bool TraverseFunctionDecl(FunctionDecl *D) {
880 AutoSetContext Asc(this, D);
881 const FunctionDecl *Def;
882 // (See the larger AutoTemplateContext comment for more information.) If a
883 // method on a templated class is declared out-of-line, we need to analyze
884 // the definition inside the scope of the template or else we won't properly
885 // handle member access on the templated type.
886 if (TemplateStack && D->isDefined(Def) && Def && D != Def) {
887 const auto _ = ValueRollback(CurDeclContext, nullptr);
888 TraverseFunctionDecl(const_cast<FunctionDecl *>(Def));
889 }
890 return Super::TraverseFunctionDecl(D);
891 }
892 bool TraverseCXXMethodDecl(CXXMethodDecl *D) {
893 AutoSetContext Asc(this, D);
894 const FunctionDecl *Def;
895 // See TraverseFunctionDecl.
896 if (TemplateStack && D->isDefined(Def) && Def && D != Def) {
897 const auto _ = ValueRollback(CurDeclContext, nullptr);
898 TraverseFunctionDecl(const_cast<FunctionDecl *>(Def));
899 }
900 return Super::TraverseCXXMethodDecl(D);
901 }
902 bool TraverseCXXConstructorDecl(CXXConstructorDecl *D) {
903 AutoSetContext Asc(this, D, /*VisitImplicit=*/true);
904 const FunctionDecl *Def;
905 // See TraverseFunctionDecl.
906 if (TemplateStack && D->isDefined(Def) && Def && D != Def) {
907 const auto _ = ValueRollback(CurDeclContext, nullptr);
908 TraverseFunctionDecl(const_cast<FunctionDecl *>(Def));
909 }
910 return Super::TraverseCXXConstructorDecl(D);
911 }
912 bool TraverseCXXConversionDecl(CXXConversionDecl *D) {
913 AutoSetContext Asc(this, D);
914 const FunctionDecl *Def;
915 // See TraverseFunctionDecl.
916 if (TemplateStack && D->isDefined(Def) && Def && D != Def) {
917 const auto _ = ValueRollback(CurDeclContext, nullptr);
918 TraverseFunctionDecl(const_cast<FunctionDecl *>(Def));
919 }
920 return Super::TraverseCXXConversionDecl(D);
921 }
922 bool TraverseCXXDestructorDecl(CXXDestructorDecl *D) {
923 AutoSetContext Asc(this, D);
924 const FunctionDecl *Def;
925 // See TraverseFunctionDecl.
926 if (TemplateStack && D->isDefined(Def) && Def && D != Def) {
927 const auto _ = ValueRollback(CurDeclContext, nullptr);
928 TraverseFunctionDecl(const_cast<FunctionDecl *>(Def));
929 }
930 return Super::TraverseCXXDestructorDecl(D);
931 }
932
933 bool TraverseLambdaExpr(LambdaExpr *E) {
934 AutoSetContext Asc(this, nullptr, true);
935 return Super::TraverseLambdaExpr(E);
936 }
937
938 // Used to keep track of the context in which a token appears.
939 struct Context {
940 // Ultimately this becomes the "context" JSON property.
941 std::string Name;
942
943 // Ultimately this becomes the "contextsym" JSON property.
944 std::string Symbol;
945
946 Context() {}
947 Context(std::string Name, std::string Symbol)
948 : Name(Name), Symbol(Symbol) {}
949 };
950
951 Context translateContext(NamedDecl *D) {
952 const FunctionDecl *F = dyn_cast<FunctionDecl>(D);
953 if (F && F->isTemplateInstantiation()) {
954 D = F->getTemplateInstantiationPattern();
955 }
956
957 return Context(D->getQualifiedNameAsString(),
958 getMangledName(CurMangleContext, D));
959 }
960
961 Context getContext(SourceLocation Loc) {
962 if (SM.isMacroBodyExpansion(Loc)) {
963 // If we're inside a macro definition, we don't return any context. It
964 // will probably not be what the user expects if we do.
965 return Context();
966 }
967
968 AutoSetContext *Ctxt = CurDeclContext;
969 while (Ctxt) {
970 if (Ctxt->Decl) {
971 return translateContext(Ctxt->Decl);
972 }
973 Ctxt = Ctxt->Prev;
974 }
975 return Context();
976 }
977
978 // Similar to GetContext(SourceLocation), but it skips the declaration passed
979 // in. This is useful if we want the context of a declaration that's already
980 // on the stack.
981 Context getContext(Decl *D) {
982 if (SM.isMacroBodyExpansion(D->getLocation())) {
983 // If we're inside a macro definition, we don't return any context. It
984 // will probably not be what the user expects if we do.
985 return Context();
986 }
987
988 AutoSetContext *Ctxt = CurDeclContext;
989 while (Ctxt) {
990 if (Ctxt->Decl && Ctxt->Decl != D) {
991 return translateContext(Ctxt->Decl);
992 }
993 Ctxt = Ctxt->Prev;
994 }
995 return Context();
996 }
997
998 // Searches for the closest CurDeclContext parent that is a function template
999 // instantiation
1000 const FunctionDecl *getCurrentFunctionTemplateInstantiation() {
1001 const auto *Ctxt = CurDeclContext;
1002 while (Ctxt) {
1003 if (Ctxt->Decl && isa<FunctionDecl>(Ctxt->Decl)) {
1004 const auto *F = Ctxt->Decl->getAsFunction();
1005 if (F->isTemplateInstantiation())
1006 return F;
1007 }
1008 Ctxt = Ctxt->Prev;
1009 }
1010 return nullptr;
1011 }
1012
1013 // Analyzing template code is tricky. Suppose we have this code:
1014 //
1015 // template<class T>
1016 // bool Foo(T* ptr) { return T::StaticMethod(ptr); }
1017 //
1018 // If we analyze the body of Foo without knowing the type T, then we will not
1019 // be able to generate any information for StaticMethod. However, analyzing
1020 // Foo for every possible instantiation is inefficient and it also generates
1021 // too much data in some cases. For example, the following code would generate
1022 // one definition of Baz for every instantiation, which is undesirable:
1023 //
1024 // template<class T>
1025 // class Bar { struct Baz { ... }; };
1026 //
1027 // To solve this problem, we analyze templates only once. We do so in a
1028 // GatherDependent mode where we look for "dependent scoped member
1029 // expressions" (i.e., things like StaticMethod). We keep track of the
1030 // locations of these expressions. If we find one or more of them, we analyze
1031 // the template for each instantiation, in an AnalyzeDependent mode. This mode
1032 // ignores all source locations except for the ones where we found dependent
1033 // scoped member expressions before. For these locations, we generate a
1034 // separate JSON result for each instantiation.
1035 //
1036 // We inherit our parent's mode if it is exists. This is because if our
1037 // parent is in analyze mode, it means we've already lived a full life in
1038 // gather mode and we must not restart in gather mode or we'll cause the
1039 // indexer to visit EVERY identifier, which is way too much data.
1040 struct AutoTemplateContext {
1041 AutoTemplateContext(IndexConsumer *Self)
1042 : Self(Self), CurMode(Self->TemplateStack ? Self->TemplateStack->CurMode
1043 : Mode::GatherDependent),
1044 Parent(Self->TemplateStack) {
1045 Self->TemplateStack = this;
1046 }
1047
1048 ~AutoTemplateContext() { Self->TemplateStack = Parent; }
1049
1050 // We traverse templates in two modes:
1051 enum class Mode {
1052 // Gather mode does not traverse into specializations. It looks for
1053 // locations where it would help to have more info from template
1054 // specializations.
1055 GatherDependent,
1056
1057 // Analyze mode traverses into template specializations and records
1058 // information about token locations saved in gather mode.
1059 AnalyzeDependent,
1060 };
1061
1062 // We found a dependent scoped member expression! Keep track of it for
1063 // later.
1064 void visitDependent(SourceLocation Loc) {
1065 if (CurMode == Mode::AnalyzeDependent) {
1066 return;
1067 }
1068
1069 DependentLocations.insert(Loc.getRawEncoding());
1070 if (Parent) {
1071 Parent->visitDependent(Loc);
1072 }
1073 }
1074
1075 bool inGatherMode() { return CurMode == Mode::GatherDependent; }
1076
1077 // Do we need to perform the extra AnalyzeDependent passes (one per
1078 // instantiation)?
1079 bool needsAnalysis() const {
1080 if (!DependentLocations.empty()) {
1081 return true;
1082 }
1083 if (Parent) {
1084 return Parent->needsAnalysis();
1085 }
1086 return false;
1087 }
1088
1089 void switchMode() { CurMode = Mode::AnalyzeDependent; }
1090
1091 // Do we want to analyze each template instantiation separately?
1092 bool shouldVisitTemplateInstantiations() const {
1093 if (CurMode == Mode::AnalyzeDependent) {
1094 return true;
1095 }
1096 if (Parent) {
1097 return Parent->shouldVisitTemplateInstantiations();
1098 }
1099 return false;
1100 }
1101
1102 // For a given expression/statement, should we emit JSON data for it?
1103 bool shouldVisit(SourceLocation Loc) {
1104 if (CurMode == Mode::GatherDependent) {
1105 return true;
1106 }
1107 if (DependentLocations.find(Loc.getRawEncoding()) !=
1108 DependentLocations.end()) {
1109 return true;
1110 }
1111 if (Parent) {
1112 return Parent->shouldVisit(Loc);
1113 }
1114 return false;
1115 }
1116
1117 private:
1118 IndexConsumer *Self;
1119 Mode CurMode;
1120 std::unordered_set<unsigned> DependentLocations;
1121 AutoTemplateContext *Parent;
1122 };
1123
1124 AutoTemplateContext *TemplateStack;
1125
1126 std::unordered_multimap<const FunctionDecl *, const Stmt *>
1127 ForwardingTemplates;
1128 std::unordered_set<unsigned> ForwardedTemplateLocations;
1129
1130 bool shouldVisitTemplateInstantiations() const {
1131 if (TemplateStack) {
1132 return TemplateStack->shouldVisitTemplateInstantiations();
1133 }
1134 return false;
1135 }
1136
1137 bool shouldVisitImplicitCode() const {
1138 return CurDeclContext && CurDeclContext->VisitImplicit;
1139 }
1140
1141 // We don't want to traverse all specializations everytime we find a forward
1142 // declaration, so only traverse specializations related to an actual
1143 // definition.
1144 //
1145 // ```
1146 // // This is the canonical declaration for Maybe but isn't really useful.
1147 // template <typename T>
1148 // struct Maybe;
1149 //
1150 // // This is another ClassTemplateDecl, but not the canonical one, where we
1151 // // actually have the definition. This is the one we want to traverse.
1152 // template <typename T>
1153 // struct Maybe {
1154 // // This is both the canonical declaration and the definition for
1155 // // inline_method and we want to traverse it.
1156 // template <typename... Args>
1157 // T *inline_method(Args&&... args) {
1158 // // definition
1159 // }
1160 //
1161 // // This is the canonical declaration, TraverseFunctionTemplateDecl
1162 // // traverses its out of line definition too.
1163 // template <typename... Args>
1164 // T *out_of_line_method(Args&&... args);
1165 // }
1166 //
1167 // // This is the definition for Maybe<T>::out_of_line_method<Args...>
1168 // // It is traversed when calling TraverseFunctionTemplateDecl on the
1169 // // canonical declaration.
1170 // template <typename T>
1171 // template <typename... Args>
1172 // T *maybe(Args&&... args) {
1173 // // definition
1174 // }
1175 // ```
1176 //
1177 // So:
1178 // - for class templates we check isThisDeclarationADefinition
1179 // - for function templates we check isCanonicalDecl
1180 bool TraverseClassTemplateDecl(ClassTemplateDecl *D) {
1181 AutoTemplateContext Atc(this);
1182 Super::TraverseClassTemplateDecl(D);
1183
1184 // Gather dependent locations from partial specializations too
1185 SmallVector<ClassTemplatePartialSpecializationDecl *> PS;
1186 D->getPartialSpecializations(PS);
1187 for (auto *Spec : PS) {
1188 for (auto *Rd : Spec->redecls()) {
1189 TraverseDecl(Rd);
1190 }
1191 }
1192
1193 if (!Atc.needsAnalysis()) {
1194 return true;
1195 }
1196
1197 Atc.switchMode();
1198
1199 if (!D->isThisDeclarationADefinition())
1200 return true;
1201
1202 for (auto *Spec : D->specializations()) {
1203 for (auto *Rd : Spec->redecls()) {
1204 // We don't want to visit injected-class-names in this traversal.
1205 if (cast<CXXRecordDecl>(Rd)->isInjectedClassName())
1206 continue;
1207
1208 TraverseDecl(Rd);
1209 }
1210 }
1211
1212 return true;
1213 }
1214
1215 // See also comment above TraverseClassTemplateDecl
1216 bool TraverseFunctionTemplateDecl(FunctionTemplateDecl *D) {
1217 AutoTemplateContext Atc(this);
1218 if (Atc.inGatherMode()) {
1219 Super::TraverseFunctionTemplateDecl(D);
1220 }
1221
1222 if (!Atc.needsAnalysis()) {
1223 return true;
1224 }
1225
1226 Atc.switchMode();
1227
1228 if (!D->isCanonicalDecl())
1229 return true;
1230
1231 for (auto *Spec : D->specializations()) {
1232 for (auto *Rd : Spec->redecls()) {
1233 TraverseDecl(Rd);
1234 }
1235 }
1236
1237 return true;
1238 }
1239
1240 bool shouldVisit(SourceLocation Loc) {
1241 if (TemplateStack) {
1242 return TemplateStack->shouldVisit(Loc);
1243 }
1244 return true;
1245 }
1246
1247 enum {
1248 // Flag to omit the identifier from being cross-referenced across files.
1249 // This is usually desired for local variables.
1250 NoCrossref = 1 << 0,
1251 // Flag to indicate the token with analysis data is not an identifier.
1252 // Indicates
1253 // we want to skip the check that tries to ensure a sane identifier token.
1254 NotIdentifierToken = 1 << 1,
1255 // This indicates that the end of the provided SourceRange is valid and
1256 // should be respected. If this flag is not set, the visitIdentifier
1257 // function should use only the start of the SourceRange and auto-detect
1258 // the end based on whatever token is found at the start.
1259 LocRangeEndValid = 1 << 2,
1260 // Indicates this record was generated through heuristic template
1261 // resolution.
1262 Heuristic = 1 << 3,
1263 };
1264
1265 void emitStructuredRecordInfo(llvm::json::OStream &J, SourceLocation Loc,
1266 const RecordDecl *decl) {
1267 J.attribute("kind",
1268 TypeWithKeyword::getTagTypeKindName(decl->getTagKind()));
1269
1270 const ASTContext &C = *AstContext;
1271 const ASTRecordLayout &Layout = C.getASTRecordLayout(decl);
1272
1273 J.attribute("sizeBytes", Layout.getSize().getQuantity());
1274 J.attribute("alignmentBytes", Layout.getAlignment().getQuantity());
1275
1276 emitBindingAttributes(J, *decl);
1277
1278 auto cxxDecl = dyn_cast<CXXRecordDecl>(decl);
1279
1280 if (cxxDecl) {
1281 if (Layout.hasOwnVFPtr()) {
1282 // Encode the size of virtual function table pointer
1283 // instead of just true/false, for 2 reasons:
1284 // * having the size here is easier for the consumer
1285 // * the size string 4/8 is shorter than true/false in the analysis
1286 // file
1287 const QualType ptrType = C.getUIntPtrType();
1288 J.attribute("ownVFPtrBytes",
1289 C.getTypeSizeInChars(ptrType).getQuantity());
1290 }
1291
1292 J.attributeBegin("supers");
1293 J.arrayBegin();
1294 for (const CXXBaseSpecifier &Base : cxxDecl->bases()) {
1295 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
1296
1297 J.objectBegin();
1298
1299 J.attribute("sym", getMangledName(CurMangleContext, BaseDecl));
1300
1301 if (Base.isVirtual()) {
1302 CharUnits superOffsetBytes = Layout.getVBaseClassOffset(BaseDecl);
1303 J.attribute("offsetBytes", superOffsetBytes.getQuantity());
1304 } else {
1305 CharUnits superOffsetBytes = Layout.getBaseClassOffset(BaseDecl);
1306 J.attribute("offsetBytes", superOffsetBytes.getQuantity());
1307 }
1308
1309 J.attributeBegin("props");
1310 J.arrayBegin();
1311 if (Base.isVirtual()) {
1312 J.value("virtual");
1313 }
1314 J.arrayEnd();
1315 J.attributeEnd();
1316
1317 J.objectEnd();
1318 }
1319 J.arrayEnd();
1320 J.attributeEnd();
1321
1322 J.attributeBegin("methods");
1323 J.arrayBegin();
1324 for (const CXXMethodDecl *MethodDecl : cxxDecl->methods()) {
1325 J.objectBegin();
1326
1327 J.attribute("pretty", getQualifiedName(MethodDecl));
1328 J.attribute("sym", getMangledName(CurMangleContext, MethodDecl));
1329
1330 // TODO: Better figure out what to do for non-isUserProvided methods
1331 // which means there's potentially semantic data that doesn't correspond
1332 // to a source location in the source. Should we be emitting
1333 // structured info for those when we're processing the class here?
1334
1335 J.attributeBegin("props");
1336 J.arrayBegin();
1337 if (MethodDecl->isStatic()) {
1338 J.value("static");
1339 }
1340 if (MethodDecl->isInstance()) {
1341 J.value("instance");
1342 }
1343 if (MethodDecl->isVirtual()) {
1344 J.value("virtual");
1345 }
1346 if (MethodDecl->isUserProvided()) {
1347 J.value("user");
1348 }
1349 if (MethodDecl->isDefaulted()) {
1350 J.value("defaulted");
1351 }
1352 if (MethodDecl->isDeleted()) {
1353 J.value("deleted");
1354 }
1355 if (MethodDecl->isConstexpr()) {
1356 J.value("constexpr");
1357 }
1358 J.arrayEnd();
1359 J.attributeEnd();
1360
1361 J.objectEnd();
1362 }
1363 J.arrayEnd();
1364 J.attributeEnd();
1365 }
1366
1367 FileID structFileID = SM.getFileID(Loc);
1368
1369 J.attributeBegin("fields");
1370 J.arrayBegin();
1371 uint64_t iField = 0;
1372 for (RecordDecl::field_iterator It = decl->field_begin(),
1373 End = decl->field_end();
1374 It != End; ++It, ++iField) {
1375 const FieldDecl &Field = **It;
1376 auto sourceRange =
1377 SM.getExpansionRange(Field.getSourceRange()).getAsRange();
1378 uint64_t localOffsetBits = Layout.getFieldOffset(iField);
1379 CharUnits localOffsetBytes = C.toCharUnitsFromBits(localOffsetBits);
1380
1381 J.objectBegin();
1382 J.attribute("lineRange",
1383 pathAndLineRangeToString(structFileID, sourceRange));
1384 J.attribute("pretty", getQualifiedName(&Field));
1385 J.attribute("sym", getMangledName(CurMangleContext, &Field));
1386
1387 QualType FieldType = Field.getType();
1388 QualType CanonicalFieldType = FieldType.getCanonicalType();
1389 LangOptions langOptions;
1390 PrintingPolicy Policy(langOptions);
1391 Policy.PrintCanonicalTypes = true;
1392 J.attribute("type", CanonicalFieldType.getAsString(Policy));
1393
1394 const TagDecl *tagDecl = CanonicalFieldType->getAsTagDecl();
1395 if (!tagDecl) {
1396 // Try again piercing any pointers/references involved. Note that our
1397 // typesym semantics are dubious-ish and right now crossref just does
1398 // some parsing of "type" itself until we improve this rep.
1399 CanonicalFieldType = CanonicalFieldType->getPointeeType();
1400 if (!CanonicalFieldType.isNull()) {
1401 tagDecl = CanonicalFieldType->getAsTagDecl();
1402 }
1403 }
1404 if (tagDecl) {
1405 J.attribute("typesym", getMangledName(CurMangleContext, tagDecl));
1406 }
1407 J.attribute("offsetBytes", localOffsetBytes.getQuantity());
1408 if (Field.isBitField()) {
1409 J.attributeBegin("bitPositions");
1410 J.objectBegin();
1411
1412 J.attribute("begin",
1413 unsigned(localOffsetBits - C.toBits(localOffsetBytes)));
1414 #if CLANG_VERSION_MAJOR < 20
1415 J.attribute("width", Field.getBitWidthValue(C));
1416 #else
1417 J.attribute("width", Field.getBitWidthValue());
1418 #endif
1419
1420 J.objectEnd();
1421 J.attributeEnd();
1422 } else {
1423 // Try and get the field as a record itself so we can know its size, but
1424 // we don't actually want to recurse into it.
1425 if (auto FieldRec = Field.getType()->getAs<RecordType>()) {
1426 auto const &FieldLayout = C.getASTRecordLayout(FieldRec->getDecl());
1427 J.attribute("sizeBytes", FieldLayout.getSize().getQuantity());
1428 } else {
1429 // We were unable to get it as a record, which suggests it's a normal
1430 // type, in which case let's just ask for the type size. (Maybe this
1431 // would also work for the above case too?)
1432 uint64_t typeSizeBits = C.getTypeSize(Field.getType());
1433 CharUnits typeSizeBytes = C.toCharUnitsFromBits(typeSizeBits);
1434 J.attribute("sizeBytes", typeSizeBytes.getQuantity());
1435 }
1436 }
1437 J.objectEnd();
1438 }
1439 J.arrayEnd();
1440 J.attributeEnd();
1441 }
1442
1443 void emitStructuredEnumInfo(llvm::json::OStream &J, const EnumDecl *ED) {
1444 J.attribute("kind", "enum");
1445 }
1446
1447 void emitStructuredEnumConstantInfo(llvm::json::OStream &J,
1448 const EnumConstantDecl *ECD) {
1449 J.attribute("kind", "enumConstant");
1450 }
1451
1452 void emitStructuredFunctionInfo(llvm::json::OStream &J,
1453 const FunctionDecl *decl) {
1454 emitBindingAttributes(J, *decl);
1455
1456 J.attributeBegin("args");
1457 J.arrayBegin();
1458
1459 for (auto param : decl->parameters()) {
1460 J.objectBegin();
1461
1462 J.attribute("name", param->getName());
1463 QualType ArgType = param->getOriginalType();
1464 J.attribute("type", ArgType.getAsString());
1465
1466 QualType CanonicalArgType = ArgType.getCanonicalType();
1467 const TagDecl *canonDecl = CanonicalArgType->getAsTagDecl();
1468 if (!canonDecl) {
1469 // Try again piercing any pointers/references involved. Note that our
1470 // typesym semantics are dubious-ish and right now crossref just does
1471 // some parsing of "type" itself until we improve this rep.
1472 CanonicalArgType = CanonicalArgType->getPointeeType();
1473 if (!CanonicalArgType.isNull()) {
1474 canonDecl = CanonicalArgType->getAsTagDecl();
1475 }
1476 }
1477 if (canonDecl) {
1478 J.attribute("typesym", getMangledName(CurMangleContext, canonDecl));
1479 }
1480
1481 J.objectEnd();
1482 }
1483
1484 J.arrayEnd();
1485 J.attributeEnd();
1486
1487 auto cxxDecl = dyn_cast<CXXMethodDecl>(decl);
1488
1489 if (cxxDecl) {
1490 J.attribute("kind", "method");
1491 if (auto parentDecl = cxxDecl->getParent()) {
1492 J.attribute("parentsym", getMangledName(CurMangleContext, parentDecl));
1493 }
1494
1495 J.attributeBegin("overrides");
1496 J.arrayBegin();
1497 for (const CXXMethodDecl *MethodDecl : cxxDecl->overridden_methods()) {
1498 J.objectBegin();
1499
1500 // TODO: Make sure we're doing template traversals appropriately...
1501 // findOverriddenMethods (now removed) liked to do:
1502 // if (Decl->isTemplateInstantiation()) {
1503 // Decl =
1504 // dyn_cast<CXXMethodDecl>(Decl->getTemplateInstantiationPattern());
1505 // }
1506 // I think our pre-emptive dereferencing/avoidance of templates may
1507 // protect us from this, but it needs more investigation.
1508
1509 J.attribute("sym", getMangledName(CurMangleContext, MethodDecl));
1510
1511 J.objectEnd();
1512 }
1513 J.arrayEnd();
1514 J.attributeEnd();
1515
1516 } else {
1517 J.attribute("kind", "function");
1518 }
1519
1520 // ## Props
1521 J.attributeBegin("props");
1522 J.arrayBegin();
1523 // some of these are only possible on a CXXMethodDecl, but we want them all
1524 // in the same array, so condition these first ones.
1525 if (cxxDecl) {
1526 if (cxxDecl->isStatic()) {
1527 J.value("static");
1528 }
1529 if (cxxDecl->isInstance()) {
1530 J.value("instance");
1531 }
1532 if (cxxDecl->isVirtual()) {
1533 J.value("virtual");
1534 }
1535 if (cxxDecl->isUserProvided()) {
1536 J.value("user");
1537 }
1538 }
1539 if (decl->isDefaulted()) {
1540 J.value("defaulted");
1541 }
1542 if (decl->isDeleted()) {
1543 J.value("deleted");
1544 }
1545 if (decl->isConstexpr()) {
1546 J.value("constexpr");
1547 }
1548 J.arrayEnd();
1549 J.attributeEnd();
1550 }
1551
1552 /**
1553 * Emit structured info for a field. Right now the intent is for this to just
1554 * be a pointer to its parent's structured info with this method entirely
1555 * avoiding getting the ASTRecordLayout.
1556 *
1557 * TODO: Give more thought on where to locate the canonical info on fields and
1558 * how to normalize their exposure over the web. We could relink the info
1559 * both at cross-reference time and web-server lookup time. This is also
1560 * called out in `analysis.md`.
1561 */
1562 void emitStructuredFieldInfo(llvm::json::OStream &J, const FieldDecl *decl) {
1563 J.attribute("kind", "field");
1564
1565 // XXX the call to decl::getParent will assert below for ObjCIvarDecl
1566 // instances because their DecContext is not a RecordDecl. So just bail
1567 // for now.
1568 // TODO: better support ObjC.
1569 if (!dyn_cast<ObjCIvarDecl>(decl)) {
1570 if (auto parentDecl = decl->getParent()) {
1571 J.attribute("parentsym", getMangledName(CurMangleContext, parentDecl));
1572 }
1573 }
1574 }
1575
1576 /**
1577 * Emit structured info for a variable if it is a static class member.
1578 */
1579 void emitStructuredVarInfo(llvm::json::OStream &J, const VarDecl *decl) {
1580 const auto *parentDecl =
1581 dyn_cast_or_null<RecordDecl>(decl->getDeclContext());
1582
1583 if (parentDecl) {
1584 J.attribute("kind", "field");
1585 } else if (llvm::isa<ParmVarDecl>(decl)) {
1586 J.attribute("kind", "parameter");
1587 } else if (decl->isLocalVarDecl()) {
1588 J.attribute("kind", "localVar");
1589 } else {
1590 // namespace scope variable
1591 J.attribute("kind", "variable");
1592 }
1593
1594 if (parentDecl) {
1595 J.attribute("parentsym", getMangledName(CurMangleContext, parentDecl));
1596 }
1597
1598 emitBindingAttributes(J, *decl);
1599 }
1600
1601 void emitStructuredInfo(SourceLocation Loc, const NamedDecl *decl) {
1602 std::string json_str;
1603 llvm::raw_string_ostream ros(json_str);
1604 llvm::json::OStream J(ros);
1605 // Start the top-level object.
1606 J.objectBegin();
1607
1608 unsigned StartOffset = SM.getFileOffset(Loc);
1609 unsigned EndOffset =
1610 StartOffset + Lexer::MeasureTokenLength(Loc, SM, CI.getLangOpts());
1611 J.attribute("loc", locationToString(Loc, EndOffset - StartOffset));
1612 J.attribute("structured", 1);
1613 J.attribute("pretty", getQualifiedName(decl));
1614 J.attribute("sym", getMangledName(CurMangleContext, decl));
1615
1616 if (const RecordDecl *RD = dyn_cast<RecordDecl>(decl)) {
1617 emitStructuredRecordInfo(J, Loc, RD);
1618 } else if (const EnumDecl *ED = dyn_cast<EnumDecl>(decl)) {
1619 emitStructuredEnumInfo(J, ED);
1620 } else if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(decl)) {
1621 emitStructuredEnumConstantInfo(J, ECD);
1622 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
1623 emitStructuredFunctionInfo(J, FD);
1624 } else if (const FieldDecl *FD = dyn_cast<FieldDecl>(decl)) {
1625 emitStructuredFieldInfo(J, FD);
1626 } else if (const VarDecl *VD = dyn_cast<VarDecl>(decl)) {
1627 emitStructuredVarInfo(J, VD);
1628 }
1629
1630 // End the top-level object.
1631 J.objectEnd();
1632
1633 FileInfo *F = getFileInfo(Loc);
1634 // we want a newline.
1635 ros << '\n';
1636 F->Output.push_back(std::move(ros.str()));
1637 }
1638
1639 // XXX Type annotating.
1640 // QualType is the type class. It has helpers like TagDecl via getAsTagDecl.
1641 // ValueDecl exposes a getType() method.
1642 //
1643 // Arguably it makes sense to only expose types that Searchfox has definitions
1644 // for as first-class. Probably the way to go is like context/contextsym.
1645 // We expose a "type" which is just a human-readable string which has no
1646 // semantic purposes and is just a display string, plus then a "typesym" which
1647 // we expose if we were able to map the type.
1648 //
1649 // Other meta-info: field offsets. Ancestor types.
1650
1651 // This is the only function that emits analysis JSON data. It should be
1652 // called for each identifier that corresponds to a symbol.
1653 void visitIdentifier(const char *Kind, const char *SyntaxKind,
1654 llvm::StringRef QualName, SourceRange LocRange,
1655 std::string Symbol, QualType MaybeType = QualType(),
1656 Context TokenContext = Context(), int Flags = 0,
1657 SourceRange PeekRange = SourceRange(),
1658 SourceRange NestingRange = SourceRange(),
1659 std::vector<SourceRange> *ArgRanges = nullptr) {
1660 SourceLocation Loc = LocRange.getBegin();
1661
1662 // Also visit the spelling site.
1663 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
1664 if (SpellingLoc != Loc) {
1665 visitIdentifier(Kind, SyntaxKind, QualName, SpellingLoc, Symbol,
1666 MaybeType, TokenContext, Flags, PeekRange, NestingRange,
1667 ArgRanges);
1668 }
1669
1670 SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
1671 normalizeLocation(&ExpansionLoc);
1672
1673 if (!shouldVisit(ExpansionLoc)) {
1674 return;
1675 }
1676
1677 if (ExpansionLoc != Loc)
1678 Flags = Flags & ~LocRangeEndValid;
1679
1680 // Find the file positions corresponding to the token.
1681 unsigned StartOffset = SM.getFileOffset(ExpansionLoc);
1682 unsigned EndOffset =
1683 (Flags & LocRangeEndValid)
1684 ? SM.getFileOffset(LocRange.getEnd())
1685 : StartOffset +
1686 Lexer::MeasureTokenLength(ExpansionLoc, SM, CI.getLangOpts());
1687
1688 std::string LocStr =
1689 locationToString(ExpansionLoc, EndOffset - StartOffset);
1690 std::string RangeStr =
1691 locationToString(ExpansionLoc, EndOffset - StartOffset);
1692 std::string PeekRangeStr;
1693
1694 if (!(Flags & NotIdentifierToken)) {
1695 // Get the token's characters so we can make sure it's a valid token.
1696 const char *StartChars = SM.getCharacterData(ExpansionLoc);
1697 std::string Text(StartChars, EndOffset - StartOffset);
1698 if (!isValidIdentifier(Text)) {
1699 return;
1700 }
1701 }
1702
1703 FileInfo *F = getFileInfo(ExpansionLoc);
1704
1705 if (!(Flags & NoCrossref)) {
1706 std::string json_str;
1707 llvm::raw_string_ostream ros(json_str);
1708 llvm::json::OStream J(ros);
1709 // Start the top-level object.
1710 J.objectBegin();
1711
1712 J.attribute("loc", LocStr);
1713 J.attribute("target", 1);
1714 J.attribute("kind", Kind);
1715 J.attribute("pretty", QualName.data());
1716 J.attribute("sym", Symbol);
1717 if (!TokenContext.Name.empty()) {
1718 J.attribute("context", TokenContext.Name);
1719 }
1720 if (!TokenContext.Symbol.empty()) {
1721 J.attribute("contextsym", TokenContext.Symbol);
1722 }
1723 if (PeekRange.isValid()) {
1724 PeekRangeStr = lineRangeToString(PeekRange);
1725 if (!PeekRangeStr.empty()) {
1726 J.attribute("peekRange", PeekRangeStr);
1727 }
1728 }
1729
1730 if (ArgRanges) {
1731 J.attributeBegin("argRanges");
1732 J.arrayBegin();
1733
1734 for (auto range : *ArgRanges) {
1735 std::string ArgRangeStr = fullRangeToString(range);
1736 if (!ArgRangeStr.empty()) {
1737 J.value(ArgRangeStr);
1738 }
1739 }
1740
1741 J.arrayEnd();
1742 J.attributeEnd();
1743 }
1744
1745 // End the top-level object.
1746 J.objectEnd();
1747 // we want a newline.
1748 ros << '\n';
1749 F->Output.push_back(std::move(ros.str()));
1750 }
1751
1752 // Generate a single "source":1 for all the symbols. If we search from here,
1753 // we want to union the results for every symbol in `symbols`.
1754 std::string json_str;
1755 llvm::raw_string_ostream ros(json_str);
1756 llvm::json::OStream J(ros);
1757 // Start the top-level object.
1758 J.objectBegin();
1759
1760 J.attribute("loc", RangeStr);
1761 J.attribute("source", 1);
1762
1763 if (NestingRange.isValid()) {
1764 std::string NestingRangeStr = fullRangeToString(NestingRange);
1765 if (!NestingRangeStr.empty()) {
1766 J.attribute("nestingRange", NestingRangeStr);
1767 }
1768 }
1769
1770 std::string Syntax;
1771 if (Flags & NoCrossref) {
1772 J.attribute("syntax", "");
1773 } else {
1774 Syntax = Kind;
1775 Syntax.push_back(',');
1776 Syntax.append(SyntaxKind);
1777 J.attribute("syntax", Syntax);
1778 }
1779
1780 if (!MaybeType.isNull()) {
1781 J.attribute("type", MaybeType.getAsString());
1782 QualType canonical = MaybeType.getCanonicalType();
1783 const TagDecl *decl = canonical->getAsTagDecl();
1784 if (!decl) {
1785 // Try again piercing any pointers/references involved. Note that our
1786 // typesym semantics are dubious-ish and right now crossref just does
1787 // some parsing of "type" itself until we improve this rep.
1788 canonical = canonical->getPointeeType();
1789 if (!canonical.isNull()) {
1790 decl = canonical->getAsTagDecl();
1791 }
1792 }
1793 if (decl) {
1794 std::string Mangled = getMangledName(CurMangleContext, decl);
1795 J.attribute("typesym", Mangled);
1796 }
1797 }
1798
1799 std::string Pretty(SyntaxKind);
1800 Pretty.push_back(' ');
1801 Pretty.append(QualName.data());
1802 J.attribute("pretty", Pretty);
1803
1804 J.attribute("sym", Symbol);
1805
1806 if (Flags & NoCrossref) {
1807 J.attribute("no_crossref", 1);
1808 }
1809
1810 if (Flags & Heuristic) {
1811 J.attributeBegin("confidence");
1812 J.arrayBegin();
1813 J.value("cppTemplateHeuristic");
1814 J.arrayEnd();
1815 J.attributeEnd();
1816 }
1817
1818 if (ArgRanges) {
1819 J.attributeBegin("argRanges");
1820 J.arrayBegin();
1821
1822 for (auto range : *ArgRanges) {
1823 std::string ArgRangeStr = fullRangeToString(range);
1824 if (!ArgRangeStr.empty()) {
1825 J.value(ArgRangeStr);
1826 }
1827 }
1828
1829 J.arrayEnd();
1830 J.attributeEnd();
1831 }
1832
1833 const auto macro = MacroMaps.find(ExpansionLoc);
1834 if (macro != MacroMaps.end()) {
1835 const auto &macroInfo = macro->second;
1836 if (macroInfo.Symbol == Symbol) {
1837 J.attributeBegin("expandsTo");
1838 J.objectBegin();
1839 J.attributeBegin(macroInfo.Key);
1840 J.objectBegin();
1841 J.attribute("", macroInfo.Expansion); // "" is the platform key,
1842 // populated by the merge step
1843 J.objectEnd();
1844 J.attributeEnd();
1845 J.objectEnd();
1846 J.attributeEnd();
1847 } else {
1848 const auto it = macroInfo.TokenLocations.find(Loc);
1849 if (it != macroInfo.TokenLocations.end()) {
1850 J.attributeBegin("inExpansionAt");
1851 J.objectBegin();
1852 J.attributeBegin(macroInfo.Key);
1853 J.objectBegin();
1854 J.attributeBegin(
1855 ""); // "" is the platform key, populated by the merge step
1856 J.arrayBegin();
1857 J.value(it->second);
1858 J.arrayEnd();
1859 J.attributeEnd();
1860 J.objectEnd();
1861 J.attributeEnd();
1862 J.objectEnd();
1863 J.attributeEnd();
1864 }
1865 }
1866 }
1867
1868 // End the top-level object.
1869 J.objectEnd();
1870
1871 // we want a newline.
1872 ros << '\n';
1873 F->Output.push_back(std::move(ros.str()));
1874 }
1875
1876 void normalizeLocation(SourceLocation *Loc) {
1877 *Loc = SM.getSpellingLoc(*Loc);
1878 }
1879
1880 // For cases where the left-brace is not directly accessible from the AST,
1881 // helper to use the lexer to find the brace. Make sure you're picking the
1882 // start location appropriately!
1883 SourceLocation findLeftBraceFromLoc(SourceLocation Loc) {
1884 return Lexer::findLocationAfterToken(Loc, tok::l_brace, SM, LO, false);
1885 }
1886
1887 // If the provided statement is compound, return its range.
1888 SourceRange getCompoundStmtRange(Stmt *D) {
1889 if (!D) {
1890 return SourceRange();
1891 }
1892
1893 CompoundStmt *D2 = dyn_cast<CompoundStmt>(D);
1894 if (D2) {
1895 return D2->getSourceRange();
1896 }
1897
1898 return SourceRange();
1899 }
1900
1901 SourceRange getFunctionPeekRange(FunctionDecl *D) {
1902 // We always start at the start of the function decl, which may include the
1903 // return type on a separate line.
1904 SourceLocation Start = D->getBeginLoc();
1905
1906 // By default, we end at the line containing the function's name.
1907 SourceLocation End = D->getLocation();
1908
1909 std::pair<FileID, unsigned> FuncLoc = SM.getDecomposedLoc(End);
1910
1911 // But if there are parameters, we want to include those as well.
1912 for (ParmVarDecl *Param : D->parameters()) {
1913 std::pair<FileID, unsigned> ParamLoc =
1914 SM.getDecomposedLoc(Param->getLocation());
1915
1916 // It's possible there are macros involved or something. We don't include
1917 // the parameters in that case.
1918 if (ParamLoc.first == FuncLoc.first) {
1919 // Assume parameters are in order, so we always take the last one.
1920 End = Param->getEndLoc();
1921 }
1922 }
1923
1924 return SourceRange(Start, End);
1925 }
1926
1927 SourceRange getTagPeekRange(TagDecl *D) {
1928 SourceLocation Start = D->getBeginLoc();
1929
1930 // By default, we end at the line containing the name.
1931 SourceLocation End = D->getLocation();
1932
1933 std::pair<FileID, unsigned> FuncLoc = SM.getDecomposedLoc(End);
1934
1935 if (CXXRecordDecl *D2 = dyn_cast<CXXRecordDecl>(D)) {
1936 // But if there are parameters, we want to include those as well.
1937 for (CXXBaseSpecifier &Base : D2->bases()) {
1938 std::pair<FileID, unsigned> Loc = SM.getDecomposedLoc(Base.getEndLoc());
1939
1940 // It's possible there are macros involved or something. We don't
1941 // include the parameters in that case.
1942 if (Loc.first == FuncLoc.first) {
1943 // Assume parameters are in order, so we always take the last one.
1944 End = Base.getEndLoc();
1945 }
1946 }
1947 }
1948
1949 return SourceRange(Start, End);
1950 }
1951
1952 SourceRange getCommentRange(NamedDecl *D) {
1953 const RawComment *RC = AstContext->getRawCommentForDeclNoCache(D);
1954 if (!RC) {
1955 return SourceRange();
1956 }
1957
1958 return RC->getSourceRange();
1959 }
1960
1961 // Sanity checks that all ranges are in the same file, returning the first if
1962 // they're in different files. Unions the ranges based on which is first.
1963 SourceRange combineRanges(SourceRange Range1, SourceRange Range2) {
1964 if (Range1.isInvalid()) {
1965 return Range2;
1966 }
1967 if (Range2.isInvalid()) {
1968 return Range1;
1969 }
1970
1971 std::pair<FileID, unsigned> Begin1 = SM.getDecomposedLoc(Range1.getBegin());
1972 std::pair<FileID, unsigned> End1 = SM.getDecomposedLoc(Range1.getEnd());
1973 std::pair<FileID, unsigned> Begin2 = SM.getDecomposedLoc(Range2.getBegin());
1974 std::pair<FileID, unsigned> End2 = SM.getDecomposedLoc(Range2.getEnd());
1975
1976 if (End1.first != Begin2.first) {
1977 // Something weird is probably happening with the preprocessor. Just
1978 // return the first range.
1979 return Range1;
1980 }
1981
1982 // See which range comes first.
1983 if (Begin1.second <= End2.second) {
1984 return SourceRange(Range1.getBegin(), Range2.getEnd());
1985 } else {
1986 return SourceRange(Range2.getBegin(), Range1.getEnd());
1987 }
1988 }
1989
1990 // Given a location and a range, returns the range if:
1991 // - The location and the range live in the same file.
1992 // - The range is well ordered (end is not before begin).
1993 // Returns an empty range otherwise.
1994 SourceRange validateRange(SourceLocation Loc, SourceRange Range) {
1995 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc);
1996 std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(Range.getBegin());
1997 std::pair<FileID, unsigned> End = SM.getDecomposedLoc(Range.getEnd());
1998
1999 if (Begin.first != Decomposed.first || End.first != Decomposed.first) {
2000 return SourceRange();
2001 }
2002
2003 if (Begin.second >= End.second) {
2004 return SourceRange();
2005 }
2006
2007 return Range;
2008 }
2009
2010 bool VisitNamedDecl(NamedDecl *D) {
2011 SourceLocation Loc = D->getLocation();
2012 if (!isInterestingLocation(Loc)) {
2013 return true;
2014 }
2015
2016 SourceLocation ExpansionLoc = Loc;
2017 if (SM.isMacroBodyExpansion(Loc)) {
2018 ExpansionLoc = SM.getFileLoc(Loc);
2019 }
2020 normalizeLocation(&ExpansionLoc);
2021
2022 if (isa<ParmVarDecl>(D) && !D->getDeclName().getAsIdentifierInfo()) {
2023 // Unnamed parameter in function proto.
2024 return true;
2025 }
2026
2027 int Flags = 0;
2028 const char *Kind = "def";
2029 const char *PrettyKind = "?";
2030 bool wasTemplate = false;
2031 SourceRange PeekRange(D->getBeginLoc(), D->getEndLoc());
2032 // The nesting range identifies the left brace and right brace, which
2033 // heavily depends on the AST node type.
2034 SourceRange NestingRange;
2035 QualType qtype = QualType();
2036 if (FunctionDecl *D2 = dyn_cast<FunctionDecl>(D)) {
2037 if (D2->isTemplateInstantiation()) {
2038 wasTemplate = true;
2039 D = D2->getTemplateInstantiationPattern();
2040 }
2041 // We treat pure virtual declarations as definitions.
2042 Kind =
2043 (D2->isThisDeclarationADefinition() || isPure(D2)) ? "def" : "decl";
2044 PrettyKind = "function";
2045 PeekRange = getFunctionPeekRange(D2);
2046
2047 // Only emit the nesting range if:
2048 // - This is a definition AND
2049 // - This isn't a template instantiation. Function templates'
2050 // instantiations can end up as a definition with a Loc at their point
2051 // of declaration but with the CompoundStmt of the template's
2052 // point of definition. This really messes up the nesting range logic.
2053 // At the time of writing this, the test repo's `big_header.h`'s
2054 // `WhatsYourVector_impl::forwardDeclaredTemplateThingInlinedBelow` as
2055 // instantiated by `big_cpp.cpp` triggers this phenomenon.
2056 //
2057 // Note: As covered elsewhere, template processing is tricky and it's
2058 // conceivable that we may change traversal patterns in the future,
2059 // mooting this guard.
2060 if (D2->isThisDeclarationADefinition() &&
2061 !D2->isTemplateInstantiation()) {
2062 // The CompoundStmt range is the brace range.
2063 NestingRange = getCompoundStmtRange(D2->getBody());
2064 }
2065 } else if (TagDecl *D2 = dyn_cast<TagDecl>(D)) {
2066 Kind = D2->isThisDeclarationADefinition() ? "def" : "forward";
2067 PrettyKind = "type";
2068
2069 if (D2->isThisDeclarationADefinition() && D2->getDefinition() == D2) {
2070 PeekRange = getTagPeekRange(D2);
2071 NestingRange = D2->getBraceRange();
2072 } else {
2073 PeekRange = SourceRange();
2074 }
2075 } else if (TypedefNameDecl *D2 = dyn_cast<TypedefNameDecl>(D)) {
2076 Kind = "alias";
2077 PrettyKind = "type";
2078 PeekRange = SourceRange(ExpansionLoc, ExpansionLoc);
2079 qtype = D2->getUnderlyingType();
2080 } else if (VarDecl *D2 = dyn_cast<VarDecl>(D)) {
2081 if (D2->isLocalVarDeclOrParm()) {
2082 Flags = NoCrossref;
2083 }
2084
2085 Kind = D2->isThisDeclarationADefinition() == VarDecl::DeclarationOnly
2086 ? "decl"
2087 : "def";
2088 PrettyKind = "variable";
2089 } else if (isa<NamespaceDecl>(D) || isa<NamespaceAliasDecl>(D)) {
2090 Kind = "def";
2091 PrettyKind = "namespace";
2092 PeekRange = SourceRange(ExpansionLoc, ExpansionLoc);
2093 NamespaceDecl *D2 = dyn_cast<NamespaceDecl>(D);
2094 if (D2) {
2095 // There's no exposure of the left brace so we have to find it.
2096 NestingRange = SourceRange(
2097 findLeftBraceFromLoc(D2->isAnonymousNamespace() ? D2->getBeginLoc()
2098 : ExpansionLoc),
2099 D2->getRBraceLoc());
2100 }
2101 } else if (isa<FieldDecl>(D)) {
2102 Kind = "def";
2103 PrettyKind = "field";
2104 } else if (isa<EnumConstantDecl>(D)) {
2105 Kind = "def";
2106 PrettyKind = "enum constant";
2107 } else {
2108 return true;
2109 }
2110
2111 if (ValueDecl *D2 = dyn_cast<ValueDecl>(D)) {
2112 qtype = D2->getType();
2113 }
2114
2115 SourceRange CommentRange = getCommentRange(D);
2116 PeekRange = combineRanges(PeekRange, CommentRange);
2117 PeekRange = validateRange(Loc, PeekRange);
2118 NestingRange = validateRange(Loc, NestingRange);
2119
2120 std::string Symbol = getMangledName(CurMangleContext, D);
2121
2122 // In the case of destructors, Loc might point to the ~ character. In that
2123 // case we want to skip to the name of the class. However, Loc might also
2124 // point to other places that generate destructors, such as a lambda
2125 // (apparently clang 8 creates a destructor declaration for at least some
2126 // lambdas). In that case we'll just drop the declaration.
2127 if (isa<CXXDestructorDecl>(D)) {
2128 PrettyKind = "destructor";
2129 const char *P = SM.getCharacterData(Loc);
2130 if (*P == '~') {
2131 // Advance Loc to the class name
2132 P++;
2133
2134 unsigned Skipped = 1;
2135 while (*P == ' ' || *P == '\t' || *P == '\r' || *P == '\n') {
2136 P++;
2137 Skipped++;
2138 }
2139
2140 Loc = Loc.getLocWithOffset(Skipped);
2141 } else {
2142 return true;
2143 }
2144 }
2145
2146 visitIdentifier(Kind, PrettyKind, getQualifiedName(D), SourceRange(Loc),
2147 Symbol, qtype, getContext(D), Flags, PeekRange,
2148 NestingRange);
2149
2150 // In-progress structured info emission.
2151 if (RecordDecl *D2 = dyn_cast<RecordDecl>(D)) {
2152 if (D2->isThisDeclarationADefinition() &&
2153 // XXX getASTRecordLayout doesn't work for dependent types, so we
2154 // avoid calling into emitStructuredInfo for now if there's a
2155 // dependent type or if we're in any kind of template context. This
2156 // should be re-evaluated once this is working for normal classes and
2157 // we can better evaluate what is useful.
2158 !D2->isDependentType() && !TemplateStack) {
2159 if (auto *D3 = dyn_cast<CXXRecordDecl>(D2)) {
2160 findBindingToJavaClass(*AstContext, *D3);
2161 findBoundAsJavaClasses(*AstContext, *D3);
2162 }
2163 emitStructuredInfo(ExpansionLoc, D2);
2164 }
2165 }
2166 if (EnumDecl *D2 = dyn_cast<EnumDecl>(D)) {
2167 if (D2->isThisDeclarationADefinition() && !D2->isDependentType() &&
2168 !TemplateStack) {
2169 emitStructuredInfo(ExpansionLoc, D2);
2170 }
2171 }
2172 if (EnumConstantDecl *D2 = dyn_cast<EnumConstantDecl>(D)) {
2173 if (!D2->isTemplated() && !TemplateStack) {
2174 emitStructuredInfo(ExpansionLoc, D2);
2175 }
2176 }
2177 if (FunctionDecl *D2 = dyn_cast<FunctionDecl>(D)) {
2178 if ((D2->isThisDeclarationADefinition() || isPure(D2)) &&
2179 // a clause at the top should have generalized and set wasTemplate so
2180 // it shouldn't be the case that isTemplateInstantiation() is true.
2181 !D2->isTemplateInstantiation() && !wasTemplate &&
2182 !D2->isFunctionTemplateSpecialization() && !TemplateStack) {
2183 if (auto *D3 = dyn_cast<CXXMethodDecl>(D2)) {
2184 findBindingToJavaMember(*AstContext, *D3);
2185 } else {
2186 findBindingToJavaFunction(*AstContext, *D2);
2187 }
2188 emitStructuredInfo(ExpansionLoc, D2);
2189 }
2190 }
2191 if (FieldDecl *D2 = dyn_cast<FieldDecl>(D)) {
2192 if (!D2->isTemplated() && !TemplateStack) {
2193 emitStructuredInfo(ExpansionLoc, D2);
2194 }
2195 }
2196 if (VarDecl *D2 = dyn_cast<VarDecl>(D)) {
2197 if (!D2->isTemplated() && !TemplateStack) {
2198 findBindingToJavaConstant(*AstContext, *D2);
2199 emitStructuredInfo(ExpansionLoc, D2);
2200 }
2201 }
2202
2203 return true;
2204 }
2205
2206 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2207 // If we are in a template and find a Stmt that was registed in
2208 // ForwardedTemplateLocations, convert the location to an actual Stmt* in
2209 // ForwardingTemplates
2210 if (TemplateStack && !TemplateStack->inGatherMode()) {
2211 if (ForwardedTemplateLocations.find(E->getBeginLoc().getRawEncoding()) !=
2212 ForwardedTemplateLocations.end()) {
2213 if (const auto *currentTemplate =
2214 getCurrentFunctionTemplateInstantiation()) {
2215 ForwardingTemplates.insert({currentTemplate, E});
2216 }
2217 return true;
2218 }
2219 }
2220
2221 SourceLocation Loc = E->getBeginLoc();
2222 if (!isInterestingLocation(Loc)) {
2223 return true;
2224 }
2225
2226 return VisitCXXConstructExpr(E, Loc);
2227 }
2228
2229 bool VisitCXXConstructExpr(const CXXConstructExpr *E, SourceLocation Loc) {
2230 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2231
2232 FunctionDecl *Ctor = E->getConstructor();
2233 if (Ctor->isTemplateInstantiation()) {
2234 Ctor = Ctor->getTemplateInstantiationPattern();
2235 }
2236 std::string Mangled = getMangledName(CurMangleContext, Ctor);
2237
2238 // FIXME: Need to do something different for list initialization.
2239
2240 visitIdentifier("use", "constructor", getQualifiedName(Ctor), Loc, Mangled,
2241 QualType(), getContext(SpellingLoc));
2242
2243 return true;
2244 }
2245
2246 CallExpr *CurrentCall = nullptr;
2247 bool TraverseCallExpr(CallExpr *E) {
2248 const auto _ = ValueRollback(CurrentCall, E);
2249 return Super::TraverseCallExpr(E);
2250 }
2251
2252 bool VisitCallExpr(CallExpr *E) {
2253 Expr *CalleeExpr = E->getCallee()->IgnoreParenImpCasts();
2254
2255 if (TemplateStack) {
2256 const auto CalleeLocation = [&] {
2257 if (const auto *Member =
2258 dyn_cast<CXXDependentScopeMemberExpr>(CalleeExpr)) {
2259 return Member->getMemberLoc();
2260 }
2261 if (const auto *DeclRef =
2262 dyn_cast<DependentScopeDeclRefExpr>(CalleeExpr)) {
2263 return DeclRef->getLocation();
2264 }
2265 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(CalleeExpr)) {
2266 return DeclRef->getLocation();
2267 }
2268
2269 // Does the right thing for MemberExpr and UnresolvedMemberExpr at
2270 // least.
2271 return CalleeExpr->getExprLoc();
2272 }();
2273
2274 // If we are in a template:
2275 // - when in GatherDependent mode and the callee is type-dependent,
2276 // register it in ForwardedTemplateLocations
2277 // - when in AnalyseDependent mode and the callee is in
2278 // ForwardedTemplateLocations, convert the location to an actual Stmt*
2279 // in ForwardingTemplates
2280 if (TemplateStack->inGatherMode()) {
2281 if (CalleeExpr->isTypeDependent()) {
2282 TemplateStack->visitDependent(CalleeLocation);
2283 ForwardedTemplateLocations.insert(CalleeLocation.getRawEncoding());
2284 }
2285 } else {
2286 if (ForwardedTemplateLocations.find(CalleeLocation.getRawEncoding()) !=
2287 ForwardedTemplateLocations.end()) {
2288 if (const auto *currentTemplate =
2289 getCurrentFunctionTemplateInstantiation()) {
2290 ForwardingTemplates.insert({currentTemplate, E});
2291 }
2292 }
2293 }
2294 }
2295
2296 Decl *Callee = E->getCalleeDecl();
2297 if (!Callee || !FunctionDecl::classof(Callee)) {
2298 return true;
2299 }
2300
2301 const NamedDecl *NamedCallee = dyn_cast<NamedDecl>(Callee);
2302
2303 SourceLocation Loc;
2304
2305 const FunctionDecl *F = dyn_cast<FunctionDecl>(NamedCallee);
2306 if (F->isTemplateInstantiation()) {
2307 NamedCallee = F->getTemplateInstantiationPattern();
2308 }
2309
2310 std::string Mangled = getMangledName(CurMangleContext, NamedCallee);
2311 int Flags = 0;
2312
2313 if (CXXOperatorCallExpr::classof(E)) {
2314 // Just take the first token.
2315 CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E);
2316 Loc = Op->getOperatorLoc();
2317 Flags |= NotIdentifierToken;
2318 } else if (MemberExpr::classof(CalleeExpr)) {
2319 MemberExpr *Member = dyn_cast<MemberExpr>(CalleeExpr);
2320 Loc = Member->getMemberLoc();
2321 } else if (DeclRefExpr::classof(CalleeExpr)) {
2322 // We handle this in VisitDeclRefExpr.
2323 return true;
2324 } else {
2325 return true;
2326 }
2327
2328 if (!isInterestingLocation(Loc)) {
2329 return true;
2330 }
2331
2332 if (F->isTemplateInstantiation()) {
2333 VisitForwardedStatements(E, Loc);
2334 }
2335
2336 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2337
2338 std::vector<SourceRange> argRanges;
2339 for (auto argExpr : E->arguments()) {
2340 argRanges.push_back(argExpr->getSourceRange());
2341 }
2342
2343 visitIdentifier("use", "function", getQualifiedName(NamedCallee), Loc,
2344 Mangled, E->getCallReturnType(*AstContext),
2345 getContext(SpellingLoc), Flags, SourceRange(),
2346 SourceRange(), &argRanges);
2347
2348 return true;
2349 }
2350
2351 bool VisitTagTypeLoc(TagTypeLoc L) {
2352 SourceLocation Loc = L.getBeginLoc();
2353 if (!isInterestingLocation(Loc)) {
2354 return true;
2355 }
2356
2357 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2358
2359 TagDecl *Decl = L.getDecl();
2360 std::string Mangled = getMangledName(CurMangleContext, Decl);
2361 visitIdentifier("use", "type", getQualifiedName(Decl), Loc, Mangled,
2362 L.getType(), getContext(SpellingLoc));
2363 return true;
2364 }
2365
2366 bool VisitTypedefTypeLoc(TypedefTypeLoc L) {
2367 SourceLocation Loc = L.getBeginLoc();
2368 if (!isInterestingLocation(Loc)) {
2369 return true;
2370 }
2371
2372 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2373
2374 NamedDecl *Decl = L.getTypedefNameDecl();
2375 std::string Mangled = getMangledName(CurMangleContext, Decl);
2376 visitIdentifier("use", "type", getQualifiedName(Decl), Loc, Mangled,
2377 L.getType(), getContext(SpellingLoc));
2378 return true;
2379 }
2380
2381 bool VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc L) {
2382 SourceLocation Loc = L.getBeginLoc();
2383 if (!isInterestingLocation(Loc)) {
2384 return true;
2385 }
2386
2387 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2388
2389 NamedDecl *Decl = L.getDecl();
2390 std::string Mangled = getMangledName(CurMangleContext, Decl);
2391 visitIdentifier("use", "type", getQualifiedName(Decl), Loc, Mangled,
2392 L.getType(), getContext(SpellingLoc));
2393 return true;
2394 }
2395
2396 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
2397 SourceLocation Loc = L.getBeginLoc();
2398 if (!isInterestingLocation(Loc)) {
2399 return true;
2400 }
2401
2402 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2403
2404 TemplateDecl *Td = L.getTypePtr()->getTemplateName().getAsTemplateDecl();
2405 if (ClassTemplateDecl *D = dyn_cast<ClassTemplateDecl>(Td)) {
2406 NamedDecl *Decl = D->getTemplatedDecl();
2407 std::string Mangled = getMangledName(CurMangleContext, Decl);
2408 visitIdentifier("use", "type", getQualifiedName(Decl), Loc, Mangled,
2409 QualType(), getContext(SpellingLoc));
2410 } else if (TypeAliasTemplateDecl *D = dyn_cast<TypeAliasTemplateDecl>(Td)) {
2411 NamedDecl *Decl = D->getTemplatedDecl();
2412 std::string Mangled = getMangledName(CurMangleContext, Decl);
2413 visitIdentifier("use", "type", getQualifiedName(Decl), Loc, Mangled,
2414 QualType(), getContext(SpellingLoc));
2415 }
2416
2417 return true;
2418 }
2419
2420 bool VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
2421 SourceLocation Loc = L.getNameLoc();
2422 if (!isInterestingLocation(Loc)) {
2423 return true;
2424 }
2425
2426 for (const NamedDecl *D :
2427 Resolver->resolveDependentNameType(L.getTypePtr())) {
2428 visitHeuristicResult(Loc, D);
2429 }
2430 return true;
2431 }
2432
2433 void VisitForwardedStatements(const Expr *E, SourceLocation Loc) {
2434 // If Loc itself is forwarded to its callers, do nothing
2435 if (ForwardedTemplateLocations.find(Loc.getRawEncoding()) !=
2436 ForwardedTemplateLocations.cend())
2437 return;
2438
2439 // If this is a forwarding template (eg MakeUnique), visit the forwarded
2440 // statements
2441 auto todo = std::stack{std::vector<const Stmt *>{E}};
2442 auto seen = std::unordered_set<const Stmt *>{};
2443 while (!todo.empty()) {
2444 const auto forwarded = std::move(todo.top());
2445 todo.pop();
2446 if (seen.find(forwarded) != seen.end())
2447 continue;
2448 seen.insert(forwarded);
2449
2450 if (const auto *C = dyn_cast<CXXConstructExpr>(forwarded))
2451 VisitCXXConstructExpr(C, Loc);
2452
2453 const Decl *Decl = nullptr;
2454 if (const auto *D = dyn_cast<CallExpr>(forwarded))
2455 Decl = D->getCalleeDecl();
2456 if (const auto *D = dyn_cast<DeclRefExpr>(forwarded))
2457 Decl = D->getDecl();
2458
2459 if (!Decl)
2460 continue;
2461 const auto *F = Decl->getAsFunction();
2462 if (!F)
2463 continue;
2464 if (!F->isTemplateInstantiation())
2465 continue;
2466 const auto [ForwardedBegin, ForwardedEnd] =
2467 ForwardingTemplates.equal_range(F);
2468 for (auto ForwardedIt = ForwardedBegin; ForwardedIt != ForwardedEnd;
2469 ++ForwardedIt)
2470 if (seen.find(ForwardedIt->second) == seen.end())
2471 todo.push(ForwardedIt->second);
2472 }
2473 }
2474
2475 bool VisitDeclRefExpr(const DeclRefExpr *E) {
2476 SourceLocation Loc = E->getExprLoc();
2477 if (!isInterestingLocation(Loc)) {
2478 return true;
2479 }
2480
2481 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2482
2483 if (E->hasQualifier()) {
2484 Loc = E->getNameInfo().getLoc();
2485 SpellingLoc = SM.getSpellingLoc(Loc);
2486 }
2487
2488 const NamedDecl *Decl = E->getDecl();
2489 if (const VarDecl *D2 = dyn_cast<VarDecl>(Decl)) {
2490 int Flags = 0;
2491 if (D2->isLocalVarDeclOrParm()) {
2492 Flags = NoCrossref;
2493 }
2494 std::string Mangled = getMangledName(CurMangleContext, Decl);
2495 visitIdentifier("use", "variable", getQualifiedName(Decl), Loc, Mangled,
2496 D2->getType(), getContext(SpellingLoc), Flags);
2497 } else if (isa<FunctionDecl>(Decl)) {
2498 const FunctionDecl *F = dyn_cast<FunctionDecl>(Decl);
2499 if (F->isTemplateInstantiation()) {
2500 Decl = F->getTemplateInstantiationPattern();
2501 VisitForwardedStatements(E, Loc);
2502 }
2503
2504 std::string Mangled = getMangledName(CurMangleContext, Decl);
2505 visitIdentifier("use", "function", getQualifiedName(Decl), Loc, Mangled,
2506 E->getType(), getContext(SpellingLoc));
2507 } else if (isa<EnumConstantDecl>(Decl)) {
2508 std::string Mangled = getMangledName(CurMangleContext, Decl);
2509 visitIdentifier("use", "enum", getQualifiedName(Decl), Loc, Mangled,
2510 E->getType(), getContext(SpellingLoc));
2511 }
2512
2513 return true;
2514 }
2515
2516 bool VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2517 if (!isInterestingLocation(D->getLocation())) {
2518 return true;
2519 }
2520
2521 for (CXXConstructorDecl::init_const_iterator It = D->init_begin();
2522 It != D->init_end(); ++It) {
2523 const CXXCtorInitializer *Ci = *It;
2524 if (!Ci->getMember() || !Ci->isWritten()) {
2525 continue;
2526 }
2527
2528 SourceLocation Loc = Ci->getMemberLocation();
2529 if (!isInterestingLocation(Loc)) {
2530 continue;
2531 }
2532
2533 FieldDecl *Member = Ci->getMember();
2534 std::string Mangled = getMangledName(CurMangleContext, Member);
2535 // We want the constructor to be the context of the field use and
2536 // `getContext(D)` would skip the current context. An alternate approach
2537 // would be `getContext(Loc)` but the heuristic to omit a context if we're
2538 // in a macro body expansion seems incorrect for field initializations; if
2539 // code is using macros to initialize the fields, we still care.
2540 visitIdentifier("use", "field", getQualifiedName(Member), Loc, Mangled,
2541 Member->getType(), translateContext(D));
2542 }
2543
2544 return true;
2545 }
2546
2547 bool VisitMemberExpr(MemberExpr *E) {
2548 SourceLocation Loc = E->getExprLoc();
2549 if (!isInterestingLocation(Loc)) {
2550 return true;
2551 }
2552
2553 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2554
2555 ValueDecl *Decl = E->getMemberDecl();
2556 if (FieldDecl *Field = dyn_cast<FieldDecl>(Decl)) {
2557 std::string Mangled = getMangledName(CurMangleContext, Field);
2558 visitIdentifier("use", "field", getQualifiedName(Field), Loc, Mangled,
2559 Field->getType(), getContext(SpellingLoc));
2560 }
2561 return true;
2562 }
2563
2564 // Helper function for producing heuristic results for usages in dependent
2565 // code. These are distinguished from concrete results (obtained for dependent
2566 // code using the AutoTemplateContext machinery) by setting the “confidence”
2567 // property to “cppTemplateHeuristic”. We don't expect this method to be
2568 // intentionally called multiple times for a given (Loc, NamedDecl) pair
2569 // because our callers should be mutually exclusive AST node types. However,
2570 // it's fine if this method is called multiple time for a given pair because
2571 // we explicitly de-duplicate records with an identical string representation
2572 // (which is a good reason to have this helper, as it ensures identical
2573 // representations).
2574 void visitHeuristicResult(SourceLocation Loc, const NamedDecl *ND) {
2575 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
2576
2577 if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(ND)) {
2578 ND = USD->getTargetDecl();
2579 }
2580 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND)) {
2581 ND = TD->getTemplatedDecl();
2582 }
2583 QualType MaybeType;
2584 const char *SyntaxKind = nullptr;
2585 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(ND)) {
2586 MaybeType = F->getType();
2587 SyntaxKind = "function";
2588 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(ND)) {
2589 MaybeType = F->getType();
2590 SyntaxKind = "field";
2591 } else if (const EnumConstantDecl *E = dyn_cast<EnumConstantDecl>(ND)) {
2592 MaybeType = E->getType();
2593 SyntaxKind = "enum";
2594 } else if (const TypedefNameDecl *T = dyn_cast<TypedefNameDecl>(ND)) {
2595 MaybeType = T->getUnderlyingType();
2596 SyntaxKind = "type";
2597 }
2598 if (SyntaxKind) {
2599 std::string Mangled = getMangledName(CurMangleContext, ND);
2600 visitIdentifier("use", SyntaxKind, getQualifiedName(ND), Loc, Mangled,
2601 MaybeType, getContext(SpellingLoc), Heuristic);
2602 }
2603 }
2604
2605 bool arityMatchesCurrentCallExpr(const Expr *E, const NamedDecl *Candidate) {
2606 const auto IsCurrentCallee = CurrentCall && E == CurrentCall->getCallee();
2607 const auto CallNumArgs =
2608 IsCurrentCallee ? CurrentCall->getNumArgs() : std::optional<uint>{};
2609
2610 const FunctionDecl *CandidateFunc;
2611 if (const auto *UsingDecl = dyn_cast<UsingShadowDecl>(Candidate)) {
2612 CandidateFunc = UsingDecl->getTargetDecl()->getAsFunction();
2613 } else {
2614 CandidateFunc = Candidate->getAsFunction();
2615 }
2616
2617 // We try and filter candidates by arity, but be conservative and accept
2618 // them when we don't know better
2619 if (!CandidateFunc || !CallNumArgs) {
2620 return true;
2621 }
2622
2623 const auto MinNumArgs = CandidateFunc->getMinRequiredExplicitArguments();
2624 const auto MaxNumArgs = [&]() -> std::optional<uint> {
2625 const auto IsVariadic =
2626 CandidateFunc->isVariadic() ||
2627 std::any_of(CandidateFunc->param_begin(), CandidateFunc->param_end(),
2628 [](const ParmVarDecl *param) {
2629 return param->isParameterPack();
2630 });
2631
2632 if (IsVariadic)
2633 return {};
2634
2635 return CandidateFunc->getNumNonObjectParams();
2636 }();
2637
2638 if (CallNumArgs < MinNumArgs || (MaxNumArgs && CallNumArgs > *MaxNumArgs)) {
2639 return false;
2640 }
2641
2642 return true;
2643 }
2644
2645 bool VisitOverloadExpr(OverloadExpr *E) {
2646 SourceLocation Loc = E->getExprLoc();
2647 normalizeLocation(&Loc);
2648 if (!isInterestingLocation(Loc)) {
2649 return true;
2650 }
2651
2652 for (auto *Candidate : E->decls()) {
2653 if (arityMatchesCurrentCallExpr(E, Candidate))
2654 visitHeuristicResult(Loc, Candidate);
2655 }
2656
2657 // Also record this location so that if we have instantiations, we can
2658 // gather more accurate results from them.
2659 if (TemplateStack) {
2660 TemplateStack->visitDependent(Loc);
2661 }
2662 return true;
2663 }
2664
2665 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
2666 SourceLocation Loc = E->getMemberLoc();
2667 normalizeLocation(&Loc);
2668 if (!isInterestingLocation(Loc)) {
2669 return true;
2670 }
2671
2672 for (const NamedDecl *Candidate : Resolver->resolveMemberExpr(E)) {
2673 if (arityMatchesCurrentCallExpr(E, Candidate))
2674 visitHeuristicResult(Loc, Candidate);
2675 }
2676
2677 // Also record this location so that if we have instantiations, we can
2678 // gather more accurate results from them.
2679 if (TemplateStack) {
2680 TemplateStack->visitDependent(Loc);
2681 }
2682 return true;
2683 }
2684
2685 bool VisitCXXNewExpr(CXXNewExpr *N) {
2686 // If we are in a template and the new is type-dependent, register it in
2687 // ForwardedTemplateLocations to forward its uses to the surrounding
2688 // template call site
2689 if (TemplateStack && TemplateStack->inGatherMode()) {
2690 const auto *TypeInfo = N->getAllocatedTypeSourceInfo();
2691 const auto ConstructExprLoc = TypeInfo->getTypeLoc().getBeginLoc();
2692 if (N->isTypeDependent()) {
2693 TemplateStack->visitDependent(ConstructExprLoc);
2694 ForwardedTemplateLocations.insert(ConstructExprLoc.getRawEncoding());
2695 }
2696 }
2697 return true;
2698 }
2699
2700 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
2701 SourceLocation Loc = E->getLocation();
2702 normalizeLocation(&Loc);
2703 if (!isInterestingLocation(Loc)) {
2704 return true;
2705 }
2706
2707 for (const NamedDecl *Candidate : Resolver->resolveDeclRefExpr(E)) {
2708 if (arityMatchesCurrentCallExpr(E, Candidate))
2709 visitHeuristicResult(Loc, Candidate);
2710 }
2711
2712 // Also record this location so that if we have instantiations, we can
2713 // gather more accurate results from them.
2714 if (TemplateStack) {
2715 TemplateStack->visitDependent(Loc);
2716
2717 // Also record the dependent NestedNameSpecifier locations
2718 for (auto NestedNameLoc = E->getQualifierLoc();
2719 NestedNameLoc &&
2720 NestedNameLoc.getNestedNameSpecifier()->isDependent();
2721 NestedNameLoc = NestedNameLoc.getPrefix()) {
2722 TemplateStack->visitDependent(NestedNameLoc.getLocalBeginLoc());
2723 }
2724 }
2725
2726 return true;
2727 }
2728
2729 bool VisitStringLiteral(StringLiteral *E) {
2730 if (E->getCharByteWidth() != 1) {
2731 return true;
2732 }
2733
2734 StringRef sref = E->getString();
2735 std::string s = sref.str();
2736
2737 bool isMozSrc = stringStartsWith(s, "moz-src:///");
2738
2739 if (!stringStartsWith(s, "chrome://") &&
2740 !stringStartsWith(s, "resource://") &&
2741 !isMozSrc) {
2742 return true;
2743 }
2744
2745 if (!isASCII(s)) {
2746 return true;
2747 }
2748
2749 SourceLocation Loc = E->getStrTokenLoc(0);
2750 normalizeLocation(&Loc);
2751
2752 std::string symbol;
2753
2754 if (isMozSrc) {
2755 symbol = std::string("FILE_") + mangleFile(s.substr(11), FileType::Source);
2756 } else {
2757 symbol = std::string("URL_") + mangleURL(s);
2758 }
2759
2760 visitIdentifier("use", "file", StringRef(s), Loc, symbol, QualType(),
2761 Context(), NotIdentifierToken | LocRangeEndValid);
2762
2763 return true;
2764 }
2765
2766 void enterSourceFile(SourceLocation Loc) {
2767 normalizeLocation(&Loc);
2768 FileInfo *newFile = getFileInfo(Loc);
2769 if (!newFile->Interesting) {
2770 return;
2771 }
2772 FileType type = newFile->Generated ? FileType::Generated : FileType::Source;
2773 std::string symbol =
2774 std::string("FILE_") + mangleFile(newFile->Realname, type);
2775
2776 // We use an explicit zero-length source range at the start of the file. If
2777 // we don't set the LocRangeEndValid flag, the visitIdentifier code will use
2778 // the entire first token, which could be e.g. a long multiline-comment.
2779 visitIdentifier("def", "file", newFile->Realname, SourceRange(Loc), symbol,
2780 QualType(), Context(),
2781 NotIdentifierToken | LocRangeEndValid);
2782 }
2783
2784 void inclusionDirective(SourceRange FileNameRange, const FileEntry *File) {
2785 std::string includedFile(File->tryGetRealPathName());
2786 FileType type = relativizePath(includedFile);
2787 if (type == FileType::Unknown) {
2788 return;
2789 }
2790 std::string symbol = std::string("FILE_") + mangleFile(includedFile, type);
2791
2792 // Support the #include MACRO use-case
2793 // When parsing #include MACRO:
2794 // - the filename is never passed to onTokenLexed
2795 // - inclusionDirective is called before endMacroExpansion (which is only
2796 // called when the following token is parsed) So add the filename here and
2797 // call endMacroExpansion immediately. This ensures the macro has a correct
2798 // expansion and it has been added to MacroMaps so the referenced filename
2799 // knows to populate inExpansionAt.
2800 if (MacroExpansionState) {
2801 MacroExpansionState->TokenLocations[FileNameRange.getBegin()] =
2802 MacroExpansionState->Expansion.length();
2803 MacroExpansionState->Expansion += '"';
2804 MacroExpansionState->Expansion += includedFile;
2805 MacroExpansionState->Expansion += '"';
2806 endMacroExpansion();
2807 }
2808
2809 visitIdentifier("use", "file", includedFile, FileNameRange, symbol,
2810 QualType(), Context(),
2811 NotIdentifierToken | LocRangeEndValid);
2812 }
2813
2814 void macroDefined(const Token &Tok, const MacroDirective *Macro) {
2815 if (Macro->getMacroInfo()->isBuiltinMacro()) {
2816 return;
2817 }
2818 SourceLocation Loc = Tok.getLocation();
2819 normalizeLocation(&Loc);
2820 if (!isInterestingLocation(Loc)) {
2821 return;
2822 }
2823
2824 IdentifierInfo *Ident = Tok.getIdentifierInfo();
2825 if (Ident) {
2826 std::string Mangled = std::string("M_") +
2827 mangleLocation(Loc, std::string(Ident->getName()));
2828 visitIdentifier("def", "macro", Ident->getName(), Loc, Mangled);
2829 }
2830 }
2831
2832 void macroUsed(const Token &Tok, const MacroInfo *Macro) {
2833 if (!Macro) {
2834 return;
2835 }
2836 if (Macro->isBuiltinMacro()) {
2837 return;
2838 }
2839 SourceLocation Loc = Tok.getLocation();
2840 if (!isInterestingLocation(Loc)) {
2841 return;
2842 }
2843
2844 IdentifierInfo *Ident = Tok.getIdentifierInfo();
2845 if (Ident) {
2846 std::string Mangled =
2847 std::string("M_") + mangleLocation(Macro->getDefinitionLoc(),
2848 std::string(Ident->getName()));
2849 visitIdentifier("use", "macro", Ident->getName(), Loc, Mangled);
2850 }
2851 }
2852
2853 void beginMacroExpansion(const Token &Tok, const MacroInfo *Macro,
2854 SourceRange Range) {
2855 if (!Macro)
2856 return;
2857
2858 if (Macro->isBuiltinMacro())
2859 return;
2860
2861 if (!Tok.getIdentifierInfo())
2862 return;
2863
2864 auto location = Tok.getLocation();
2865 normalizeLocation(&location);
2866 if (!isInterestingLocation(location))
2867 return;
2868
2869 if (MacroExpansionState) {
2870 const auto InMacroArgs = MacroExpansionState->Range.fullyContains(
2871 SM.getExpansionRange(Range).getAsRange());
2872 const auto InMacroBody =
2873 SM.getExpansionLoc(Tok.getLocation()) ==
2874 SM.getExpansionLoc(MacroExpansionState->MacroNameToken.getLocation());
2875 if (InMacroArgs || InMacroBody) {
2876 if (MacroExpansionState->MacroInfo->getDefinitionLoc() !=
2877 Macro->getDefinitionLoc()) {
2878 IdentifierInfo *DependencyIdent = Tok.getIdentifierInfo();
2879 std::string DependencySymbol =
2880 std::string("M_") +
2881 mangleLocation(Macro->getDefinitionLoc(),
2882 std::string(DependencyIdent->getName()));
2883
2884 MacroExpansionState->Dependencies.push_back(DependencySymbol);
2885 }
2886
2887 macroUsed(Tok, Macro);
2888 return;
2889 }
2890
2891 endMacroExpansion();
2892 }
2893
2894 MacroExpansionState = ::MacroExpansionState{
2895 .MacroNameToken = Tok,
2896 .MacroInfo = Macro,
2897 .Expansion = {},
2898 .TokenLocations = {},
2899 .Range = Range,
2900 .PrevPrevTok = {},
2901 .PrevTok = {},
2902 };
2903 }
2904
2905 void endMacroExpansion() {
2906 // large macros are too slow to reformat, don't reformat macros larger than
2907 // those arbitrary thresholds
2908 static constexpr auto includedFileExpansionReformatThreshold = 20'000;
2909 static constexpr auto mainFileExpansionReformatThreshold = 200'000;
2910
2911 const auto expansionLocation =
2912 SM.getExpansionLoc(MacroExpansionState->MacroNameToken.getLocation());
2913 const auto expansionFilename = SM.getFilename(expansionLocation);
2914 const auto includedExtensions =
2915 std::array{".h", ".hpp", ".hxx", ".inc", ".def"};
2916 const auto isIncludedFile =
2917 std::any_of(includedExtensions.begin(), includedExtensions.end(),
2918 [&](const auto *extension) {
2919 return expansionFilename.ends_with_insensitive(extension);
2920 });
2921 const auto expansionReformatThreshold =
2922 isIncludedFile ? includedFileExpansionReformatThreshold
2923 : mainFileExpansionReformatThreshold;
2924
2925 if (MacroExpansionState->Expansion.length() < expansionReformatThreshold) {
2926 // large macros are too memory-hungry to reformat with ColumnLimit != 0
2927 // see https://github.com/llvm/llvm-project/issues/107434
2928 auto style = clang::format::getMozillaStyle();
2929 if (MacroExpansionState->Expansion.length() >
2930 includedFileExpansionReformatThreshold)
2931 style.ColumnLimit = 0;
2932
2933 const auto replacements = clang::format::reformat(
2934 style, MacroExpansionState->Expansion,
2935 {tooling::Range(0, MacroExpansionState->Expansion.length())});
2936 auto formatted = clang::tooling::applyAllReplacements(
2937 MacroExpansionState->Expansion, replacements);
2938 if (formatted) {
2939 for (auto &[k, v] : MacroExpansionState->TokenLocations) {
2940 v = replacements.getShiftedCodePosition(v);
2941 }
2942 MacroExpansionState->Expansion = std::move(formatted.get());
2943 }
2944 }
2945
2946 IdentifierInfo *Ident =
2947 MacroExpansionState->MacroNameToken.getIdentifierInfo();
2948 std::string Symbol =
2949 std::string("M_") +
2950 mangleLocation(MacroExpansionState->MacroInfo->getDefinitionLoc(),
2951 std::string(Ident->getName()));
2952
2953 const auto dependenciesBegin = MacroExpansionState->Dependencies.begin();
2954 const auto dependenciesEnd = MacroExpansionState->Dependencies.end();
2955 std::sort(dependenciesBegin, dependenciesEnd);
2956 MacroExpansionState->Dependencies.erase(
2957 std::unique(dependenciesBegin, dependenciesEnd), dependenciesEnd);
2958
2959 auto Key = Symbol;
2960 for (const auto &Dependency : MacroExpansionState->Dependencies) {
2961 Key.push_back(',');
2962 Key += Dependency;
2963 }
2964
2965 MacroMaps.emplace(std::pair{
2966 MacroExpansionState->MacroNameToken.getLocation(),
2967 ExpandedMacro{
2968 std::move(Symbol),
2969 std::move(Key),
2970 std::move(MacroExpansionState->Expansion),
2971 std::move(MacroExpansionState->TokenLocations),
2972 },
2973 });
2974
2975 MacroExpansionState.reset();
2976
2977 macroUsed(MacroExpansionState->MacroNameToken,
2978 MacroExpansionState->MacroInfo);
2979 }
2980
2981 void onTokenLexed(const Token &Tok) {
2982 if (!MacroExpansionState)
2983 return;
2984
2985 // check if we exited the macro expansion
2986 SourceLocation SLoc = Tok.getLocation();
2987 if (!SLoc.isMacroID()) {
2988 endMacroExpansion();
2989 return;
2990 }
2991
2992 if (ConcatInfo.AvoidConcat(MacroExpansionState->PrevPrevTok,
2993 MacroExpansionState->PrevTok, Tok)) {
2994 MacroExpansionState->Expansion += ' ';
2995 }
2996
2997 if (Tok.isAnnotation()) {
2998 const auto Range = SM.getImmediateExpansionRange(Tok.getLocation());
2999 const char *Start = SM.getCharacterData(Range.getBegin());
3000 const char *End = SM.getCharacterData(Range.getEnd()) + 1;
3001 MacroExpansionState->Expansion += StringRef(Start, End - Start);
3002 } else {
3003 const auto spelling = CI.getPreprocessor().getSpelling(Tok);
3004 if (Tok.isAnyIdentifier()) {
3005 MacroExpansionState->TokenLocations[SLoc] =
3006 MacroExpansionState->Expansion.length();
3007 }
3008 MacroExpansionState->Expansion += spelling;
3009 }
3010
3011 MacroExpansionState->PrevPrevTok = MacroExpansionState->PrevTok;
3012 MacroExpansionState->PrevTok = Tok;
3013 }
3014 };
3015
3016 void PreprocessorHook::FileChanged(SourceLocation Loc, FileChangeReason Reason,
3017 SrcMgr::CharacteristicKind FileType,
3018 FileID PrevFID = FileID()) {
3019 switch (Reason) {
3020 case PPCallbacks::RenameFile:
3021 case PPCallbacks::SystemHeaderPragma:
3022 // Don't care about these, since we want the actual on-disk filenames
3023 break;
3024 case PPCallbacks::EnterFile:
3025 Indexer->enterSourceFile(Loc);
3026 break;
3027 case PPCallbacks::ExitFile:
3028 // Don't care about exiting files
3029 break;
3030 }
3031 }
3032
3033 void PreprocessorHook::InclusionDirective(
3034 SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
3035 bool IsAngled, CharSourceRange FileNameRange,
3036 #if CLANG_VERSION_MAJOR >= 16
3037 OptionalFileEntryRef File,
3038 #elif CLANG_VERSION_MAJOR >= 15
3039 Optional<FileEntryRef> File,
3040 #else
3041 const FileEntry *File,
3042 #endif
3043 StringRef SearchPath, StringRef RelativePath,
3044 #if CLANG_VERSION_MAJOR >= 19
3045 const Module *SuggestedModule, bool ModuleImported,
3046 #else
3047 const Module *Imported,
3048 #endif
3049 SrcMgr::CharacteristicKind FileType) {
3050 #if CLANG_VERSION_MAJOR >= 15
3051 if (!File) {
3052 return;
3053 }
3054 Indexer->inclusionDirective(FileNameRange.getAsRange(),
3055 &File->getFileEntry());
3056 #else
3057 Indexer->inclusionDirective(FileNameRange.getAsRange(), File);
3058 #endif
3059 }
3060
3061 void PreprocessorHook::MacroDefined(const Token &Tok,
3062 const MacroDirective *Md) {
3063 Indexer->macroDefined(Tok, Md);
3064 }
3065
3066 void PreprocessorHook::MacroExpands(const Token &Tok, const MacroDefinition &Md,
3067 SourceRange Range, const MacroArgs *Ma) {
3068 Indexer->beginMacroExpansion(Tok, Md.getMacroInfo(), Range);
3069 }
3070
3071 void PreprocessorHook::MacroUndefined(const Token &Tok,
3072 const MacroDefinition &Md,
3073 const MacroDirective *Undef) {
3074 Indexer->macroUsed(Tok, Md.getMacroInfo());
3075 }
3076
3077 void PreprocessorHook::Defined(const Token &Tok, const MacroDefinition &Md,
3078 SourceRange Range) {
3079 Indexer->macroUsed(Tok, Md.getMacroInfo());
3080 }
3081
3082 void PreprocessorHook::Ifdef(SourceLocation Loc, const Token &Tok,
3083 const MacroDefinition &Md) {
3084 Indexer->macroUsed(Tok, Md.getMacroInfo());
3085 }
3086
3087 void PreprocessorHook::Ifndef(SourceLocation Loc, const Token &Tok,
3088 const MacroDefinition &Md) {
3089 Indexer->macroUsed(Tok, Md.getMacroInfo());
3090 }
3091
3092 class IndexAction : public PluginASTAction {
3093 protected:
3094 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
3095 llvm::StringRef F) {
3096 return make_unique<IndexConsumer>(CI);
3097 }
3098
3099 bool ParseArgs(const CompilerInstance &CI,
3100 const std::vector<std::string> &Args) {
3101 if (Args.size() != 3) {
3102 DiagnosticsEngine &D = CI.getDiagnostics();
3103 unsigned DiagID = D.getCustomDiagID(
3104 DiagnosticsEngine::Error,
3105 "Need arguments for the source, output, and object directories");
3106 D.Report(DiagID);
3107 return false;
3108 }
3109
3110 // Load our directories
3111 Srcdir = getAbsolutePath(Args[0]);
3112 if (Srcdir.empty()) {
3113 DiagnosticsEngine &D = CI.getDiagnostics();
3114 unsigned DiagID = D.getCustomDiagID(
3115 DiagnosticsEngine::Error, "Source directory '%0' does not exist");
3116 D.Report(DiagID) << Args[0];
3117 return false;
3118 }
3119
3120 ensurePath(Args[1] + PATHSEP_STRING);
3121 Outdir = getAbsolutePath(Args[1]);
3122 Outdir += PATHSEP_STRING;
3123
3124 Objdir = getAbsolutePath(Args[2]);
3125 if (Objdir.empty()) {
3126 DiagnosticsEngine &D = CI.getDiagnostics();
3127 unsigned DiagID = D.getCustomDiagID(DiagnosticsEngine::Error,
3128 "Objdir '%0' does not exist");
3129 D.Report(DiagID) << Args[2];
3130 return false;
3131 }
3132 Objdir += PATHSEP_STRING;
3133
3134 printf("MOZSEARCH: %s %s %s\n", Srcdir.c_str(), Outdir.c_str(),
3135 Objdir.c_str());
3136
3137 return true;
3138 }
3139
3140 void printHelp(llvm::raw_ostream &Ros) {
3141 Ros << "Help for mozsearch plugin goes here\n";
3142 }
3143 };
3144
3145 static FrontendPluginRegistry::Add<IndexAction>
3146 Y("mozsearch-index", "create the mozsearch index database");