1 //===--- RewriteMacros.cpp - Rewrite macros into their expansions ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This code rewrites macro invocations into their expansions. This gives you
11 // a macro expanded file that retains comments and #includes.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Rewrite/Rewriter.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "llvm/Support/Streams.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/System/Path.h"
22 #include "llvm/ADT/OwningPtr.h"
23 using namespace clang;
25 /// isSameToken - Return true if the two specified tokens start have the same
27 static bool isSameToken(Token &RawTok, Token &PPTok) {
28 // If two tokens have the same kind and the same identifier info, they are
29 // obviously the same.
30 if (PPTok.getKind() == RawTok.getKind() &&
31 PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
34 // Otherwise, if they are different but have the same identifier info, they
35 // are also considered to be the same. This allows keywords and raw lexed
36 // identifiers with the same name to be treated the same.
37 if (PPTok.getIdentifierInfo() &&
38 PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
45 /// GetNextRawTok - Return the next raw token in the stream, skipping over
46 /// comments if ReturnComment is false.
47 static const Token &GetNextRawTok(const std::vector<Token> &RawTokens,
48 unsigned &CurTok, bool ReturnComment) {
49 assert(CurTok < RawTokens.size() && "Overran eof!");
51 // If the client doesn't want comments and we have one, skip it.
52 if (!ReturnComment && RawTokens[CurTok].is(tok::comment))
55 return RawTokens[CurTok++];
59 /// LexRawTokensFromMainFile - Lets all the raw tokens from the main file into
60 /// the specified vector.
61 static void LexRawTokensFromMainFile(Preprocessor &PP,
62 std::vector<Token> &RawTokens) {
63 SourceManager &SM = PP.getSourceManager();
65 // Create a lexer to lex all the tokens of the main file in raw mode. Even
66 // though it is in raw mode, it will not return comments.
67 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
69 // Switch on comment lexing because we really do want them.
70 RawLex.SetCommentRetentionState(true);
74 RawLex.LexFromRawLexer(RawTok);
76 // If we have an identifier with no identifier info for our raw token, look
77 // up the indentifier info. This is important for equality comparison of
79 if (RawTok.is(tok::identifier) && !RawTok.getIdentifierInfo())
80 RawTok.setIdentifierInfo(PP.LookUpIdentifierInfo(RawTok));
82 RawTokens.push_back(RawTok);
83 } while (RawTok.isNot(tok::eof));
87 /// RewriteMacrosInInput - Implement -rewrite-macros mode.
88 void clang::RewriteMacrosInInput(Preprocessor &PP, llvm::raw_ostream *OS) {
89 SourceManager &SM = PP.getSourceManager();
92 Rewrite.setSourceMgr(SM, PP.getLangOptions());
93 RewriteBuffer &RB = Rewrite.getEditBuffer(SM.getMainFileID());
95 std::vector<Token> RawTokens;
96 LexRawTokensFromMainFile(PP, RawTokens);
97 unsigned CurRawTok = 0;
98 Token RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
101 // Get the first preprocessing token.
102 PP.EnterMainSourceFile();
106 // Preprocess the input file in parallel with raw lexing the main file. Ignore
107 // all tokens that are preprocessed from a file other than the main file (e.g.
108 // a header). If we see tokens that are in the preprocessed file but not the
109 // lexed file, we have a macro expansion. If we see tokens in the lexed file
110 // that aren't in the preprocessed view, we have macros that expand to no
111 // tokens, or macro arguments etc.
112 while (RawTok.isNot(tok::eof) || PPTok.isNot(tok::eof)) {
113 SourceLocation PPLoc = SM.getInstantiationLoc(PPTok.getLocation());
115 // If PPTok is from a different source file, ignore it.
116 if (!SM.isFromMainFile(PPLoc)) {
121 // If the raw file hits a preprocessor directive, they will be extra tokens
122 // in the raw file that don't exist in the preprocsesed file. However, we
123 // choose to preserve them in the output file and otherwise handle them
125 if (RawTok.is(tok::hash) && RawTok.isAtStartOfLine()) {
126 // If this is a #warning directive or #pragma mark (GNU extensions),
127 // comment the line out.
128 if (RawTokens[CurRawTok].is(tok::identifier)) {
129 const IdentifierInfo *II = RawTokens[CurRawTok].getIdentifierInfo();
130 if (!strcmp(II->getName(), "warning")) {
131 // Comment out #warning.
132 RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//", 2);
133 } else if (!strcmp(II->getName(), "pragma") &&
134 RawTokens[CurRawTok+1].is(tok::identifier) &&
135 !strcmp(RawTokens[CurRawTok+1].getIdentifierInfo()->getName(),
137 // Comment out #pragma mark.
138 RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//", 2);
142 // Otherwise, if this is a #include or some other directive, just leave it
143 // in the file by skipping over the line.
144 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
145 while (!RawTok.isAtStartOfLine() && RawTok.isNot(tok::eof))
146 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
150 // Okay, both tokens are from the same file. Get their offsets from the
151 // start of the file.
152 unsigned PPOffs = SM.getFileOffset(PPLoc);
153 unsigned RawOffs = SM.getFileOffset(RawTok.getLocation());
155 // If the offsets are the same and the token kind is the same, ignore them.
156 if (PPOffs == RawOffs && isSameToken(RawTok, PPTok)) {
157 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
162 // If the PP token is farther along than the raw token, something was
163 // deleted. Comment out the raw token.
164 if (RawOffs <= PPOffs) {
165 // Comment out a whole run of tokens instead of bracketing each one with
166 // comments. Add a leading space if RawTok didn't have one.
167 bool HasSpace = RawTok.hasLeadingSpace();
168 RB.InsertTextAfter(RawOffs, " /*"+HasSpace, 2+!HasSpace);
172 EndPos = RawOffs+RawTok.getLength();
174 RawTok = GetNextRawTok(RawTokens, CurRawTok, true);
175 RawOffs = SM.getFileOffset(RawTok.getLocation());
177 if (RawTok.is(tok::comment)) {
178 // Skip past the comment.
179 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
183 } while (RawOffs <= PPOffs && !RawTok.isAtStartOfLine() &&
184 (PPOffs != RawOffs || !isSameToken(RawTok, PPTok)));
186 RB.InsertTextBefore(EndPos, "*/", 2);
190 // Otherwise, there was a replacement an expansion. Insert the new token
191 // in the output buffer. Insert the whole run of new tokens at once to get
192 // them in the right order.
193 unsigned InsertPos = PPOffs;
194 std::string Expansion;
195 while (PPOffs < RawOffs) {
196 Expansion += ' ' + PP.getSpelling(PPTok);
198 PPLoc = SM.getInstantiationLoc(PPTok.getLocation());
199 PPOffs = SM.getFileOffset(PPLoc);
202 RB.InsertTextBefore(InsertPos, &Expansion[0], Expansion.size());
205 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
207 if (const RewriteBuffer *RewriteBuf =
208 Rewrite.getRewriteBufferFor(SM.getMainFileID())) {
209 //printf("Changed:\n");
210 *OS << std::string(RewriteBuf->begin(), RewriteBuf->end());
212 fprintf(stderr, "No changes\n");