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/CharInfo.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Frontend/PreprocessorOutputOptions.h"
20 #include "clang/Lex/MacroInfo.h"
21 #include "clang/Lex/PPCallbacks.h"
22 #include "clang/Lex/Pragma.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Lex/TokenConcatenation.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.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, 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 SmallString<128> SpellingBuffer;
67 for (const auto &T : MI.tokens()) {
68 if (T.hasLeadingSpace())
71 OS << PP.getSpelling(T, SpellingBuffer);
75 //===----------------------------------------------------------------------===//
76 // Preprocessed token printer
77 //===----------------------------------------------------------------------===//
80 class PrintPPOutputPPCallbacks : public PPCallbacks {
83 TokenConcatenation ConcatInfo;
89 bool EmittedTokensOnThisLine;
90 bool EmittedDirectiveOnThisLine;
91 SrcMgr::CharacteristicKind FileType;
92 SmallString<512> CurFilename;
94 bool DisableLineMarkers;
96 bool DumpIncludeDirectives;
97 bool UseLineDirectives;
98 bool IsFirstFileEntered;
100 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
101 bool defines, bool DumpIncludeDirectives,
102 bool UseLineDirectives)
103 : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
104 DisableLineMarkers(lineMarkers), DumpDefines(defines),
105 DumpIncludeDirectives(DumpIncludeDirectives),
106 UseLineDirectives(UseLineDirectives) {
108 CurFilename += "<uninit>";
109 EmittedTokensOnThisLine = false;
110 EmittedDirectiveOnThisLine = false;
111 FileType = SrcMgr::C_User;
113 IsFirstFileEntered = false;
116 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
117 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
119 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
120 bool hasEmittedDirectiveOnThisLine() const {
121 return EmittedDirectiveOnThisLine;
124 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
126 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
127 SrcMgr::CharacteristicKind FileType,
128 FileID PrevFID) override;
129 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
130 StringRef FileName, bool IsAngled,
131 CharSourceRange FilenameRange, const FileEntry *File,
132 StringRef SearchPath, StringRef RelativePath,
133 const Module *Imported) override;
134 void Ident(SourceLocation Loc, StringRef str) override;
135 void PragmaMessage(SourceLocation Loc, StringRef Namespace,
136 PragmaMessageKind Kind, StringRef Str) override;
137 void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
138 void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
139 void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
140 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
141 diag::Severity Map, StringRef Str) override;
142 void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
143 ArrayRef<int> Ids) override;
144 void PragmaWarningPush(SourceLocation Loc, int Level) override;
145 void PragmaWarningPop(SourceLocation Loc) override;
147 bool HandleFirstTokOnLine(Token &Tok);
149 /// Move to the line of the provided source location. This will
150 /// return true if the output stream required adjustment or if
151 /// the requested location is on the first line.
152 bool MoveToLine(SourceLocation Loc) {
153 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
154 if (PLoc.isInvalid())
156 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
158 bool MoveToLine(unsigned LineNo);
160 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
162 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
164 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
165 unsigned ExtraLen=0);
166 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
167 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
169 /// MacroDefined - This hook is called whenever a macro definition is seen.
170 void MacroDefined(const Token &MacroNameTok,
171 const MacroDirective *MD) override;
173 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
174 void MacroUndefined(const Token &MacroNameTok,
175 const MacroDefinition &MD,
176 const MacroDirective *Undef) override;
178 } // end anonymous namespace
180 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
183 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
185 // Emit #line directives or GNU line markers depending on what mode we're in.
186 if (UseLineDirectives) {
187 OS << "#line" << ' ' << LineNo << ' ' << '"';
188 OS.write_escaped(CurFilename);
191 OS << '#' << ' ' << LineNo << ' ' << '"';
192 OS.write_escaped(CurFilename);
196 OS.write(Extra, ExtraLen);
198 if (FileType == SrcMgr::C_System)
200 else if (FileType == SrcMgr::C_ExternCSystem)
206 /// MoveToLine - Move the output to the source line specified by the location
207 /// object. We can do this by emitting some number of \n's, or be emitting a
208 /// #line directive. This returns false if already at the specified line, true
209 /// if some newlines were emitted.
210 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
211 // If this line is "close enough" to the original line, just print newlines,
212 // otherwise print a #line directive.
213 if (LineNo-CurLine <= 8) {
214 if (LineNo-CurLine == 1)
216 else if (LineNo == CurLine)
217 return false; // Spelling line moved, but expansion line didn't.
219 const char *NewLines = "\n\n\n\n\n\n\n\n";
220 OS.write(NewLines, LineNo-CurLine);
222 } else if (!DisableLineMarkers) {
223 // Emit a #line or line marker.
224 WriteLineInfo(LineNo, nullptr, 0);
226 // Okay, we're in -P mode, which turns off line markers. However, we still
227 // need to emit a newline between tokens on different lines.
228 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
236 PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
237 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
239 EmittedTokensOnThisLine = false;
240 EmittedDirectiveOnThisLine = false;
241 if (ShouldUpdateCurrentLine)
249 /// FileChanged - Whenever the preprocessor enters or exits a #include file
250 /// it invokes this handler. Update our conception of the current source
252 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
253 FileChangeReason Reason,
254 SrcMgr::CharacteristicKind NewFileType,
256 // Unless we are exiting a #include, make sure to skip ahead to the line the
257 // #include directive was at.
258 SourceManager &SourceMgr = SM;
260 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
261 if (UserLoc.isInvalid())
264 unsigned NewLine = UserLoc.getLine();
266 if (Reason == PPCallbacks::EnterFile) {
267 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
268 if (IncludeLoc.isValid())
269 MoveToLine(IncludeLoc);
270 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
271 // GCC emits the # directive for this directive on the line AFTER the
272 // directive and emits a bunch of spaces that aren't needed. This is because
273 // otherwise we will emit a line marker for THIS line, which requires an
274 // extra blank line after the directive to avoid making all following lines
275 // off by one. We can do better by simply incrementing NewLine here.
282 CurFilename += UserLoc.getFilename();
283 FileType = NewFileType;
285 if (DisableLineMarkers) {
286 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
291 WriteLineInfo(CurLine);
295 // Do not emit an enter marker for the main file (which we expect is the first
296 // entered file). This matches gcc, and improves compatibility with some tools
297 // which track the # line markers as a way to determine when the preprocessed
298 // output is in the context of the main file.
299 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
300 IsFirstFileEntered = true;
305 case PPCallbacks::EnterFile:
306 WriteLineInfo(CurLine, " 1", 2);
308 case PPCallbacks::ExitFile:
309 WriteLineInfo(CurLine, " 2", 2);
311 case PPCallbacks::SystemHeaderPragma:
312 case PPCallbacks::RenameFile:
313 WriteLineInfo(CurLine);
318 void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
319 const Token &IncludeTok,
322 CharSourceRange FilenameRange,
323 const FileEntry *File,
324 StringRef SearchPath,
325 StringRef RelativePath,
326 const Module *Imported) {
327 // In -dI mode, dump #include directives prior to dumping their content or
329 if (DumpIncludeDirectives) {
330 startNewLineIfNeeded();
332 const std::string TokenText = PP.getSpelling(IncludeTok);
333 assert(!TokenText.empty());
334 OS << "#" << TokenText << " "
335 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
336 << " /* clang -E -dI */";
337 setEmittedDirectiveOnThisLine();
338 startNewLineIfNeeded();
341 // When preprocessing, turn implicit imports into module import pragmas.
343 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
344 case tok::pp_include:
346 case tok::pp_include_next:
347 startNewLineIfNeeded();
349 OS << "#pragma clang module import " << Imported->getFullModuleName()
350 << " /* clang -E: implicit import for "
351 << "#" << PP.getSpelling(IncludeTok) << " "
352 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
354 // Since we want a newline after the pragma, but not a #<line>, start a
355 // new line immediately.
356 EmittedTokensOnThisLine = true;
357 startNewLineIfNeeded();
360 case tok::pp___include_macros:
361 // #__include_macros has no effect on a user of a preprocessed source
362 // file; the only effect is on preprocessing.
364 // FIXME: That's not *quite* true: it causes the module in question to
365 // be loaded, which can affect downstream diagnostics.
369 llvm_unreachable("unknown include directive kind");
375 /// Ident - Handle #ident directives when read by the preprocessor.
377 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
380 OS.write("#ident ", strlen("#ident "));
381 OS.write(S.begin(), S.size());
382 EmittedTokensOnThisLine = true;
385 /// MacroDefined - This hook is called whenever a macro definition is seen.
386 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
387 const MacroDirective *MD) {
388 const MacroInfo *MI = MD->getMacroInfo();
389 // Only print out macro definitions in -dD mode.
391 // Ignore __FILE__ etc.
392 MI->isBuiltinMacro()) return;
394 MoveToLine(MI->getDefinitionLoc());
395 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
396 setEmittedDirectiveOnThisLine();
399 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
400 const MacroDefinition &MD,
401 const MacroDirective *Undef) {
402 // Only print out macro definitions in -dD mode.
403 if (!DumpDefines) return;
405 MoveToLine(MacroNameTok.getLocation());
406 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
407 setEmittedDirectiveOnThisLine();
410 static void outputPrintable(raw_ostream &OS, StringRef Str) {
411 for (unsigned char Char : Str) {
412 if (isPrintable(Char) && Char != '\\' && Char != '"')
414 else // Output anything hard as an octal escape.
416 << (char)('0' + ((Char >> 6) & 7))
417 << (char)('0' + ((Char >> 3) & 7))
418 << (char)('0' + ((Char >> 0) & 7));
422 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
424 PragmaMessageKind Kind,
426 startNewLineIfNeeded();
429 if (!Namespace.empty())
430 OS << Namespace << ' ';
443 outputPrintable(OS, Str);
445 if (Kind == PMK_Message)
447 setEmittedDirectiveOnThisLine();
450 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
451 StringRef DebugType) {
452 startNewLineIfNeeded();
455 OS << "#pragma clang __debug ";
458 setEmittedDirectiveOnThisLine();
461 void PrintPPOutputPPCallbacks::
462 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
463 startNewLineIfNeeded();
465 OS << "#pragma " << Namespace << " diagnostic push";
466 setEmittedDirectiveOnThisLine();
469 void PrintPPOutputPPCallbacks::
470 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
471 startNewLineIfNeeded();
473 OS << "#pragma " << Namespace << " diagnostic pop";
474 setEmittedDirectiveOnThisLine();
477 void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
481 startNewLineIfNeeded();
483 OS << "#pragma " << Namespace << " diagnostic ";
485 case diag::Severity::Remark:
488 case diag::Severity::Warning:
491 case diag::Severity::Error:
494 case diag::Severity::Ignored:
497 case diag::Severity::Fatal:
501 OS << " \"" << Str << '"';
502 setEmittedDirectiveOnThisLine();
505 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
506 StringRef WarningSpec,
508 startNewLineIfNeeded();
510 OS << "#pragma warning(" << WarningSpec << ':';
511 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
514 setEmittedDirectiveOnThisLine();
517 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
519 startNewLineIfNeeded();
521 OS << "#pragma warning(push";
525 setEmittedDirectiveOnThisLine();
528 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
529 startNewLineIfNeeded();
531 OS << "#pragma warning(pop)";
532 setEmittedDirectiveOnThisLine();
535 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
536 /// is called for the first token on each new line. If this really is the start
537 /// of a new logical line, handle it and return true, otherwise return false.
538 /// This may not be the start of a logical line because the "start of line"
539 /// marker is set for spelling lines, not expansion ones.
540 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
541 // Figure out what line we went to and insert the appropriate number of
542 // newline characters.
543 if (!MoveToLine(Tok.getLocation()))
546 // Print out space characters so that the first token on a line is
547 // indented for easy reading.
548 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
550 // The first token on a line can have a column number of 1, yet still expect
551 // leading white space, if a macro expansion in column 1 starts with an empty
552 // macro argument, or an empty nested macro expansion. In this case, move the
553 // token to column 2.
554 if (ColNo == 1 && Tok.hasLeadingSpace())
557 // This hack prevents stuff like:
559 // HASH define foo bar
560 // From having the # character end up at column 1, which makes it so it
561 // is not handled as a #define next time through the preprocessor if in
562 // -fpreprocessed mode.
563 if (ColNo <= 1 && Tok.is(tok::hash))
566 // Otherwise, indent the appropriate number of spaces.
567 for (; ColNo > 1; --ColNo)
573 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
575 unsigned NumNewlines = 0;
576 for (; Len; --Len, ++TokStr) {
577 if (*TokStr != '\n' &&
583 // If we have \n\r or \r\n, skip both and count as one line.
585 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
586 TokStr[0] != TokStr[1]) {
592 if (NumNewlines == 0) return;
594 CurLine += NumNewlines;
599 struct UnknownPragmaHandler : public PragmaHandler {
601 PrintPPOutputPPCallbacks *Callbacks;
603 // Set to true if tokens should be expanded
604 bool ShouldExpandTokens;
606 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
607 bool RequireTokenExpansion)
608 : Prefix(prefix), Callbacks(callbacks),
609 ShouldExpandTokens(RequireTokenExpansion) {}
610 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
611 Token &PragmaTok) override {
612 // Figure out what line we went to and insert the appropriate number of
613 // newline characters.
614 Callbacks->startNewLineIfNeeded();
615 Callbacks->MoveToLine(PragmaTok.getLocation());
616 Callbacks->OS.write(Prefix, strlen(Prefix));
618 if (ShouldExpandTokens) {
619 // The first token does not have expanded macros. Expand them, if
621 auto Toks = llvm::make_unique<Token[]>(1);
623 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
624 /*DisableMacroExpansion=*/false);
629 PrevToken.startToken();
630 PrevPrevToken.startToken();
632 // Read and print all of the pragma tokens.
633 while (PragmaTok.isNot(tok::eod)) {
634 if (PragmaTok.hasLeadingSpace() ||
635 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
636 Callbacks->OS << ' ';
637 std::string TokSpell = PP.getSpelling(PragmaTok);
638 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
640 PrevPrevToken = PrevToken;
641 PrevToken = PragmaTok;
643 if (ShouldExpandTokens)
646 PP.LexUnexpandedToken(PragmaTok);
648 Callbacks->setEmittedDirectiveOnThisLine();
651 } // end anonymous namespace
654 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
655 PrintPPOutputPPCallbacks *Callbacks,
657 bool DropComments = PP.getLangOpts().TraditionalCPP &&
658 !PP.getCommentRetentionState();
661 Token PrevPrevTok, PrevTok;
662 PrevPrevTok.startToken();
663 PrevTok.startToken();
665 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
666 Callbacks->startNewLineIfNeeded();
667 Callbacks->MoveToLine(Tok.getLocation());
670 // If this token is at the start of a line, emit newlines if needed.
671 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
673 } else if (Tok.hasLeadingSpace() ||
674 // If we haven't emitted a token on this line yet, PrevTok isn't
675 // useful to look at and no concatenation could happen anyway.
676 (Callbacks->hasEmittedTokensOnThisLine() &&
677 // Don't print "-" next to "-", it would form "--".
678 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
682 if (DropComments && Tok.is(tok::comment)) {
683 // Skip comments. Normally the preprocessor does not generate
684 // tok::comment nodes at all when not keeping comments, but under
685 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
686 SourceLocation StartLoc = Tok.getLocation();
687 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
688 } else if (Tok.is(tok::annot_module_include) ||
689 Tok.is(tok::annot_module_begin) ||
690 Tok.is(tok::annot_module_end)) {
691 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
692 // appropriate output here. Ignore this token entirely.
695 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
697 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
698 Tok.getLiteralData()) {
699 OS.write(Tok.getLiteralData(), Tok.getLength());
700 } else if (Tok.getLength() < 256) {
701 const char *TokPtr = Buffer;
702 unsigned Len = PP.getSpelling(Tok, TokPtr);
703 OS.write(TokPtr, Len);
705 // Tokens that can contain embedded newlines need to adjust our current
707 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
708 Callbacks->HandleNewlinesInToken(TokPtr, Len);
710 std::string S = PP.getSpelling(Tok);
711 OS.write(&S[0], S.size());
713 // Tokens that can contain embedded newlines need to adjust our current
715 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
716 Callbacks->HandleNewlinesInToken(&S[0], S.size());
718 Callbacks->setEmittedTokensOnThisLine();
720 if (Tok.is(tok::eof)) break;
722 PrevPrevTok = PrevTok;
728 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
729 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
730 return LHS->first->getName().compare(RHS->first->getName());
733 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
734 // Ignore unknown pragmas.
737 // -dM mode just scans and ignores all tokens in the files, then dumps out
738 // the macro table at the end.
739 PP.EnterMainSourceFile();
743 while (Tok.isNot(tok::eof));
745 SmallVector<id_macro_pair, 128> MacrosByID;
746 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
748 auto *MD = I->second.getLatest();
749 if (MD && MD->isDefined())
750 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
752 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
754 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
755 MacroInfo &MI = *MacrosByID[i].second;
756 // Ignore computed macros like __LINE__ and friends.
757 if (MI.isBuiltinMacro()) continue;
759 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
764 /// DoPrintPreprocessedInput - This implements -E mode.
766 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
767 const PreprocessorOutputOptions &Opts) {
768 // Show macros with no output is handled specially.
770 assert(Opts.ShowMacros && "Not yet implemented!");
771 DoPrintMacros(PP, OS);
775 // Inform the preprocessor whether we want it to retain comments or not, due
777 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
779 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
780 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
781 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
783 // Expand macros in pragmas with -fms-extensions. The assumption is that
784 // the majority of pragmas in such a file will be Microsoft pragmas.
785 // Remember the handlers we will add so that we can remove them later.
786 std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
787 new UnknownPragmaHandler(
788 "#pragma", Callbacks,
789 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
791 std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
792 "#pragma GCC", Callbacks,
793 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
795 std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
796 "#pragma clang", Callbacks,
797 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
799 PP.AddPragmaHandler(MicrosoftExtHandler.get());
800 PP.AddPragmaHandler("GCC", GCCHandler.get());
801 PP.AddPragmaHandler("clang", ClangHandler.get());
803 // The tokens after pragma omp need to be expanded.
805 // OpenMP [2.1, Directive format]
806 // Preprocessing tokens following the #pragma omp are subject to macro
808 std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
809 new UnknownPragmaHandler("#pragma omp", Callbacks,
810 /*RequireTokenExpansion=*/true));
811 PP.AddPragmaHandler("omp", OpenMPHandler.get());
813 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
815 // After we have configured the preprocessor, enter the main file.
816 PP.EnterMainSourceFile();
818 // Consume all of the tokens that come from the predefines buffer. Those
819 // should not be emitted into the output and are guaranteed to be at the
821 const SourceManager &SourceMgr = PP.getSourceManager();
825 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
828 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
829 if (PLoc.isInvalid())
832 if (strcmp(PLoc.getFilename(), "<built-in>"))
836 // Read all the preprocessed tokens, printing them out to the stream.
837 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
840 // Remove the handlers we just added to leave the preprocessor in a sane state
841 // so that it can be reused (for example by a clang::Parser instance).
842 PP.RemovePragmaHandler(MicrosoftExtHandler.get());
843 PP.RemovePragmaHandler("GCC", GCCHandler.get());
844 PP.RemovePragmaHandler("clang", ClangHandler.get());
845 PP.RemovePragmaHandler("omp", OpenMPHandler.get());