RewriteMacros.cpp 7.9 KB

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