PrintPreprocessedOutput.cpp revision 207619
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 (DisableLineMarkers) {
178    if (LineNo == CurLine) return false;
179
180    CurLine = LineNo;
181
182    if (!EmittedTokensOnThisLine && !EmittedMacroOnThisLine)
183      return true;
184
185    OS << '\n';
186    EmittedTokensOnThisLine = false;
187    EmittedMacroOnThisLine = false;
188    return true;
189  }
190
191  // If this line is "close enough" to the original line, just print newlines,
192  // otherwise print a #line directive.
193  if (LineNo-CurLine <= 8) {
194    if (LineNo-CurLine == 1)
195      OS << '\n';
196    else if (LineNo == CurLine)
197      return false;    // Spelling line moved, but instantiation line didn't.
198    else {
199      const char *NewLines = "\n\n\n\n\n\n\n\n";
200      OS.write(NewLines, LineNo-CurLine);
201    }
202  } else {
203    WriteLineInfo(LineNo, 0, 0);
204  }
205
206  CurLine = LineNo;
207  return true;
208}
209
210
211/// FileChanged - Whenever the preprocessor enters or exits a #include file
212/// it invokes this handler.  Update our conception of the current source
213/// position.
214void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
215                                           FileChangeReason Reason,
216                                       SrcMgr::CharacteristicKind NewFileType) {
217  // Unless we are exiting a #include, make sure to skip ahead to the line the
218  // #include directive was at.
219  SourceManager &SourceMgr = SM;
220
221  PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
222  unsigned NewLine = UserLoc.getLine();
223
224  if (Reason == PPCallbacks::EnterFile) {
225    SourceLocation IncludeLoc = SourceMgr.getPresumedLoc(Loc).getIncludeLoc();
226    if (IncludeLoc.isValid())
227      MoveToLine(IncludeLoc);
228  } else if (Reason == PPCallbacks::SystemHeaderPragma) {
229    MoveToLine(NewLine);
230
231    // TODO GCC emits the # directive for this directive on the line AFTER the
232    // directive and emits a bunch of spaces that aren't needed.  Emulate this
233    // strange behavior.
234  }
235
236  CurLine = NewLine;
237
238  if (DisableLineMarkers) return;
239
240  CurFilename.clear();
241  CurFilename += UserLoc.getFilename();
242  Lexer::Stringify(CurFilename);
243  FileType = NewFileType;
244
245  if (!Initialized) {
246    WriteLineInfo(CurLine);
247    Initialized = true;
248  }
249
250  switch (Reason) {
251  case PPCallbacks::EnterFile:
252    WriteLineInfo(CurLine, " 1", 2);
253    break;
254  case PPCallbacks::ExitFile:
255    WriteLineInfo(CurLine, " 2", 2);
256    break;
257  case PPCallbacks::SystemHeaderPragma:
258  case PPCallbacks::RenameFile:
259    WriteLineInfo(CurLine);
260    break;
261  }
262}
263
264/// Ident - Handle #ident directives when read by the preprocessor.
265///
266void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
267  MoveToLine(Loc);
268
269  OS.write("#ident ", strlen("#ident "));
270  OS.write(&S[0], S.size());
271  EmittedTokensOnThisLine = true;
272}
273
274/// MacroDefined - This hook is called whenever a macro definition is seen.
275void PrintPPOutputPPCallbacks::MacroDefined(const IdentifierInfo *II,
276                                            const MacroInfo *MI) {
277  // Only print out macro definitions in -dD mode.
278  if (!DumpDefines ||
279      // Ignore __FILE__ etc.
280      MI->isBuiltinMacro()) return;
281
282  MoveToLine(MI->getDefinitionLoc());
283  PrintMacroDefinition(*II, *MI, PP, OS);
284  EmittedMacroOnThisLine = true;
285}
286
287
288void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
289                                             const IdentifierInfo *Kind,
290                                             const std::string &Str) {
291  MoveToLine(Loc);
292  OS << "#pragma comment(" << Kind->getName();
293
294  if (!Str.empty()) {
295    OS << ", \"";
296
297    for (unsigned i = 0, e = Str.size(); i != e; ++i) {
298      unsigned char Char = Str[i];
299      if (isprint(Char) && Char != '\\' && Char != '"')
300        OS << (char)Char;
301      else  // Output anything hard as an octal escape.
302        OS << '\\'
303           << (char)('0'+ ((Char >> 6) & 7))
304           << (char)('0'+ ((Char >> 3) & 7))
305           << (char)('0'+ ((Char >> 0) & 7));
306    }
307    OS << '"';
308  }
309
310  OS << ')';
311  EmittedTokensOnThisLine = true;
312}
313
314
315/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
316/// is called for the first token on each new line.  If this really is the start
317/// of a new logical line, handle it and return true, otherwise return false.
318/// This may not be the start of a logical line because the "start of line"
319/// marker is set for spelling lines, not instantiation ones.
320bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
321  // Figure out what line we went to and insert the appropriate number of
322  // newline characters.
323  if (!MoveToLine(Tok.getLocation()))
324    return false;
325
326  // Print out space characters so that the first token on a line is
327  // indented for easy reading.
328  unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
329
330  // This hack prevents stuff like:
331  // #define HASH #
332  // HASH define foo bar
333  // From having the # character end up at column 1, which makes it so it
334  // is not handled as a #define next time through the preprocessor if in
335  // -fpreprocessed mode.
336  if (ColNo <= 1 && Tok.is(tok::hash))
337    OS << ' ';
338
339  // Otherwise, indent the appropriate number of spaces.
340  for (; ColNo > 1; --ColNo)
341    OS << ' ';
342
343  return true;
344}
345
346void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
347                                                     unsigned Len) {
348  unsigned NumNewlines = 0;
349  for (; Len; --Len, ++TokStr) {
350    if (*TokStr != '\n' &&
351        *TokStr != '\r')
352      continue;
353
354    ++NumNewlines;
355
356    // If we have \n\r or \r\n, skip both and count as one line.
357    if (Len != 1 &&
358        (TokStr[1] == '\n' || TokStr[1] == '\r') &&
359        TokStr[0] != TokStr[1])
360      ++TokStr, --Len;
361  }
362
363  if (NumNewlines == 0) return;
364
365  CurLine += NumNewlines;
366}
367
368
369namespace {
370struct UnknownPragmaHandler : public PragmaHandler {
371  const char *Prefix;
372  PrintPPOutputPPCallbacks *Callbacks;
373
374  UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
375    : PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
376  virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
377    // Figure out what line we went to and insert the appropriate number of
378    // newline characters.
379    Callbacks->MoveToLine(PragmaTok.getLocation());
380    Callbacks->OS.write(Prefix, strlen(Prefix));
381
382    // Read and print all of the pragma tokens.
383    while (PragmaTok.isNot(tok::eom)) {
384      if (PragmaTok.hasLeadingSpace())
385        Callbacks->OS << ' ';
386      std::string TokSpell = PP.getSpelling(PragmaTok);
387      Callbacks->OS.write(&TokSpell[0], TokSpell.size());
388      PP.LexUnexpandedToken(PragmaTok);
389    }
390    Callbacks->OS << '\n';
391  }
392};
393} // end anonymous namespace
394
395
396static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
397                                    PrintPPOutputPPCallbacks *Callbacks,
398                                    llvm::raw_ostream &OS) {
399  char Buffer[256];
400  Token PrevPrevTok;
401  Token PrevTok;
402  while (1) {
403
404    // If this token is at the start of a line, emit newlines if needed.
405    if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
406      // done.
407    } else if (Tok.hasLeadingSpace() ||
408               // If we haven't emitted a token on this line yet, PrevTok isn't
409               // useful to look at and no concatenation could happen anyway.
410               (Callbacks->hasEmittedTokensOnThisLine() &&
411                // Don't print "-" next to "-", it would form "--".
412                Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
413      OS << ' ';
414    }
415
416    if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
417      OS << II->getName();
418    } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
419               Tok.getLiteralData()) {
420      OS.write(Tok.getLiteralData(), Tok.getLength());
421    } else if (Tok.getLength() < 256) {
422      const char *TokPtr = Buffer;
423      unsigned Len = PP.getSpelling(Tok, TokPtr);
424      OS.write(TokPtr, Len);
425
426      // Tokens that can contain embedded newlines need to adjust our current
427      // line number.
428      if (Tok.getKind() == tok::comment)
429        Callbacks->HandleNewlinesInToken(TokPtr, Len);
430    } else {
431      std::string S = PP.getSpelling(Tok);
432      OS.write(&S[0], S.size());
433
434      // Tokens that can contain embedded newlines need to adjust our current
435      // line number.
436      if (Tok.getKind() == tok::comment)
437        Callbacks->HandleNewlinesInToken(&S[0], S.size());
438    }
439    Callbacks->SetEmittedTokensOnThisLine();
440
441    if (Tok.is(tok::eof)) break;
442
443    PrevPrevTok = PrevTok;
444    PrevTok = Tok;
445    PP.Lex(Tok);
446  }
447}
448
449typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
450static int MacroIDCompare(const void* a, const void* b) {
451  const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
452  const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
453  return LHS->first->getName().compare(RHS->first->getName());
454}
455
456static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
457  // -dM mode just scans and ignores all tokens in the files, then dumps out
458  // the macro table at the end.
459  PP.EnterMainSourceFile();
460
461  Token Tok;
462  do PP.Lex(Tok);
463  while (Tok.isNot(tok::eof));
464
465  llvm::SmallVector<id_macro_pair, 128>
466    MacrosByID(PP.macro_begin(), PP.macro_end());
467  llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
468
469  for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
470    MacroInfo &MI = *MacrosByID[i].second;
471    // Ignore computed macros like __LINE__ and friends.
472    if (MI.isBuiltinMacro()) continue;
473
474    PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
475    *OS << '\n';
476  }
477}
478
479/// DoPrintPreprocessedInput - This implements -E mode.
480///
481void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
482                                     const PreprocessorOutputOptions &Opts) {
483  // Show macros with no output is handled specially.
484  if (!Opts.ShowCPP) {
485    assert(Opts.ShowMacros && "Not yet implemented!");
486    DoPrintMacros(PP, OS);
487    return;
488  }
489
490  // Inform the preprocessor whether we want it to retain comments or not, due
491  // to -C or -CC.
492  PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
493
494  PrintPPOutputPPCallbacks *Callbacks =
495      new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
496                                   Opts.ShowMacros);
497  PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
498  PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",
499                                                      Callbacks));
500
501  PP.addPPCallbacks(Callbacks);
502
503  // After we have configured the preprocessor, enter the main file.
504  PP.EnterMainSourceFile();
505
506  // Consume all of the tokens that come from the predefines buffer.  Those
507  // should not be emitted into the output and are guaranteed to be at the
508  // start.
509  const SourceManager &SourceMgr = PP.getSourceManager();
510  Token Tok;
511  do PP.Lex(Tok);
512  while (Tok.isNot(tok::eof) && Tok.getLocation().isFileID() &&
513         !strcmp(SourceMgr.getPresumedLoc(Tok.getLocation()).getFilename(),
514                 "<built-in>"));
515
516  // Read all the preprocessed tokens, printing them out to the stream.
517  PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
518  *OS << '\n';
519}
520
521