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