blob: f857fd63b683b58e32586eed37e25be3bb789bee [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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/PPCallbacks.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Lex/Pragma.h"
19#include "clang/Basic/SourceManager.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Config/config.h"
23#include <cstdio>
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
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
100static llvm::cl::opt<bool>
101DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
102static llvm::cl::opt<bool>
103EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
104static llvm::cl::opt<bool>
105EnableMacroCommentOutput("CC",
106 llvm::cl::desc("Enable comment output in -E mode, "
107 "even from macro expansions"));
108
109namespace {
110class PrintPPOutputPPCallbacks : public PPCallbacks {
111 Preprocessor &PP;
112 unsigned CurLine;
113 std::string CurFilename;
114 bool EmittedTokensOnThisLine;
115 DirectoryLookup::DirType FileType;
116public:
117 PrintPPOutputPPCallbacks(Preprocessor &pp) : PP(pp) {
118 CurLine = 0;
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000119 CurFilename = "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 EmittedTokensOnThisLine = false;
121 FileType = DirectoryLookup::NormalHeaderDir;
122 }
123
124 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
125
126 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
127 DirectoryLookup::DirType FileType);
128 virtual void Ident(SourceLocation Loc, const std::string &str);
129
130
Chris Lattnerd2177732007-07-20 16:59:19 +0000131 void HandleFirstTokOnLine(Token &Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 void MoveToLine(SourceLocation Loc);
Chris Lattnerd2177732007-07-20 16:59:19 +0000133 bool AvoidConcat(const Token &PrevTok, const Token &Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000134};
135}
136
137/// MoveToLine - Move the output to the source line specified by the location
138/// object. We can do this by emitting some number of \n's, or be emitting a
139/// #line directive.
140void PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
141 if (DisableLineMarkers) {
142 if (EmittedTokensOnThisLine) {
143 OutputChar('\n');
144 EmittedTokensOnThisLine = false;
145 }
146 return;
147 }
148
Chris Lattner9dc1f532007-07-20 16:37:10 +0000149 unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000150
151 // If this line is "close enough" to the original line, just print newlines,
152 // otherwise print a #line directive.
153 if (LineNo-CurLine < 8) {
154 unsigned Line = CurLine;
155 for (; Line != LineNo; ++Line)
156 OutputChar('\n');
157 CurLine = Line;
158 } else {
159 if (EmittedTokensOnThisLine) {
160 OutputChar('\n');
161 EmittedTokensOnThisLine = false;
162 }
163
164 CurLine = LineNo;
165
166 OutputChar('#');
167 OutputChar(' ');
168 std::string Num = llvm::utostr_32(LineNo);
169 OutputString(&Num[0], Num.size());
170 OutputChar(' ');
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000171 OutputChar('"');
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 OutputString(&CurFilename[0], CurFilename.size());
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000173 OutputChar('"');
Reid Spencer5f016e22007-07-11 17:01:13 +0000174
175 if (FileType == DirectoryLookup::SystemHeaderDir)
176 OutputString(" 3", 2);
177 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
178 OutputString(" 3 4", 4);
179 OutputChar('\n');
180 }
181}
182
183
184/// FileChanged - Whenever the preprocessor enters or exits a #include file
185/// it invokes this handler. Update our conception of the current source
186/// position.
187void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
188 FileChangeReason Reason,
189 DirectoryLookup::DirType FileType) {
190 if (DisableLineMarkers) return;
191
192 // Unless we are exiting a #include, make sure to skip ahead to the line the
193 // #include directive was at.
194 SourceManager &SourceMgr = PP.getSourceManager();
195 if (Reason == PPCallbacks::EnterFile) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000196 MoveToLine(SourceMgr.getIncludeLoc(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
198 MoveToLine(Loc);
199
200 // TODO GCC emits the # directive for this directive on the line AFTER the
201 // directive and emits a bunch of spaces that aren't needed. Emulate this
202 // strange behavior.
203 }
204
Chris Lattner9dc1f532007-07-20 16:37:10 +0000205 Loc = SourceMgr.getLogicalLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 CurLine = SourceMgr.getLineNumber(Loc);
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000207 CurFilename = Lexer::Stringify(SourceMgr.getSourceName(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 FileType = FileType;
209
210 if (EmittedTokensOnThisLine) {
211 OutputChar('\n');
212 EmittedTokensOnThisLine = false;
213 }
214
Reid Spencer5f016e22007-07-11 17:01:13 +0000215 OutputChar('#');
216 OutputChar(' ');
217 std::string Num = llvm::utostr_32(CurLine);
218 OutputString(&Num[0], Num.size());
219 OutputChar(' ');
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000220 OutputChar('"');
Reid Spencer5f016e22007-07-11 17:01:13 +0000221 OutputString(&CurFilename[0], CurFilename.size());
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000222 OutputChar('"');
Reid Spencer5f016e22007-07-11 17:01:13 +0000223
224 switch (Reason) {
225 case PPCallbacks::EnterFile:
226 OutputString(" 1", 2);
227 break;
228 case PPCallbacks::ExitFile:
229 OutputString(" 2", 2);
230 break;
231 case PPCallbacks::SystemHeaderPragma: break;
232 case PPCallbacks::RenameFile: break;
233 }
234
235 if (FileType == DirectoryLookup::SystemHeaderDir)
236 OutputString(" 3", 2);
237 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
238 OutputString(" 3 4", 4);
239
240 OutputChar('\n');
241}
242
243/// HandleIdent - Handle #ident directives when read by the preprocessor.
244///
245void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
246 MoveToLine(Loc);
247
248 OutputString("#ident ", strlen("#ident "));
249 OutputString(&S[0], S.size());
250 EmittedTokensOnThisLine = true;
251}
252
253/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
254/// is called for the first token on each new line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000255void PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 // Figure out what line we went to and insert the appropriate number of
257 // newline characters.
258 MoveToLine(Tok.getLocation());
259
260 // Print out space characters so that the first token on a line is
261 // indented for easy reading.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000262 const SourceManager &SourceMgr = PP.getSourceManager();
263 unsigned ColNo = SourceMgr.getLogicalColumnNumber(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000264
265 // This hack prevents stuff like:
266 // #define HASH #
267 // HASH define foo bar
268 // From having the # character end up at column 1, which makes it so it
269 // is not handled as a #define next time through the preprocessor if in
270 // -fpreprocessed mode.
271 if (ColNo <= 1 && Tok.getKind() == tok::hash)
272 OutputChar(' ');
273
274 // Otherwise, indent the appropriate number of spaces.
275 for (; ColNo > 1; --ColNo)
276 OutputChar(' ');
277}
278
279namespace {
280struct UnknownPragmaHandler : public PragmaHandler {
281 const char *Prefix;
282 PrintPPOutputPPCallbacks *Callbacks;
283
284 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
285 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000286 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 // Figure out what line we went to and insert the appropriate number of
288 // newline characters.
289 Callbacks->MoveToLine(PragmaTok.getLocation());
290 OutputString(Prefix, strlen(Prefix));
291
292 // Read and print all of the pragma tokens.
293 while (PragmaTok.getKind() != tok::eom) {
294 if (PragmaTok.hasLeadingSpace())
295 OutputChar(' ');
296 std::string TokSpell = PP.getSpelling(PragmaTok);
297 OutputString(&TokSpell[0], TokSpell.size());
298 PP.LexUnexpandedToken(PragmaTok);
299 }
300 OutputChar('\n');
301 }
302};
303} // end anonymous namespace
304
305/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
306/// the two individual tokens to be lexed as a single token, return true (which
307/// causes a space to be printed between them). This allows the output of -E
308/// mode to be lexed to the same token stream as lexing the input directly
309/// would.
310///
311/// This code must conservatively return true if it doesn't want to be 100%
312/// accurate. This will cause the output to include extra space characters, but
313/// the resulting output won't have incorrect concatenations going on. Examples
314/// include "..", which we print with a space between, because we don't want to
315/// track enough to tell "x.." from "...".
Chris Lattnerd2177732007-07-20 16:59:19 +0000316bool PrintPPOutputPPCallbacks::AvoidConcat(const Token &PrevTok,
317 const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 char Buffer[256];
319
320 // If we haven't emitted a token on this line yet, PrevTok isn't useful to
321 // look at and no concatenation could happen anyway.
322 if (!EmittedTokensOnThisLine)
323 return false;
324
325 // Basic algorithm: we look at the first character of the second token, and
326 // determine whether it, if appended to the first token, would form (or would
327 // contribute) to a larger token if concatenated.
328 char FirstChar;
329 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
330 // Avoid spelling identifiers, the most common form of token.
331 FirstChar = II->getName()[0];
332 } else if (Tok.getLength() < 256) {
333 const char *TokPtr = Buffer;
334 PP.getSpelling(Tok, TokPtr);
335 FirstChar = TokPtr[0];
336 } else {
337 FirstChar = PP.getSpelling(Tok)[0];
338 }
339
340 tok::TokenKind PrevKind = PrevTok.getKind();
341 if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
342 PrevKind = tok::identifier;
343
344 switch (PrevKind) {
345 default: return false;
346 case tok::identifier: // id+id or id+number or id+L"foo".
347 return isalnum(FirstChar) || FirstChar == '_';
348 case tok::numeric_constant:
349 return isalnum(FirstChar) || Tok.getKind() == tok::numeric_constant ||
350 FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
351 case tok::period: // ..., .*, .1234
352 return FirstChar == '.' || FirstChar == '*' || isdigit(FirstChar);
353 case tok::amp: // &&, &=
354 return FirstChar == '&' || FirstChar == '=';
355 case tok::plus: // ++, +=
356 return FirstChar == '+' || FirstChar == '=';
357 case tok::minus: // --, ->, -=, ->*
358 return FirstChar == '-' || FirstChar == '>' || FirstChar == '=';
359 case tok::slash: // /=, /*, //
360 return FirstChar == '=' || FirstChar == '*' || FirstChar == '/';
361 case tok::less: // <<, <<=, <=, <?=, <?, <:, <%
362 return FirstChar == '<' || FirstChar == '?' || FirstChar == '=' ||
363 FirstChar == ':' || FirstChar == '%';
Chris Lattner349b42a2007-07-22 22:33:25 +0000364 case tok::greater: // >>, >=, >>=, >?=, >?
365 return FirstChar == '>' || FirstChar == '?' || FirstChar == '=';
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 case tok::pipe: // ||, |=
367 return FirstChar == '|' || FirstChar == '=';
368 case tok::percent: // %=, %>, %:
369 return FirstChar == '=' || FirstChar == '>' || FirstChar == ':';
370 case tok::colon: // ::, :>
371 return FirstChar == ':' || FirstChar == '>';
372 case tok::hash: // ##, #@, %:%:
373 return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
374 case tok::arrow: // ->*
375 return FirstChar == '*';
376
377 case tok::star: // *=
378 case tok::exclaim: // !=
379 case tok::lessless: // <<=
380 case tok::greaterequal: // >>=
381 case tok::caret: // ^=
382 case tok::equal: // ==
383 // Cases that concatenate only if the next char is =.
384 return FirstChar == '=';
385 }
386}
387
388/// DoPrintPreprocessedInput - This implements -E mode.
389///
390void clang::DoPrintPreprocessedInput(unsigned MainFileID, Preprocessor &PP,
391 const LangOptions &Options) {
392 // Inform the preprocessor whether we want it to retain comments or not, due
393 // to -C or -CC.
394 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
395
396 InitOutputBuffer();
397
Chris Lattnerd2177732007-07-20 16:59:19 +0000398 Token Tok, PrevTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 char Buffer[256];
400 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(PP);
401 PP.setPPCallbacks(Callbacks);
402
403 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
404 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
405
406 // After we have configured the preprocessor, enter the main file.
407
408 // Start parsing the specified input file.
409 PP.EnterSourceFile(MainFileID, 0, true);
410
411 do {
412 PrevTok = Tok;
413 PP.Lex(Tok);
414
415 // If this token is at the start of a line, emit newlines if needed.
416 if (Tok.isAtStartOfLine()) {
417 Callbacks->HandleFirstTokOnLine(Tok);
418 } else if (Tok.hasLeadingSpace() ||
419 // Don't print "-" next to "-", it would form "--".
420 Callbacks->AvoidConcat(PrevTok, Tok)) {
421 OutputChar(' ');
422 }
423
424 if (Tok.getLength() < 256) {
425 const char *TokPtr = Buffer;
426 unsigned Len = PP.getSpelling(Tok, TokPtr);
427 OutputString(TokPtr, Len);
428 } else {
429 std::string S = PP.getSpelling(Tok);
430 OutputString(&S[0], S.size());
431 }
432 Callbacks->SetEmittedTokensOnThisLine();
433 } while (Tok.getKind() != tok::eof);
434 OutputChar('\n');
435
436 CleanupOutputBuffer();
437}
438