RewriteMacros.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. //===--- RewriteMacros.cpp - Rewrite macros into their expansions ---------===//
  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. //
  9. // This code rewrites macro invocations into their expansions. This gives you
  10. // a macro expanded file that retains comments and #includes.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Rewrite/Frontend/Rewriters.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Lex/Preprocessor.h"
  16. #include "clang/Rewrite/Core/Rewriter.h"
  17. #include "llvm/Support/Path.h"
  18. #include "llvm/Support/raw_ostream.h"
  19. #include <cstdio>
  20. #include <memory>
  21. using namespace clang;
  22. /// isSameToken - Return true if the two specified tokens start have the same
  23. /// content.
  24. static bool isSameToken(Token &RawTok, Token &PPTok) {
  25. // If two tokens have the same kind and the same identifier info, they are
  26. // obviously the same.
  27. if (PPTok.getKind() == RawTok.getKind() &&
  28. PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
  29. return true;
  30. // Otherwise, if they are different but have the same identifier info, they
  31. // are also considered to be the same. This allows keywords and raw lexed
  32. // identifiers with the same name to be treated the same.
  33. if (PPTok.getIdentifierInfo() &&
  34. PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
  35. return true;
  36. return false;
  37. }
  38. /// GetNextRawTok - Return the next raw token in the stream, skipping over
  39. /// comments if ReturnComment is false.
  40. static const Token &GetNextRawTok(const std::vector<Token> &RawTokens,
  41. unsigned &CurTok, bool ReturnComment) {
  42. assert(CurTok < RawTokens.size() && "Overran eof!");
  43. // If the client doesn't want comments and we have one, skip it.
  44. if (!ReturnComment && RawTokens[CurTok].is(tok::comment))
  45. ++CurTok;
  46. return RawTokens[CurTok++];
  47. }
  48. /// LexRawTokensFromMainFile - Lets all the raw tokens from the main file into
  49. /// the specified vector.
  50. static void LexRawTokensFromMainFile(Preprocessor &PP,
  51. std::vector<Token> &RawTokens) {
  52. SourceManager &SM = PP.getSourceManager();
  53. // Create a lexer to lex all the tokens of the main file in raw mode. Even
  54. // though it is in raw mode, it will not return comments.
  55. llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
  56. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
  57. // Switch on comment lexing because we really do want them.
  58. RawLex.SetCommentRetentionState(true);
  59. Token RawTok;
  60. do {
  61. RawLex.LexFromRawLexer(RawTok);
  62. // If we have an identifier with no identifier info for our raw token, look
  63. // up the identifier info. This is important for equality comparison of
  64. // identifier tokens.
  65. if (RawTok.is(tok::raw_identifier))
  66. PP.LookUpIdentifierInfo(RawTok);
  67. RawTokens.push_back(RawTok);
  68. } while (RawTok.isNot(tok::eof));
  69. }
  70. /// RewriteMacrosInInput - Implement -rewrite-macros mode.
  71. void clang::RewriteMacrosInInput(Preprocessor &PP, raw_ostream *OS) {
  72. SourceManager &SM = PP.getSourceManager();
  73. Rewriter Rewrite;
  74. Rewrite.setSourceMgr(SM, PP.getLangOpts());
  75. RewriteBuffer &RB = Rewrite.getEditBuffer(SM.getMainFileID());
  76. std::vector<Token> RawTokens;
  77. LexRawTokensFromMainFile(PP, RawTokens);
  78. unsigned CurRawTok = 0;
  79. Token RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
  80. // Get the first preprocessing token.
  81. PP.EnterMainSourceFile();
  82. Token PPTok;
  83. PP.Lex(PPTok);
  84. // Preprocess the input file in parallel with raw lexing the main file. Ignore
  85. // all tokens that are preprocessed from a file other than the main file (e.g.
  86. // a header). If we see tokens that are in the preprocessed file but not the
  87. // lexed file, we have a macro expansion. If we see tokens in the lexed file
  88. // that aren't in the preprocessed view, we have macros that expand to no
  89. // tokens, or macro arguments etc.
  90. while (RawTok.isNot(tok::eof) || PPTok.isNot(tok::eof)) {
  91. SourceLocation PPLoc = SM.getExpansionLoc(PPTok.getLocation());
  92. // If PPTok is from a different source file, ignore it.
  93. if (!SM.isWrittenInMainFile(PPLoc)) {
  94. PP.Lex(PPTok);
  95. continue;
  96. }
  97. // If the raw file hits a preprocessor directive, they will be extra tokens
  98. // in the raw file that don't exist in the preprocsesed file. However, we
  99. // choose to preserve them in the output file and otherwise handle them
  100. // specially.
  101. if (RawTok.is(tok::hash) && RawTok.isAtStartOfLine()) {
  102. // If this is a #warning directive or #pragma mark (GNU extensions),
  103. // comment the line out.
  104. if (RawTokens[CurRawTok].is(tok::identifier)) {
  105. const IdentifierInfo *II = RawTokens[CurRawTok].getIdentifierInfo();
  106. if (II->getName() == "warning") {
  107. // Comment out #warning.
  108. RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//");
  109. } else if (II->getName() == "pragma" &&
  110. RawTokens[CurRawTok+1].is(tok::identifier) &&
  111. (RawTokens[CurRawTok+1].getIdentifierInfo()->getName() ==
  112. "mark")) {
  113. // Comment out #pragma mark.
  114. RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//");
  115. }
  116. }
  117. // Otherwise, if this is a #include or some other directive, just leave it
  118. // in the file by skipping over the line.
  119. RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
  120. while (!RawTok.isAtStartOfLine() && RawTok.isNot(tok::eof))
  121. RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
  122. continue;
  123. }
  124. // Okay, both tokens are from the same file. Get their offsets from the
  125. // start of the file.
  126. unsigned PPOffs = SM.getFileOffset(PPLoc);
  127. unsigned RawOffs = SM.getFileOffset(RawTok.getLocation());
  128. // If the offsets are the same and the token kind is the same, ignore them.
  129. if (PPOffs == RawOffs && isSameToken(RawTok, PPTok)) {
  130. RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
  131. PP.Lex(PPTok);
  132. continue;
  133. }
  134. // If the PP token is farther along than the raw token, something was
  135. // deleted. Comment out the raw token.
  136. if (RawOffs <= PPOffs) {
  137. // Comment out a whole run of tokens instead of bracketing each one with
  138. // comments. Add a leading space if RawTok didn't have one.
  139. bool HasSpace = RawTok.hasLeadingSpace();
  140. RB.InsertTextAfter(RawOffs, &" /*"[HasSpace]);
  141. unsigned EndPos;
  142. do {
  143. EndPos = RawOffs+RawTok.getLength();
  144. RawTok = GetNextRawTok(RawTokens, CurRawTok, true);
  145. RawOffs = SM.getFileOffset(RawTok.getLocation());
  146. if (RawTok.is(tok::comment)) {
  147. // Skip past the comment.
  148. RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
  149. break;
  150. }
  151. } while (RawOffs <= PPOffs && !RawTok.isAtStartOfLine() &&
  152. (PPOffs != RawOffs || !isSameToken(RawTok, PPTok)));
  153. RB.InsertTextBefore(EndPos, "*/");
  154. continue;
  155. }
  156. // Otherwise, there was a replacement an expansion. Insert the new token
  157. // in the output buffer. Insert the whole run of new tokens at once to get
  158. // them in the right order.
  159. unsigned InsertPos = PPOffs;
  160. std::string Expansion;
  161. while (PPOffs < RawOffs) {
  162. Expansion += ' ' + PP.getSpelling(PPTok);
  163. PP.Lex(PPTok);
  164. PPLoc = SM.getExpansionLoc(PPTok.getLocation());
  165. PPOffs = SM.getFileOffset(PPLoc);
  166. }
  167. Expansion += ' ';
  168. RB.InsertTextBefore(InsertPos, Expansion);
  169. }
  170. // Get the buffer corresponding to MainFileID. If we haven't changed it, then
  171. // we are done.
  172. if (const RewriteBuffer *RewriteBuf =
  173. Rewrite.getRewriteBufferFor(SM.getMainFileID())) {
  174. //printf("Changed:\n");
  175. *OS << std::string(RewriteBuf->begin(), RewriteBuf->end());
  176. } else {
  177. fprintf(stderr, "No changes\n");
  178. }
  179. OS->flush();
  180. }