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