blob: 6f5e6baa1635c6fe3dbcabe8d504395e20814552 [file] [log] [blame]
Chris Lattner1665a9f2008-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 Lattner1665a9f2008-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 Lattner3a8c36d2008-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 Lattner3c11e952008-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 Lattner3a8c36d2008-05-10 00:02:33 +000031 return true;
32
Chris Lattner3c11e952008-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 Lattner3a8c36d2008-05-10 00:02:33 +000036 if (PPTok.getIdentifierInfo() &&
37 PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())
38 return true;
39
40 return false;
41}
42
Chris Lattnerb9326c52008-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 Lattner3a8c36d2008-05-10 00:02:33 +000049
Chris Lattnerb9326c52008-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 Lattner3a8c36d2008-05-10 00:02:33 +000055}
56
Chris Lattnerb9326c52008-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 Lattner1665a9f2008-05-08 06:52:13 +000088/// RewriteMacrosInInput - Implement -rewrite-macros mode.
Chris Lattner302b0622008-05-09 22:43:24 +000089void clang::RewriteMacrosInInput(Preprocessor &PP,const std::string &InFileName,
Chris Lattner1665a9f2008-05-08 06:52:13 +000090 const std::string &OutFileName) {
91 SourceManager &SM = PP.getSourceManager();
92
93 Rewriter Rewrite;
94 Rewrite.setSourceMgr(SM);
Chris Lattner3a8c36d2008-05-10 00:02:33 +000095 RewriteBuffer &RB = Rewrite.getEditBuffer(SM.getMainFileID());
Chris Lattner1665a9f2008-05-08 06:52:13 +000096
Chris Lattnerb9326c52008-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 Lattner3a8c36d2008-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
124 // in the input file, but we don't want to treat them as such... just ignore
125 // them.
126 if (RawTok.is(tok::hash) && RawTok.isAtStartOfLine()) {
Chris Lattnerb9326c52008-07-25 16:29:12 +0000127 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000128 while (!RawTok.isAtStartOfLine() && RawTok.isNot(tok::eof))
Chris Lattnerb9326c52008-07-25 16:29:12 +0000129 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000130 continue;
131 }
132
133 // Okay, both tokens are from the same file. Get their offsets from the
134 // start of the file.
135 unsigned PPOffs = SM.getFullFilePos(PPLoc);
136 unsigned RawOffs = SM.getFullFilePos(RawTok.getLocation());
137
138 // If the offsets are the same and the token kind is the same, ignore them.
139 if (PPOffs == RawOffs && isSameToken(RawTok, PPTok)) {
Chris Lattnerb9326c52008-07-25 16:29:12 +0000140 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000141 PP.Lex(PPTok);
142 continue;
143 }
144
145 // If the PP token is farther along than the raw token, something was
146 // deleted. Comment out the raw token.
147 if (RawOffs <= PPOffs) {
148 // Comment out a whole run of tokens instead of bracketing each one with
Chris Lattner460d2372008-06-03 06:10:17 +0000149 // comments. Add a leading space if RawTok didn't have one.
150 bool HasSpace = RawTok.hasLeadingSpace();
151 RB.InsertTextAfter(RawOffs, " /*"+HasSpace, 2+!HasSpace);
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000152 unsigned EndPos;
153
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000154 do {
155 EndPos = RawOffs+RawTok.getLength();
156
Chris Lattnerb9326c52008-07-25 16:29:12 +0000157 RawTok = GetNextRawTok(RawTokens, CurRawTok, true);
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000158 RawOffs = SM.getFullFilePos(RawTok.getLocation());
159
160 if (RawTok.is(tok::comment)) {
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000161 // Skip past the comment.
Chris Lattnerb9326c52008-07-25 16:29:12 +0000162 RawTok = GetNextRawTok(RawTokens, CurRawTok, false);
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000163 break;
164 }
165
166 } while (RawOffs <= PPOffs && !RawTok.isAtStartOfLine() &&
167 (PPOffs != RawOffs || !isSameToken(RawTok, PPTok)));
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000168
169 RB.InsertTextBefore(EndPos, "*/", 2);
170 continue;
171 }
172
173 // Otherwise, there was a replacement an expansion. Insert the new token
174 // in the output buffer. Insert the whole run of new tokens at once to get
175 // them in the right order.
176 unsigned InsertPos = PPOffs;
177 std::string Expansion;
178 while (PPOffs < RawOffs) {
179 Expansion += ' ' + PP.getSpelling(PPTok);
180 PP.Lex(PPTok);
181 PPLoc = SM.getLogicalLoc(PPTok.getLocation());
182 PPOffs = SM.getFullFilePos(PPLoc);
183 }
184 Expansion += ' ';
185 RB.InsertTextBefore(InsertPos, &Expansion[0], Expansion.size());
186 }
Chris Lattner1665a9f2008-05-08 06:52:13 +0000187
188 // Create the output file.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000189 std::ostream *OutFile;
190 if (OutFileName == "-") {
191 OutFile = llvm::cout.stream();
192 } else if (!OutFileName.empty()) {
193 OutFile = new std::ofstream(OutFileName.c_str(),
194 std::ios_base::binary|std::ios_base::out);
195 } else if (InFileName == "-") {
196 OutFile = llvm::cout.stream();
197 } else {
198 llvm::sys::Path Path(InFileName);
199 Path.eraseSuffix();
200 Path.appendSuffix("cpp");
201 OutFile = new std::ofstream(Path.toString().c_str(),
202 std::ios_base::binary|std::ios_base::out);
203 }
204
205 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
206 // we are done.
207 if (const RewriteBuffer *RewriteBuf =
Chris Lattner3a8c36d2008-05-10 00:02:33 +0000208 Rewrite.getRewriteBufferFor(SM.getMainFileID())) {
Chris Lattner1665a9f2008-05-08 06:52:13 +0000209 //printf("Changed:\n");
210 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
211 } else {
212 fprintf(stderr, "No changes\n");
213 }
Chris Lattner1665a9f2008-05-08 06:52:13 +0000214}