blob: 68a2f954ed9c1e7b51fd2719a10b8ec03bcace55 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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"
Chris Lattner6619f662008-04-08 04:16:20 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/StringExtras.h"
Chris Lattner6619f662008-04-08 04:16:20 +000023#include "llvm/System/Path.h"
24#include "llvm/Support/CommandLine.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/Config/config.h"
26#include <cstdio>
27using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// Simple buffered I/O
31//===----------------------------------------------------------------------===//
32//
33// Empirically, iostream is over 30% slower than stdio for this workload, and
34// stdio itself isn't very well suited. The problem with stdio is use of
35// putchar_unlocked. We have many newline characters that need to be emitted,
36// but stdio needs to do extra checks to handle line buffering mode. These
37// extra checks make putchar_unlocked fall off its inlined code path, hitting
38// slow system code. In practice, using 'write' directly makes 'clang -E -P'
39// about 10% faster than using the stdio path on darwin.
40
Chris Lattnerefd02a32008-01-27 23:55:11 +000041#if defined(HAVE_UNISTD_H) && defined(HAVE_FCNTL_H)
Chris Lattner4b009652007-07-25 00:24:17 +000042#include <unistd.h>
Chris Lattnerefd02a32008-01-27 23:55:11 +000043#include <fcntl.h>
Chris Lattner4b009652007-07-25 00:24:17 +000044#else
45#define USE_STDIO 1
46#endif
47
Chris Lattner6619f662008-04-08 04:16:20 +000048static std::string OutputFilename;
Chris Lattnerefd02a32008-01-27 23:55:11 +000049#ifdef USE_STDIO
Chris Lattner6619f662008-04-08 04:16:20 +000050static FILE *OutputFILE;
Chris Lattnerefd02a32008-01-27 23:55:11 +000051#else
52static int OutputFD;
Chris Lattner4b009652007-07-25 00:24:17 +000053static char *OutBufStart = 0, *OutBufEnd, *OutBufCur;
Chris Lattnerefd02a32008-01-27 23:55:11 +000054#endif
Chris Lattner4b009652007-07-25 00:24:17 +000055
56/// InitOutputBuffer - Initialize our output buffer.
57///
Chris Lattnerefd02a32008-01-27 23:55:11 +000058static void InitOutputBuffer(const std::string& Output) {
59#ifdef USE_STDIO
60 if (!Output.size() || Output == "-")
61 OutputFILE = stdout;
Chris Lattner6619f662008-04-08 04:16:20 +000062 else {
Chris Lattnerefd02a32008-01-27 23:55:11 +000063 OutputFILE = fopen(Output.c_str(), "w+");
Chris Lattner6619f662008-04-08 04:16:20 +000064 OutputFilename = Output;
65 }
Chris Lattnerefd02a32008-01-27 23:55:11 +000066
67 assert(OutputFILE && "failed to open output file");
68#else
Chris Lattner4b009652007-07-25 00:24:17 +000069 OutBufStart = new char[64*1024];
70 OutBufEnd = OutBufStart+64*1024;
71 OutBufCur = OutBufStart;
Chris Lattnerefd02a32008-01-27 23:55:11 +000072
73 if (!Output.size() || Output == "-")
74 OutputFD = STDOUT_FILENO;
Chris Lattner6619f662008-04-08 04:16:20 +000075 else {
Chris Lattnerefd02a32008-01-27 23:55:11 +000076 OutputFD = open(Output.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
Chris Lattner6619f662008-04-08 04:16:20 +000077 OutputFilename = Output;
78 }
Chris Lattnerefd02a32008-01-27 23:55:11 +000079
80 assert(OutputFD >= 0 && "failed to open output file");
Chris Lattner4b009652007-07-25 00:24:17 +000081#endif
82}
83
Chris Lattnerefd02a32008-01-27 23:55:11 +000084#ifndef USE_STDIO
Chris Lattner4b009652007-07-25 00:24:17 +000085/// FlushBuffer - Write the accumulated bytes to the output stream.
86///
87static void FlushBuffer() {
Chris Lattnerefd02a32008-01-27 23:55:11 +000088 write(OutputFD, OutBufStart, OutBufCur-OutBufStart);
Chris Lattner4b009652007-07-25 00:24:17 +000089 OutBufCur = OutBufStart;
Chris Lattner4b009652007-07-25 00:24:17 +000090}
Chris Lattnerefd02a32008-01-27 23:55:11 +000091#endif
Chris Lattner4b009652007-07-25 00:24:17 +000092
93/// CleanupOutputBuffer - Finish up output.
94///
Chris Lattner6619f662008-04-08 04:16:20 +000095static void CleanupOutputBuffer(bool ErrorOccurred) {
96#ifdef USE_STDIO
97 if (OutputFILE != stdout)
98 fclose(OutputFILE);
99#else
Chris Lattner4b009652007-07-25 00:24:17 +0000100 FlushBuffer();
101 delete [] OutBufStart;
Chris Lattner6619f662008-04-08 04:16:20 +0000102 if (OutputFD != STDOUT_FILENO)
103 close(OutputFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000104#endif
Chris Lattner6619f662008-04-08 04:16:20 +0000105
106 // If an error occurred, remove the output file.
107 if (ErrorOccurred && !OutputFilename.empty())
108 llvm::sys::Path(OutputFilename).eraseFromDisk();
Chris Lattner4b009652007-07-25 00:24:17 +0000109}
110
111static void OutputChar(char c) {
Chris Lattnera09a2c02007-09-03 18:24:56 +0000112#if defined(_MSC_VER)
Chris Lattnerefd02a32008-01-27 23:55:11 +0000113 putc(c, OutputFILE);
Chris Lattnera09a2c02007-09-03 18:24:56 +0000114#elif defined(USE_STDIO)
Chris Lattnerefd02a32008-01-27 23:55:11 +0000115 putc_unlocked(c, OutputFILE);
Chris Lattner4b009652007-07-25 00:24:17 +0000116#else
117 if (OutBufCur >= OutBufEnd)
118 FlushBuffer();
119 *OutBufCur++ = c;
120#endif
121}
122
123static void OutputString(const char *Ptr, unsigned Size) {
124#ifdef USE_STDIO
Chris Lattnerefd02a32008-01-27 23:55:11 +0000125 fwrite(Ptr, Size, 1, OutputFILE);
Chris Lattner4b009652007-07-25 00:24:17 +0000126#else
127 if (OutBufCur+Size >= OutBufEnd)
128 FlushBuffer();
129
130 switch (Size) {
131 default:
132 memcpy(OutBufCur, Ptr, Size);
133 break;
134 case 3:
135 OutBufCur[2] = Ptr[2];
136 case 2:
137 OutBufCur[1] = Ptr[1];
138 case 1:
139 OutBufCur[0] = Ptr[0];
140 case 0:
141 break;
142 }
143 OutBufCur += Size;
144#endif
145}
146
147
148//===----------------------------------------------------------------------===//
149// Preprocessed token printer
150//===----------------------------------------------------------------------===//
151
152static llvm::cl::opt<bool>
153DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
154static llvm::cl::opt<bool>
155EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
156static llvm::cl::opt<bool>
157EnableMacroCommentOutput("CC",
158 llvm::cl::desc("Enable comment output in -E mode, "
159 "even from macro expansions"));
160
161namespace {
162class PrintPPOutputPPCallbacks : public PPCallbacks {
163 Preprocessor &PP;
164 unsigned CurLine;
165 bool EmittedTokensOnThisLine;
166 DirectoryLookup::DirType FileType;
167 llvm::SmallString<512> CurFilename;
168public:
169 PrintPPOutputPPCallbacks(Preprocessor &pp) : PP(pp) {
170 CurLine = 0;
171 CurFilename += "<uninit>";
172 EmittedTokensOnThisLine = false;
173 FileType = DirectoryLookup::NormalHeaderDir;
174 }
175
176 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
177 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
178
179 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
180 DirectoryLookup::DirType FileType);
181 virtual void Ident(SourceLocation Loc, const std::string &str);
182
183
Chris Lattner6c451292007-12-09 21:11:08 +0000184 bool HandleFirstTokOnLine(Token &Tok);
185 bool MoveToLine(SourceLocation Loc);
Chris Lattner4b009652007-07-25 00:24:17 +0000186 bool AvoidConcat(const Token &PrevTok, const Token &Tok);
187};
Chris Lattner6619f662008-04-08 04:16:20 +0000188} // end anonymous namespace
Chris Lattner4b009652007-07-25 00:24:17 +0000189
190/// UToStr - Do itoa on the specified number, in-place in the specified buffer.
191/// endptr points to the end of the buffer.
192static char *UToStr(unsigned N, char *EndPtr) {
193 // Null terminate the buffer.
194 *--EndPtr = '\0';
195 if (N == 0) // Zero is a special case.
196 *--EndPtr = '0';
197 while (N) {
198 *--EndPtr = '0' + char(N % 10);
199 N /= 10;
200 }
201 return EndPtr;
202}
203
204
205/// MoveToLine - Move the output to the source line specified by the location
206/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner6c451292007-12-09 21:11:08 +0000207/// #line directive. This returns false if already at the specified line, true
208/// if some newlines were emitted.
209bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
Chris Lattner4b009652007-07-25 00:24:17 +0000210 if (DisableLineMarkers) {
Chris Lattner6c451292007-12-09 21:11:08 +0000211 unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
212 if (LineNo == CurLine) return false;
213
214 CurLine = LineNo;
215
216 if (!EmittedTokensOnThisLine)
217 return true;
218
219 OutputChar('\n');
220 EmittedTokensOnThisLine = false;
221 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000222 }
223
224 unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
225
226 // If this line is "close enough" to the original line, just print newlines,
227 // otherwise print a #line directive.
228 if (LineNo-CurLine < 8) {
229 if (LineNo-CurLine == 1)
230 OutputChar('\n');
Chris Lattner6c451292007-12-09 21:11:08 +0000231 else if (LineNo == CurLine)
232 return false; // Phys line moved, but logical line didn't.
Chris Lattner4b009652007-07-25 00:24:17 +0000233 else {
234 const char *NewLines = "\n\n\n\n\n\n\n\n";
235 OutputString(NewLines, LineNo-CurLine);
Chris Lattner4b009652007-07-25 00:24:17 +0000236 }
Chris Lattner45ac8172007-12-09 20:45:43 +0000237 CurLine = LineNo;
Chris Lattner4b009652007-07-25 00:24:17 +0000238 } else {
239 if (EmittedTokensOnThisLine) {
240 OutputChar('\n');
241 EmittedTokensOnThisLine = false;
242 }
243
244 CurLine = LineNo;
245
246 OutputChar('#');
247 OutputChar(' ');
248 char NumberBuffer[20];
249 const char *NumStr = UToStr(LineNo, NumberBuffer+20);
250 OutputString(NumStr, (NumberBuffer+20)-NumStr-1);
251 OutputChar(' ');
252 OutputChar('"');
253 OutputString(&CurFilename[0], CurFilename.size());
254 OutputChar('"');
255
256 if (FileType == DirectoryLookup::SystemHeaderDir)
257 OutputString(" 3", 2);
258 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
259 OutputString(" 3 4", 4);
260 OutputChar('\n');
261 }
Chris Lattner6c451292007-12-09 21:11:08 +0000262 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000263}
264
265
266/// FileChanged - Whenever the preprocessor enters or exits a #include file
267/// it invokes this handler. Update our conception of the current source
268/// position.
269void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
270 FileChangeReason Reason,
271 DirectoryLookup::DirType FileType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000272 // Unless we are exiting a #include, make sure to skip ahead to the line the
273 // #include directive was at.
274 SourceManager &SourceMgr = PP.getSourceManager();
275 if (Reason == PPCallbacks::EnterFile) {
276 MoveToLine(SourceMgr.getIncludeLoc(Loc));
277 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
278 MoveToLine(Loc);
279
280 // TODO GCC emits the # directive for this directive on the line AFTER the
281 // directive and emits a bunch of spaces that aren't needed. Emulate this
282 // strange behavior.
283 }
284
285 Loc = SourceMgr.getLogicalLoc(Loc);
286 CurLine = SourceMgr.getLineNumber(Loc);
Chris Lattner6c451292007-12-09 21:11:08 +0000287
288 if (DisableLineMarkers) return;
289
Chris Lattner4b009652007-07-25 00:24:17 +0000290 CurFilename.clear();
291 CurFilename += SourceMgr.getSourceName(Loc);
292 Lexer::Stringify(CurFilename);
293 FileType = FileType;
294
295 if (EmittedTokensOnThisLine) {
296 OutputChar('\n');
297 EmittedTokensOnThisLine = false;
298 }
299
300 OutputChar('#');
301 OutputChar(' ');
302
303 char NumberBuffer[20];
304 const char *NumStr = UToStr(CurLine, NumberBuffer+20);
305 OutputString(NumStr, (NumberBuffer+20)-NumStr-1);
306 OutputChar(' ');
307 OutputChar('"');
308 OutputString(&CurFilename[0], CurFilename.size());
309 OutputChar('"');
310
311 switch (Reason) {
312 case PPCallbacks::EnterFile:
313 OutputString(" 1", 2);
314 break;
315 case PPCallbacks::ExitFile:
316 OutputString(" 2", 2);
317 break;
318 case PPCallbacks::SystemHeaderPragma: break;
319 case PPCallbacks::RenameFile: break;
320 }
321
322 if (FileType == DirectoryLookup::SystemHeaderDir)
323 OutputString(" 3", 2);
324 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
325 OutputString(" 3 4", 4);
326
327 OutputChar('\n');
328}
329
330/// HandleIdent - Handle #ident directives when read by the preprocessor.
331///
332void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
333 MoveToLine(Loc);
334
335 OutputString("#ident ", strlen("#ident "));
336 OutputString(&S[0], S.size());
337 EmittedTokensOnThisLine = true;
338}
339
340/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner6c451292007-12-09 21:11:08 +0000341/// is called for the first token on each new line. If this really is the start
342/// of a new logical line, handle it and return true, otherwise return false.
343/// This may not be the start of a logical line because the "start of line"
344/// marker is set for physical lines, not logical ones.
345bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000346 // Figure out what line we went to and insert the appropriate number of
347 // newline characters.
Chris Lattner6c451292007-12-09 21:11:08 +0000348 if (!MoveToLine(Tok.getLocation()))
349 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000350
351 // Print out space characters so that the first token on a line is
352 // indented for easy reading.
353 const SourceManager &SourceMgr = PP.getSourceManager();
354 unsigned ColNo = SourceMgr.getLogicalColumnNumber(Tok.getLocation());
355
356 // This hack prevents stuff like:
357 // #define HASH #
358 // HASH define foo bar
359 // From having the # character end up at column 1, which makes it so it
360 // is not handled as a #define next time through the preprocessor if in
361 // -fpreprocessed mode.
Chris Lattner3b494152007-10-09 18:03:42 +0000362 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner4b009652007-07-25 00:24:17 +0000363 OutputChar(' ');
364
365 // Otherwise, indent the appropriate number of spaces.
366 for (; ColNo > 1; --ColNo)
367 OutputChar(' ');
Chris Lattner6c451292007-12-09 21:11:08 +0000368
369 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000370}
371
372namespace {
373struct UnknownPragmaHandler : public PragmaHandler {
374 const char *Prefix;
375 PrintPPOutputPPCallbacks *Callbacks;
376
377 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
378 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
379 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
380 // Figure out what line we went to and insert the appropriate number of
381 // newline characters.
382 Callbacks->MoveToLine(PragmaTok.getLocation());
383 OutputString(Prefix, strlen(Prefix));
384
385 // Read and print all of the pragma tokens.
Chris Lattner3b494152007-10-09 18:03:42 +0000386 while (PragmaTok.isNot(tok::eom)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000387 if (PragmaTok.hasLeadingSpace())
388 OutputChar(' ');
389 std::string TokSpell = PP.getSpelling(PragmaTok);
390 OutputString(&TokSpell[0], TokSpell.size());
391 PP.LexUnexpandedToken(PragmaTok);
392 }
393 OutputChar('\n');
394 }
395};
396} // end anonymous namespace
397
398
399enum AvoidConcatInfo {
400 /// By default, a token never needs to avoid concatenation. Most tokens (e.g.
401 /// ',', ')', etc) don't cause a problem when concatenated.
402 aci_never_avoid_concat = 0,
403
404 /// aci_custom_firstchar - AvoidConcat contains custom code to handle this
405 /// token's requirements, and it needs to know the first character of the
406 /// token.
407 aci_custom_firstchar = 1,
408
409 /// aci_custom - AvoidConcat contains custom code to handle this token's
410 /// requirements, but it doesn't need to know the first character of the
411 /// token.
412 aci_custom = 2,
413
414 /// aci_avoid_equal - Many tokens cannot be safely followed by an '='
415 /// character. For example, "<<" turns into "<<=" when followed by an =.
416 aci_avoid_equal = 4
417};
418
419/// This array contains information for each token on what action to take when
420/// avoiding concatenation of tokens in the AvoidConcat method.
421static char TokenInfo[tok::NUM_TOKENS];
422
423/// InitAvoidConcatTokenInfo - Tokens that must avoid concatenation should be
424/// marked by this function.
425static void InitAvoidConcatTokenInfo() {
426 // These tokens have custom code in AvoidConcat.
427 TokenInfo[tok::identifier ] |= aci_custom;
428 TokenInfo[tok::numeric_constant] |= aci_custom_firstchar;
429 TokenInfo[tok::period ] |= aci_custom_firstchar;
430 TokenInfo[tok::amp ] |= aci_custom_firstchar;
431 TokenInfo[tok::plus ] |= aci_custom_firstchar;
432 TokenInfo[tok::minus ] |= aci_custom_firstchar;
433 TokenInfo[tok::slash ] |= aci_custom_firstchar;
434 TokenInfo[tok::less ] |= aci_custom_firstchar;
435 TokenInfo[tok::greater ] |= aci_custom_firstchar;
436 TokenInfo[tok::pipe ] |= aci_custom_firstchar;
437 TokenInfo[tok::percent ] |= aci_custom_firstchar;
438 TokenInfo[tok::colon ] |= aci_custom_firstchar;
439 TokenInfo[tok::hash ] |= aci_custom_firstchar;
440 TokenInfo[tok::arrow ] |= aci_custom_firstchar;
441
442 // These tokens change behavior if followed by an '='.
443 TokenInfo[tok::amp ] |= aci_avoid_equal; // &=
444 TokenInfo[tok::plus ] |= aci_avoid_equal; // +=
445 TokenInfo[tok::minus ] |= aci_avoid_equal; // -=
446 TokenInfo[tok::slash ] |= aci_avoid_equal; // /=
447 TokenInfo[tok::less ] |= aci_avoid_equal; // <=
448 TokenInfo[tok::greater ] |= aci_avoid_equal; // >=
449 TokenInfo[tok::pipe ] |= aci_avoid_equal; // |=
450 TokenInfo[tok::percent ] |= aci_avoid_equal; // %=
451 TokenInfo[tok::star ] |= aci_avoid_equal; // *=
452 TokenInfo[tok::exclaim ] |= aci_avoid_equal; // !=
453 TokenInfo[tok::lessless ] |= aci_avoid_equal; // <<=
454 TokenInfo[tok::greaterequal] |= aci_avoid_equal; // >>=
455 TokenInfo[tok::caret ] |= aci_avoid_equal; // ^=
456 TokenInfo[tok::equal ] |= aci_avoid_equal; // ==
457}
458
Chris Lattnerafa40122008-01-15 05:22:14 +0000459/// StartsWithL - Return true if the spelling of this token starts with 'L'.
Chris Lattner400f0242008-01-15 05:14:19 +0000460static bool StartsWithL(const Token &Tok, Preprocessor &PP) {
Chris Lattner400f0242008-01-15 05:14:19 +0000461 if (!Tok.needsCleaning()) {
462 SourceManager &SrcMgr = PP.getSourceManager();
463 return *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()))
464 == 'L';
465 }
466
467 if (Tok.getLength() < 256) {
Chris Lattnerafa40122008-01-15 05:22:14 +0000468 char Buffer[256];
Chris Lattner400f0242008-01-15 05:14:19 +0000469 const char *TokPtr = Buffer;
470 PP.getSpelling(Tok, TokPtr);
471 return TokPtr[0] == 'L';
472 }
473
474 return PP.getSpelling(Tok)[0] == 'L';
475}
476
Chris Lattnerafa40122008-01-15 05:22:14 +0000477/// IsIdentifierL - Return true if the spelling of this token is literally 'L'.
478static bool IsIdentifierL(const Token &Tok, Preprocessor &PP) {
479 if (!Tok.needsCleaning()) {
480 if (Tok.getLength() != 1)
481 return false;
482 SourceManager &SrcMgr = PP.getSourceManager();
483 return *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()))
484 == 'L';
485 }
486
487 if (Tok.getLength() < 256) {
488 char Buffer[256];
489 const char *TokPtr = Buffer;
490 if (PP.getSpelling(Tok, TokPtr) != 1)
491 return false;
492 return TokPtr[0] == 'L';
493 }
494
495 return PP.getSpelling(Tok) == "L";
496}
497
498
Chris Lattner4b009652007-07-25 00:24:17 +0000499/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
500/// the two individual tokens to be lexed as a single token, return true (which
501/// causes a space to be printed between them). This allows the output of -E
502/// mode to be lexed to the same token stream as lexing the input directly
503/// would.
504///
505/// This code must conservatively return true if it doesn't want to be 100%
506/// accurate. This will cause the output to include extra space characters, but
507/// the resulting output won't have incorrect concatenations going on. Examples
508/// include "..", which we print with a space between, because we don't want to
509/// track enough to tell "x.." from "...".
510bool PrintPPOutputPPCallbacks::AvoidConcat(const Token &PrevTok,
511 const Token &Tok) {
512 char Buffer[256];
513
514 tok::TokenKind PrevKind = PrevTok.getKind();
515 if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
516 PrevKind = tok::identifier;
517
518 // Look up information on when we should avoid concatenation with prevtok.
519 unsigned ConcatInfo = TokenInfo[PrevKind];
520
521 // If prevtok never causes a problem for anything after it, return quickly.
522 if (ConcatInfo == 0) return false;
523
524 if (ConcatInfo & aci_avoid_equal) {
525 // If the next token is '=' or '==', avoid concatenation.
Chris Lattner3b494152007-10-09 18:03:42 +0000526 if (Tok.is(tok::equal) || Tok.is(tok::equalequal))
Chris Lattner4b009652007-07-25 00:24:17 +0000527 return true;
528 ConcatInfo &= ~aci_avoid_equal;
529 }
530
531 if (ConcatInfo == 0) return false;
532
533
534
535 // Basic algorithm: we look at the first character of the second token, and
536 // determine whether it, if appended to the first token, would form (or would
537 // contribute) to a larger token if concatenated.
538 char FirstChar = 0;
539 if (ConcatInfo & aci_custom) {
540 // If the token does not need to know the first character, don't get it.
541 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
542 // Avoid spelling identifiers, the most common form of token.
543 FirstChar = II->getName()[0];
544 } else if (!Tok.needsCleaning()) {
545 SourceManager &SrcMgr = PP.getSourceManager();
546 FirstChar =
547 *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()));
548 } else if (Tok.getLength() < 256) {
549 const char *TokPtr = Buffer;
550 PP.getSpelling(Tok, TokPtr);
551 FirstChar = TokPtr[0];
552 } else {
553 FirstChar = PP.getSpelling(Tok)[0];
554 }
555
556 switch (PrevKind) {
557 default: assert(0 && "InitAvoidConcatTokenInfo built wrong");
558 case tok::identifier: // id+id or id+number or id+L"foo".
Chris Lattner3b494152007-10-09 18:03:42 +0000559 if (Tok.is(tok::numeric_constant) || Tok.getIdentifierInfo() ||
560 Tok.is(tok::wide_string_literal) /* ||
561 Tok.is(tok::wide_char_literal)*/)
Chris Lattner4b009652007-07-25 00:24:17 +0000562 return true;
Chris Lattner400f0242008-01-15 05:14:19 +0000563
564 // If this isn't identifier + string, we're done.
565 if (Tok.isNot(tok::char_constant) && Tok.isNot(tok::string_literal))
Chris Lattner4b009652007-07-25 00:24:17 +0000566 return false;
567
568 // FIXME: need a wide_char_constant!
Chris Lattner400f0242008-01-15 05:14:19 +0000569
570 // If the string was a wide string L"foo" or wide char L'f', it would concat
571 // with the previous identifier into fooL"bar". Avoid this.
572 if (StartsWithL(Tok, PP))
573 return true;
574
Chris Lattnerafa40122008-01-15 05:22:14 +0000575 // Otherwise, this is a narrow character or string. If the *identifier* is
576 // a literal 'L', avoid pasting L "foo" -> L"foo".
577 return IsIdentifierL(PrevTok, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000578 case tok::numeric_constant:
Chris Lattner3b494152007-10-09 18:03:42 +0000579 return isalnum(FirstChar) || Tok.is(tok::numeric_constant) ||
Chris Lattner4b009652007-07-25 00:24:17 +0000580 FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
581 case tok::period: // ..., .*, .1234
582 return FirstChar == '.' || FirstChar == '*' || isdigit(FirstChar);
583 case tok::amp: // &&
584 return FirstChar == '&';
585 case tok::plus: // ++
586 return FirstChar == '+';
587 case tok::minus: // --, ->, ->*
588 return FirstChar == '-' || FirstChar == '>';
589 case tok::slash: //, /*, //
590 return FirstChar == '*' || FirstChar == '/';
591 case tok::less: // <<, <<=, <:, <%
592 return FirstChar == '<' || FirstChar == ':' || FirstChar == '%';
593 case tok::greater: // >>, >>=
594 return FirstChar == '>';
595 case tok::pipe: // ||
596 return FirstChar == '|';
597 case tok::percent: // %>, %:
598 return FirstChar == '>' || FirstChar == ':';
599 case tok::colon: // ::, :>
600 return FirstChar == ':' || FirstChar == '>';
601 case tok::hash: // ##, #@, %:%:
602 return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
603 case tok::arrow: // ->*
604 return FirstChar == '*';
605 }
606}
607
608/// DoPrintPreprocessedInput - This implements -E mode.
609///
Chris Lattner6619f662008-04-08 04:16:20 +0000610void clang::DoPrintPreprocessedInput(Preprocessor &PP,
611 const std::string &OutFile) {
Chris Lattner4b009652007-07-25 00:24:17 +0000612 // Inform the preprocessor whether we want it to retain comments or not, due
613 // to -C or -CC.
614 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
615
Chris Lattnerefd02a32008-01-27 23:55:11 +0000616 InitOutputBuffer(OutFile);
Chris Lattner4b009652007-07-25 00:24:17 +0000617 InitAvoidConcatTokenInfo();
618
619 Token Tok, PrevTok;
620 char Buffer[256];
621 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(PP);
622 PP.setPPCallbacks(Callbacks);
623
624 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
625 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
626
627 // After we have configured the preprocessor, enter the main file.
628
629 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +0000630 PP.EnterMainSourceFile();
Chris Lattner3eddc862007-10-10 20:45:16 +0000631
632 // Consume all of the tokens that come from the predefines buffer. Those
633 // should not be emitted into the output and are guaranteed to be at the
634 // start.
635 const SourceManager &SourceMgr = PP.getSourceManager();
636 do PP.Lex(Tok);
Chris Lattner890c5932007-10-10 23:31:03 +0000637 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
Chris Lattner3eddc862007-10-10 20:45:16 +0000638 !strcmp(SourceMgr.getSourceName(Tok.getLocation()), "<predefines>"));
639
640 while (1) {
Chris Lattner4b009652007-07-25 00:24:17 +0000641
642 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner6c451292007-12-09 21:11:08 +0000643 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
644 // done.
Chris Lattner4b009652007-07-25 00:24:17 +0000645 } else if (Tok.hasLeadingSpace() ||
646 // If we haven't emitted a token on this line yet, PrevTok isn't
647 // useful to look at and no concatenation could happen anyway.
648 (Callbacks->hasEmittedTokensOnThisLine() &&
649 // Don't print "-" next to "-", it would form "--".
650 Callbacks->AvoidConcat(PrevTok, Tok))) {
651 OutputChar(' ');
652 }
653
654 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
655 const char *Str = II->getName();
656 unsigned Len = Tok.needsCleaning() ? strlen(Str) : Tok.getLength();
657 OutputString(Str, Len);
658 } else if (Tok.getLength() < 256) {
659 const char *TokPtr = Buffer;
660 unsigned Len = PP.getSpelling(Tok, TokPtr);
661 OutputString(TokPtr, Len);
662 } else {
663 std::string S = PP.getSpelling(Tok);
664 OutputString(&S[0], S.size());
665 }
666 Callbacks->SetEmittedTokensOnThisLine();
Chris Lattner3eddc862007-10-10 20:45:16 +0000667
668 if (Tok.is(tok::eof)) break;
669
670 PrevTok = Tok;
671 PP.Lex(Tok);
672 }
Chris Lattner4b009652007-07-25 00:24:17 +0000673 OutputChar('\n');
674
Chris Lattner6619f662008-04-08 04:16:20 +0000675 CleanupOutputBuffer(PP.getDiagnostics().hasErrorOccurred());
Chris Lattner4b009652007-07-25 00:24:17 +0000676}
677