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