1 //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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"
31 using namespace clang;
33 /// PrintMacroDefinition - Print a macro definition in a form that will be
34 /// properly accepted back as a definition.
35 static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
36 Preprocessor &PP, llvm::raw_ostream &OS) {
37 OS << "#define " << II.getName();
39 if (MI.isFunctionLike()) {
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();
49 if ((*AI)->getName() == "__VA_ARGS__")
52 OS << (*AI)->getName();
55 if (MI.isGNUVarargs())
56 OS << "..."; // #define foo(x...)
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())
66 llvm::SmallString<128> SpellingBuffer;
67 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
69 if (I->hasLeadingSpace())
72 OS << PP.getSpelling(*I, SpellingBuffer);
76 //===----------------------------------------------------------------------===//
77 // Preprocessed token printer
78 //===----------------------------------------------------------------------===//
81 class PrintPPOutputPPCallbacks : public PPCallbacks {
84 TokenConcatenation ConcatInfo;
86 llvm::raw_ostream &OS;
90 bool EmittedTokensOnThisLine;
91 bool EmittedMacroOnThisLine;
92 SrcMgr::CharacteristicKind FileType;
93 llvm::SmallString<512> CurFilename;
95 bool DisableLineMarkers;
97 bool UseLineDirective;
99 PrintPPOutputPPCallbacks(Preprocessor &pp, llvm::raw_ostream &os,
100 bool lineMarkers, bool defines)
101 : PP(pp), SM(PP.getSourceManager()),
102 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
103 DumpDefines(defines) {
105 CurFilename += "<uninit>";
106 EmittedTokensOnThisLine = false;
107 EmittedMacroOnThisLine = false;
108 FileType = SrcMgr::C_User;
111 // If we're in microsoft mode, use normal #line instead of line markers.
112 UseLineDirective = PP.getLangOptions().Microsoft;
115 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
116 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
118 bool StartNewLineIfNeeded();
120 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
121 SrcMgr::CharacteristicKind FileType);
122 virtual void Ident(SourceLocation Loc, const std::string &str);
123 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
124 const std::string &Str);
125 virtual void PragmaMessage(SourceLocation Loc, llvm::StringRef Str);
126 virtual void PragmaDiagnosticPush(SourceLocation Loc,
127 llvm::StringRef Namespace);
128 virtual void PragmaDiagnosticPop(SourceLocation Loc,
129 llvm::StringRef Namespace);
130 virtual void PragmaDiagnostic(SourceLocation Loc, llvm::StringRef Namespace,
131 diag::Mapping Map, llvm::StringRef Str);
133 bool HandleFirstTokOnLine(Token &Tok);
134 bool MoveToLine(SourceLocation Loc) {
135 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
136 if (PLoc.isInvalid())
138 return MoveToLine(PLoc.getLine());
140 bool MoveToLine(unsigned LineNo);
142 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
144 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
146 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
147 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
148 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
150 /// MacroDefined - This hook is called whenever a macro definition is seen.
151 void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI);
153 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
154 void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI);
156 } // end anonymous namespace
158 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
161 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
163 EmittedTokensOnThisLine = false;
164 EmittedMacroOnThisLine = false;
167 // Emit #line directives or GNU line markers depending on what mode we're in.
168 if (UseLineDirective) {
169 OS << "#line" << ' ' << LineNo << ' ' << '"';
170 OS.write(CurFilename.data(), CurFilename.size());
173 OS << '#' << ' ' << LineNo << ' ' << '"';
174 OS.write(CurFilename.data(), CurFilename.size());
178 OS.write(Extra, ExtraLen);
180 if (FileType == SrcMgr::C_System)
182 else if (FileType == SrcMgr::C_ExternCSystem)
188 /// MoveToLine - Move the output to the source line specified by the location
189 /// object. We can do this by emitting some number of \n's, or be emitting a
190 /// #line directive. This returns false if already at the specified line, true
191 /// if some newlines were emitted.
192 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
193 // If this line is "close enough" to the original line, just print newlines,
194 // otherwise print a #line directive.
195 if (LineNo-CurLine <= 8) {
196 if (LineNo-CurLine == 1)
198 else if (LineNo == CurLine)
199 return false; // Spelling line moved, but expansion line didn't.
201 const char *NewLines = "\n\n\n\n\n\n\n\n";
202 OS.write(NewLines, LineNo-CurLine);
204 } else if (!DisableLineMarkers) {
205 // Emit a #line or line marker.
206 WriteLineInfo(LineNo, 0, 0);
208 // Okay, we're in -P mode, which turns off line markers. However, we still
209 // need to emit a newline between tokens on different lines.
210 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
212 EmittedTokensOnThisLine = false;
213 EmittedMacroOnThisLine = false;
221 bool PrintPPOutputPPCallbacks::StartNewLineIfNeeded() {
222 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
224 EmittedTokensOnThisLine = false;
225 EmittedMacroOnThisLine = false;
233 /// FileChanged - Whenever the preprocessor enters or exits a #include file
234 /// it invokes this handler. Update our conception of the current source
236 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
237 FileChangeReason Reason,
238 SrcMgr::CharacteristicKind NewFileType) {
239 // Unless we are exiting a #include, make sure to skip ahead to the line the
240 // #include directive was at.
241 SourceManager &SourceMgr = SM;
243 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
244 if (UserLoc.isInvalid())
247 unsigned NewLine = UserLoc.getLine();
249 if (Reason == PPCallbacks::EnterFile) {
250 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
251 if (IncludeLoc.isValid())
252 MoveToLine(IncludeLoc);
253 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
256 // TODO GCC emits the # directive for this directive on the line AFTER the
257 // directive and emits a bunch of spaces that aren't needed. Emulate this
264 CurFilename += UserLoc.getFilename();
265 Lexer::Stringify(CurFilename);
266 FileType = NewFileType;
268 if (DisableLineMarkers) return;
271 WriteLineInfo(CurLine);
276 case PPCallbacks::EnterFile:
277 WriteLineInfo(CurLine, " 1", 2);
279 case PPCallbacks::ExitFile:
280 WriteLineInfo(CurLine, " 2", 2);
282 case PPCallbacks::SystemHeaderPragma:
283 case PPCallbacks::RenameFile:
284 WriteLineInfo(CurLine);
289 /// Ident - Handle #ident directives when read by the preprocessor.
291 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
294 OS.write("#ident ", strlen("#ident "));
295 OS.write(&S[0], S.size());
296 EmittedTokensOnThisLine = true;
299 /// MacroDefined - This hook is called whenever a macro definition is seen.
300 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
301 const MacroInfo *MI) {
302 // Only print out macro definitions in -dD mode.
304 // Ignore __FILE__ etc.
305 MI->isBuiltinMacro()) return;
307 MoveToLine(MI->getDefinitionLoc());
308 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
309 EmittedMacroOnThisLine = true;
312 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
313 const MacroInfo *MI) {
314 // Only print out macro definitions in -dD mode.
315 if (!DumpDefines) return;
317 MoveToLine(MacroNameTok.getLocation());
318 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
319 EmittedMacroOnThisLine = true;
322 void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
323 const IdentifierInfo *Kind,
324 const std::string &Str) {
326 OS << "#pragma comment(" << Kind->getName();
331 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
332 unsigned char Char = Str[i];
333 if (isprint(Char) && Char != '\\' && Char != '"')
335 else // Output anything hard as an octal escape.
337 << (char)('0'+ ((Char >> 6) & 7))
338 << (char)('0'+ ((Char >> 3) & 7))
339 << (char)('0'+ ((Char >> 0) & 7));
345 EmittedTokensOnThisLine = true;
348 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
349 llvm::StringRef Str) {
351 OS << "#pragma message(";
355 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
356 unsigned char Char = Str[i];
357 if (isprint(Char) && Char != '\\' && Char != '"')
359 else // Output anything hard as an octal escape.
361 << (char)('0'+ ((Char >> 6) & 7))
362 << (char)('0'+ ((Char >> 3) & 7))
363 << (char)('0'+ ((Char >> 0) & 7));
368 EmittedTokensOnThisLine = true;
371 void PrintPPOutputPPCallbacks::
372 PragmaDiagnosticPush(SourceLocation Loc, llvm::StringRef Namespace) {
374 OS << "#pragma " << Namespace << " diagnostic push";
375 EmittedTokensOnThisLine = true;
378 void PrintPPOutputPPCallbacks::
379 PragmaDiagnosticPop(SourceLocation Loc, llvm::StringRef Namespace) {
381 OS << "#pragma " << Namespace << " diagnostic pop";
382 EmittedTokensOnThisLine = true;
385 void PrintPPOutputPPCallbacks::
386 PragmaDiagnostic(SourceLocation Loc, llvm::StringRef Namespace,
387 diag::Mapping Map, llvm::StringRef Str) {
389 OS << "#pragma " << Namespace << " diagnostic ";
391 default: llvm_unreachable("unexpected diagnostic kind");
392 case diag::MAP_WARNING:
395 case diag::MAP_ERROR:
398 case diag::MAP_IGNORE:
401 case diag::MAP_FATAL:
405 OS << " \"" << Str << '"';
406 EmittedTokensOnThisLine = true;
409 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
410 /// is called for the first token on each new line. If this really is the start
411 /// of a new logical line, handle it and return true, otherwise return false.
412 /// This may not be the start of a logical line because the "start of line"
413 /// marker is set for spelling lines, not expansion ones.
414 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
415 // Figure out what line we went to and insert the appropriate number of
416 // newline characters.
417 if (!MoveToLine(Tok.getLocation()))
420 // Print out space characters so that the first token on a line is
421 // indented for easy reading.
422 unsigned ColNo = SM.getInstantiationColumnNumber(Tok.getLocation());
424 // This hack prevents stuff like:
426 // HASH define foo bar
427 // From having the # character end up at column 1, which makes it so it
428 // is not handled as a #define next time through the preprocessor if in
429 // -fpreprocessed mode.
430 if (ColNo <= 1 && Tok.is(tok::hash))
433 // Otherwise, indent the appropriate number of spaces.
434 for (; ColNo > 1; --ColNo)
440 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
442 unsigned NumNewlines = 0;
443 for (; Len; --Len, ++TokStr) {
444 if (*TokStr != '\n' &&
450 // If we have \n\r or \r\n, skip both and count as one line.
452 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
453 TokStr[0] != TokStr[1])
457 if (NumNewlines == 0) return;
459 CurLine += NumNewlines;
464 struct UnknownPragmaHandler : public PragmaHandler {
466 PrintPPOutputPPCallbacks *Callbacks;
468 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
469 : Prefix(prefix), Callbacks(callbacks) {}
470 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
472 // Figure out what line we went to and insert the appropriate number of
473 // newline characters.
474 Callbacks->StartNewLineIfNeeded();
475 Callbacks->MoveToLine(PragmaTok.getLocation());
476 Callbacks->OS.write(Prefix, strlen(Prefix));
477 Callbacks->SetEmittedTokensOnThisLine();
478 // Read and print all of the pragma tokens.
479 while (PragmaTok.isNot(tok::eod)) {
480 if (PragmaTok.hasLeadingSpace())
481 Callbacks->OS << ' ';
482 std::string TokSpell = PP.getSpelling(PragmaTok);
483 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
484 PP.LexUnexpandedToken(PragmaTok);
486 Callbacks->StartNewLineIfNeeded();
489 } // end anonymous namespace
492 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
493 PrintPPOutputPPCallbacks *Callbacks,
494 llvm::raw_ostream &OS) {
496 Token PrevPrevTok, PrevTok;
497 PrevPrevTok.startToken();
498 PrevTok.startToken();
501 // If this token is at the start of a line, emit newlines if needed.
502 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
504 } else if (Tok.hasLeadingSpace() ||
505 // If we haven't emitted a token on this line yet, PrevTok isn't
506 // useful to look at and no concatenation could happen anyway.
507 (Callbacks->hasEmittedTokensOnThisLine() &&
508 // Don't print "-" next to "-", it would form "--".
509 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
513 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
515 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
516 Tok.getLiteralData()) {
517 OS.write(Tok.getLiteralData(), Tok.getLength());
518 } else if (Tok.getLength() < 256) {
519 const char *TokPtr = Buffer;
520 unsigned Len = PP.getSpelling(Tok, TokPtr);
521 OS.write(TokPtr, Len);
523 // Tokens that can contain embedded newlines need to adjust our current
525 if (Tok.getKind() == tok::comment)
526 Callbacks->HandleNewlinesInToken(TokPtr, Len);
528 std::string S = PP.getSpelling(Tok);
529 OS.write(&S[0], S.size());
531 // Tokens that can contain embedded newlines need to adjust our current
533 if (Tok.getKind() == tok::comment)
534 Callbacks->HandleNewlinesInToken(&S[0], S.size());
536 Callbacks->SetEmittedTokensOnThisLine();
538 if (Tok.is(tok::eof)) break;
540 PrevPrevTok = PrevTok;
546 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
547 static int MacroIDCompare(const void* a, const void* b) {
548 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
549 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
550 return LHS->first->getName().compare(RHS->first->getName());
553 static void DoPrintMacros(Preprocessor &PP, llvm::raw_ostream *OS) {
554 // Ignore unknown pragmas.
555 PP.AddPragmaHandler(new EmptyPragmaHandler());
557 // -dM mode just scans and ignores all tokens in the files, then dumps out
558 // the macro table at the end.
559 PP.EnterMainSourceFile();
563 while (Tok.isNot(tok::eof));
565 llvm::SmallVector<id_macro_pair, 128>
566 MacrosByID(PP.macro_begin(), PP.macro_end());
567 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
569 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
570 MacroInfo &MI = *MacrosByID[i].second;
571 // Ignore computed macros like __LINE__ and friends.
572 if (MI.isBuiltinMacro()) continue;
574 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
579 /// DoPrintPreprocessedInput - This implements -E mode.
581 void clang::DoPrintPreprocessedInput(Preprocessor &PP, llvm::raw_ostream *OS,
582 const PreprocessorOutputOptions &Opts) {
583 // Show macros with no output is handled specially.
585 assert(Opts.ShowMacros && "Not yet implemented!");
586 DoPrintMacros(PP, OS);
590 // Inform the preprocessor whether we want it to retain comments or not, due
592 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
594 PrintPPOutputPPCallbacks *Callbacks =
595 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
597 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
598 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
599 PP.AddPragmaHandler("clang",
600 new UnknownPragmaHandler("#pragma clang", Callbacks));
602 PP.addPPCallbacks(Callbacks);
604 // After we have configured the preprocessor, enter the main file.
605 PP.EnterMainSourceFile();
607 // Consume all of the tokens that come from the predefines buffer. Those
608 // should not be emitted into the output and are guaranteed to be at the
610 const SourceManager &SourceMgr = PP.getSourceManager();
614 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
617 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
618 if (PLoc.isInvalid())
621 if (strcmp(PLoc.getFilename(), "<built-in>"))
625 // Read all the preprocessed tokens, printing them out to the stream.
626 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);