blob: c2989438fde28a8b3044fbd02f308a1f93fb4eef [file] [log] [blame]
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001//===--- 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
15#include "clang.h"
16#include "clang/Rewrite/Rewriter.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Basic/SourceManager.h"
Chris Lattnerb57e3d42008-05-08 06:52:13 +000019#include "llvm/Support/Streams.h"
20#include "llvm/System/Path.h"
21#include <fstream>
22using namespace clang;
23
Chris Lattnerec921562008-05-10 00:02:33 +000024/// isSameToken - Return true if the two specified tokens start have the same
25/// content.
26static bool isSameToken(Token &RawTok, Token &PPTok) {
Chris Lattner8ea78e62008-05-31 22:01:01 +000027 // If two tokens have the same kind and the same identifier info, they are
28 // obviously the same.
29 if (PPTok.getKind() == RawTok.getKind() &&
30 PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
Chris Lattnerec921562008-05-10 00:02:33 +000031 return true;
32
Chris Lattner8ea78e62008-05-31 22:01:01 +000033 // Otherwise, if they are different but have the same identifier info, they
34 // are also considered to be the same. This allows keywords and raw lexed
35 // identifiers with the same name to be treated the same.
Chris Lattnerec921562008-05-10 00:02:33 +000036 if (PPTok.getIdentifierInfo() &&
37 PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
38 return true;
39
40 return false;
41}
42
Chris Lattner0d76fcd2008-07-25 16:29:12 +000043
44/// GetNextRawTok - Return the next raw token in the stream, skipping over
45/// comments if ReturnComment is false.
46static const Token &GetNextRawTok(const std::vector<Token> &RawTokens,
47 unsigned &CurTok, bool ReturnComment) {
48 assert(CurTok < RawTokens.size() && "Overran eof!");
Chris Lattnerec921562008-05-10 00:02:33 +000049
Chris Lattner0d76fcd2008-07-25 16:29:12 +000050 // If the client doesn't want comments and we have one, skip it.
51 if (!ReturnComment && RawTokens[CurTok].is(tok::comment))
52 ++CurTok;
53
54 return RawTokens[CurTok++];
Chris Lattnerec921562008-05-10 00:02:33 +000055}
56
Chris Lattner0d76fcd2008-07-25 16:29:12 +000057
58/// LexRawTokensFromMainFile - Lets all the raw tokens from the main file into
59/// the specified vector.
60static void LexRawTokensFromMainFile(Preprocessor &PP,
61 std::vector<Token> &RawTokens) {
62 SourceManager &SM = PP.getSourceManager();
63 std::pair<const char*,const char*> File =SM.getBufferData(SM.getMainFileID());
64
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(SourceLocation::getFileLoc(SM.getMainFileID(), 0),
68 PP.getLangOptions(), File.first, File.second);
69
70 // Switch on comment lexing because we really do want them.
71 RawLex.SetCommentRetentionState(true);
72
73 Token RawTok;
74 do {
75 RawLex.LexRawToken(RawTok);
76
77 // If we have an identifier with no identifier info for our raw token, look
78 // up the indentifier info. This is important for equality comparison of
79 // identifier tokens.
80 if (RawTok.is(tok::identifier) && !RawTok.getIdentifierInfo())
81 RawTok.setIdentifierInfo(PP.LookUpIdentifierInfo(RawTok));
82
83 RawTokens.push_back(RawTok);
84 } while (RawTok.isNot(tok::eof));
85}
86
87
Chris Lattnerb57e3d42008-05-08 06:52:13 +000088/// RewriteMacrosInInput - Implement -rewrite-macros mode.
Chris Lattner09510522008-05-09 22:43:24 +000089void clang::RewriteMacrosInInput(Preprocessor &PP,const std::string &InFileName,
Chris Lattnerb57e3d42008-05-08 06:52:13 +000090 const std::string &OutFileName) {
91 SourceManager &SM = PP.getSourceManager();
92
93 Rewriter Rewrite;
94 Rewrite.setSourceMgr(SM);
Chris Lattnerec921562008-05-10 00:02:33 +000095 RewriteBuffer &RB = Rewrite.getEditBuffer(SM.getMainFileID());
Chris Lattnerb57e3d42008-05-08 06:52:13 +000096
Chris Lattner0d76fcd2008-07-25 16:29:12 +000097 std::vector<Token> RawTokens;
98 LexRawTokensFromMainFile(PP, RawTokens);
99 unsigned CurRawTok = 0;
100 Token RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
101
Chris Lattnerec921562008-05-10 00:02:33 +0000102
103 // Get the first preprocessing token.
104 PP.EnterMainSourceFile();
105 Token PPTok;
106 PP.Lex(PPTok);
107
108 // Preprocess the input file in parallel with raw lexing the main file. Ignore
109 // all tokens that are preprocessed from a file other than the main file (e.g.
110 // a header). If we see tokens that are in the preprocessed file bug not the
111 // lexed file, we have a macro expansion. If we see tokens in the lexed file
112 // that aren't in the preprocessed view, we have macros that expand to no
113 // tokens, or macro arguments etc.
114 while (RawTok.isNot(tok::eof) || PPTok.isNot(tok::eof)) {
115 SourceLocation PPLoc = SM.getLogicalLoc(PPTok.getLocation());
116
117 // If PPTok is from a different source file, ignore it.
118 if (!SM.isFromMainFile(PPLoc)) {
119 PP.Lex(PPTok);
120 continue;
121 }
122
123 // If the raw file hits a preprocessor directive, they will be extra tokens
Chris Lattnera59e0502008-07-25 16:37:06 +0000124 // in the raw file that don't exist in the preprocsesed file. However, we
125 // choose to preserve them in the output file and otherwise handle them
126 // specially.
Chris Lattnerec921562008-05-10 00:02:33 +0000127 if (RawTok.is(tok::hash) && RawTok.isAtStartOfLine()) {
Chris Lattnera59e0502008-07-25 16:37:06 +0000128 // If this is a #warning directive or #pragma mark (GNU extensions),
129 // comment the line out.
130 if (RawTokens[CurRawTok].is(tok::identifier)) {
131 const IdentifierInfo *II = RawTokens[CurRawTok].getIdentifierInfo();
132 if (!strcmp(II->getName(), "warning")) {
133 // Comment out #warning.
134 RB.InsertTextAfter(SM.getFullFilePos(RawTok.getLocation()), "//", 2);
135 } else if (!strcmp(II->getName(), "pragma") &&
136 RawTokens[CurRawTok+1].is(tok::identifier) &&
137 !strcmp(RawTokens[CurRawTok+1].getIdentifierInfo()->getName(),
138 "mark")){
139 // Comment out #pragma mark.
140 RB.InsertTextAfter(SM.getFullFilePos(RawTok.getLocation()), "//", 2);
141 }
142 }
143
144 // Otherwise, if this is a #include or some other directive, just leave it
145 // in the file by skipping over the line.
Chris Lattner0d76fcd2008-07-25 16:29:12 +0000146 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
Chris Lattnerec921562008-05-10 00:02:33 +0000147 while (!RawTok.isAtStartOfLine() && RawTok.isNot(tok::eof))
Chris Lattner0d76fcd2008-07-25 16:29:12 +0000148 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
Chris Lattnerec921562008-05-10 00:02:33 +0000149 continue;
150 }
151
152 // Okay, both tokens are from the same file. Get their offsets from the
153 // start of the file.
154 unsigned PPOffs = SM.getFullFilePos(PPLoc);
155 unsigned RawOffs = SM.getFullFilePos(RawTok.getLocation());
156
157 // If the offsets are the same and the token kind is the same, ignore them.
158 if (PPOffs == RawOffs && isSameToken(RawTok, PPTok)) {
Chris Lattner0d76fcd2008-07-25 16:29:12 +0000159 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
Chris Lattnerec921562008-05-10 00:02:33 +0000160 PP.Lex(PPTok);
161 continue;
162 }
163
164 // If the PP token is farther along than the raw token, something was
165 // deleted. Comment out the raw token.
166 if (RawOffs <= PPOffs) {
167 // Comment out a whole run of tokens instead of bracketing each one with
Chris Lattner1a787352008-06-03 06:10:17 +0000168 // comments. Add a leading space if RawTok didn't have one.
169 bool HasSpace = RawTok.hasLeadingSpace();
170 RB.InsertTextAfter(RawOffs, " /*"+HasSpace, 2+!HasSpace);
Chris Lattnerec921562008-05-10 00:02:33 +0000171 unsigned EndPos;
172
Chris Lattnerec921562008-05-10 00:02:33 +0000173 do {
174 EndPos = RawOffs+RawTok.getLength();
175
Chris Lattner0d76fcd2008-07-25 16:29:12 +0000176 RawTok = GetNextRawTok(RawTokens, CurRawTok, true);
Chris Lattnerec921562008-05-10 00:02:33 +0000177 RawOffs = SM.getFullFilePos(RawTok.getLocation());
178
179 if (RawTok.is(tok::comment)) {
Chris Lattnerec921562008-05-10 00:02:33 +0000180 // Skip past the comment.
Chris Lattner0d76fcd2008-07-25 16:29:12 +0000181 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
Chris Lattnerec921562008-05-10 00:02:33 +0000182 break;
183 }
184
185 } while (RawOffs <= PPOffs && !RawTok.isAtStartOfLine() &&
186 (PPOffs != RawOffs || !isSameToken(RawTok, PPTok)));
Chris Lattnerec921562008-05-10 00:02:33 +0000187
188 RB.InsertTextBefore(EndPos, "*/", 2);
189 continue;
190 }
191
192 // Otherwise, there was a replacement an expansion. Insert the new token
193 // in the output buffer. Insert the whole run of new tokens at once to get
194 // them in the right order.
195 unsigned InsertPos = PPOffs;
196 std::string Expansion;
197 while (PPOffs < RawOffs) {
198 Expansion += ' ' + PP.getSpelling(PPTok);
199 PP.Lex(PPTok);
200 PPLoc = SM.getLogicalLoc(PPTok.getLocation());
201 PPOffs = SM.getFullFilePos(PPLoc);
202 }
203 Expansion += ' ';
204 RB.InsertTextBefore(InsertPos, &Expansion[0], Expansion.size());
205 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000206
207 // Create the output file.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000208 std::ostream *OutFile;
209 if (OutFileName == "-") {
210 OutFile = llvm::cout.stream();
211 } else if (!OutFileName.empty()) {
212 OutFile = new std::ofstream(OutFileName.c_str(),
213 std::ios_base::binary|std::ios_base::out);
214 } else if (InFileName == "-") {
215 OutFile = llvm::cout.stream();
216 } else {
217 llvm::sys::Path Path(InFileName);
218 Path.eraseSuffix();
219 Path.appendSuffix("cpp");
220 OutFile = new std::ofstream(Path.toString().c_str(),
221 std::ios_base::binary|std::ios_base::out);
222 }
223
224 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
225 // we are done.
226 if (const RewriteBuffer *RewriteBuf =
Chris Lattnerec921562008-05-10 00:02:33 +0000227 Rewrite.getRewriteBufferFor(SM.getMainFileID())) {
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000228 //printf("Changed:\n");
229 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
230 } else {
231 fprintf(stderr, "No changes\n");
232 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000233}