blob: deb005ca4f9f995ffcc71c778443eb4a8ec2993d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner5db17c92008-04-08 04:16:20 +000020#include "clang/Basic/Diagnostic.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"
Chris Lattner5db17c92008-04-08 04:16:20 +000023#include "llvm/System/Path.h"
24#include "llvm/Support/CommandLine.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/Config/config.h"
Chris Lattnerdceb6a72008-08-17 01:47:12 +000026#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include <cstdio>
28using namespace clang;
29
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnere96de3e2008-08-17 03:12:02 +000046public:
47 llvm::raw_ostream &OS;
48private:
Reid Spencer5f016e22007-07-11 17:01:13 +000049 unsigned CurLine;
Reid Spencer5f016e22007-07-11 17:01:13 +000050 bool EmittedTokensOnThisLine;
Chris Lattner9d728512008-10-27 01:19:25 +000051 SrcMgr::CharacteristicKind FileType;
Chris Lattnerd8e30832007-07-24 06:57:14 +000052 llvm::SmallString<512> CurFilename;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000053 bool Initialized;
Reid Spencer5f016e22007-07-11 17:01:13 +000054public:
Chris Lattnere96de3e2008-08-17 03:12:02 +000055 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os)
56 : PP(pp), OS(os) {
Reid Spencer5f016e22007-07-11 17:01:13 +000057 CurLine = 0;
Chris Lattnerd8e30832007-07-24 06:57:14 +000058 CurFilename += "<uninit>";
Reid Spencer5f016e22007-07-11 17:01:13 +000059 EmittedTokensOnThisLine = false;
Chris Lattner0b9e7362008-09-26 21:18:42 +000060 FileType = SrcMgr::C_User;
Daniel Dunbar737bdb42008-09-05 03:22:57 +000061 Initialized = false;
Reid Spencer5f016e22007-07-11 17:01:13 +000062 }
63
64 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
Chris Lattnerf0f2b292007-07-23 06:09:34 +000065 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
Reid Spencer5f016e22007-07-11 17:01:13 +000066
67 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +000068 SrcMgr::CharacteristicKind FileType);
Reid Spencer5f016e22007-07-11 17:01:13 +000069 virtual void Ident(SourceLocation Loc, const std::string &str);
70
71
Chris Lattner5f180322007-12-09 21:11:08 +000072 bool HandleFirstTokOnLine(Token &Tok);
73 bool MoveToLine(SourceLocation Loc);
Chris Lattnerd2177732007-07-20 16:59:19 +000074 bool AvoidConcat(const Token &PrevTok, const Token &Tok);
Daniel Dunbar737bdb42008-09-05 03:22:57 +000075 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
Reid Spencer5f016e22007-07-11 17:01:13 +000076};
Chris Lattner5db17c92008-04-08 04:16:20 +000077} // end anonymous namespace
Reid Spencer5f016e22007-07-11 17:01:13 +000078
Daniel Dunbar737bdb42008-09-05 03:22:57 +000079void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
80 const char *Extra,
81 unsigned ExtraLen) {
82 if (EmittedTokensOnThisLine) {
83 OS << '\n';
84 EmittedTokensOnThisLine = false;
85 }
86
87 OS << '#' << ' ' << LineNo << ' ' << '"';
88 OS.write(&CurFilename[0], CurFilename.size());
89 OS << '"';
90
91 if (ExtraLen)
92 OS.write(Extra, ExtraLen);
93
Chris Lattner0b9e7362008-09-26 21:18:42 +000094 if (FileType == SrcMgr::C_System)
Daniel Dunbar737bdb42008-09-05 03:22:57 +000095 OS.write(" 3", 2);
Chris Lattner0b9e7362008-09-26 21:18:42 +000096 else if (FileType == SrcMgr::C_ExternCSystem)
Daniel Dunbar737bdb42008-09-05 03:22:57 +000097 OS.write(" 3 4", 4);
98 OS << '\n';
99}
100
Reid Spencer5f016e22007-07-11 17:01:13 +0000101/// MoveToLine - Move the output to the source line specified by the location
102/// object. We can do this by emitting some number of \n's, or be emitting a
Chris Lattner5f180322007-12-09 21:11:08 +0000103/// #line directive. This returns false if already at the specified line, true
104/// if some newlines were emitted.
105bool PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000106 unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 if (DisableLineMarkers) {
Chris Lattner5f180322007-12-09 21:11:08 +0000109 if (LineNo == CurLine) return false;
110
111 CurLine = LineNo;
112
113 if (!EmittedTokensOnThisLine)
114 return true;
115
Chris Lattnere96de3e2008-08-17 03:12:02 +0000116 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000117 EmittedTokensOnThisLine = false;
118 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 // If this line is "close enough" to the original line, just print newlines,
122 // otherwise print a #line directive.
Daniel Dunbarfd966842008-09-26 01:13:35 +0000123 if (LineNo-CurLine <= 8) {
Chris Lattner822f9402007-07-23 05:14:05 +0000124 if (LineNo-CurLine == 1)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000125 OS << '\n';
Chris Lattner5f180322007-12-09 21:11:08 +0000126 else if (LineNo == CurLine)
127 return false; // Phys line moved, but logical line didn't.
Chris Lattner822f9402007-07-23 05:14:05 +0000128 else {
129 const char *NewLines = "\n\n\n\n\n\n\n\n";
Chris Lattnere96de3e2008-08-17 03:12:02 +0000130 OS.write(NewLines, LineNo-CurLine);
Chris Lattner822f9402007-07-23 05:14:05 +0000131 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 } else {
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000133 WriteLineInfo(LineNo, 0, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000135
136 CurLine = LineNo;
Chris Lattner5f180322007-12-09 21:11:08 +0000137 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000138}
139
140
141/// FileChanged - Whenever the preprocessor enters or exits a #include file
142/// it invokes this handler. Update our conception of the current source
143/// position.
144void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
145 FileChangeReason Reason,
Chris Lattner9d728512008-10-27 01:19:25 +0000146 SrcMgr::CharacteristicKind NewFileType) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 // Unless we are exiting a #include, make sure to skip ahead to the line the
148 // #include directive was at.
149 SourceManager &SourceMgr = PP.getSourceManager();
150 if (Reason == PPCallbacks::EnterFile) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000151 MoveToLine(SourceMgr.getIncludeLoc(Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
153 MoveToLine(Loc);
154
155 // TODO GCC emits the # directive for this directive on the line AFTER the
156 // directive and emits a bunch of spaces that aren't needed. Emulate this
157 // strange behavior.
158 }
159
Chris Lattner9dc1f532007-07-20 16:37:10 +0000160 Loc = SourceMgr.getLogicalLoc(Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000161 CurLine = SourceMgr.getLineNumber(Loc);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000162
Chris Lattner5f180322007-12-09 21:11:08 +0000163 if (DisableLineMarkers) return;
164
Chris Lattnerd8e30832007-07-24 06:57:14 +0000165 CurFilename.clear();
166 CurFilename += SourceMgr.getSourceName(Loc);
167 Lexer::Stringify(CurFilename);
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000168 FileType = NewFileType;
169
170 if (!Initialized) {
171 WriteLineInfo(CurLine);
172 Initialized = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000173 }
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000174
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 switch (Reason) {
176 case PPCallbacks::EnterFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000177 WriteLineInfo(CurLine, " 1", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 break;
179 case PPCallbacks::ExitFile:
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000180 WriteLineInfo(CurLine, " 2", 2);
Reid Spencer5f016e22007-07-11 17:01:13 +0000181 break;
Daniel Dunbar737bdb42008-09-05 03:22:57 +0000182 case PPCallbacks::SystemHeaderPragma:
183 case PPCallbacks::RenameFile:
184 WriteLineInfo(CurLine);
185 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000187}
188
189/// HandleIdent - Handle #ident directives when read by the preprocessor.
190///
191void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
192 MoveToLine(Loc);
193
Chris Lattnere96de3e2008-08-17 03:12:02 +0000194 OS.write("#ident ", strlen("#ident "));
195 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 EmittedTokensOnThisLine = true;
197}
198
199/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
Chris Lattner5f180322007-12-09 21:11:08 +0000200/// is called for the first token on each new line. If this really is the start
201/// of a new logical line, handle it and return true, otherwise return false.
202/// This may not be the start of a logical line because the "start of line"
203/// marker is set for physical lines, not logical ones.
204bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 // Figure out what line we went to and insert the appropriate number of
206 // newline characters.
Chris Lattner5f180322007-12-09 21:11:08 +0000207 if (!MoveToLine(Tok.getLocation()))
208 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000209
210 // Print out space characters so that the first token on a line is
211 // indented for easy reading.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000212 const SourceManager &SourceMgr = PP.getSourceManager();
213 unsigned ColNo = SourceMgr.getLogicalColumnNumber(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000214
215 // This hack prevents stuff like:
216 // #define HASH #
217 // HASH define foo bar
218 // From having the # character end up at column 1, which makes it so it
219 // is not handled as a #define next time through the preprocessor if in
220 // -fpreprocessed mode.
Chris Lattner057aaf62007-10-09 18:03:42 +0000221 if (ColNo <= 1 && Tok.is(tok::hash))
Chris Lattnere96de3e2008-08-17 03:12:02 +0000222 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000223
224 // Otherwise, indent the appropriate number of spaces.
225 for (; ColNo > 1; --ColNo)
Chris Lattnere96de3e2008-08-17 03:12:02 +0000226 OS << ' ';
Chris Lattner5f180322007-12-09 21:11:08 +0000227
228 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000229}
230
231namespace {
232struct UnknownPragmaHandler : public PragmaHandler {
233 const char *Prefix;
234 PrintPPOutputPPCallbacks *Callbacks;
235
236 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
237 : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000238 virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 // Figure out what line we went to and insert the appropriate number of
240 // newline characters.
241 Callbacks->MoveToLine(PragmaTok.getLocation());
Chris Lattnere96de3e2008-08-17 03:12:02 +0000242 Callbacks->OS.write(Prefix, strlen(Prefix));
Reid Spencer5f016e22007-07-11 17:01:13 +0000243
244 // Read and print all of the pragma tokens.
Chris Lattner057aaf62007-10-09 18:03:42 +0000245 while (PragmaTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 if (PragmaTok.hasLeadingSpace())
Chris Lattnere96de3e2008-08-17 03:12:02 +0000247 Callbacks->OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 std::string TokSpell = PP.getSpelling(PragmaTok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000249 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 PP.LexUnexpandedToken(PragmaTok);
251 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000252 Callbacks->OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 }
254};
255} // end anonymous namespace
256
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000257
258enum AvoidConcatInfo {
259 /// By default, a token never needs to avoid concatenation. Most tokens (e.g.
260 /// ',', ')', etc) don't cause a problem when concatenated.
261 aci_never_avoid_concat = 0,
262
263 /// aci_custom_firstchar - AvoidConcat contains custom code to handle this
264 /// token's requirements, and it needs to know the first character of the
265 /// token.
266 aci_custom_firstchar = 1,
267
268 /// aci_custom - AvoidConcat contains custom code to handle this token's
269 /// requirements, but it doesn't need to know the first character of the
270 /// token.
271 aci_custom = 2,
272
273 /// aci_avoid_equal - Many tokens cannot be safely followed by an '='
274 /// character. For example, "<<" turns into "<<=" when followed by an =.
275 aci_avoid_equal = 4
276};
277
278/// This array contains information for each token on what action to take when
279/// avoiding concatenation of tokens in the AvoidConcat method.
280static char TokenInfo[tok::NUM_TOKENS];
281
282/// InitAvoidConcatTokenInfo - Tokens that must avoid concatenation should be
283/// marked by this function.
284static void InitAvoidConcatTokenInfo() {
285 // These tokens have custom code in AvoidConcat.
286 TokenInfo[tok::identifier ] |= aci_custom;
287 TokenInfo[tok::numeric_constant] |= aci_custom_firstchar;
288 TokenInfo[tok::period ] |= aci_custom_firstchar;
289 TokenInfo[tok::amp ] |= aci_custom_firstchar;
290 TokenInfo[tok::plus ] |= aci_custom_firstchar;
291 TokenInfo[tok::minus ] |= aci_custom_firstchar;
292 TokenInfo[tok::slash ] |= aci_custom_firstchar;
293 TokenInfo[tok::less ] |= aci_custom_firstchar;
294 TokenInfo[tok::greater ] |= aci_custom_firstchar;
295 TokenInfo[tok::pipe ] |= aci_custom_firstchar;
296 TokenInfo[tok::percent ] |= aci_custom_firstchar;
297 TokenInfo[tok::colon ] |= aci_custom_firstchar;
298 TokenInfo[tok::hash ] |= aci_custom_firstchar;
299 TokenInfo[tok::arrow ] |= aci_custom_firstchar;
300
301 // These tokens change behavior if followed by an '='.
302 TokenInfo[tok::amp ] |= aci_avoid_equal; // &=
303 TokenInfo[tok::plus ] |= aci_avoid_equal; // +=
304 TokenInfo[tok::minus ] |= aci_avoid_equal; // -=
305 TokenInfo[tok::slash ] |= aci_avoid_equal; // /=
306 TokenInfo[tok::less ] |= aci_avoid_equal; // <=
307 TokenInfo[tok::greater ] |= aci_avoid_equal; // >=
308 TokenInfo[tok::pipe ] |= aci_avoid_equal; // |=
309 TokenInfo[tok::percent ] |= aci_avoid_equal; // %=
310 TokenInfo[tok::star ] |= aci_avoid_equal; // *=
311 TokenInfo[tok::exclaim ] |= aci_avoid_equal; // !=
312 TokenInfo[tok::lessless ] |= aci_avoid_equal; // <<=
313 TokenInfo[tok::greaterequal] |= aci_avoid_equal; // >>=
314 TokenInfo[tok::caret ] |= aci_avoid_equal; // ^=
315 TokenInfo[tok::equal ] |= aci_avoid_equal; // ==
316}
317
Chris Lattnerb1a17ae2008-01-15 05:22:14 +0000318/// StartsWithL - Return true if the spelling of this token starts with 'L'.
Chris Lattnerfdc0d3c2008-01-15 05:14:19 +0000319static bool StartsWithL(const Token &Tok, Preprocessor &PP) {
Chris Lattnerfdc0d3c2008-01-15 05:14:19 +0000320 if (!Tok.needsCleaning()) {
321 SourceManager &SrcMgr = PP.getSourceManager();
322 return *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()))
323 == 'L';
324 }
325
326 if (Tok.getLength() < 256) {
Chris Lattnerb1a17ae2008-01-15 05:22:14 +0000327 char Buffer[256];
Chris Lattnerfdc0d3c2008-01-15 05:14:19 +0000328 const char *TokPtr = Buffer;
329 PP.getSpelling(Tok, TokPtr);
330 return TokPtr[0] == 'L';
331 }
332
333 return PP.getSpelling(Tok)[0] == 'L';
334}
335
Chris Lattnerb1a17ae2008-01-15 05:22:14 +0000336/// IsIdentifierL - Return true if the spelling of this token is literally 'L'.
337static bool IsIdentifierL(const Token &Tok, Preprocessor &PP) {
338 if (!Tok.needsCleaning()) {
339 if (Tok.getLength() != 1)
340 return false;
341 SourceManager &SrcMgr = PP.getSourceManager();
342 return *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()))
343 == 'L';
344 }
345
346 if (Tok.getLength() < 256) {
347 char Buffer[256];
348 const char *TokPtr = Buffer;
349 if (PP.getSpelling(Tok, TokPtr) != 1)
350 return false;
351 return TokPtr[0] == 'L';
352 }
353
354 return PP.getSpelling(Tok) == "L";
355}
356
357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
359/// the two individual tokens to be lexed as a single token, return true (which
360/// causes a space to be printed between them). This allows the output of -E
361/// mode to be lexed to the same token stream as lexing the input directly
362/// would.
363///
364/// This code must conservatively return true if it doesn't want to be 100%
365/// accurate. This will cause the output to include extra space characters, but
366/// the resulting output won't have incorrect concatenations going on. Examples
367/// include "..", which we print with a space between, because we don't want to
368/// track enough to tell "x.." from "...".
Chris Lattnerd2177732007-07-20 16:59:19 +0000369bool PrintPPOutputPPCallbacks::AvoidConcat(const Token &PrevTok,
370 const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 char Buffer[256];
372
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000373 tok::TokenKind PrevKind = PrevTok.getKind();
374 if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
375 PrevKind = tok::identifier;
376
377 // Look up information on when we should avoid concatenation with prevtok.
378 unsigned ConcatInfo = TokenInfo[PrevKind];
379
380 // If prevtok never causes a problem for anything after it, return quickly.
381 if (ConcatInfo == 0) return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000382
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000383 if (ConcatInfo & aci_avoid_equal) {
384 // If the next token is '=' or '==', avoid concatenation.
Chris Lattner057aaf62007-10-09 18:03:42 +0000385 if (Tok.is(tok::equal) || Tok.is(tok::equalequal))
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000386 return true;
Chris Lattnerb638a302007-07-23 23:21:34 +0000387 ConcatInfo &= ~aci_avoid_equal;
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000388 }
389
390 if (ConcatInfo == 0) return false;
391
392
393
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 // Basic algorithm: we look at the first character of the second token, and
395 // determine whether it, if appended to the first token, would form (or would
396 // contribute) to a larger token if concatenated.
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000397 char FirstChar = 0;
398 if (ConcatInfo & aci_custom) {
399 // If the token does not need to know the first character, don't get it.
400 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // Avoid spelling identifiers, the most common form of token.
402 FirstChar = II->getName()[0];
Chris Lattnerb19f5e82007-07-23 05:18:42 +0000403 } else if (!Tok.needsCleaning()) {
404 SourceManager &SrcMgr = PP.getSourceManager();
405 FirstChar =
406 *SrcMgr.getCharacterData(SrcMgr.getPhysicalLoc(Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 } else if (Tok.getLength() < 256) {
408 const char *TokPtr = Buffer;
409 PP.getSpelling(Tok, TokPtr);
410 FirstChar = TokPtr[0];
411 } else {
412 FirstChar = PP.getSpelling(Tok)[0];
413 }
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000414
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 switch (PrevKind) {
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000416 default: assert(0 && "InitAvoidConcatTokenInfo built wrong");
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 case tok::identifier: // id+id or id+number or id+L"foo".
Chris Lattner057aaf62007-10-09 18:03:42 +0000418 if (Tok.is(tok::numeric_constant) || Tok.getIdentifierInfo() ||
419 Tok.is(tok::wide_string_literal) /* ||
420 Tok.is(tok::wide_char_literal)*/)
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000421 return true;
Chris Lattnerfdc0d3c2008-01-15 05:14:19 +0000422
423 // If this isn't identifier + string, we're done.
424 if (Tok.isNot(tok::char_constant) && Tok.isNot(tok::string_literal))
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000425 return false;
426
427 // FIXME: need a wide_char_constant!
Chris Lattnerfdc0d3c2008-01-15 05:14:19 +0000428
429 // If the string was a wide string L"foo" or wide char L'f', it would concat
430 // with the previous identifier into fooL"bar". Avoid this.
431 if (StartsWithL(Tok, PP))
432 return true;
433
Chris Lattnerb1a17ae2008-01-15 05:22:14 +0000434 // Otherwise, this is a narrow character or string. If the *identifier* is
435 // a literal 'L', avoid pasting L "foo" -> L"foo".
436 return IsIdentifierL(PrevTok, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 case tok::numeric_constant:
Chris Lattner057aaf62007-10-09 18:03:42 +0000438 return isalnum(FirstChar) || Tok.is(tok::numeric_constant) ||
Reid Spencer5f016e22007-07-11 17:01:13 +0000439 FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
440 case tok::period: // ..., .*, .1234
Chris Lattnerd7a7c002009-01-11 19:48:19 +0000441 return FirstChar == '.' || isdigit(FirstChar) ||
442 (FirstChar == '*' && PP.getLangOptions().CPlusPlus);
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000443 case tok::amp: // &&
444 return FirstChar == '&';
445 case tok::plus: // ++
446 return FirstChar == '+';
447 case tok::minus: // --, ->, ->*
448 return FirstChar == '-' || FirstChar == '>';
449 case tok::slash: //, /*, //
450 return FirstChar == '*' || FirstChar == '/';
451 case tok::less: // <<, <<=, <:, <%
452 return FirstChar == '<' || FirstChar == ':' || FirstChar == '%';
453 case tok::greater: // >>, >>=
454 return FirstChar == '>';
455 case tok::pipe: // ||
456 return FirstChar == '|';
457 case tok::percent: // %>, %:
Chris Lattnerd7a7c002009-01-11 19:48:19 +0000458 return (FirstChar == '>' || FirstChar == ':') &&
459 PP.getLangOptions().Digraphs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 case tok::colon: // ::, :>
Chris Lattnerd7a7c002009-01-11 19:48:19 +0000461 return (FirstChar == ':' && PP.getLangOptions().CPlusPlus) ||
462 (FirstChar == '>' && PP.getLangOptions().Digraphs);
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 case tok::hash: // ##, #@, %:%:
464 return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
465 case tok::arrow: // ->*
466 return FirstChar == '*';
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 }
468}
469
470/// DoPrintPreprocessedInput - This implements -E mode.
471///
Chris Lattner5db17c92008-04-08 04:16:20 +0000472void clang::DoPrintPreprocessedInput(Preprocessor &PP,
473 const std::string &OutFile) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // Inform the preprocessor whether we want it to retain comments or not, due
475 // to -C or -CC.
476 PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000477 InitAvoidConcatTokenInfo();
Chris Lattnere96de3e2008-08-17 03:12:02 +0000478
479
480 // Open the output buffer.
Chris Lattner202e9ac2008-08-17 03:54:39 +0000481 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +0000482 llvm::raw_fd_ostream OS(OutFile.empty() ? "-" : OutFile.c_str(), false, Err);
Chris Lattner202e9ac2008-08-17 03:54:39 +0000483 if (!Err.empty()) {
484 fprintf(stderr, "%s\n", Err.c_str());
485 exit(1);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000486 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000487
Chris Lattner202e9ac2008-08-17 03:54:39 +0000488 OS.SetBufferSize(64*1024);
489
Reid Spencer5f016e22007-07-11 17:01:13 +0000490
Chris Lattnerd2177732007-07-20 16:59:19 +0000491 Token Tok, PrevTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 char Buffer[256];
Chris Lattnere96de3e2008-08-17 03:12:02 +0000493 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(PP, OS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 PP.setPPCallbacks(Callbacks);
495
496 PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
497 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
498
499 // After we have configured the preprocessor, enter the main file.
500
501 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000502 PP.EnterMainSourceFile();
Chris Lattner6f688e12007-10-10 20:45:16 +0000503
504 // Consume all of the tokens that come from the predefines buffer. Those
505 // should not be emitted into the output and are guaranteed to be at the
506 // start.
507 const SourceManager &SourceMgr = PP.getSourceManager();
508 do PP.Lex(Tok);
Chris Lattnera1a51782007-10-10 23:31:03 +0000509 while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
Chris Lattner6f688e12007-10-10 20:45:16 +0000510 !strcmp(SourceMgr.getSourceName(Tok.getLocation()), "<predefines>"));
511
512 while (1) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000513
514 // If this token is at the start of a line, emit newlines if needed.
Chris Lattner5f180322007-12-09 21:11:08 +0000515 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
516 // done.
Reid Spencer5f016e22007-07-11 17:01:13 +0000517 } else if (Tok.hasLeadingSpace() ||
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000518 // If we haven't emitted a token on this line yet, PrevTok isn't
519 // useful to look at and no concatenation could happen anyway.
Chris Lattnerb638a302007-07-23 23:21:34 +0000520 (Callbacks->hasEmittedTokensOnThisLine() &&
Chris Lattnerf0f2b292007-07-23 06:09:34 +0000521 // Don't print "-" next to "-", it would form "--".
522 Callbacks->AvoidConcat(PrevTok, Tok))) {
Chris Lattnere96de3e2008-08-17 03:12:02 +0000523 OS << ' ';
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 }
525
Chris Lattner2933f412007-07-23 06:14:36 +0000526 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
527 const char *Str = II->getName();
528 unsigned Len = Tok.needsCleaning() ? strlen(Str) : Tok.getLength();
Chris Lattnere96de3e2008-08-17 03:12:02 +0000529 OS.write(Str, Len);
Chris Lattner2933f412007-07-23 06:14:36 +0000530 } else if (Tok.getLength() < 256) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 const char *TokPtr = Buffer;
532 unsigned Len = PP.getSpelling(Tok, TokPtr);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000533 OS.write(TokPtr, Len);
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 } else {
535 std::string S = PP.getSpelling(Tok);
Chris Lattnere96de3e2008-08-17 03:12:02 +0000536 OS.write(&S[0], S.size());
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 }
538 Callbacks->SetEmittedTokensOnThisLine();
Chris Lattner6f688e12007-10-10 20:45:16 +0000539
540 if (Tok.is(tok::eof)) break;
541
542 PrevTok = Tok;
543 PP.Lex(Tok);
544 }
Chris Lattnere96de3e2008-08-17 03:12:02 +0000545 OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000546
Chris Lattner76b3a722008-08-17 07:07:01 +0000547 // Flush the ostream.
548 OS.flush();
Chris Lattnere96de3e2008-08-17 03:12:02 +0000549
550 // If an error occurred, remove the output file.
551 if (PP.getDiagnostics().hasErrorOccurred() && !OutFile.empty())
552 llvm::sys::Path(OutFile).eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000553}
554