blob: 3fe3e40a54c09a68ec26e1f359d01f3a616e11a6 [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"
Chris Lattner93b4f302008-08-17 01:47:12 +000026#include "llvm/Support/raw_ostream.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include <cstdio>
28using namespace clang;
29
Chris Lattner4b009652007-07-25 00:24:17 +000030//===----------------------------------------------------------------------===//
31// Preprocessed token printer
32//===----------------------------------------------------------------------===//
33
34static llvm::cl::opt<bool>
35DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
36static llvm::cl::opt<bool>
37EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
38static llvm::cl::opt<bool>
39EnableMacroCommentOutput("CC",
40 llvm::cl::desc("Enable comment output in -E mode, "
41 "even from macro expansions"));
42
43namespace {
44class PrintPPOutputPPCallbacks : public PPCallbacks {
45 Preprocessor &PP;
Chris Lattner21494222008-08-17 03:12:02 +000046public:
47 llvm::raw_ostream &OS;
48private:
Chris Lattner4b009652007-07-25 00:24:17 +000049 unsigned CurLine;
50 bool EmittedTokensOnThisLine;
51 DirectoryLookup::DirType FileType;
52 llvm::SmallString<512> CurFilename;
53public:
Chris Lattner21494222008-08-17 03:12:02 +000054 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os)
55 : PP(pp), OS(os) {
Chris Lattner4b009652007-07-25 00:24:17 +000056 CurLine = 0;
57 CurFilename += "<uninit>";
58 EmittedTokensOnThisLine = false;
59 FileType = DirectoryLookup::NormalHeaderDir;
60 }
61
62 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
63 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
64
65 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
66 DirectoryLookup::DirType FileType);
67 virtual void Ident(SourceLocation Loc, const std::string &str);
68
69
Chris Lattner6c451292007-12-09 21:11:08 +000070 bool HandleFirstTokOnLine(Token &Tok);
71 bool MoveToLine(SourceLocation Loc);
Chris Lattner4b009652007-07-25 00:24:17 +000072 bool AvoidConcat(const Token &PrevTok, const Token &Tok);
73};
Chris Lattner6619f662008-04-08 04:16:20 +000074} // end anonymous namespace
Chris Lattner4b009652007-07-25 00:24:17 +000075
Chris Lattner4b009652007-07-25 00:24:17 +000076/// MoveToLine - Move the output to the source line specified by the location
77/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner6c451292007-12-09 21:11:08 +000078/// #line directive. This returns false if already at the specified line, true
79/// if some newlines were emitted.
80bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
Chris Lattner4b009652007-07-25 00:24:17 +000081 if (DisableLineMarkers) {
Chris Lattner6c451292007-12-09 21:11:08 +000082 unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
83 if (LineNo == CurLine) return false;
84
85 CurLine = LineNo;
86
87 if (!EmittedTokensOnThisLine)
88 return true;
89
Chris Lattner21494222008-08-17 03:12:02 +000090 OS << '\n';
Chris Lattner6c451292007-12-09 21:11:08 +000091 EmittedTokensOnThisLine = false;
92 return true;
Chris Lattner4b009652007-07-25 00:24:17 +000093 }
94
95 unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
96
97 // If this line is "close enough" to the original line, just print newlines,
98 // otherwise print a #line directive.
99 if (LineNo-CurLine < 8) {
100 if (LineNo-CurLine == 1)
Chris Lattner21494222008-08-17 03:12:02 +0000101 OS << '\n';
Chris Lattner6c451292007-12-09 21:11:08 +0000102 else if (LineNo == CurLine)
103 return false; // Phys line moved, but logical line didn't.
Chris Lattner4b009652007-07-25 00:24:17 +0000104 else {
105 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattner21494222008-08-17 03:12:02 +0000106 OS.write(NewLines, LineNo-CurLine);
Chris Lattner4b009652007-07-25 00:24:17 +0000107 }
Chris Lattner45ac8172007-12-09 20:45:43 +0000108 CurLine = LineNo;
Chris Lattner4b009652007-07-25 00:24:17 +0000109 } else {
110 if (EmittedTokensOnThisLine) {
Chris Lattner21494222008-08-17 03:12:02 +0000111 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000112 EmittedTokensOnThisLine = false;
113 }
114
115 CurLine = LineNo;
116
Chris Lattner36882512008-08-19 04:23:15 +0000117 OS << '#' << ' ' << LineNo << ' ' << '"';
Chris Lattner21494222008-08-17 03:12:02 +0000118 OS.write(&CurFilename[0], CurFilename.size());
119 OS << '"';
Chris Lattner4b009652007-07-25 00:24:17 +0000120
121 if (FileType == DirectoryLookup::SystemHeaderDir)
Chris Lattner21494222008-08-17 03:12:02 +0000122 OS.write(" 3", 2);
Chris Lattner4b009652007-07-25 00:24:17 +0000123 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
Chris Lattner21494222008-08-17 03:12:02 +0000124 OS.write(" 3 4", 4);
125 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000126 }
Chris Lattner6c451292007-12-09 21:11:08 +0000127 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000128}
129
130
131/// FileChanged - Whenever the preprocessor enters or exits a #include file
132/// it invokes this handler. Update our conception of the current source
133/// position.
134void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
135 FileChangeReason Reason,
136 DirectoryLookup::DirType FileType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000137 // Unless we are exiting a #include, make sure to skip ahead to the line the
138 // #include directive was at.
139 SourceManager &SourceMgr = PP.getSourceManager();
140 if (Reason == PPCallbacks::EnterFile) {
141 MoveToLine(SourceMgr.getIncludeLoc(Loc));
142 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
143 MoveToLine(Loc);
144
145 // TODO GCC emits the # directive for this directive on the line AFTER the
146 // directive and emits a bunch of spaces that aren't needed. Emulate this
147 // strange behavior.
148 }
149
150 Loc = SourceMgr.getLogicalLoc(Loc);
151 CurLine = SourceMgr.getLineNumber(Loc);
Chris Lattner6c451292007-12-09 21:11:08 +0000152
153 if (DisableLineMarkers) return;
154
Chris Lattner4b009652007-07-25 00:24:17 +0000155 CurFilename.clear();
156 CurFilename += SourceMgr.getSourceName(Loc);
157 Lexer::Stringify(CurFilename);
158 FileType = FileType;
159
160 if (EmittedTokensOnThisLine) {
Chris Lattner21494222008-08-17 03:12:02 +0000161 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000162 EmittedTokensOnThisLine = false;
163 }
164
Chris Lattner36882512008-08-19 04:23:15 +0000165 OS << '#' << ' ' << CurLine << ' ' << '"';
Chris Lattner21494222008-08-17 03:12:02 +0000166 OS.write(&CurFilename[0], CurFilename.size());
167 OS << '"';
Chris Lattner4b009652007-07-25 00:24:17 +0000168
169 switch (Reason) {
170 case PPCallbacks::EnterFile:
Chris Lattner21494222008-08-17 03:12:02 +0000171 OS.write(" 1", 2);
Chris Lattner4b009652007-07-25 00:24:17 +0000172 break;
173 case PPCallbacks::ExitFile:
Chris Lattner21494222008-08-17 03:12:02 +0000174 OS.write(" 2", 2);
Chris Lattner4b009652007-07-25 00:24:17 +0000175 break;
176 case PPCallbacks::SystemHeaderPragma: break;
177 case PPCallbacks::RenameFile: break;
178 }
179
180 if (FileType == DirectoryLookup::SystemHeaderDir)
Chris Lattner21494222008-08-17 03:12:02 +0000181 OS.write(" 3", 2);
Chris Lattner4b009652007-07-25 00:24:17 +0000182 else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
Chris Lattner21494222008-08-17 03:12:02 +0000183 OS.write(" 3 4", 4);
Chris Lattner4b009652007-07-25 00:24:17 +0000184
Chris Lattner21494222008-08-17 03:12:02 +0000185 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000186}
187
188/// HandleIdent - Handle #ident directives when read by the preprocessor.
189///
190void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
191 MoveToLine(Loc);
192
Chris Lattner21494222008-08-17 03:12:02 +0000193 OS.write("#ident ", strlen("#ident "));
194 OS.write(&S[0], S.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000195 EmittedTokensOnThisLine = true;
196}
197
198/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner6c451292007-12-09 21:11:08 +0000199/// is called for the first token on each new line. If this really is the start
200/// of a new logical line, handle it and return true, otherwise return false.
201/// This may not be the start of a logical line because the "start of line"
202/// marker is set for physical lines, not logical ones.
203bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000204 // Figure out what line we went to and insert the appropriate number of
205 // newline characters.
Chris Lattner6c451292007-12-09 21:11:08 +0000206 if (!MoveToLine(Tok.getLocation()))
207 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000208
209 // Print out space characters so that the first token on a line is
210 // indented for easy reading.
211 const SourceManager &SourceMgr = PP.getSourceManager();
212 unsigned ColNo = SourceMgr.getLogicalColumnNumber(Tok.getLocation());
213
214 // This hack prevents stuff like:
215 // #define HASH #
216 // HASH define foo bar
217 // From having the # character end up at column 1, which makes it so it
218 // is not handled as a #define next time through the preprocessor if in
219 // -fpreprocessed mode.
Chris Lattner3b494152007-10-09 18:03:42 +0000220 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattner21494222008-08-17 03:12:02 +0000221 OS << ' ';
Chris Lattner4b009652007-07-25 00:24:17 +0000222
223 // Otherwise, indent the appropriate number of spaces.
224 for (; ColNo > 1; --ColNo)
Chris Lattner21494222008-08-17 03:12:02 +0000225 OS << ' ';
Chris Lattner6c451292007-12-09 21:11:08 +0000226
227 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000228}
229
230namespace {
231struct UnknownPragmaHandler : public PragmaHandler {
232 const char *Prefix;
233 PrintPPOutputPPCallbacks *Callbacks;
234
235 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
236 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
237 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
238 // Figure out what line we went to and insert the appropriate number of
239 // newline characters.
240 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattner21494222008-08-17 03:12:02 +0000241 Callbacks->OS.write(Prefix, strlen(Prefix));
Chris Lattner4b009652007-07-25 00:24:17 +0000242
243 // Read and print all of the pragma tokens.
Chris Lattner3b494152007-10-09 18:03:42 +0000244 while (PragmaTok.isNot(tok::eom)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000245 if (PragmaTok.hasLeadingSpace())
Chris Lattner21494222008-08-17 03:12:02 +0000246 Callbacks->OS << ' ';
Chris Lattner4b009652007-07-25 00:24:17 +0000247 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattner21494222008-08-17 03:12:02 +0000248 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000249 PP.LexUnexpandedToken(PragmaTok);
250 }
Chris Lattner21494222008-08-17 03:12:02 +0000251 Callbacks->OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000252 }
253};
254} // end anonymous namespace
255
256
257enum AvoidConcatInfo {
258 /// By default, a token never needs to avoid concatenation. Most tokens (e.g.
259 /// ',', ')', etc) don't cause a problem when concatenated.
260 aci_never_avoid_concat = 0,
261
262 /// aci_custom_firstchar - AvoidConcat contains custom code to handle this
263 /// token's requirements, and it needs to know the first character of the
264 /// token.
265 aci_custom_firstchar = 1,
266
267 /// aci_custom - AvoidConcat contains custom code to handle this token's
268 /// requirements, but it doesn't need to know the first character of the
269 /// token.
270 aci_custom = 2,
271
272 /// aci_avoid_equal - Many tokens cannot be safely followed by an '='
273 /// character. For example, "<<" turns into "<<=" when followed by an =.
274 aci_avoid_equal = 4
275};
276
277/// This array contains information for each token on what action to take when
278/// avoiding concatenation of tokens in the AvoidConcat method.
279static char TokenInfo[tok::NUM_TOKENS];
280
281/// InitAvoidConcatTokenInfo - Tokens that must avoid concatenation should be
282/// marked by this function.
283static void InitAvoidConcatTokenInfo() {
284 // These tokens have custom code in AvoidConcat.
285 TokenInfo[tok::identifier ] |= aci_custom;
286 TokenInfo[tok::numeric_constant] |= aci_custom_firstchar;
287 TokenInfo[tok::period ] |= aci_custom_firstchar;
288 TokenInfo[tok::amp ] |= aci_custom_firstchar;
289 TokenInfo[tok::plus ] |= aci_custom_firstchar;
290 TokenInfo[tok::minus ] |= aci_custom_firstchar;
291 TokenInfo[tok::slash ] |= aci_custom_firstchar;
292 TokenInfo[tok::less ] |= aci_custom_firstchar;
293 TokenInfo[tok::greater ] |= aci_custom_firstchar;
294 TokenInfo[tok::pipe ] |= aci_custom_firstchar;
295 TokenInfo[tok::percent ] |= aci_custom_firstchar;
296 TokenInfo[tok::colon ] |= aci_custom_firstchar;
297 TokenInfo[tok::hash ] |= aci_custom_firstchar;
298 TokenInfo[tok::arrow ] |= aci_custom_firstchar;
299
300 // These tokens change behavior if followed by an '='.
301 TokenInfo[tok::amp ] |= aci_avoid_equal; // &=
302 TokenInfo[tok::plus ] |= aci_avoid_equal; // +=
303 TokenInfo[tok::minus ] |= aci_avoid_equal; // -=
304 TokenInfo[tok::slash ] |= aci_avoid_equal; // /=
305 TokenInfo[tok::less ] |= aci_avoid_equal; // <=
306 TokenInfo[tok::greater ] |= aci_avoid_equal; // >=
307 TokenInfo[tok::pipe ] |= aci_avoid_equal; // |=
308 TokenInfo[tok::percent ] |= aci_avoid_equal; // %=
309 TokenInfo[tok::star ] |= aci_avoid_equal; // *=
310 TokenInfo[tok::exclaim ] |= aci_avoid_equal; // !=
311 TokenInfo[tok::lessless ] |= aci_avoid_equal; // <<=
312 TokenInfo[tok::greaterequal] |= aci_avoid_equal; // >>=
313 TokenInfo[tok::caret ] |= aci_avoid_equal; // ^=
314 TokenInfo[tok::equal ] |= aci_avoid_equal; // ==
315}
316
Chris Lattnerafa40122008-01-15 05:22:14 +0000317/// StartsWithL - Return true if the spelling of this token starts with 'L'.
Chris Lattner400f0242008-01-15 05:14:19 +0000318static bool StartsWithL(const Token &Tok, Preprocessor &PP) {
Chris Lattner400f0242008-01-15 05:14:19 +0000319 if (!Tok.needsCleaning()) {
320 SourceManager &SrcMgr = PP.getSourceManager();
321 return *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()))
322 == 'L';
323 }
324
325 if (Tok.getLength() < 256) {
Chris Lattnerafa40122008-01-15 05:22:14 +0000326 char Buffer[256];
Chris Lattner400f0242008-01-15 05:14:19 +0000327 const char *TokPtr = Buffer;
328 PP.getSpelling(Tok, TokPtr);
329 return TokPtr[0] == 'L';
330 }
331
332 return PP.getSpelling(Tok)[0] == 'L';
333}
334
Chris Lattnerafa40122008-01-15 05:22:14 +0000335/// IsIdentifierL - Return true if the spelling of this token is literally 'L'.
336static bool IsIdentifierL(const Token &Tok, Preprocessor &PP) {
337 if (!Tok.needsCleaning()) {
338 if (Tok.getLength() != 1)
339 return false;
340 SourceManager &SrcMgr = PP.getSourceManager();
341 return *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()))
342 == 'L';
343 }
344
345 if (Tok.getLength() < 256) {
346 char Buffer[256];
347 const char *TokPtr = Buffer;
348 if (PP.getSpelling(Tok, TokPtr) != 1)
349 return false;
350 return TokPtr[0] == 'L';
351 }
352
353 return PP.getSpelling(Tok) == "L";
354}
355
356
Chris Lattner4b009652007-07-25 00:24:17 +0000357/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
358/// the two individual tokens to be lexed as a single token, return true (which
359/// causes a space to be printed between them). This allows the output of -E
360/// mode to be lexed to the same token stream as lexing the input directly
361/// would.
362///
363/// This code must conservatively return true if it doesn't want to be 100%
364/// accurate. This will cause the output to include extra space characters, but
365/// the resulting output won't have incorrect concatenations going on. Examples
366/// include "..", which we print with a space between, because we don't want to
367/// track enough to tell "x.." from "...".
368bool PrintPPOutputPPCallbacks::AvoidConcat(const Token &PrevTok,
369 const Token &Tok) {
370 char Buffer[256];
371
372 tok::TokenKind PrevKind = PrevTok.getKind();
373 if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
374 PrevKind = tok::identifier;
375
376 // Look up information on when we should avoid concatenation with prevtok.
377 unsigned ConcatInfo = TokenInfo[PrevKind];
378
379 // If prevtok never causes a problem for anything after it, return quickly.
380 if (ConcatInfo == 0) return false;
381
382 if (ConcatInfo & aci_avoid_equal) {
383 // If the next token is '=' or '==', avoid concatenation.
Chris Lattner3b494152007-10-09 18:03:42 +0000384 if (Tok.is(tok::equal) || Tok.is(tok::equalequal))
Chris Lattner4b009652007-07-25 00:24:17 +0000385 return true;
386 ConcatInfo &= ~aci_avoid_equal;
387 }
388
389 if (ConcatInfo == 0) return false;
390
391
392
393 // Basic algorithm: we look at the first character of the second token, and
394 // determine whether it, if appended to the first token, would form (or would
395 // contribute) to a larger token if concatenated.
396 char FirstChar = 0;
397 if (ConcatInfo & aci_custom) {
398 // If the token does not need to know the first character, don't get it.
399 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
400 // Avoid spelling identifiers, the most common form of token.
401 FirstChar = II->getName()[0];
402 } else if (!Tok.needsCleaning()) {
403 SourceManager &SrcMgr = PP.getSourceManager();
404 FirstChar =
405 *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()));
406 } else if (Tok.getLength() < 256) {
407 const char *TokPtr = Buffer;
408 PP.getSpelling(Tok, TokPtr);
409 FirstChar = TokPtr[0];
410 } else {
411 FirstChar = PP.getSpelling(Tok)[0];
412 }
413
414 switch (PrevKind) {
415 default: assert(0 && "InitAvoidConcatTokenInfo built wrong");
416 case tok::identifier: // id+id or id+number or id+L"foo".
Chris Lattner3b494152007-10-09 18:03:42 +0000417 if (Tok.is(tok::numeric_constant) || Tok.getIdentifierInfo() ||
418 Tok.is(tok::wide_string_literal) /* ||
419 Tok.is(tok::wide_char_literal)*/)
Chris Lattner4b009652007-07-25 00:24:17 +0000420 return true;
Chris Lattner400f0242008-01-15 05:14:19 +0000421
422 // If this isn't identifier + string, we're done.
423 if (Tok.isNot(tok::char_constant) && Tok.isNot(tok::string_literal))
Chris Lattner4b009652007-07-25 00:24:17 +0000424 return false;
425
426 // FIXME: need a wide_char_constant!
Chris Lattner400f0242008-01-15 05:14:19 +0000427
428 // If the string was a wide string L"foo" or wide char L'f', it would concat
429 // with the previous identifier into fooL"bar". Avoid this.
430 if (StartsWithL(Tok, PP))
431 return true;
432
Chris Lattnerafa40122008-01-15 05:22:14 +0000433 // Otherwise, this is a narrow character or string. If the *identifier* is
434 // a literal 'L', avoid pasting L "foo" -> L"foo".
435 return IsIdentifierL(PrevTok, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000436 case tok::numeric_constant:
Chris Lattner3b494152007-10-09 18:03:42 +0000437 return isalnum(FirstChar) || Tok.is(tok::numeric_constant) ||
Chris Lattner4b009652007-07-25 00:24:17 +0000438 FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
439 case tok::period: // ..., .*, .1234
440 return FirstChar == '.' || FirstChar == '*' || isdigit(FirstChar);
441 case tok::amp: // &&
442 return FirstChar == '&';
443 case tok::plus: // ++
444 return FirstChar == '+';
445 case tok::minus: // --, ->, ->*
446 return FirstChar == '-' || FirstChar == '>';
447 case tok::slash: //, /*, //
448 return FirstChar == '*' || FirstChar == '/';
449 case tok::less: // <<, <<=, <:, <%
450 return FirstChar == '<' || FirstChar == ':' || FirstChar == '%';
451 case tok::greater: // >>, >>=
452 return FirstChar == '>';
453 case tok::pipe: // ||
454 return FirstChar == '|';
455 case tok::percent: // %>, %:
456 return FirstChar == '>' || FirstChar == ':';
457 case tok::colon: // ::, :>
458 return FirstChar == ':' || FirstChar == '>';
459 case tok::hash: // ##, #@, %:%:
460 return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
461 case tok::arrow: // ->*
462 return FirstChar == '*';
463 }
464}
465
466/// DoPrintPreprocessedInput - This implements -E mode.
467///
Chris Lattner6619f662008-04-08 04:16:20 +0000468void clang::DoPrintPreprocessedInput(Preprocessor &PP,
469 const std::string &OutFile) {
Chris Lattner4b009652007-07-25 00:24:17 +0000470 // Inform the preprocessor whether we want it to retain comments or not, due
471 // to -C or -CC.
472 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
Chris Lattner4b009652007-07-25 00:24:17 +0000473 InitAvoidConcatTokenInfo();
Chris Lattner21494222008-08-17 03:12:02 +0000474
475
476 // Open the output buffer.
Chris Lattner1be96902008-08-17 03:54:39 +0000477 std::string Err;
Chris Lattner03074ed2008-08-17 07:09:08 +0000478 llvm::raw_fd_ostream OS(OutFile.empty() ? "-" : OutFile.c_str(), Err);
Chris Lattner1be96902008-08-17 03:54:39 +0000479 if (!Err.empty()) {
480 fprintf(stderr, "%s\n", Err.c_str());
481 exit(1);
Chris Lattner21494222008-08-17 03:12:02 +0000482 }
Chris Lattner21494222008-08-17 03:12:02 +0000483
Chris Lattner1be96902008-08-17 03:54:39 +0000484 OS.SetBufferSize(64*1024);
485
Chris Lattner4b009652007-07-25 00:24:17 +0000486
487 Token Tok, PrevTok;
488 char Buffer[256];
Chris Lattner21494222008-08-17 03:12:02 +0000489 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(PP, OS);
Chris Lattner4b009652007-07-25 00:24:17 +0000490 PP.setPPCallbacks(Callbacks);
491
492 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
493 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
494
495 // After we have configured the preprocessor, enter the main file.
496
497 // Start parsing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +0000498 PP.EnterMainSourceFile();
Chris Lattner3eddc862007-10-10 20:45:16 +0000499
500 // Consume all of the tokens that come from the predefines buffer. Those
501 // should not be emitted into the output and are guaranteed to be at the
502 // start.
503 const SourceManager &SourceMgr = PP.getSourceManager();
504 do PP.Lex(Tok);
Chris Lattner890c5932007-10-10 23:31:03 +0000505 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
Chris Lattner3eddc862007-10-10 20:45:16 +0000506 !strcmp(SourceMgr.getSourceName(Tok.getLocation()), "<predefines>"));
507
508 while (1) {
Chris Lattner4b009652007-07-25 00:24:17 +0000509
510 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner6c451292007-12-09 21:11:08 +0000511 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
512 // done.
Chris Lattner4b009652007-07-25 00:24:17 +0000513 } else if (Tok.hasLeadingSpace() ||
514 // If we haven't emitted a token on this line yet, PrevTok isn't
515 // useful to look at and no concatenation could happen anyway.
516 (Callbacks->hasEmittedTokensOnThisLine() &&
517 // Don't print "-" next to "-", it would form "--".
518 Callbacks->AvoidConcat(PrevTok, Tok))) {
Chris Lattner21494222008-08-17 03:12:02 +0000519 OS << ' ';
Chris Lattner4b009652007-07-25 00:24:17 +0000520 }
521
522 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
523 const char *Str = II->getName();
524 unsigned Len = Tok.needsCleaning() ? strlen(Str) : Tok.getLength();
Chris Lattner21494222008-08-17 03:12:02 +0000525 OS.write(Str, Len);
Chris Lattner4b009652007-07-25 00:24:17 +0000526 } else if (Tok.getLength() < 256) {
527 const char *TokPtr = Buffer;
528 unsigned Len = PP.getSpelling(Tok, TokPtr);
Chris Lattner21494222008-08-17 03:12:02 +0000529 OS.write(TokPtr, Len);
Chris Lattner4b009652007-07-25 00:24:17 +0000530 } else {
531 std::string S = PP.getSpelling(Tok);
Chris Lattner21494222008-08-17 03:12:02 +0000532 OS.write(&S[0], S.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000533 }
534 Callbacks->SetEmittedTokensOnThisLine();
Chris Lattner3eddc862007-10-10 20:45:16 +0000535
536 if (Tok.is(tok::eof)) break;
537
538 PrevTok = Tok;
539 PP.Lex(Tok);
540 }
Chris Lattner21494222008-08-17 03:12:02 +0000541 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000542
Chris Lattnercb7f1802008-08-17 07:07:01 +0000543 // Flush the ostream.
544 OS.flush();
Chris Lattner21494222008-08-17 03:12:02 +0000545
546 // If an error occurred, remove the output file.
547 if (PP.getDiagnostics().hasErrorOccurred() && !OutFile.empty())
548 llvm::sys::Path(OutFile).eraseFromDisk();
Chris Lattner4b009652007-07-25 00:24:17 +0000549}
550