PPCallbacksTracker.cpp 23.1 KB
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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
//===--- PPCallbacksTracker.cpp - Preprocessor tracker -*--*---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Implementations for preprocessor tracking.
///
/// See the header for details.
///
//===----------------------------------------------------------------------===//

#include "PPCallbacksTracker.h"
#include "clang/Lex/MacroArgs.h"
#include "llvm/Support/raw_ostream.h"

namespace clang {
namespace pp_trace {

// Get a "file:line:column" source location string.
static std::string getSourceLocationString(Preprocessor &PP,
                                           SourceLocation Loc) {
  if (Loc.isInvalid())
    return std::string("(none)");

  if (Loc.isFileID()) {
    PresumedLoc PLoc = PP.getSourceManager().getPresumedLoc(Loc);

    if (PLoc.isInvalid()) {
      return std::string("(invalid)");
    }

    std::string Str;
    llvm::raw_string_ostream SS(Str);

    // The macro expansion and spelling pos is identical for file locs.
    SS << "\"" << PLoc.getFilename() << ':' << PLoc.getLine() << ':'
       << PLoc.getColumn() << "\"";

    std::string Result = SS.str();

    // YAML treats backslash as escape, so use forward slashes.
    std::replace(Result.begin(), Result.end(), '\\', '/');

    return Result;
  }

  return std::string("(nonfile)");
}

// Enum string tables.

// FileChangeReason strings.
static const char *const FileChangeReasonStrings[] = {
  "EnterFile", "ExitFile", "SystemHeaderPragma", "RenameFile"
};

// CharacteristicKind strings.
static const char *const CharacteristicKindStrings[] = { "C_User", "C_System",
                                                         "C_ExternCSystem" };

// MacroDirective::Kind strings.
static const char *const MacroDirectiveKindStrings[] = {
  "MD_Define","MD_Undefine", "MD_Visibility"
};

// PragmaIntroducerKind strings.
static const char *const PragmaIntroducerKindStrings[] = { "PIK_HashPragma",
                                                           "PIK__Pragma",
                                                           "PIK___pragma" };

// PragmaMessageKind strings.
static const char *const PragmaMessageKindStrings[] = {
  "PMK_Message", "PMK_Warning", "PMK_Error"
};

// ConditionValueKind strings.
static const char *const ConditionValueKindStrings[] = {
  "CVK_NotEvaluated", "CVK_False", "CVK_True"
};

// Mapping strings.
static const char *const MappingStrings[] = { "0",          "MAP_IGNORE",
                                              "MAP_REMARK", "MAP_WARNING",
                                              "MAP_ERROR",  "MAP_FATAL" };

// PPCallbacksTracker functions.

PPCallbacksTracker::PPCallbacksTracker(const FilterType &Filters,
                                       std::vector<CallbackCall> &CallbackCalls,
                                       Preprocessor &PP)
    : CallbackCalls(CallbackCalls), Filters(Filters), PP(PP) {}

PPCallbacksTracker::~PPCallbacksTracker() {}

// Callback functions.

// Callback invoked whenever a source file is entered or exited.
void PPCallbacksTracker::FileChanged(SourceLocation Loc,
                                     PPCallbacks::FileChangeReason Reason,
                                     SrcMgr::CharacteristicKind FileType,
                                     FileID PrevFID) {
  beginCallback("FileChanged");
  appendArgument("Loc", Loc);
  appendArgument("Reason", Reason, FileChangeReasonStrings);
  appendArgument("FileType", FileType, CharacteristicKindStrings);
  appendArgument("PrevFID", PrevFID);
}

// Callback invoked whenever a source file is skipped as the result
// of header guard optimization.
void PPCallbacksTracker::FileSkipped(const FileEntryRef &SkippedFile,
                                     const Token &FilenameTok,
                                     SrcMgr::CharacteristicKind FileType) {
  beginCallback("FileSkipped");
  appendArgument("ParentFile", &SkippedFile.getFileEntry());
  appendArgument("FilenameTok", FilenameTok);
  appendArgument("FileType", FileType, CharacteristicKindStrings);
}

// Callback invoked whenever an inclusion directive results in a
// file-not-found error.
bool
PPCallbacksTracker::FileNotFound(llvm::StringRef FileName,
                                 llvm::SmallVectorImpl<char> &RecoveryPath) {
  beginCallback("FileNotFound");
  appendFilePathArgument("FileName", FileName);
  return false;
}

// Callback invoked whenever an inclusion directive of
// any kind (#include, #import, etc.) has been processed, regardless
// of whether the inclusion will actually result in an inclusion.
void PPCallbacksTracker::InclusionDirective(
    SourceLocation HashLoc, const Token &IncludeTok, llvm::StringRef FileName,
    bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File,
    llvm::StringRef SearchPath, llvm::StringRef RelativePath,
    const Module *Imported, SrcMgr::CharacteristicKind FileType) {
  beginCallback("InclusionDirective");
  appendArgument("IncludeTok", IncludeTok);
  appendFilePathArgument("FileName", FileName);
  appendArgument("IsAngled", IsAngled);
  appendArgument("FilenameRange", FilenameRange);
  appendArgument("File", File);
  appendFilePathArgument("SearchPath", SearchPath);
  appendFilePathArgument("RelativePath", RelativePath);
  appendArgument("Imported", Imported);
}

// Callback invoked whenever there was an explicit module-import
// syntax.
void PPCallbacksTracker::moduleImport(SourceLocation ImportLoc,
                                      ModuleIdPath Path,
                                      const Module *Imported) {
  beginCallback("moduleImport");
  appendArgument("ImportLoc", ImportLoc);
  appendArgument("Path", Path);
  appendArgument("Imported", Imported);
}

// Callback invoked when the end of the main file is reached.
// No subsequent callbacks will be made.
void PPCallbacksTracker::EndOfMainFile() { beginCallback("EndOfMainFile"); }

// Callback invoked when a #ident or #sccs directive is read.
void PPCallbacksTracker::Ident(SourceLocation Loc, llvm::StringRef Str) {
  beginCallback("Ident");
  appendArgument("Loc", Loc);
  appendArgument("Str", Str);
}

// Callback invoked when start reading any pragma directive.
void PPCallbacksTracker::PragmaDirective(SourceLocation Loc,
                                         PragmaIntroducerKind Introducer) {
  beginCallback("PragmaDirective");
  appendArgument("Loc", Loc);
  appendArgument("Introducer", Introducer, PragmaIntroducerKindStrings);
}

// Callback invoked when a #pragma comment directive is read.
void PPCallbacksTracker::PragmaComment(SourceLocation Loc,
                                       const IdentifierInfo *Kind,
                                       llvm::StringRef Str) {
  beginCallback("PragmaComment");
  appendArgument("Loc", Loc);
  appendArgument("Kind", Kind);
  appendArgument("Str", Str);
}

// Callback invoked when a #pragma detect_mismatch directive is
// read.
void PPCallbacksTracker::PragmaDetectMismatch(SourceLocation Loc,
                                              llvm::StringRef Name,
                                              llvm::StringRef Value) {
  beginCallback("PragmaDetectMismatch");
  appendArgument("Loc", Loc);
  appendArgument("Name", Name);
  appendArgument("Value", Value);
}

// Callback invoked when a #pragma clang __debug directive is read.
void PPCallbacksTracker::PragmaDebug(SourceLocation Loc,
                                     llvm::StringRef DebugType) {
  beginCallback("PragmaDebug");
  appendArgument("Loc", Loc);
  appendArgument("DebugType", DebugType);
}

// Callback invoked when a #pragma message directive is read.
void PPCallbacksTracker::PragmaMessage(SourceLocation Loc,
                                       llvm::StringRef Namespace,
                                       PPCallbacks::PragmaMessageKind Kind,
                                       llvm::StringRef Str) {
  beginCallback("PragmaMessage");
  appendArgument("Loc", Loc);
  appendArgument("Namespace", Namespace);
  appendArgument("Kind", Kind, PragmaMessageKindStrings);
  appendArgument("Str", Str);
}

// Callback invoked when a #pragma gcc diagnostic push directive
// is read.
void PPCallbacksTracker::PragmaDiagnosticPush(SourceLocation Loc,
                                              llvm::StringRef Namespace) {
  beginCallback("PragmaDiagnosticPush");
  appendArgument("Loc", Loc);
  appendArgument("Namespace", Namespace);
}

// Callback invoked when a #pragma gcc diagnostic pop directive
// is read.
void PPCallbacksTracker::PragmaDiagnosticPop(SourceLocation Loc,
                                             llvm::StringRef Namespace) {
  beginCallback("PragmaDiagnosticPop");
  appendArgument("Loc", Loc);
  appendArgument("Namespace", Namespace);
}

// Callback invoked when a #pragma gcc diagnostic directive is read.
void PPCallbacksTracker::PragmaDiagnostic(SourceLocation Loc,
                                          llvm::StringRef Namespace,
                                          diag::Severity Mapping,
                                          llvm::StringRef Str) {
  beginCallback("PragmaDiagnostic");
  appendArgument("Loc", Loc);
  appendArgument("Namespace", Namespace);
  appendArgument("Mapping", (unsigned)Mapping, MappingStrings);
  appendArgument("Str", Str);
}

// Called when an OpenCL extension is either disabled or
// enabled with a pragma.
void PPCallbacksTracker::PragmaOpenCLExtension(SourceLocation NameLoc,
                                               const IdentifierInfo *Name,
                                               SourceLocation StateLoc,
                                               unsigned State) {
  beginCallback("PragmaOpenCLExtension");
  appendArgument("NameLoc", NameLoc);
  appendArgument("Name", Name);
  appendArgument("StateLoc", StateLoc);
  appendArgument("State", (int)State);
}

// Callback invoked when a #pragma warning directive is read.
void PPCallbacksTracker::PragmaWarning(SourceLocation Loc,
                                       llvm::StringRef WarningSpec,
                                       llvm::ArrayRef<int> Ids) {
  beginCallback("PragmaWarning");
  appendArgument("Loc", Loc);
  appendArgument("WarningSpec", WarningSpec);

  std::string Str;
  llvm::raw_string_ostream SS(Str);
  SS << "[";
  for (int i = 0, e = Ids.size(); i != e; ++i) {
    if (i)
      SS << ", ";
    SS << Ids[i];
  }
  SS << "]";
  appendArgument("Ids", SS.str());
}

// Callback invoked when a #pragma warning(push) directive is read.
void PPCallbacksTracker::PragmaWarningPush(SourceLocation Loc, int Level) {
  beginCallback("PragmaWarningPush");
  appendArgument("Loc", Loc);
  appendArgument("Level", Level);
}

// Callback invoked when a #pragma warning(pop) directive is read.
void PPCallbacksTracker::PragmaWarningPop(SourceLocation Loc) {
  beginCallback("PragmaWarningPop");
  appendArgument("Loc", Loc);
}

// Callback invoked when a #pragma execution_character_set(push) directive
// is read.
void PPCallbacksTracker::PragmaExecCharsetPush(SourceLocation Loc,
                                               StringRef Str) {
  beginCallback("PragmaExecCharsetPush");
  appendArgument("Loc", Loc);
  appendArgument("Charset", Str);
}

// Callback invoked when a #pragma execution_character_set(pop) directive
// is read.
void PPCallbacksTracker::PragmaExecCharsetPop(SourceLocation Loc) {
  beginCallback("PragmaExecCharsetPop");
  appendArgument("Loc", Loc);
}

// Called by Preprocessor::HandleMacroExpandedIdentifier when a
// macro invocation is found.
void PPCallbacksTracker::MacroExpands(const Token &MacroNameTok,
                                      const MacroDefinition &MacroDefinition,
                                      SourceRange Range,
                                      const MacroArgs *Args) {
  beginCallback("MacroExpands");
  appendArgument("MacroNameTok", MacroNameTok);
  appendArgument("MacroDefinition", MacroDefinition);
  appendArgument("Range", Range);
  appendArgument("Args", Args);
}

// Hook called whenever a macro definition is seen.
void PPCallbacksTracker::MacroDefined(const Token &MacroNameTok,
                                      const MacroDirective *MacroDirective) {
  beginCallback("MacroDefined");
  appendArgument("MacroNameTok", MacroNameTok);
  appendArgument("MacroDirective", MacroDirective);
}

// Hook called whenever a macro #undef is seen.
void PPCallbacksTracker::MacroUndefined(const Token &MacroNameTok,
                                        const MacroDefinition &MacroDefinition,
                                        const MacroDirective *Undef) {
  beginCallback("MacroUndefined");
  appendArgument("MacroNameTok", MacroNameTok);
  appendArgument("MacroDefinition", MacroDefinition);
}

// Hook called whenever the 'defined' operator is seen.
void PPCallbacksTracker::Defined(const Token &MacroNameTok,
                                 const MacroDefinition &MacroDefinition,
                                 SourceRange Range) {
  beginCallback("Defined");
  appendArgument("MacroNameTok", MacroNameTok);
  appendArgument("MacroDefinition", MacroDefinition);
  appendArgument("Range", Range);
}

// Hook called when a source range is skipped.
void PPCallbacksTracker::SourceRangeSkipped(SourceRange Range,
                                            SourceLocation EndifLoc) {
  beginCallback("SourceRangeSkipped");
  appendArgument("Range", SourceRange(Range.getBegin(), EndifLoc));
}

// Hook called whenever an #if is seen.
void PPCallbacksTracker::If(SourceLocation Loc, SourceRange ConditionRange,
                            ConditionValueKind ConditionValue) {
  beginCallback("If");
  appendArgument("Loc", Loc);
  appendArgument("ConditionRange", ConditionRange);
  appendArgument("ConditionValue", ConditionValue, ConditionValueKindStrings);
}

// Hook called whenever an #elif is seen.
void PPCallbacksTracker::Elif(SourceLocation Loc, SourceRange ConditionRange,
                              ConditionValueKind ConditionValue,
                              SourceLocation IfLoc) {
  beginCallback("Elif");
  appendArgument("Loc", Loc);
  appendArgument("ConditionRange", ConditionRange);
  appendArgument("ConditionValue", ConditionValue, ConditionValueKindStrings);
  appendArgument("IfLoc", IfLoc);
}

// Hook called whenever an #ifdef is seen.
void PPCallbacksTracker::Ifdef(SourceLocation Loc, const Token &MacroNameTok,
                               const MacroDefinition &MacroDefinition) {
  beginCallback("Ifdef");
  appendArgument("Loc", Loc);
  appendArgument("MacroNameTok", MacroNameTok);
  appendArgument("MacroDefinition", MacroDefinition);
}

// Hook called whenever an #ifndef is seen.
void PPCallbacksTracker::Ifndef(SourceLocation Loc, const Token &MacroNameTok,
                                const MacroDefinition &MacroDefinition) {
  beginCallback("Ifndef");
  appendArgument("Loc", Loc);
  appendArgument("MacroNameTok", MacroNameTok);
  appendArgument("MacroDefinition", MacroDefinition);
}

// Hook called whenever an #else is seen.
void PPCallbacksTracker::Else(SourceLocation Loc, SourceLocation IfLoc) {
  beginCallback("Else");
  appendArgument("Loc", Loc);
  appendArgument("IfLoc", IfLoc);
}

// Hook called whenever an #endif is seen.
void PPCallbacksTracker::Endif(SourceLocation Loc, SourceLocation IfLoc) {
  beginCallback("Endif");
  appendArgument("Loc", Loc);
  appendArgument("IfLoc", IfLoc);
}

// Helper functions.

// Start a new callback.
void PPCallbacksTracker::beginCallback(const char *Name) {
  auto R = CallbackIsEnabled.try_emplace(Name, false);
  if (R.second) {
    llvm::StringRef N(Name);
    for (const std::pair<llvm::GlobPattern, bool> &Filter : Filters)
      if (Filter.first.match(N))
        R.first->second = Filter.second;
  }
  DisableTrace = !R.first->second;
  if (DisableTrace)
    return;
  CallbackCalls.push_back(CallbackCall(Name));
}

// Append a bool argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, bool Value) {
  appendArgument(Name, (Value ? "true" : "false"));
}

// Append an int argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, int Value) {
  std::string Str;
  llvm::raw_string_ostream SS(Str);
  SS << Value;
  appendArgument(Name, SS.str());
}

// Append a string argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, const char *Value) {
  if (DisableTrace)
    return;
  CallbackCalls.back().Arguments.push_back(Argument{Name, Value});
}

// Append a string object argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        llvm::StringRef Value) {
  appendArgument(Name, Value.str());
}

// Append a string object argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        const std::string &Value) {
  appendArgument(Name, Value.c_str());
}

// Append a token argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, const Token &Value) {
  appendArgument(Name, PP.getSpelling(Value));
}

// Append an enum argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, int Value,
                                        const char *const Strings[]) {
  appendArgument(Name, Strings[Value]);
}

// Append a FileID argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, FileID Value) {
  if (Value.isInvalid()) {
    appendArgument(Name, "(invalid)");
    return;
  }
  const FileEntry *FileEntry = PP.getSourceManager().getFileEntryForID(Value);
  if (!FileEntry) {
    appendArgument(Name, "(getFileEntryForID failed)");
    return;
  }
  appendFilePathArgument(Name, FileEntry->getName());
}

// Append a FileEntry argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        const FileEntry *Value) {
  if (!Value) {
    appendArgument(Name, "(null)");
    return;
  }
  appendFilePathArgument(Name, Value->getName());
}

// Append a SourceLocation argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        SourceLocation Value) {
  if (Value.isInvalid()) {
    appendArgument(Name, "(invalid)");
    return;
  }
  appendArgument(Name, getSourceLocationString(PP, Value).c_str());
}

// Append a SourceRange argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, SourceRange Value) {
  if (DisableTrace)
    return;
  if (Value.isInvalid()) {
    appendArgument(Name, "(invalid)");
    return;
  }
  std::string Str;
  llvm::raw_string_ostream SS(Str);
  SS << "[" << getSourceLocationString(PP, Value.getBegin()) << ", "
     << getSourceLocationString(PP, Value.getEnd()) << "]";
  appendArgument(Name, SS.str());
}

// Append a CharSourceRange argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        CharSourceRange Value) {
  if (Value.isInvalid()) {
    appendArgument(Name, "(invalid)");
    return;
  }
  appendArgument(Name, getSourceString(Value).str().c_str());
}

// Append a SourceLocation argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, ModuleIdPath Value) {
  if (DisableTrace)
    return;
  std::string Str;
  llvm::raw_string_ostream SS(Str);
  SS << "[";
  for (int I = 0, E = Value.size(); I != E; ++I) {
    if (I)
      SS << ", ";
    SS << "{"
       << "Name: " << Value[I].first->getName() << ", "
       << "Loc: " << getSourceLocationString(PP, Value[I].second) << "}";
  }
  SS << "]";
  appendArgument(Name, SS.str());
}

// Append an IdentifierInfo argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        const IdentifierInfo *Value) {
  if (!Value) {
    appendArgument(Name, "(null)");
    return;
  }
  appendArgument(Name, Value->getName().str().c_str());
}

// Append a MacroDirective argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        const MacroDirective *Value) {
  if (!Value) {
    appendArgument(Name, "(null)");
    return;
  }
  appendArgument(Name, MacroDirectiveKindStrings[Value->getKind()]);
}

// Append a MacroDefinition argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        const MacroDefinition &Value) {
  std::string Str;
  llvm::raw_string_ostream SS(Str);
  SS << "[";
  bool Any = false;
  if (Value.getLocalDirective()) {
    SS << "(local)";
    Any = true;
  }
  for (auto *MM : Value.getModuleMacros()) {
    if (Any) SS << ", ";
    SS << MM->getOwningModule()->getFullModuleName();
  }
  SS << "]";
  appendArgument(Name, SS.str());
}

// Append a MacroArgs argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name,
                                        const MacroArgs *Value) {
  if (!Value) {
    appendArgument(Name, "(null)");
    return;
  }
  std::string Str;
  llvm::raw_string_ostream SS(Str);
  SS << "[";

  // Each argument is is a series of contiguous Tokens, terminated by a eof.
  // Go through each argument printing tokens until we reach eof.
  for (unsigned I = 0; I < Value->getNumMacroArguments(); ++I) {
    const Token *Current = Value->getUnexpArgument(I);
    if (I)
      SS << ", ";
    bool First = true;
    while (Current->isNot(tok::eof)) {
      if (!First)
        SS << " ";
      // We need to be careful here because the arguments might not be legal in
      // YAML, so we use the token name for anything but identifiers and
      // numeric literals.
      if (Current->isAnyIdentifier() || Current->is(tok::numeric_constant)) {
        SS << PP.getSpelling(*Current);
      } else {
        SS << "<" << Current->getName() << ">";
      }
      ++Current;
      First = false;
    }
  }
  SS << "]";
  appendArgument(Name, SS.str());
}

// Append a Module argument to the top trace item.
void PPCallbacksTracker::appendArgument(const char *Name, const Module *Value) {
  if (!Value) {
    appendArgument(Name, "(null)");
    return;
  }
  appendArgument(Name, Value->Name.c_str());
}

// Append a double-quoted argument to the top trace item.
void PPCallbacksTracker::appendQuotedArgument(const char *Name,
                                              const std::string &Value) {
  std::string Str;
  llvm::raw_string_ostream SS(Str);
  SS << "\"" << Value << "\"";
  appendArgument(Name, SS.str());
}

// Append a double-quoted file path argument to the top trace item.
void PPCallbacksTracker::appendFilePathArgument(const char *Name,
                                                llvm::StringRef Value) {
  std::string Path(Value);
  // YAML treats backslash as escape, so use forward slashes.
  std::replace(Path.begin(), Path.end(), '\\', '/');
  appendQuotedArgument(Name, Path);
}

// Get the raw source string of the range.
llvm::StringRef PPCallbacksTracker::getSourceString(CharSourceRange Range) {
  const char *B = PP.getSourceManager().getCharacterData(Range.getBegin());
  const char *E = PP.getSourceManager().getCharacterData(Range.getEnd());
  return llvm::StringRef(B, E - B);
}

} // namespace pp_trace
} // namespace clang