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