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