blob: 3eb11b719cf89dc8bd0256158cffe951727ba421 [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"
Chris Lattnerd8e30832007-07-24 06:57:14 +000021#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/ADT/StringExtras.h"
23#include "llvm/Config/config.h"
24#include <cstdio>
25using namespace clang;
26
27//===----------------------------------------------------------------------===//
28// Simple buffered I/O
29//===----------------------------------------------------------------------===//
30//
31// Empirically, iostream is over 30% slower than stdio for this workload, and
32// stdio itself isn't very well suited. The problem with stdio is use of
33// putchar_unlocked. We have many newline characters that need to be emitted,
34// but stdio needs to do extra checks to handle line buffering mode. These
35// extra checks make putchar_unlocked fall off its inlined code path, hitting
36// slow system code. In practice, using 'write' directly makes 'clang -E -P'
37// about 10% faster than using the stdio path on darwin.
38
39#ifdef HAVE_UNISTD_H
40#include <unistd.h>
41#else
42#define USE_STDIO 1
43#endif
44
45static char *OutBufStart = 0, *OutBufEnd, *OutBufCur;
46
47/// InitOutputBuffer - Initialize our output buffer.
48///
49static void InitOutputBuffer() {
50#ifndef USE_STDIO
51 OutBufStart = new char[64*1024];
52 OutBufEnd = OutBufStart+64*1024;
53 OutBufCur = OutBufStart;
54#endif
55}
56
57/// FlushBuffer - Write the accumulated bytes to the output stream.
58///
59static void FlushBuffer() {
60#ifndef USE_STDIO
61 write(STDOUT_FILENO, OutBufStart, OutBufCur-OutBufStart);
62 OutBufCur = OutBufStart;
63#endif
64}
65
66/// CleanupOutputBuffer - Finish up output.
67///
68static void CleanupOutputBuffer() {
69#ifndef USE_STDIO
70 FlushBuffer();
71 delete [] OutBufStart;
72#endif
73}
74
75static void OutputChar(char c) {
76#ifdef USE_STDIO
77 putchar_unlocked(c);
78#else
79 if (OutBufCur >= OutBufEnd)
80 FlushBuffer();
81 *OutBufCur++ = c;
82#endif
83}
84
85static void OutputString(const char *Ptr, unsigned Size) {
86#ifdef USE_STDIO
87 fwrite(Ptr, Size, 1, stdout);
88#else
89 if (OutBufCur+Size >= OutBufEnd)
90 FlushBuffer();
Chris Lattnere225e372007-07-23 06:23:07 +000091
92 switch (Size) {
93 default:
94 memcpy(OutBufCur, Ptr, Size);
95 break;
96 case 3:
97 OutBufCur[2] = Ptr[2];
98 case 2:
99 OutBufCur[1] = Ptr[1];
100 case 1:
101 OutBufCur[0] = Ptr[0];
102 case 0:
103 break;
104 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 OutBufCur += Size;
106#endif
107}
108
109
110//===----------------------------------------------------------------------===//
111// Preprocessed token printer
112//===----------------------------------------------------------------------===//
113
114static llvm::cl::opt<bool>
115DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
116static llvm::cl::opt<bool>
117EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
118static llvm::cl::opt<bool>
119EnableMacroCommentOutput("CC",
120 llvm::cl::desc("Enable comment output in -E mode, "
121 "even from macro expansions"));
122
123namespace {
124class PrintPPOutputPPCallbacks : public PPCallbacks {
125 Preprocessor &PP;
126 unsigned CurLine;
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 bool EmittedTokensOnThisLine;
128 DirectoryLookup::DirType FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000129 llvm::SmallString<512> CurFilename;
Reid Spencer5f016e22007-07-11 17:01:13 +0000130public:
131 PrintPPOutputPPCallbacks(Preprocessor &pp) : PP(pp) {
132 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +0000133 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 EmittedTokensOnThisLine = false;
135 FileType = DirectoryLookup::NormalHeaderDir;
136 }
137
138 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000139 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Reid Spencer5f016e22007-07-11 17:01:13 +0000140
141 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
142 DirectoryLookup::DirType FileType);
143 virtual void Ident(SourceLocation Loc, const std::string &str);
144
145
Chris Lattnerd2177732007-07-20 16:59:19 +0000146 void HandleFirstTokOnLine(Token &Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 void MoveToLine(SourceLocation Loc);
Chris Lattnerd2177732007-07-20 16:59:19 +0000148 bool AvoidConcat(const Token &PrevTok, const Token &Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000149};
150}
151
Chris Lattnerf0637212007-07-23 06:31:11 +0000152/// UToStr - Do itoa on the specified number, in-place in the specified buffer.
153/// endptr points to the end of the buffer.
154static char *UToStr(unsigned N, char *EndPtr) {
155 // Null terminate the buffer.
156 *--EndPtr = '\0';
157 if (N == 0) // Zero is a special case.
158 *--EndPtr = '0';
159 while (N) {
160 *--EndPtr = '0' + char(N % 10);
161 N /= 10;
162 }
163 return EndPtr;
164}
165
166
Reid Spencer5f016e22007-07-11 17:01:13 +0000167/// MoveToLine - Move the output to the source line specified by the location
168/// object. We can do this by emitting some number of \n's, or be emitting a
169/// #line directive.
170void PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
171 if (DisableLineMarkers) {
172 if (EmittedTokensOnThisLine) {
173 OutputChar('\n');
174 EmittedTokensOnThisLine = false;
175 }
176 return;
177 }
178
Chris Lattner9dc1f532007-07-20 16:37:10 +0000179 unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000180
181 // If this line is "close enough" to the original line, just print newlines,
182 // otherwise print a #line directive.
183 if (LineNo-CurLine < 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000184 if (LineNo-CurLine == 1)
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 OutputChar('\n');
Chris Lattner822f9402007-07-23 05:14:05 +0000186 else {
187 const char *NewLines = "\n\n\n\n\n\n\n\n";
188 OutputString(NewLines, LineNo-CurLine);
189 CurLine = LineNo;
190 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 } else {
192 if (EmittedTokensOnThisLine) {
193 OutputChar('\n');
194 EmittedTokensOnThisLine = false;
195 }
196
197 CurLine = LineNo;
198
199 OutputChar('#');
200 OutputChar(' ');
Chris Lattnerf0637212007-07-23 06:31:11 +0000201 char NumberBuffer[20];
202 const char *NumStr = UToStr(LineNo, NumberBuffer+20);
203 OutputString(NumStr, (NumberBuffer+20)-NumStr-1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 OutputChar(' ');
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000205 OutputChar('"');
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 OutputString(&CurFilename[0], CurFilename.size());
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000207 OutputChar('"');
Reid Spencer5f016e22007-07-11 17:01:13 +0000208
209 if (FileType == DirectoryLookup::SystemHeaderDir)
210 OutputString(" 3", 2);
211 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
212 OutputString(" 3 4", 4);
213 OutputChar('\n');
214 }
215}
216
217
218/// FileChanged - Whenever the preprocessor enters or exits a #include file
219/// it invokes this handler. Update our conception of the current source
220/// position.
221void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
222 FileChangeReason Reason,
223 DirectoryLookup::DirType FileType) {
224 if (DisableLineMarkers) return;
225
226 // Unless we are exiting a #include, make sure to skip ahead to the line the
227 // #include directive was at.
228 SourceManager &SourceMgr = PP.getSourceManager();
229 if (Reason == PPCallbacks::EnterFile) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000230 MoveToLine(SourceMgr.getIncludeLoc(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
232 MoveToLine(Loc);
233
234 // TODO GCC emits the # directive for this directive on the line AFTER the
235 // directive and emits a bunch of spaces that aren't needed. Emulate this
236 // strange behavior.
237 }
238
Chris Lattner9dc1f532007-07-20 16:37:10 +0000239 Loc = SourceMgr.getLogicalLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 CurLine = SourceMgr.getLineNumber(Loc);
Chris Lattnerd8e30832007-07-24 06:57:14 +0000241 CurFilename.clear();
242 CurFilename += SourceMgr.getSourceName(Loc);
243 Lexer::Stringify(CurFilename);
Reid Spencer5f016e22007-07-11 17:01:13 +0000244 FileType = FileType;
245
246 if (EmittedTokensOnThisLine) {
247 OutputChar('\n');
248 EmittedTokensOnThisLine = false;
249 }
250
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 OutputChar('#');
252 OutputChar(' ');
Chris Lattner51431962007-07-24 06:59:01 +0000253
254 char NumberBuffer[20];
255 const char *NumStr = UToStr(CurLine, NumberBuffer+20);
256 OutputString(NumStr, (NumberBuffer+20)-NumStr-1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 OutputChar(' ');
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000258 OutputChar('"');
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 OutputString(&CurFilename[0], CurFilename.size());
Chris Lattner0cbc4b52007-07-22 06:38:50 +0000260 OutputChar('"');
Reid Spencer5f016e22007-07-11 17:01:13 +0000261
262 switch (Reason) {
263 case PPCallbacks::EnterFile:
264 OutputString(" 1", 2);
265 break;
266 case PPCallbacks::ExitFile:
267 OutputString(" 2", 2);
268 break;
269 case PPCallbacks::SystemHeaderPragma: break;
270 case PPCallbacks::RenameFile: break;
271 }
272
273 if (FileType == DirectoryLookup::SystemHeaderDir)
274 OutputString(" 3", 2);
275 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
276 OutputString(" 3 4", 4);
277
278 OutputChar('\n');
279}
280
281/// HandleIdent - Handle #ident directives when read by the preprocessor.
282///
283void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
284 MoveToLine(Loc);
285
286 OutputString("#ident ", strlen("#ident "));
287 OutputString(&S[0], S.size());
288 EmittedTokensOnThisLine = true;
289}
290
291/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
292/// is called for the first token on each new line.
Chris Lattnerd2177732007-07-20 16:59:19 +0000293void PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 // Figure out what line we went to and insert the appropriate number of
295 // newline characters.
296 MoveToLine(Tok.getLocation());
297
298 // Print out space characters so that the first token on a line is
299 // indented for easy reading.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000300 const SourceManager &SourceMgr = PP.getSourceManager();
301 unsigned ColNo = SourceMgr.getLogicalColumnNumber(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000302
303 // This hack prevents stuff like:
304 // #define HASH #
305 // HASH define foo bar
306 // From having the # character end up at column 1, which makes it so it
307 // is not handled as a #define next time through the preprocessor if in
308 // -fpreprocessed mode.
309 if (ColNo <= 1 && Tok.getKind() == tok::hash)
310 OutputChar(' ');
311
312 // Otherwise, indent the appropriate number of spaces.
313 for (; ColNo > 1; --ColNo)
314 OutputChar(' ');
315}
316
317namespace {
318struct UnknownPragmaHandler : public PragmaHandler {
319 const char *Prefix;
320 PrintPPOutputPPCallbacks *Callbacks;
321
322 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
323 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000324 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 // Figure out what line we went to and insert the appropriate number of
326 // newline characters.
327 Callbacks->MoveToLine(PragmaTok.getLocation());
328 OutputString(Prefix, strlen(Prefix));
329
330 // Read and print all of the pragma tokens.
331 while (PragmaTok.getKind() != tok::eom) {
332 if (PragmaTok.hasLeadingSpace())
333 OutputChar(' ');
334 std::string TokSpell = PP.getSpelling(PragmaTok);
335 OutputString(&TokSpell[0], TokSpell.size());
336 PP.LexUnexpandedToken(PragmaTok);
337 }
338 OutputChar('\n');
339 }
340};
341} // end anonymous namespace
342
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000343
344enum AvoidConcatInfo {
345 /// By default, a token never needs to avoid concatenation. Most tokens (e.g.
346 /// ',', ')', etc) don't cause a problem when concatenated.
347 aci_never_avoid_concat = 0,
348
349 /// aci_custom_firstchar - AvoidConcat contains custom code to handle this
350 /// token's requirements, and it needs to know the first character of the
351 /// token.
352 aci_custom_firstchar = 1,
353
354 /// aci_custom - AvoidConcat contains custom code to handle this token's
355 /// requirements, but it doesn't need to know the first character of the
356 /// token.
357 aci_custom = 2,
358
359 /// aci_avoid_equal - Many tokens cannot be safely followed by an '='
360 /// character. For example, "<<" turns into "<<=" when followed by an =.
361 aci_avoid_equal = 4
362};
363
364/// This array contains information for each token on what action to take when
365/// avoiding concatenation of tokens in the AvoidConcat method.
366static char TokenInfo[tok::NUM_TOKENS];
367
368/// InitAvoidConcatTokenInfo - Tokens that must avoid concatenation should be
369/// marked by this function.
370static void InitAvoidConcatTokenInfo() {
371 // These tokens have custom code in AvoidConcat.
372 TokenInfo[tok::identifier ] |= aci_custom;
373 TokenInfo[tok::numeric_constant] |= aci_custom_firstchar;
374 TokenInfo[tok::period ] |= aci_custom_firstchar;
375 TokenInfo[tok::amp ] |= aci_custom_firstchar;
376 TokenInfo[tok::plus ] |= aci_custom_firstchar;
377 TokenInfo[tok::minus ] |= aci_custom_firstchar;
378 TokenInfo[tok::slash ] |= aci_custom_firstchar;
379 TokenInfo[tok::less ] |= aci_custom_firstchar;
380 TokenInfo[tok::greater ] |= aci_custom_firstchar;
381 TokenInfo[tok::pipe ] |= aci_custom_firstchar;
382 TokenInfo[tok::percent ] |= aci_custom_firstchar;
383 TokenInfo[tok::colon ] |= aci_custom_firstchar;
384 TokenInfo[tok::hash ] |= aci_custom_firstchar;
385 TokenInfo[tok::arrow ] |= aci_custom_firstchar;
386
387 // These tokens change behavior if followed by an '='.
388 TokenInfo[tok::amp ] |= aci_avoid_equal; // &=
389 TokenInfo[tok::plus ] |= aci_avoid_equal; // +=
390 TokenInfo[tok::minus ] |= aci_avoid_equal; // -=
391 TokenInfo[tok::slash ] |= aci_avoid_equal; // /=
392 TokenInfo[tok::less ] |= aci_avoid_equal; // <=
393 TokenInfo[tok::greater ] |= aci_avoid_equal; // >=
394 TokenInfo[tok::pipe ] |= aci_avoid_equal; // |=
395 TokenInfo[tok::percent ] |= aci_avoid_equal; // %=
396 TokenInfo[tok::star ] |= aci_avoid_equal; // *=
397 TokenInfo[tok::exclaim ] |= aci_avoid_equal; // !=
398 TokenInfo[tok::lessless ] |= aci_avoid_equal; // <<=
399 TokenInfo[tok::greaterequal] |= aci_avoid_equal; // >>=
400 TokenInfo[tok::caret ] |= aci_avoid_equal; // ^=
401 TokenInfo[tok::equal ] |= aci_avoid_equal; // ==
402}
403
Reid Spencer5f016e22007-07-11 17:01:13 +0000404/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
405/// the two individual tokens to be lexed as a single token, return true (which
406/// causes a space to be printed between them). This allows the output of -E
407/// mode to be lexed to the same token stream as lexing the input directly
408/// would.
409///
410/// This code must conservatively return true if it doesn't want to be 100%
411/// accurate. This will cause the output to include extra space characters, but
412/// the resulting output won't have incorrect concatenations going on. Examples
413/// include "..", which we print with a space between, because we don't want to
414/// track enough to tell "x.." from "...".
Chris Lattnerd2177732007-07-20 16:59:19 +0000415bool PrintPPOutputPPCallbacks::AvoidConcat(const Token &PrevTok,
416 const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 char Buffer[256];
418
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000419 tok::TokenKind PrevKind = PrevTok.getKind();
420 if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
421 PrevKind = tok::identifier;
422
423 // Look up information on when we should avoid concatenation with prevtok.
424 unsigned ConcatInfo = TokenInfo[PrevKind];
425
426 // If prevtok never causes a problem for anything after it, return quickly.
427 if (ConcatInfo == 0) return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000428
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000429 if (ConcatInfo & aci_avoid_equal) {
430 // If the next token is '=' or '==', avoid concatenation.
431 if (Tok.getKind() == tok::equal ||
432 Tok.getKind() == tok::equalequal)
433 return true;
Chris Lattnerb638a302007-07-23 23:21:34 +0000434 ConcatInfo &= ~aci_avoid_equal;
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000435 }
436
437 if (ConcatInfo == 0) return false;
438
439
440
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 // Basic algorithm: we look at the first character of the second token, and
442 // determine whether it, if appended to the first token, would form (or would
443 // contribute) to a larger token if concatenated.
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000444 char FirstChar = 0;
445 if (ConcatInfo & aci_custom) {
446 // If the token does not need to know the first character, don't get it.
447 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 // Avoid spelling identifiers, the most common form of token.
449 FirstChar = II->getName()[0];
Chris Lattnerb19f5e82007-07-23 05:18:42 +0000450 } else if (!Tok.needsCleaning()) {
451 SourceManager &SrcMgr = PP.getSourceManager();
452 FirstChar =
453 *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 } else if (Tok.getLength() < 256) {
455 const char *TokPtr = Buffer;
456 PP.getSpelling(Tok, TokPtr);
457 FirstChar = TokPtr[0];
458 } else {
459 FirstChar = PP.getSpelling(Tok)[0];
460 }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000461
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 switch (PrevKind) {
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000463 default: assert(0 && "InitAvoidConcatTokenInfo built wrong");
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 case tok::identifier: // id+id or id+number or id+L"foo".
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000465 if (Tok.getKind() == tok::numeric_constant || Tok.getIdentifierInfo() ||
466 Tok.getKind() == tok::wide_string_literal /* ||
467 Tok.getKind() == tok::wide_char_literal*/)
468 return true;
469 if (Tok.getKind() != tok::char_constant)
470 return false;
471
472 // FIXME: need a wide_char_constant!
473 if (!Tok.needsCleaning()) {
474 SourceManager &SrcMgr = PP.getSourceManager();
475 return *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()))
476 == 'L';
477 } else if (Tok.getLength() < 256) {
478 const char *TokPtr = Buffer;
479 PP.getSpelling(Tok, TokPtr);
480 return TokPtr[0] == 'L';
481 } else {
482 return PP.getSpelling(Tok)[0] == 'L';
483 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 case tok::numeric_constant:
485 return isalnum(FirstChar) || Tok.getKind() == tok::numeric_constant ||
486 FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
487 case tok::period: // ..., .*, .1234
488 return FirstChar == '.' || FirstChar == '*' || isdigit(FirstChar);
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000489 case tok::amp: // &&
490 return FirstChar == '&';
491 case tok::plus: // ++
492 return FirstChar == '+';
493 case tok::minus: // --, ->, ->*
494 return FirstChar == '-' || FirstChar == '>';
495 case tok::slash: //, /*, //
496 return FirstChar == '*' || FirstChar == '/';
497 case tok::less: // <<, <<=, <:, <%
498 return FirstChar == '<' || FirstChar == ':' || FirstChar == '%';
499 case tok::greater: // >>, >>=
500 return FirstChar == '>';
501 case tok::pipe: // ||
502 return FirstChar == '|';
503 case tok::percent: // %>, %:
504 return FirstChar == '>' || FirstChar == ':';
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 case tok::colon: // ::, :>
506 return FirstChar == ':' || FirstChar == '>';
507 case tok::hash: // ##, #@, %:%:
508 return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
509 case tok::arrow: // ->*
510 return FirstChar == '*';
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 }
512}
513
514/// DoPrintPreprocessedInput - This implements -E mode.
515///
516void clang::DoPrintPreprocessedInput(unsigned MainFileID, Preprocessor &PP,
517 const LangOptions &Options) {
518 // Inform the preprocessor whether we want it to retain comments or not, due
519 // to -C or -CC.
520 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
521
522 InitOutputBuffer();
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000523 InitAvoidConcatTokenInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +0000524
Chris Lattnerd2177732007-07-20 16:59:19 +0000525 Token Tok, PrevTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 char Buffer[256];
527 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(PP);
528 PP.setPPCallbacks(Callbacks);
529
530 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
531 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
532
533 // After we have configured the preprocessor, enter the main file.
534
535 // Start parsing the specified input file.
536 PP.EnterSourceFile(MainFileID, 0, true);
537
538 do {
539 PrevTok = Tok;
540 PP.Lex(Tok);
541
542 // If this token is at the start of a line, emit newlines if needed.
543 if (Tok.isAtStartOfLine()) {
544 Callbacks->HandleFirstTokOnLine(Tok);
545 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000546 // If we haven't emitted a token on this line yet, PrevTok isn't
547 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000548 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000549 // Don't print "-" next to "-", it would form "--".
550 Callbacks->AvoidConcat(PrevTok, Tok))) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 OutputChar(' ');
552 }
553
Chris Lattner2933f412007-07-23 06:14:36 +0000554 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
555 const char *Str = II->getName();
556 unsigned Len = Tok.needsCleaning() ? strlen(Str) : Tok.getLength();
557 OutputString(Str, Len);
558 } else if (Tok.getLength() < 256) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 const char *TokPtr = Buffer;
560 unsigned Len = PP.getSpelling(Tok, TokPtr);
561 OutputString(TokPtr, Len);
562 } else {
563 std::string S = PP.getSpelling(Tok);
564 OutputString(&S[0], S.size());
565 }
566 Callbacks->SetEmittedTokensOnThisLine();
567 } while (Tok.getKind() != tok::eof);
568 OutputChar('\n');
569
570 CleanupOutputBuffer();
571}
572