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