PrintPreprocessedOutput.cpp revision c54539cd173e20d8b179b9488fabfc5eb4cf5ee6
1//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/Frontend/Utils.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Frontend/PreprocessorOutputOptions.h"
19#include "clang/Lex/MacroInfo.h"
20#include "clang/Lex/PPCallbacks.h"
21#include "clang/Lex/Pragma.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Lex/TokenConcatenation.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Config/config.h"
27#include "llvm/Support/raw_ostream.h"
28#include <cstdio>
29using namespace clang;
30
31/// PrintMacroDefinition - Print a macro definition in a form that will be
32/// properly accepted back as a definition.
33static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
34                                 Preprocessor &PP, llvm::raw_ostream &OS) {
35  OS << "#define " << II.getName();
36
37  if (MI.isFunctionLike()) {
38    OS << '(';
39    if (!MI.arg_empty()) {
40      MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
41      for (; AI+1 != E; ++AI) {
42        OS << (*AI)->getName();
43        OS << ',';
44      }
45
46      // Last argument.
47      if ((*AI)->getName() == "__VA_ARGS__")
48        OS << "...";
49      else
50        OS << (*AI)->getName();
51    }
52
53    if (MI.isGNUVarargs())
54      OS << "...";  // #define foo(x...)
55
56    OS << ')';
57  }
58
59  // GCC always emits a space, even if the macro body is empty.  However, do not
60  // want to emit two spaces if the first token has a leading space.
61  if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
62    OS << ' ';
63
64  llvm::SmallString<128> SpellingBuffer;
65  for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
66       I != E; ++I) {
67    if (I->hasLeadingSpace())
68      OS << ' ';
69
70    OS << PP.getSpelling(*I, SpellingBuffer);
71  }
72}
73
74//===----------------------------------------------------------------------===//
75// Preprocessed token printer
76//===----------------------------------------------------------------------===//
77
78namespace {
79class PrintPPOutputPPCallbacks : public PPCallbacks {
80  Preprocessor &PP;
81  SourceManager &SM;
82  TokenConcatenation ConcatInfo;
83public:
84  llvm::raw_ostream &OS;
85private:
86  unsigned CurLine;
87  bool EmittedTokensOnThisLine;
88  bool EmittedMacroOnThisLine;
89  SrcMgr::CharacteristicKind FileType;
90  llvm::SmallString<512> CurFilename;
91  bool Initialized;
92  bool DisableLineMarkers;
93  bool DumpDefines;
94  bool UseLineDirective;
95public:
96  PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
97                           bool lineMarkers, bool defines)
98     : PP(pp), SM(PP.getSourceManager()),
99       ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
100       DumpDefines(defines) {
101    CurLine = 0;
102    CurFilename += "<uninit>";
103    EmittedTokensOnThisLine = false;
104    EmittedMacroOnThisLine = false;
105    FileType = SrcMgr::C_User;
106    Initialized = false;
107
108    // If we're in microsoft mode, use normal #line instead of line markers.
109    UseLineDirective = PP.getLangOptions().Microsoft;
110  }
111
112  void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
113  bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
114
115  virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
116                           SrcMgr::CharacteristicKind FileType);
117  virtual void Ident(SourceLocation Loc, const std::string &str);
118  virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
119                             const std::string &Str);
120
121
122  bool HandleFirstTokOnLine(Token &Tok);
123  bool MoveToLine(SourceLocation Loc) {
124    return MoveToLine(SM.getPresumedLoc(Loc).getLine());
125  }
126  bool MoveToLine(unsigned LineNo);
127
128  bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
129                   const Token &Tok) {
130    return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
131  }
132  void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
133
134  void HandleNewlinesInToken(const char *TokStr, unsigned Len);
135
136  /// MacroDefined - This hook is called whenever a macro definition is seen.
137  void MacroDefined(const IdentifierInfo *II, const MacroInfo *MI);
138
139};
140}  // end anonymous namespace
141
142void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
143                                             const char *Extra,
144                                             unsigned ExtraLen) {
145  if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
146    OS << '\n';
147    EmittedTokensOnThisLine = false;
148    EmittedMacroOnThisLine = false;
149  }
150
151  // Emit #line directives or GNU line markers depending on what mode we're in.
152  if (UseLineDirective) {
153    OS << "#line" << ' ' << LineNo << ' ' << '"';
154    OS.write(&CurFilename[0], CurFilename.size());
155    OS << '"';
156  } else {
157    OS << '#' << ' ' << LineNo << ' ' << '"';
158    OS.write(&CurFilename[0], CurFilename.size());
159    OS << '"';
160
161    if (ExtraLen)
162      OS.write(Extra, ExtraLen);
163
164    if (FileType == SrcMgr::C_System)
165      OS.write(" 3", 2);
166    else if (FileType == SrcMgr::C_ExternCSystem)
167      OS.write(" 3 4", 4);
168  }
169  OS << '\n';
170}
171
172/// MoveToLine - Move the output to the source line specified by the location
173/// object.  We can do this by emitting some number of \n's, or be emitting a
174/// #line directive.  This returns false if already at the specified line, true
175/// if some newlines were emitted.
176bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
177  // If this line is "close enough" to the original line, just print newlines,
178  // otherwise print a #line directive.
179  if (LineNo-CurLine <= 8) {
180    if (LineNo-CurLine == 1)
181      OS << '\n';
182    else if (LineNo == CurLine)
183      return false;    // Spelling line moved, but instantiation line didn't.
184    else {
185      const char *NewLines = "\n\n\n\n\n\n\n\n";
186      OS.write(NewLines, LineNo-CurLine);
187    }
188  } else if (!DisableLineMarkers) {
189    // Emit a #line or line marker.
190    WriteLineInfo(LineNo, 0, 0);
191  } else {
192    // Okay, we're in -P mode, which turns off line markers.  However, we still
193    // need to emit a newline between tokens on different lines.
194    if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
195      OS << '\n';
196      EmittedTokensOnThisLine = false;
197      EmittedMacroOnThisLine = false;
198    }
199  }
200
201  CurLine = LineNo;
202  return true;
203}
204
205
206/// FileChanged - Whenever the preprocessor enters or exits a #include file
207/// it invokes this handler.  Update our conception of the current source
208/// position.
209void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
210                                           FileChangeReason Reason,
211                                       SrcMgr::CharacteristicKind NewFileType) {
212  // Unless we are exiting a #include, make sure to skip ahead to the line the
213  // #include directive was at.
214  SourceManager &SourceMgr = SM;
215
216  PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
217  unsigned NewLine = UserLoc.getLine();
218
219  if (Reason == PPCallbacks::EnterFile) {
220    SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
221    if (IncludeLoc.isValid())
222      MoveToLine(IncludeLoc);
223  } else if (Reason == PPCallbacks::SystemHeaderPragma) {
224    MoveToLine(NewLine);
225
226    // TODO GCC emits the # directive for this directive on the line AFTER the
227    // directive and emits a bunch of spaces that aren't needed.  Emulate this
228    // strange behavior.
229  }
230
231  CurLine = NewLine;
232
233  if (DisableLineMarkers) return;
234
235  CurFilename.clear();
236  CurFilename += UserLoc.getFilename();
237  Lexer::Stringify(CurFilename);
238  FileType = NewFileType;
239
240  if (!Initialized) {
241    WriteLineInfo(CurLine);
242    Initialized = true;
243  }
244
245  switch (Reason) {
246  case PPCallbacks::EnterFile:
247    WriteLineInfo(CurLine, " 1", 2);
248    break;
249  case PPCallbacks::ExitFile:
250    WriteLineInfo(CurLine, " 2", 2);
251    break;
252  case PPCallbacks::SystemHeaderPragma:
253  case PPCallbacks::RenameFile:
254    WriteLineInfo(CurLine);
255    break;
256  }
257}
258
259/// Ident - Handle #ident directives when read by the preprocessor.
260///
261void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
262  MoveToLine(Loc);
263
264  OS.write("#ident ", strlen("#ident "));
265  OS.write(&S[0], S.size());
266  EmittedTokensOnThisLine = true;
267}
268
269/// MacroDefined - This hook is called whenever a macro definition is seen.
270void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
271                                            const MacroInfo *MI) {
272  // Only print out macro definitions in -dD mode.
273  if (!DumpDefines ||
274      // Ignore __FILE__ etc.
275      MI->isBuiltinMacro()) return;
276
277  MoveToLine(MI->getDefinitionLoc());
278  PrintMacroDefinition(*II, *MI, PP, OS);
279  EmittedMacroOnThisLine = true;
280}
281
282
283void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
284                                             const IdentifierInfo *Kind,
285                                             const std::string &Str) {
286  MoveToLine(Loc);
287  OS << "#pragma comment(" << Kind->getName();
288
289  if (!Str.empty()) {
290    OS << ", \"";
291
292    for (unsigned i = 0, e = Str.size(); i != e; ++i) {
293      unsigned char Char = Str[i];
294      if (isprint(Char) && Char != '\\' && Char != '"')
295        OS << (char)Char;
296      else  // Output anything hard as an octal escape.
297        OS << '\\'
298           << (char)('0'+ ((Char >> 6) & 7))
299           << (char)('0'+ ((Char >> 3) & 7))
300           << (char)('0'+ ((Char >> 0) & 7));
301    }
302    OS << '"';
303  }
304
305  OS << ')';
306  EmittedTokensOnThisLine = true;
307}
308
309
310/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
311/// is called for the first token on each new line.  If this really is the start
312/// of a new logical line, handle it and return true, otherwise return false.
313/// This may not be the start of a logical line because the "start of line"
314/// marker is set for spelling lines, not instantiation ones.
315bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
316  // Figure out what line we went to and insert the appropriate number of
317  // newline characters.
318  if (!MoveToLine(Tok.getLocation()))
319    return false;
320
321  // Print out space characters so that the first token on a line is
322  // indented for easy reading.
323  unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
324
325  // This hack prevents stuff like:
326  // #define HASH #
327  // HASH define foo bar
328  // From having the # character end up at column 1, which makes it so it
329  // is not handled as a #define next time through the preprocessor if in
330  // -fpreprocessed mode.
331  if (ColNo <= 1 && Tok.is(tok::hash))
332    OS << ' ';
333
334  // Otherwise, indent the appropriate number of spaces.
335  for (; ColNo > 1; --ColNo)
336    OS << ' ';
337
338  return true;
339}
340
341void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
342                                                     unsigned Len) {
343  unsigned NumNewlines = 0;
344  for (; Len; --Len, ++TokStr) {
345    if (*TokStr != '\n' &&
346        *TokStr != '\r')
347      continue;
348
349    ++NumNewlines;
350
351    // If we have \n\r or \r\n, skip both and count as one line.
352    if (Len != 1 &&
353        (TokStr[1] == '\n' || TokStr[1] == '\r') &&
354        TokStr[0] != TokStr[1])
355      ++TokStr, --Len;
356  }
357
358  if (NumNewlines == 0) return;
359
360  CurLine += NumNewlines;
361}
362
363
364namespace {
365struct UnknownPragmaHandler : public PragmaHandler {
366  const char *Prefix;
367  PrintPPOutputPPCallbacks *Callbacks;
368
369  UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
370    : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
371  virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
372    // Figure out what line we went to and insert the appropriate number of
373    // newline characters.
374    Callbacks->MoveToLine(PragmaTok.getLocation());
375    Callbacks->OS.write(Prefix, strlen(Prefix));
376
377    // Read and print all of the pragma tokens.
378    while (PragmaTok.isNot(tok::eom)) {
379      if (PragmaTok.hasLeadingSpace())
380        Callbacks->OS << ' ';
381      std::string TokSpell = PP.getSpelling(PragmaTok);
382      Callbacks->OS.write(&TokSpell[0], TokSpell.size());
383      PP.LexUnexpandedToken(PragmaTok);
384    }
385    Callbacks->OS << '\n';
386  }
387};
388} // end anonymous namespace
389
390
391static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
392                                    PrintPPOutputPPCallbacks *Callbacks,
393                                    llvm::raw_ostream &OS) {
394  char Buffer[256];
395  Token PrevPrevTok, PrevTok;
396  PrevPrevTok.startToken();
397  PrevTok.startToken();
398  while (1) {
399
400    // If this token is at the start of a line, emit newlines if needed.
401    if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
402      // done.
403    } else if (Tok.hasLeadingSpace() ||
404               // If we haven't emitted a token on this line yet, PrevTok isn't
405               // useful to look at and no concatenation could happen anyway.
406               (Callbacks->hasEmittedTokensOnThisLine() &&
407                // Don't print "-" next to "-", it would form "--".
408                Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
409      OS << ' ';
410    }
411
412    if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
413      OS << II->getName();
414    } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
415               Tok.getLiteralData()) {
416      OS.write(Tok.getLiteralData(), Tok.getLength());
417    } else if (Tok.getLength() < 256) {
418      const char *TokPtr = Buffer;
419      unsigned Len = PP.getSpelling(Tok, TokPtr);
420      OS.write(TokPtr, Len);
421
422      // Tokens that can contain embedded newlines need to adjust our current
423      // line number.
424      if (Tok.getKind() == tok::comment)
425        Callbacks->HandleNewlinesInToken(TokPtr, Len);
426    } else {
427      std::string S = PP.getSpelling(Tok);
428      OS.write(&S[0], S.size());
429
430      // Tokens that can contain embedded newlines need to adjust our current
431      // line number.
432      if (Tok.getKind() == tok::comment)
433        Callbacks->HandleNewlinesInToken(&S[0], S.size());
434    }
435    Callbacks->SetEmittedTokensOnThisLine();
436
437    if (Tok.is(tok::eof)) break;
438
439    PrevPrevTok = PrevTok;
440    PrevTok = Tok;
441    PP.Lex(Tok);
442  }
443}
444
445typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
446static int MacroIDCompare(const void* a, const void* b) {
447  const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
448  const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
449  return LHS->first->getName().compare(RHS->first->getName());
450}
451
452static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
453  // Ignore unknown pragmas.
454  PP.AddPragmaHandler(0, new EmptyPragmaHandler());
455
456  // -dM mode just scans and ignores all tokens in the files, then dumps out
457  // the macro table at the end.
458  PP.EnterMainSourceFile();
459
460  Token Tok;
461  do PP.Lex(Tok);
462  while (Tok.isNot(tok::eof));
463
464  llvm::SmallVector<id_macro_pair, 128>
465    MacrosByID(PP.macro_begin(), PP.macro_end());
466  llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
467
468  for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
469    MacroInfo &MI = *MacrosByID[i].second;
470    // Ignore computed macros like __LINE__ and friends.
471    if (MI.isBuiltinMacro()) continue;
472
473    PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
474    *OS << '\n';
475  }
476}
477
478/// DoPrintPreprocessedInput - This implements -E mode.
479///
480void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
481                                     const PreprocessorOutputOptions &Opts) {
482  // Show macros with no output is handled specially.
483  if (!Opts.ShowCPP) {
484    assert(Opts.ShowMacros && "Not yet implemented!");
485    DoPrintMacros(PP, OS);
486    return;
487  }
488
489  // Inform the preprocessor whether we want it to retain comments or not, due
490  // to -C or -CC.
491  PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
492
493  PrintPPOutputPPCallbacks *Callbacks =
494      new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
495                                   Opts.ShowMacros);
496  PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
497  PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
498                                                      Callbacks));
499
500  PP.addPPCallbacks(Callbacks);
501
502  // After we have configured the preprocessor, enter the main file.
503  PP.EnterMainSourceFile();
504
505  // Consume all of the tokens that come from the predefines buffer.  Those
506  // should not be emitted into the output and are guaranteed to be at the
507  // start.
508  const SourceManager &SourceMgr = PP.getSourceManager();
509  Token Tok;
510  do PP.Lex(Tok);
511  while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
512         !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
513                 "<built-in>"));
514
515  // Read all the preprocessed tokens, printing them out to the stream.
516  PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
517  *OS << '\n';
518}
519
520