blob: dff4411ef2a1bee34219ff92d558e909a5c38b74 [file] [log] [blame]
Chris Lattner09e3cdf2006-07-04 19:04:05 +00001//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This code simply runs the preprocessor on the input file and prints out the
11// result. This is the traditional behavior of the -E option.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang.h"
16#include "clang/Lex/Preprocessor.h"
17#include "clang/Lex/Pragma.h"
18#include "clang/Basic/SourceManager.h"
19#include "llvm/Support/CommandLine.h"
Chris Lattnerf46be6c2006-07-04 22:19:33 +000020#include "llvm/ADT/StringExtras.h"
21#include "llvm/Config/config.h"
Chris Lattnerdeb37012006-07-04 19:24:06 +000022#include <cstdio>
Chris Lattner09e3cdf2006-07-04 19:04:05 +000023using namespace llvm;
24using namespace clang;
25
Chris Lattnerf46be6c2006-07-04 22:19:33 +000026//===----------------------------------------------------------------------===//
27// Simple buffered I/O
28//===----------------------------------------------------------------------===//
29//
30// Empirically, iostream is over 30% slower than stdio for this workload, and
31// stdio itself isn't very well suited. The problem with stdio is use of
32// putchar_unlocked. We have many newline characters that need to be emitted,
33// but stdio needs to do extra checks to handle line buffering mode. These
34// extra checks make putchar_unlocked fall off its inlined code path, hitting
35// slow system code. In practice, using 'write' directly makes 'clang -E -P'
36// about 10% faster than using the stdio path on darwin.
37
38#ifdef HAVE_UNISTD_H
39#include <unistd.h>
40#else
41#define USE_STDIO 1
42#endif
43
44static char *OutBufStart = 0, *OutBufEnd, *OutBufCur;
45
46/// InitOutputBuffer - Initialize our output buffer.
47///
48static void InitOutputBuffer() {
49#ifndef USE_STDIO
50 OutBufStart = new char[64*1024];
51 OutBufEnd = OutBufStart+64*1024;
52 OutBufCur = OutBufStart;
53#endif
54}
55
56/// FlushBuffer - Write the accumulated bytes to the output stream.
57///
58static void FlushBuffer() {
59#ifndef USE_STDIO
60 write(STDOUT_FILENO, OutBufStart, OutBufCur-OutBufStart);
61 OutBufCur = OutBufStart;
62#endif
63}
64
65/// CleanupOutputBuffer - Finish up output.
66///
67static void CleanupOutputBuffer() {
68#ifndef USE_STDIO
69 FlushBuffer();
70 delete [] OutBufStart;
71#endif
72}
73
74static void OutputChar(char c) {
75#ifdef USE_STDIO
76 putchar_unlocked(c);
77#else
78 if (OutBufCur >= OutBufEnd)
79 FlushBuffer();
80 *OutBufCur++ = c;
81#endif
82}
83
84static void OutputString(const char *Ptr, unsigned Size) {
85#ifdef USE_STDIO
86 fwrite(Ptr, Size, 1, stdout);
87#else
88 if (OutBufCur+Size >= OutBufEnd)
89 FlushBuffer();
90 memcpy(OutBufCur, Ptr, Size);
91 OutBufCur += Size;
92#endif
93}
94
95
96//===----------------------------------------------------------------------===//
97// Preprocessed token printer
98//===----------------------------------------------------------------------===//
99
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000100static cl::opt<bool>
101DisableLineMarkers("P", cl::desc("Disable linemarker output in -E mode"));
102
103static unsigned EModeCurLine;
104static std::string EModeCurFilename;
105static Preprocessor *EModePP;
106static bool EmodeEmittedTokensOnThisLine;
107static DirectoryLookup::DirType EmodeFileType =DirectoryLookup::NormalHeaderDir;
108
Chris Lattner728b4dc2006-07-04 21:28:37 +0000109/// MoveToLine - Move the output to the source line specified by the location
110/// object. We can do this by emitting some number of \n's, or be emitting a
111/// #line directive.
Chris Lattner3338ba82006-07-04 21:19:39 +0000112static void MoveToLine(SourceLocation Loc) {
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000113 if (DisableLineMarkers) {
114 if (EmodeEmittedTokensOnThisLine) {
115 OutputChar('\n');
116 EmodeEmittedTokensOnThisLine = false;
117 }
118 return;
119 }
Chris Lattner3338ba82006-07-04 21:19:39 +0000120
121 unsigned LineNo = EModePP->getSourceManager().getLineNumber(Loc);
122
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000123 // If this line is "close enough" to the original line, just print newlines,
124 // otherwise print a #line directive.
125 if (LineNo-EModeCurLine < 8) {
Chris Lattnerdeb37012006-07-04 19:24:06 +0000126 unsigned CurLine = EModeCurLine;
Chris Lattnerdeb37012006-07-04 19:24:06 +0000127 for (; CurLine != LineNo; ++CurLine)
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000128 OutputChar('\n');
Chris Lattnerdeb37012006-07-04 19:24:06 +0000129 EModeCurLine = CurLine;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000130 } else {
131 if (EmodeEmittedTokensOnThisLine) {
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000132 OutputChar('\n');
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000133 EmodeEmittedTokensOnThisLine = false;
134 }
135
136 EModeCurLine = LineNo;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000137
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000138 OutputChar('#');
139 OutputChar(' ');
140 std::string Num = utostr_32(LineNo);
141 OutputString(&Num[0], Num.size());
142 OutputChar(' ');
143 OutputString(&EModeCurFilename[0], EModeCurFilename.size());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000144
145 if (EmodeFileType == DirectoryLookup::SystemHeaderDir)
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000146 OutputString(" 3", 2);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000147 else if (EmodeFileType == DirectoryLookup::ExternCSystemHeaderDir)
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000148 OutputString(" 3 4", 4);
149 OutputChar('\n');
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000150 }
151}
152
153/// HandleFileChange - Whenever the preprocessor enters or exits a #include file
154/// it invokes this handler. Update our conception of the current
155static void HandleFileChange(SourceLocation Loc,
156 Preprocessor::FileChangeReason Reason,
157 DirectoryLookup::DirType FileType) {
Chris Lattner03cbe1f2006-07-04 21:24:33 +0000158 if (DisableLineMarkers) return;
Chris Lattner73b6a2f2006-07-04 19:40:52 +0000159
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000160 // Unless we are exiting a #include, make sure to skip ahead to the line the
161 // #include directive was at.
Chris Lattnerff3f5f42006-07-04 21:25:59 +0000162 SourceManager &SourceMgr = EModePP->getSourceManager();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000163 if (Reason == Preprocessor::EnterFile) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000164 MoveToLine(SourceMgr.getIncludeLoc(Loc.getFileID()));
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000165 } else if (Reason == Preprocessor::SystemHeaderPragma) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000166 MoveToLine(Loc);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000167
168 // TODO GCC emits the # directive for this directive on the line AFTER the
169 // directive and emits a bunch of spaces that aren't needed. Emulate this
170 // strange behavior.
171 }
172
173 EModeCurLine = SourceMgr.getLineNumber(Loc);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000174 EModeCurFilename = '"' + Lexer::Stringify(SourceMgr.getSourceName(Loc)) + '"';
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000175 EmodeFileType = FileType;
176
177 if (EmodeEmittedTokensOnThisLine) {
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000178 OutputChar('\n');
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000179 EmodeEmittedTokensOnThisLine = false;
180 }
181
182 if (DisableLineMarkers) return;
183
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000184 OutputChar('#');
185 OutputChar(' ');
186 std::string Num = utostr_32(EModeCurLine);
187 OutputString(&Num[0], Num.size());
188 OutputChar(' ');
189 OutputString(&EModeCurFilename[0], EModeCurFilename.size());
190
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000191 switch (Reason) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000192 case Preprocessor::EnterFile:
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000193 OutputString(" 1", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000194 break;
195 case Preprocessor::ExitFile:
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000196 OutputString(" 2", 2);
Chris Lattner3338ba82006-07-04 21:19:39 +0000197 break;
198 case Preprocessor::SystemHeaderPragma: break;
199 case Preprocessor::RenameFile: break;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000200 }
201
202 if (FileType == DirectoryLookup::SystemHeaderDir)
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000203 OutputString(" 3", 2);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000204 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000205 OutputString(" 3 4", 4);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000206
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000207 OutputChar('\n');
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000208}
209
Chris Lattner728b4dc2006-07-04 21:28:37 +0000210/// HandleIdent - Handle #ident directives when read by the preprocessor.
211///
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000212static void HandleIdent(SourceLocation Loc, const std::string &Val) {
Chris Lattner3338ba82006-07-04 21:19:39 +0000213 MoveToLine(Loc);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000214
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000215 OutputString("#ident ", strlen("#ident "));
216 OutputString(&Val[0], Val.size());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000217 EmodeEmittedTokensOnThisLine = true;
218}
219
220/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
221/// is called for the first token on each new line.
222static void HandleFirstTokOnLine(LexerToken &Tok, Preprocessor &PP) {
223 // Figure out what line we went to and insert the appropriate number of
224 // newline characters.
Chris Lattner3338ba82006-07-04 21:19:39 +0000225 MoveToLine(Tok.getLocation());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000226
227 // Print out space characters so that the first token on a line is
228 // indented for easy reading.
229 unsigned ColNo =
230 PP.getSourceManager().getColumnNumber(Tok.getLocation());
231
232 // This hack prevents stuff like:
233 // #define HASH #
234 // HASH define foo bar
235 // From having the # character end up at column 1, which makes it so it
236 // is not handled as a #define next time through the preprocessor if in
237 // -fpreprocessed mode.
238 if (ColNo <= 1 && Tok.getKind() == tok::hash)
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000239 OutputChar(' ');
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000240
241 // Otherwise, indent the appropriate number of spaces.
242 for (; ColNo > 1; --ColNo)
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000243 OutputChar(' ');
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000244}
245
Chris Lattner5de858c2006-07-04 19:04:44 +0000246namespace {
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000247struct UnknownPragmaHandler : public PragmaHandler {
248 const char *Prefix;
249 UnknownPragmaHandler(const char *prefix) : PragmaHandler(0), Prefix(prefix) {}
250 virtual void HandlePragma(Preprocessor &PP, LexerToken &PragmaTok) {
251 // Figure out what line we went to and insert the appropriate number of
252 // newline characters.
Chris Lattner3338ba82006-07-04 21:19:39 +0000253 MoveToLine(PragmaTok.getLocation());
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000254 OutputString(Prefix, strlen(Prefix));
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000255
256 // Read and print all of the pragma tokens.
257 while (PragmaTok.getKind() != tok::eom) {
258 if (PragmaTok.hasLeadingSpace())
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000259 OutputChar(' ');
260 std::string TokSpell = PP.getSpelling(PragmaTok);
261 OutputString(&TokSpell[0], TokSpell.size());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000262 PP.LexUnexpandedToken(PragmaTok);
263 }
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000264 OutputChar('\n');
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000265 }
266};
Chris Lattner5de858c2006-07-04 19:04:44 +0000267} // end anonymous namespace
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000268
Chris Lattner331ad772006-07-28 06:56:01 +0000269/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
270/// the two individual tokens to be lexed as a single token, return true (which
271/// causes a space to be printed between them). This allows the output of -E
272/// mode to be lexed to the same token stream as lexing the input directly
273/// would.
274///
275/// This code must conservatively return true if it doesn't want to be 100%
276/// accurate. This will cause the output to include extra space characters, but
277/// the resulting output won't have incorrect concatenations going on. Examples
278/// include "..", which we print with a space between, because we don't want to
279/// track enough to tell "x.." from "...".
280static bool AvoidConcat(const LexerToken &PrevTok, const LexerToken &Tok,
281 Preprocessor &PP) {
282 char Buffer[256];
283
284 // If we haven't emitted a token on this line yet, PrevTok isn't useful to
285 // look at and no concatenation could happen anyway.
286 if (!EmodeEmittedTokensOnThisLine)
287 return false;
288
289 // Basic algorithm: we look at the first character of the second token, and
290 // determine whether it, if appended to the first token, would form (or would
291 // contribute) to a larger token if concatenated.
292 char FirstChar;
293 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
294 // Avoid spelling identifiers, the most common form of token.
295 FirstChar = II->getName()[0];
296 } else if (Tok.getLength() < 256) {
297 const char *TokPtr = Buffer;
298 unsigned Len = PP.getSpelling(Tok, TokPtr);
299 FirstChar = TokPtr[0];
300 } else {
301 FirstChar = PP.getSpelling(Tok)[0];
302 }
303
304 tok::TokenKind PrevKind = PrevTok.getKind();
305 if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
306 PrevKind = tok::identifier;
307
308 switch (PrevKind) {
309 default: return false;
310 case tok::identifier: // id+id or id+number or id+L"foo".
311 return isalnum(FirstChar) || FirstChar == '_';
312 case tok::numeric_constant:
313 return isalnum(FirstChar) || Tok.getKind() == tok::numeric_constant ||
314 FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
315 case tok::period: // ..., .*, .1234
316 return FirstChar == '.' || FirstChar == '*' || isdigit(FirstChar);
317 case tok::amp: // &&, &=
318 return FirstChar == '&' || FirstChar == '=';
319 case tok::plus: // ++, +=
320 return FirstChar == '+' || FirstChar == '=';
321 case tok::minus: // --, ->, -=, ->*
322 return FirstChar == '-' || FirstChar == '>' || FirstChar == '=';
323 case tok::slash: // /=, /*, //
324 return FirstChar == '=' || FirstChar == '*' || FirstChar == '/';
325 case tok::less: // <<, <<=, <=, <?=, <?, <:, <%
326 return FirstChar == '<' || FirstChar == '?' || FirstChar == '=' ||
327 FirstChar == ':' || FirstChar == '%';
328 case tok::greater: // >>, >=, >>=, >?=, >?, ->*
329 return FirstChar == '>' || FirstChar == '?' || FirstChar == '=' ||
330 FirstChar == '*';
331 case tok::pipe: // ||, |=
332 return FirstChar == '|' || FirstChar == '=';
333 case tok::percent: // %=, %>, %:
334 return FirstChar == '=' || FirstChar == '>' || FirstChar == ':';
335 case tok::colon: // ::, :>
336 return FirstChar == ':' || FirstChar == '>';
337 case tok::hash: // ##, #@, %:%:
338 return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
339 case tok::question: // <?=, >?=, ??x -> trigraphs.
340 // Have to check for <?= in case <? is disabled.
341 return FirstChar == '?' || FirstChar == '=';
342 case tok::arrow: // ->*
343 return FirstChar == '*';
344
345 case tok::star: // *=
346 case tok::exclaim: // !=
347 case tok::lessless: // <<=
348 case tok::greaterequal: // >>=
349 case tok::caret: // ^=
350 case tok::equal: // ==
351 case tok::lessquestion: // <?=
352 case tok::greaterquestion: // >?=
353 // Cases that concatenate only if the next char is =.
354 return FirstChar == '=';
355 }
356}
357
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000358/// DoPrintPreprocessedInput - This implements -E mode.
Chris Lattner728b4dc2006-07-04 21:28:37 +0000359///
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000360void clang::DoPrintPreprocessedInput(Preprocessor &PP) {
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000361 InitOutputBuffer();
362
Chris Lattner331ad772006-07-28 06:56:01 +0000363 LexerToken Tok, PrevTok;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000364 char Buffer[256];
365 EModeCurLine = 0;
366 EModeCurFilename = "\"<uninit>\"";
367 PP.setFileChangeHandler(HandleFileChange);
368 PP.setIdentHandler(HandleIdent);
369 EModePP = &PP;
370 EmodeEmittedTokensOnThisLine = false;
371
372 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma"));
373 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC"));
374 do {
Chris Lattner331ad772006-07-28 06:56:01 +0000375 PrevTok = Tok;
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000376 PP.Lex(Tok);
377
Chris Lattner67c38482006-07-04 23:24:26 +0000378 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000379 if (Tok.isAtStartOfLine()) {
380 HandleFirstTokOnLine(Tok, PP);
Chris Lattner331ad772006-07-28 06:56:01 +0000381 } else if (Tok.hasLeadingSpace() ||
382 // Don't print "-" next to "-", it would form "--".
383 AvoidConcat(PrevTok, Tok, PP)) {
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000384 OutputChar(' ');
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000385 }
386
387 if (Tok.getLength() < 256) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000388 const char *TokPtr = Buffer;
389 unsigned Len = PP.getSpelling(Tok, TokPtr);
390 OutputString(TokPtr, Len);
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000391 } else {
Chris Lattnerdeb37012006-07-04 19:24:06 +0000392 std::string S = PP.getSpelling(Tok);
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000393 OutputString(&S[0], S.size());
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000394 }
395 EmodeEmittedTokensOnThisLine = true;
396 } while (Tok.getKind() != tok::eof);
Chris Lattnerf46be6c2006-07-04 22:19:33 +0000397 OutputChar('\n');
398
399 CleanupOutputBuffer();
Chris Lattner09e3cdf2006-07-04 19:04:05 +0000400}
401