summaryrefslogtreecommitdiff
path: root/kythe/cxx/indexer/cxx/IndexerPPCallbacks.cc
blob: db62eb7243d109362eb95a9af247766a8c2adf66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
 * Copyright 2014 The Kythe Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// This file uses the Clang style conventions.

#include "IndexerPPCallbacks.h"

#include "GraphObserver.h"
#include "absl/strings/str_format.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "glog/logging.h"
#include "kythe/cxx/extractor/path_utils.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

// TODO(zarko): IndexerASTHooks::RangeInCurrentContext should query the macro
// context. IndexerPPCallbacks doesn't need to query for the template context,
// since we'll always be in a state that looks like
//   /macro-expansion* template-inst*/,
// as template processing happens at a later stage.

// Embedding non-file source locations into vnames generates names that are
// not stable wrt include ordering (there appears to be a single scratch
// buffer with a line counter that is incrementally bumped).
// TODO(zarko): Fix this by using a hash of the scratch buffer + the file
// location into which the scratch buffer is being inlined. We might also be
// able to hook these locations to the macros that generate them, allowing us
// to insert edges for token pastes.

namespace kythe {

IndexerPPCallbacks::IndexerPPCallbacks(clang::Preprocessor& PP,
                                       GraphObserver& GO, enum Verbosity V,
                                       int UsrByteSize)
    : Preprocessor(PP), Observer(GO), Verbosity(V), UsrByteSize(UsrByteSize) {
  class MetadataPragmaHandlerWrapper : public clang::PragmaHandler {
   public:
    MetadataPragmaHandlerWrapper(IndexerPPCallbacks* context)
        : PragmaHandler("kythe_metadata"), context_(context) {}
    void HandlePragma(clang::Preprocessor& Preprocessor,
                      clang::PragmaIntroducer Introducer,
                      clang::Token& FirstToken) override {
      context_->HandleKytheMetadataPragma(Preprocessor, Introducer.Kind,
                                          FirstToken);
    }

   private:
    IndexerPPCallbacks* context_;
  };
  class InlineMetadataPragmaHandlerWrapper : public clang::PragmaHandler {
   public:
    InlineMetadataPragmaHandlerWrapper(IndexerPPCallbacks* context)
        : PragmaHandler("kythe_inline_metadata"), context_(context) {}
    void HandlePragma(clang::Preprocessor& Preprocessor,
                      clang::PragmaIntroducer Introducer,
                      clang::Token& FirstToken) override {
      context_->HandleKytheInlineMetadataPragma(Preprocessor, Introducer.Kind,
                                                FirstToken);
    }

   private:
    IndexerPPCallbacks* context_;
  };
  // Clang takes ownership.
  PP.AddPragmaHandler(new MetadataPragmaHandlerWrapper(this));
  PP.AddPragmaHandler(new InlineMetadataPragmaHandlerWrapper(this));
}

IndexerPPCallbacks::~IndexerPPCallbacks() {}

void IndexerPPCallbacks::FileChanged(clang::SourceLocation Loc,
                                     PPCallbacks::FileChangeReason Reason,
                                     clang::SrcMgr::CharacteristicKind FileType,
                                     clang::FileID PrevFID) {
  switch (Reason) {
    case clang::PPCallbacks::EnterFile:
      Observer.pushFile(LastInclusionHash, Loc);
      return;
    case clang::PPCallbacks::ExitFile:
      Observer.popFile();
      return;
    case clang::PPCallbacks::SystemHeaderPragma:
      return;
    // RenameFile occurs when a #line directive is encountered, for example:
    // #line 10 "foo.cc"
    case clang::PPCallbacks::RenameFile:
      return;
  }
  llvm::dbgs() << "Unknown FileChangeReason " << Reason << "\n";
}

void IndexerPPCallbacks::FilterAndEmitDeferredRecords() {
  for (const auto& R : DeferredRecords) {
    if (R.WasDefined) {
      if (!R.Macro->getMacroInfo()->isUsedForHeaderGuard()) {
        Observer.recordBoundQueryRange(
            R.Range,
            BuildNodeIdForMacro(R.MacroName, *R.Macro->getMacroInfo()));
      }
    }
  }
  DeferredRecords.clear();
}

void IndexerPPCallbacks::EndOfMainFile() {
  FilterAndEmitDeferredRecords();
  Observer.popFile();
}

GraphObserver::Range IndexerPPCallbacks::RangeForTokenInCurrentContext(
    const clang::Token& Token) {
  const auto Start = Token.getLocation();
  const auto End = Start.getLocWithOffset(Token.getLength());
  return RangeInCurrentContext(clang::SourceRange(Start, End));
}

void IndexerPPCallbacks::MacroDefined(const clang::Token& Token,
                                      const clang::MacroDirective* Macro) {
  if (Macro == nullptr) {
    return;
  }
  const clang::MacroInfo& Info = *Macro->getMacroInfo();
  clang::FileID MacroFileID =
      Observer.getSourceManager()->getFileID(Info.getDefinitionLoc());
  const clang::FileEntry* MacroFileEntry =
      Observer.getSourceManager()->getFileEntryForID(MacroFileID);
  if (MacroFileEntry == nullptr) {
    // This is a builtin macro. Ignore it.
    return;
  }
  GraphObserver::NodeId MacroId = BuildNodeIdForMacro(Token, Info);
  if (Observer.claimNode(MacroId)) {
    GraphObserver::NameId MacroName = BuildNameIdForMacro(Token);
    Observer.recordDefinitionBindingRange(RangeForTokenInCurrentContext(Token),
                                          MacroId);
    Observer.recordMacroNode(MacroId);
    MarkedSource MacroCode;
    MacroCode.set_kind(MarkedSource::IDENTIFIER);
    MacroCode.set_pre_text(std::string(Token.getIdentifierInfo()->getName()));
    Observer.recordMarkedSource(MacroId, MacroCode);
    if (UsrByteSize > 0) {
      llvm::SmallString<128> Usr;
      if (!clang::index::generateUSRForMacro(
              Token.getIdentifierInfo()->getName(), Macro->getLocation(),
              *Observer.getSourceManager(), Usr)) {
        Observer.assignUsr(MacroId, Usr, UsrByteSize);
      }
    }
  }
  // TODO(zarko): Record information about the definition (like other macro
  // references).
}

void IndexerPPCallbacks::MacroUndefined(const clang::Token& MacroName,
                                        const clang::MacroDefinition& Macro,
                                        const clang::MacroDirective* Undef) {
  if (!Macro) {
    return;
  }
  const clang::MacroInfo& Info = *Macro.getMacroInfo();
  GraphObserver::NodeId MacroId = BuildNodeIdForMacro(MacroName, Info);
  Observer.recordUndefinesRange(RangeForTokenInCurrentContext(MacroName),
                                MacroId);
}

void IndexerPPCallbacks::MacroExpands(const clang::Token& Token,
                                      const clang::MacroDefinition& Macro,
                                      clang::SourceRange Range,
                                      const clang::MacroArgs* Args) {
  if (!Macro || Range.isInvalid()) {
    return;
  }

  const clang::MacroInfo& Info = *Macro.getMacroInfo();
  GraphObserver::NodeId MacroId = BuildNodeIdForMacro(Token, Info);
  if (!Range.getBegin().isFileID() || !Range.getEnd().isFileID()) {
    if (Verbosity) {
      auto NewBegin =
          Observer.getSourceManager()->getExpansionLoc(Range.getBegin());
      if (!NewBegin.isFileID()) {
        return;
      }
      Range = clang::SourceRange(
          NewBegin,
          clang::Lexer::getLocForEndOfToken(
              NewBegin, 0, /* offset from token end */
              *Observer.getSourceManager(), *Observer.getLangOptions()));
      if (Range.isInvalid()) {
        return;
      }
      Observer.recordIndirectlyExpandsRange(RangeInCurrentContext(Range),
                                            MacroId);
    }
  } else {
    Observer.recordExpandsRange(RangeForTokenInCurrentContext(Token), MacroId);
  }
  // TODO(zarko): Index macro arguments.
}

void IndexerPPCallbacks::Defined(const clang::Token& MacroName,
                                 const clang::MacroDefinition& Macro,
                                 clang::SourceRange Range) {
  DeferredRecords.push_back(
      DeferredRecord{MacroName, Macro ? Macro.getLocalDirective() : nullptr,
                     Macro && Macro.getLocalDirective()->isDefined(),
                     RangeForTokenInCurrentContext(MacroName)});
}

void IndexerPPCallbacks::Ifdef(clang::SourceLocation Location,
                               const clang::Token& MacroName,
                               const clang::MacroDefinition& Macro) {
  // Just delegate.
  Defined(MacroName, Macro, clang::SourceRange(Location));
}

void IndexerPPCallbacks::Ifndef(clang::SourceLocation Location,
                                const clang::Token& MacroName,
                                const clang::MacroDefinition& Macro) {
  // Just delegate.
  Defined(MacroName, Macro, clang::SourceRange(Location));
}

void IndexerPPCallbacks::InclusionDirective(
    clang::SourceLocation HashLocation, const clang::Token& IncludeToken,
    llvm::StringRef Filename, bool IsAngled,
    clang::CharSourceRange FilenameRange, clang::OptionalFileEntryRef FileRef,
    llvm::StringRef SearchPath, llvm::StringRef RelativePath,
    const clang::Module* Imported, clang::SrcMgr::CharacteristicKind FileType) {
  // TODO(zarko) (Modules): Check if `Imported` is non-null; if so, this
  // was transformed to a module import.
  if (FileRef) {
    Observer.recordIncludesRange(
        RangeInCurrentContext(FilenameRange.getAsRange()),
        &FileRef->getFileEntry());
  }
  LastInclusionHash = HashLocation;
}

void IndexerPPCallbacks::AddMacroReferenceIfDefined(
    const clang::Token& MacroNameToken) {
  if (clang::IdentifierInfo* const NameII =
          MacroNameToken.getIdentifierInfo()) {
    if (NameII->hasMacroDefinition()) {
      if (auto* Macro = Preprocessor.getLocalMacroDirective(NameII)) {
        AddReferenceToMacro(MacroNameToken, *Macro->getMacroInfo(),
                            Macro->isDefined());
      }
    } else if (NameII->hadMacroDefinition()) {
      if (auto* Macro = Preprocessor.getLocalMacroDirectiveHistory(NameII)) {
        AddReferenceToMacro(MacroNameToken, *Macro->getMacroInfo(),
                            Macro->isDefined());
      }
    }
  } else {
    // This shouldn't happen; it's an error to do "defined TOKEN" unless
    // the preprocessor token is an identifier, in which case it should
    // have IdentifierInfo associated with it.  Note that Clang assigns
    // tok::tk_XXXX token types to preprocessing identifier tokens if
    // they have the names of tokens, rather than following the Standard's
    // formal phases of translation which would have them all be just
    // identifiers during preprocessing.
    LOG(FATAL) << "No IdentifierInfo in AddMacroReferenceIfDefined.";
  }
}

void IndexerPPCallbacks::AddReferenceToMacro(const clang::Token& MacroNameToken,
                                             clang::MacroInfo const& Info,
                                             bool IsDefined) {
  llvm::StringRef MacroName(MacroNameToken.getIdentifierInfo()->getName());
  Observer.recordExpandsRange(RangeForTokenInCurrentContext(MacroNameToken),
                              BuildNodeIdForMacro(MacroNameToken, Info));
}

GraphObserver::NameId IndexerPPCallbacks::BuildNameIdForMacro(
    const clang::Token& Spelling) {
  CHECK(Spelling.getIdentifierInfo()) << "Macro spelling lacks IdentifierInfo";
  GraphObserver::NameId Id;
  Id.EqClass = GraphObserver::NameId::NameEqClass::Macro;
  Id.Path = std::string(Spelling.getIdentifierInfo()->getName());
  return Id;
}

GraphObserver::NodeId IndexerPPCallbacks::BuildNodeIdForMacro(
    const clang::Token& Spelling, clang::MacroInfo const& Info) {
  // Macro definitions always appear at the topmost level *and* always appear
  // in source text (or are implicit). For this reason, it's safe to use
  // location information to stably unique them. However, we must be careful
  // to select canonical paths.
  clang::SourceLocation Loc = Info.getDefinitionLoc();
  std::string IdString;
  llvm::raw_string_ostream Ostream(IdString);
  Ostream << BuildNameIdForMacro(Spelling);
  auto& SM = *Observer.getSourceManager();
  if (Loc.isInvalid()) {
    Ostream << "@invalid";
  } else if (!Loc.isFileID()) {
    // This case shouldn't happen (given the above), but let's be robust.
    llvm::errs() << "Macro definition found in non-file "
                 << Loc.printToString(SM) << "\n";
    Loc.print(Ostream, SM);
  } else if (SM.getFileID(Loc) ==
             Observer.getPreprocessor()->getPredefinesFileID()) {
    // Locations of predefines in the predefine buffer can spuriously differ
    // from TU to TU, so we collapse them here.
    Ostream << "@builtin";
  } else {
    // Remember that we're inheriting the claim token (which in non-trivial
    // cases should contain canonical source file information).
    Ostream << "@" << SM.getFileOffset(Loc);
  }
  return Observer.MakeNodeId(Observer.getClaimTokenForLocation(Loc),
                             Ostream.str());
}

void IndexerPPCallbacks::HandleKytheMetadataPragma(
    clang::Preprocessor& preprocessor, clang::PragmaIntroducerKind introducer,
    clang::Token& FirstToken) {
  llvm::SmallString<1024> search_path;
  llvm::SmallString<1024> relative_path;
  llvm::SmallString<1024> filename;
  const auto* file = cxx_extractor::LookupFileForIncludePragma(
      &preprocessor, &search_path, &relative_path, &filename);
  if (!file) {
    absl::FPrintF(stderr, "Missing metadata file: %s\n",
                  std::string(filename.str()));
    return;
  }
  clang::FileID pragma_file_id =
      Observer.getSourceManager()->getFileID(FirstToken.getLocation());
  const auto* target =
      Observer.getSourceManager()->getFileEntryForID(pragma_file_id);
  if (target == nullptr) {
    LOG(WARNING) << "Missing target file entry for kythe_metadata";
    return;
  }
  if (!pragma_file_id.isInvalid()) {
    Observer.applyMetadataFile(pragma_file_id, file, "", target);
  } else {
    absl::FPrintF(stderr, "Metadata pragma was in an impossible place\n");
  }
}

void IndexerPPCallbacks::HandleKytheInlineMetadataPragma(
    clang::Preprocessor& preprocessor, clang::PragmaIntroducerKind introducer,
    clang::Token& FirstToken) {
  std::string search_string;
  clang::Token tok;
  if (!preprocessor.LexStringLiteral(tok, search_string,
                                     "pragma kythe_inline_metadata",
                                     /*AllowMacroExpansion=*/true)) {
    return;
  }
  if (search_string.empty()) {
    return;
  }
  clang::FileID pragma_file_id =
      Observer.getSourceManager()->getFileID(FirstToken.getLocation());
  if (pragma_file_id.isInvalid()) {
    LOG(WARNING) << "Invalid file ID for kythe_inline_metadata";
    return;
  }
  const clang::FileEntry* pragma_file_entry =
      Observer.getSourceManager()->getFileEntryForID(pragma_file_id);
  if (pragma_file_entry == nullptr) {
    LOG(WARNING) << "Missing file entry for kythe_inline_metadata";
    return;
  }
  Observer.applyMetadataFile(pragma_file_id, pragma_file_entry, search_string,
                             pragma_file_entry);
}

}  // namespace kythe