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/Lex/Lexer.h"
  10. namespace clang {
  11. namespace data_collection {
  12. /// Prints the macro name that contains the given SourceLocation into the given
  13. /// raw_string_ostream.
  14. static void printMacroName(llvm::raw_string_ostream &MacroStack,
  15. ASTContext &Context, SourceLocation Loc) {
  16. MacroStack << Lexer::getImmediateMacroName(Loc, Context.getSourceManager(),
  17. Context.getLangOpts());
  18. // Add an empty space at the end as a padding to prevent
  19. // that macro names concatenate to the names of other macros.
  20. MacroStack << " ";
  21. }
  22. /// Returns a string that represents all macro expansions that expanded into the
  23. /// given SourceLocation.
  24. ///
  25. /// If 'getMacroStack(A) == getMacroStack(B)' is true, then the SourceLocations
  26. /// A and B are expanded from the same macros in the same order.
  27. std::string getMacroStack(SourceLocation Loc, ASTContext &Context) {
  28. std::string MacroStack;
  29. llvm::raw_string_ostream MacroStackStream(MacroStack);
  30. SourceManager &SM = Context.getSourceManager();
  31. // Iterate over all macros that expanded into the given SourceLocation.
  32. while (Loc.isMacroID()) {
  33. // Add the macro name to the stream.
  34. printMacroName(MacroStackStream, Context, Loc);
  35. Loc = SM.getImmediateMacroCallerLoc(Loc);
  36. }
  37. MacroStackStream.flush();
  38. return MacroStack;
  39. }
  40. } // end namespace data_collection
  41. } // end namespace clang