DataCollection.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //===-- DataCollection.cpp --------------------------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/AST/DataCollection.h"
  9. #include "clang/Basic/SourceManager.h"
  10. #include "clang/Lex/Lexer.h"
  11. namespace clang {
  12. namespace data_collection {
  13. /// Prints the macro name that contains the given SourceLocation into the given
  14. /// raw_string_ostream.
  15. static void printMacroName(llvm::raw_string_ostream &MacroStack,
  16. ASTContext &Context, SourceLocation Loc) {
  17. MacroStack << Lexer::getImmediateMacroName(Loc, Context.getSourceManager(),
  18. Context.getLangOpts());
  19. // Add an empty space at the end as a padding to prevent
  20. // that macro names concatenate to the names of other macros.
  21. MacroStack << " ";
  22. }
  23. /// Returns a string that represents all macro expansions that expanded into the
  24. /// given SourceLocation.
  25. ///
  26. /// If 'getMacroStack(A) == getMacroStack(B)' is true, then the SourceLocations
  27. /// A and B are expanded from the same macros in the same order.
  28. std::string getMacroStack(SourceLocation Loc, ASTContext &Context) {
  29. std::string MacroStack;
  30. llvm::raw_string_ostream MacroStackStream(MacroStack);
  31. SourceManager &SM = Context.getSourceManager();
  32. // Iterate over all macros that expanded into the given SourceLocation.
  33. while (Loc.isMacroID()) {
  34. // Add the macro name to the stream.
  35. printMacroName(MacroStackStream, Context, Loc);
  36. Loc = SM.getImmediateMacroCallerLoc(Loc);
  37. }
  38. MacroStackStream.flush();
  39. return MacroStack;
  40. }
  41. } // end namespace data_collection
  42. } // end namespace clang