blob: 4a4f6783da36003623c88d5ce25c807c98a5c247 [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;
119 CurFilename = "\"<uninit>\"";
120 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
131 void HandleFirstTokOnLine(LexerToken &Tok);
132 void MoveToLine(SourceLocation Loc);
133 bool AvoidConcat(const LexerToken &PrevTok, const LexerToken &Tok);
134};
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
149 unsigned LineNo = PP.getSourceManager().getLineNumber(Loc);
150
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(' ');
171 OutputString(&CurFilename[0], CurFilename.size());
172
173 if (FileType == DirectoryLookup::SystemHeaderDir)
174 OutputString(" 3", 2);
175 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
176 OutputString(" 3 4", 4);
177 OutputChar('\n');
178 }
179}
180
181
182/// FileChanged - Whenever the preprocessor enters or exits a #include file
183/// it invokes this handler. Update our conception of the current source
184/// position.
185void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
186 FileChangeReason Reason,
187 DirectoryLookup::DirType FileType) {
188 if (DisableLineMarkers) return;
189
190 // Unless we are exiting a #include, make sure to skip ahead to the line the
191 // #include directive was at.
192 SourceManager &SourceMgr = PP.getSourceManager();
193 if (Reason == PPCallbacks::EnterFile) {
194 MoveToLine(SourceMgr.getIncludeLoc(Loc.getFileID()));
195 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
196 MoveToLine(Loc);
197
198 // TODO GCC emits the # directive for this directive on the line AFTER the
199 // directive and emits a bunch of spaces that aren't needed. Emulate this
200 // strange behavior.
201 }
202
203 CurLine = SourceMgr.getLineNumber(Loc);
204 CurFilename = '"' + Lexer::Stringify(SourceMgr.getSourceName(Loc)) + '"';
205 FileType = FileType;
206
207 if (EmittedTokensOnThisLine) {
208 OutputChar('\n');
209 EmittedTokensOnThisLine = false;
210 }
211
212 if (DisableLineMarkers) return;
213
214 OutputChar('#');
215 OutputChar(' ');
216 std::string Num = llvm::utostr_32(CurLine);
217 OutputString(&Num[0], Num.size());
218 OutputChar(' ');
219 OutputString(&CurFilename[0], CurFilename.size());
220
221 switch (Reason) {
222 case PPCallbacks::EnterFile:
223 OutputString(" 1", 2);
224 break;
225 case PPCallbacks::ExitFile:
226 OutputString(" 2", 2);
227 break;
228 case PPCallbacks::SystemHeaderPragma: break;
229 case PPCallbacks::RenameFile: break;
230 }
231
232 if (FileType == DirectoryLookup::SystemHeaderDir)
233 OutputString(" 3", 2);
234 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
235 OutputString(" 3 4", 4);
236
237 OutputChar('\n');
238}
239
240/// HandleIdent - Handle #ident directives when read by the preprocessor.
241///
242void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
243 MoveToLine(Loc);
244
245 OutputString("#ident ", strlen("#ident "));
246 OutputString(&S[0], S.size());
247 EmittedTokensOnThisLine = true;
248}
249
250/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
251/// is called for the first token on each new line.
252void PrintPPOutputPPCallbacks::HandleFirstTokOnLine(LexerToken &Tok) {
253 // Figure out what line we went to and insert the appropriate number of
254 // newline characters.
255 MoveToLine(Tok.getLocation());
256
257 // Print out space characters so that the first token on a line is
258 // indented for easy reading.
259 unsigned ColNo =
260 PP.getSourceManager().getColumnNumber(Tok.getLocation());
261
262 // This hack prevents stuff like:
263 // #define HASH #
264 // HASH define foo bar
265 // From having the # character end up at column 1, which makes it so it
266 // is not handled as a #define next time through the preprocessor if in
267 // -fpreprocessed mode.
268 if (ColNo <= 1 && Tok.getKind() == tok::hash)
269 OutputChar(' ');
270
271 // Otherwise, indent the appropriate number of spaces.
272 for (; ColNo > 1; --ColNo)
273 OutputChar(' ');
274}
275
276namespace {
277struct UnknownPragmaHandler : public PragmaHandler {
278 const char *Prefix;
279 PrintPPOutputPPCallbacks *Callbacks;
280
281 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
282 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
283 virtual void HandlePragma(Preprocessor &PP, LexerToken &PragmaTok) {
284 // Figure out what line we went to and insert the appropriate number of
285 // newline characters.
286 Callbacks->MoveToLine(PragmaTok.getLocation());
287 OutputString(Prefix, strlen(Prefix));
288
289 // Read and print all of the pragma tokens.
290 while (PragmaTok.getKind() != tok::eom) {
291 if (PragmaTok.hasLeadingSpace())
292 OutputChar(' ');
293 std::string TokSpell = PP.getSpelling(PragmaTok);
294 OutputString(&TokSpell[0], TokSpell.size());
295 PP.LexUnexpandedToken(PragmaTok);
296 }
297 OutputChar('\n');
298 }
299};
300} // end anonymous namespace
301
302/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
303/// the two individual tokens to be lexed as a single token, return true (which
304/// causes a space to be printed between them). This allows the output of -E
305/// mode to be lexed to the same token stream as lexing the input directly
306/// would.
307///
308/// This code must conservatively return true if it doesn't want to be 100%
309/// accurate. This will cause the output to include extra space characters, but
310/// the resulting output won't have incorrect concatenations going on. Examples
311/// include "..", which we print with a space between, because we don't want to
312/// track enough to tell "x.." from "...".
313bool PrintPPOutputPPCallbacks::AvoidConcat(const LexerToken &PrevTok,
314 const LexerToken &Tok) {
315 char Buffer[256];
316
317 // If we haven't emitted a token on this line yet, PrevTok isn't useful to
318 // look at and no concatenation could happen anyway.
319 if (!EmittedTokensOnThisLine)
320 return false;
321
322 // Basic algorithm: we look at the first character of the second token, and
323 // determine whether it, if appended to the first token, would form (or would
324 // contribute) to a larger token if concatenated.
325 char FirstChar;
326 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
327 // Avoid spelling identifiers, the most common form of token.
328 FirstChar = II->getName()[0];
329 } else if (Tok.getLength() < 256) {
330 const char *TokPtr = Buffer;
331 PP.getSpelling(Tok, TokPtr);
332 FirstChar = TokPtr[0];
333 } else {
334 FirstChar = PP.getSpelling(Tok)[0];
335 }
336
337 tok::TokenKind PrevKind = PrevTok.getKind();
338 if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
339 PrevKind = tok::identifier;
340
341 switch (PrevKind) {
342 default: return false;
343 case tok::identifier: // id+id or id+number or id+L"foo".
344 return isalnum(FirstChar) || FirstChar == '_';
345 case tok::numeric_constant:
346 return isalnum(FirstChar) || Tok.getKind() == tok::numeric_constant ||
347 FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
348 case tok::period: // ..., .*, .1234
349 return FirstChar == '.' || FirstChar == '*' || isdigit(FirstChar);
350 case tok::amp: // &&, &=
351 return FirstChar == '&' || FirstChar == '=';
352 case tok::plus: // ++, +=
353 return FirstChar == '+' || FirstChar == '=';
354 case tok::minus: // --, ->, -=, ->*
355 return FirstChar == '-' || FirstChar == '>' || FirstChar == '=';
356 case tok::slash: // /=, /*, //
357 return FirstChar == '=' || FirstChar == '*' || FirstChar == '/';
358 case tok::less: // <<, <<=, <=, <?=, <?, <:, <%
359 return FirstChar == '<' || FirstChar == '?' || FirstChar == '=' ||
360 FirstChar == ':' || FirstChar == '%';
361 case tok::greater: // >>, >=, >>=, >?=, >?, ->*
362 return FirstChar == '>' || FirstChar == '?' || FirstChar == '=' ||
363 FirstChar == '*';
364 case tok::pipe: // ||, |=
365 return FirstChar == '|' || FirstChar == '=';
366 case tok::percent: // %=, %>, %:
367 return FirstChar == '=' || FirstChar == '>' || FirstChar == ':';
368 case tok::colon: // ::, :>
369 return FirstChar == ':' || FirstChar == '>';
370 case tok::hash: // ##, #@, %:%:
371 return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
372 case tok::arrow: // ->*
373 return FirstChar == '*';
374
375 case tok::star: // *=
376 case tok::exclaim: // !=
377 case tok::lessless: // <<=
378 case tok::greaterequal: // >>=
379 case tok::caret: // ^=
380 case tok::equal: // ==
381 // Cases that concatenate only if the next char is =.
382 return FirstChar == '=';
383 }
384}
385
386/// DoPrintPreprocessedInput - This implements -E mode.
387///
388void clang::DoPrintPreprocessedInput(unsigned MainFileID, Preprocessor &PP,
389 const LangOptions &Options) {
390 // Inform the preprocessor whether we want it to retain comments or not, due
391 // to -C or -CC.
392 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
393
394 InitOutputBuffer();
395
396 LexerToken Tok, PrevTok;
397 char Buffer[256];
398 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(PP);
399 PP.setPPCallbacks(Callbacks);
400
401 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
402 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
403
404 // After we have configured the preprocessor, enter the main file.
405
406 // Start parsing the specified input file.
407 PP.EnterSourceFile(MainFileID, 0, true);
408
409 do {
410 PrevTok = Tok;
411 PP.Lex(Tok);
412
413 // If this token is at the start of a line, emit newlines if needed.
414 if (Tok.isAtStartOfLine()) {
415 Callbacks->HandleFirstTokOnLine(Tok);
416 } else if (Tok.hasLeadingSpace() ||
417 // Don't print "-" next to "-", it would form "--".
418 Callbacks->AvoidConcat(PrevTok, Tok)) {
419 OutputChar(' ');
420 }
421
422 if (Tok.getLength() < 256) {
423 const char *TokPtr = Buffer;
424 unsigned Len = PP.getSpelling(Tok, TokPtr);
425 OutputString(TokPtr, Len);
426 } else {
427 std::string S = PP.getSpelling(Tok);
428 OutputString(&S[0], S.size());
429 }
430 Callbacks->SetEmittedTokensOnThisLine();
431 } while (Tok.getKind() != tok::eof);
432 OutputChar('\n');
433
434 CleanupOutputBuffer();
435}
436