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 void BeginModule(const Module *M);
179 void EndModule(const Module *M);
181 } // end anonymous namespace
183 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
186 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
188 // Emit #line directives or GNU line markers depending on what mode we're in.
189 if (UseLineDirectives) {
190 OS << "#line" << ' ' << LineNo << ' ' << '"';
191 OS.write_escaped(CurFilename);
194 OS << '#' << ' ' << LineNo << ' ' << '"';
195 OS.write_escaped(CurFilename);
199 OS.write(Extra, ExtraLen);
201 if (FileType == SrcMgr::C_System)
203 else if (FileType == SrcMgr::C_ExternCSystem)
209 /// MoveToLine - Move the output to the source line specified by the location
210 /// object. We can do this by emitting some number of \n's, or be emitting a
211 /// #line directive. This returns false if already at the specified line, true
212 /// if some newlines were emitted.
213 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
214 // If this line is "close enough" to the original line, just print newlines,
215 // otherwise print a #line directive.
216 if (LineNo-CurLine <= 8) {
217 if (LineNo-CurLine == 1)
219 else if (LineNo == CurLine)
220 return false; // Spelling line moved, but expansion line didn't.
222 const char *NewLines = "\n\n\n\n\n\n\n\n";
223 OS.write(NewLines, LineNo-CurLine);
225 } else if (!DisableLineMarkers) {
226 // Emit a #line or line marker.
227 WriteLineInfo(LineNo, nullptr, 0);
229 // Okay, we're in -P mode, which turns off line markers. However, we still
230 // need to emit a newline between tokens on different lines.
231 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
239 PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
240 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
242 EmittedTokensOnThisLine = false;
243 EmittedDirectiveOnThisLine = false;
244 if (ShouldUpdateCurrentLine)
252 /// FileChanged - Whenever the preprocessor enters or exits a #include file
253 /// it invokes this handler. Update our conception of the current source
255 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
256 FileChangeReason Reason,
257 SrcMgr::CharacteristicKind NewFileType,
259 // Unless we are exiting a #include, make sure to skip ahead to the line the
260 // #include directive was at.
261 SourceManager &SourceMgr = SM;
263 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
264 if (UserLoc.isInvalid())
267 unsigned NewLine = UserLoc.getLine();
269 if (Reason == PPCallbacks::EnterFile) {
270 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
271 if (IncludeLoc.isValid())
272 MoveToLine(IncludeLoc);
273 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
274 // GCC emits the # directive for this directive on the line AFTER the
275 // directive and emits a bunch of spaces that aren't needed. This is because
276 // otherwise we will emit a line marker for THIS line, which requires an
277 // extra blank line after the directive to avoid making all following lines
278 // off by one. We can do better by simply incrementing NewLine here.
285 CurFilename += UserLoc.getFilename();
286 FileType = NewFileType;
288 if (DisableLineMarkers) {
289 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
294 WriteLineInfo(CurLine);
298 // Do not emit an enter marker for the main file (which we expect is the first
299 // entered file). This matches gcc, and improves compatibility with some tools
300 // which track the # line markers as a way to determine when the preprocessed
301 // output is in the context of the main file.
302 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
303 IsFirstFileEntered = true;
308 case PPCallbacks::EnterFile:
309 WriteLineInfo(CurLine, " 1", 2);
311 case PPCallbacks::ExitFile:
312 WriteLineInfo(CurLine, " 2", 2);
314 case PPCallbacks::SystemHeaderPragma:
315 case PPCallbacks::RenameFile:
316 WriteLineInfo(CurLine);
321 void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
322 const Token &IncludeTok,
325 CharSourceRange FilenameRange,
326 const FileEntry *File,
327 StringRef SearchPath,
328 StringRef RelativePath,
329 const Module *Imported) {
330 // In -dI mode, dump #include directives prior to dumping their content or
332 if (DumpIncludeDirectives) {
333 startNewLineIfNeeded();
335 const std::string TokenText = PP.getSpelling(IncludeTok);
336 assert(!TokenText.empty());
337 OS << "#" << TokenText << " "
338 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
339 << " /* clang -E -dI */";
340 setEmittedDirectiveOnThisLine();
341 startNewLineIfNeeded();
344 // When preprocessing, turn implicit imports into module import pragmas.
346 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
347 case tok::pp_include:
349 case tok::pp_include_next:
350 startNewLineIfNeeded();
352 OS << "#pragma clang module import " << Imported->getFullModuleName()
353 << " /* clang -E: implicit import for "
354 << "#" << PP.getSpelling(IncludeTok) << " "
355 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
357 // Since we want a newline after the pragma, but not a #<line>, start a
358 // new line immediately.
359 EmittedTokensOnThisLine = true;
360 startNewLineIfNeeded();
363 case tok::pp___include_macros:
364 // #__include_macros has no effect on a user of a preprocessed source
365 // file; the only effect is on preprocessing.
367 // FIXME: That's not *quite* true: it causes the module in question to
368 // be loaded, which can affect downstream diagnostics.
372 llvm_unreachable("unknown include directive kind");
378 /// Handle entering the scope of a module during a module compilation.
379 void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
380 startNewLineIfNeeded();
381 OS << "#pragma clang module begin " << M->getFullModuleName();
382 setEmittedDirectiveOnThisLine();
385 /// Handle leaving the scope of a module during a module compilation.
386 void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
387 startNewLineIfNeeded();
388 OS << "#pragma clang module end /*" << M->getFullModuleName() << "*/";
389 setEmittedDirectiveOnThisLine();
392 /// Ident - Handle #ident directives when read by the preprocessor.
394 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
397 OS.write("#ident ", strlen("#ident "));
398 OS.write(S.begin(), S.size());
399 EmittedTokensOnThisLine = true;
402 /// MacroDefined - This hook is called whenever a macro definition is seen.
403 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
404 const MacroDirective *MD) {
405 const MacroInfo *MI = MD->getMacroInfo();
406 // Only print out macro definitions in -dD mode.
408 // Ignore __FILE__ etc.
409 MI->isBuiltinMacro()) return;
411 MoveToLine(MI->getDefinitionLoc());
412 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
413 setEmittedDirectiveOnThisLine();
416 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
417 const MacroDefinition &MD,
418 const MacroDirective *Undef) {
419 // Only print out macro definitions in -dD mode.
420 if (!DumpDefines) return;
422 MoveToLine(MacroNameTok.getLocation());
423 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
424 setEmittedDirectiveOnThisLine();
427 static void outputPrintable(raw_ostream &OS, StringRef Str) {
428 for (unsigned char Char : Str) {
429 if (isPrintable(Char) && Char != '\\' && Char != '"')
431 else // Output anything hard as an octal escape.
433 << (char)('0' + ((Char >> 6) & 7))
434 << (char)('0' + ((Char >> 3) & 7))
435 << (char)('0' + ((Char >> 0) & 7));
439 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
441 PragmaMessageKind Kind,
443 startNewLineIfNeeded();
446 if (!Namespace.empty())
447 OS << Namespace << ' ';
460 outputPrintable(OS, Str);
462 if (Kind == PMK_Message)
464 setEmittedDirectiveOnThisLine();
467 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
468 StringRef DebugType) {
469 startNewLineIfNeeded();
472 OS << "#pragma clang __debug ";
475 setEmittedDirectiveOnThisLine();
478 void PrintPPOutputPPCallbacks::
479 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
480 startNewLineIfNeeded();
482 OS << "#pragma " << Namespace << " diagnostic push";
483 setEmittedDirectiveOnThisLine();
486 void PrintPPOutputPPCallbacks::
487 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
488 startNewLineIfNeeded();
490 OS << "#pragma " << Namespace << " diagnostic pop";
491 setEmittedDirectiveOnThisLine();
494 void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
498 startNewLineIfNeeded();
500 OS << "#pragma " << Namespace << " diagnostic ";
502 case diag::Severity::Remark:
505 case diag::Severity::Warning:
508 case diag::Severity::Error:
511 case diag::Severity::Ignored:
514 case diag::Severity::Fatal:
518 OS << " \"" << Str << '"';
519 setEmittedDirectiveOnThisLine();
522 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
523 StringRef WarningSpec,
525 startNewLineIfNeeded();
527 OS << "#pragma warning(" << WarningSpec << ':';
528 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
531 setEmittedDirectiveOnThisLine();
534 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
536 startNewLineIfNeeded();
538 OS << "#pragma warning(push";
542 setEmittedDirectiveOnThisLine();
545 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
546 startNewLineIfNeeded();
548 OS << "#pragma warning(pop)";
549 setEmittedDirectiveOnThisLine();
552 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
553 /// is called for the first token on each new line. If this really is the start
554 /// of a new logical line, handle it and return true, otherwise return false.
555 /// This may not be the start of a logical line because the "start of line"
556 /// marker is set for spelling lines, not expansion ones.
557 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
558 // Figure out what line we went to and insert the appropriate number of
559 // newline characters.
560 if (!MoveToLine(Tok.getLocation()))
563 // Print out space characters so that the first token on a line is
564 // indented for easy reading.
565 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
567 // The first token on a line can have a column number of 1, yet still expect
568 // leading white space, if a macro expansion in column 1 starts with an empty
569 // macro argument, or an empty nested macro expansion. In this case, move the
570 // token to column 2.
571 if (ColNo == 1 && Tok.hasLeadingSpace())
574 // This hack prevents stuff like:
576 // HASH define foo bar
577 // From having the # character end up at column 1, which makes it so it
578 // is not handled as a #define next time through the preprocessor if in
579 // -fpreprocessed mode.
580 if (ColNo <= 1 && Tok.is(tok::hash))
583 // Otherwise, indent the appropriate number of spaces.
584 for (; ColNo > 1; --ColNo)
590 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
592 unsigned NumNewlines = 0;
593 for (; Len; --Len, ++TokStr) {
594 if (*TokStr != '\n' &&
600 // If we have \n\r or \r\n, skip both and count as one line.
602 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
603 TokStr[0] != TokStr[1]) {
609 if (NumNewlines == 0) return;
611 CurLine += NumNewlines;
616 struct UnknownPragmaHandler : public PragmaHandler {
618 PrintPPOutputPPCallbacks *Callbacks;
620 // Set to true if tokens should be expanded
621 bool ShouldExpandTokens;
623 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
624 bool RequireTokenExpansion)
625 : Prefix(prefix), Callbacks(callbacks),
626 ShouldExpandTokens(RequireTokenExpansion) {}
627 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
628 Token &PragmaTok) override {
629 // Figure out what line we went to and insert the appropriate number of
630 // newline characters.
631 Callbacks->startNewLineIfNeeded();
632 Callbacks->MoveToLine(PragmaTok.getLocation());
633 Callbacks->OS.write(Prefix, strlen(Prefix));
635 if (ShouldExpandTokens) {
636 // The first token does not have expanded macros. Expand them, if
638 auto Toks = llvm::make_unique<Token[]>(1);
640 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
641 /*DisableMacroExpansion=*/false);
646 PrevToken.startToken();
647 PrevPrevToken.startToken();
649 // Read and print all of the pragma tokens.
650 while (PragmaTok.isNot(tok::eod)) {
651 if (PragmaTok.hasLeadingSpace() ||
652 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
653 Callbacks->OS << ' ';
654 std::string TokSpell = PP.getSpelling(PragmaTok);
655 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
657 PrevPrevToken = PrevToken;
658 PrevToken = PragmaTok;
660 if (ShouldExpandTokens)
663 PP.LexUnexpandedToken(PragmaTok);
665 Callbacks->setEmittedDirectiveOnThisLine();
668 } // end anonymous namespace
671 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
672 PrintPPOutputPPCallbacks *Callbacks,
674 bool DropComments = PP.getLangOpts().TraditionalCPP &&
675 !PP.getCommentRetentionState();
678 Token PrevPrevTok, PrevTok;
679 PrevPrevTok.startToken();
680 PrevTok.startToken();
682 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
683 Callbacks->startNewLineIfNeeded();
684 Callbacks->MoveToLine(Tok.getLocation());
687 // If this token is at the start of a line, emit newlines if needed.
688 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
690 } else if (Tok.hasLeadingSpace() ||
691 // If we haven't emitted a token on this line yet, PrevTok isn't
692 // useful to look at and no concatenation could happen anyway.
693 (Callbacks->hasEmittedTokensOnThisLine() &&
694 // Don't print "-" next to "-", it would form "--".
695 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
699 if (DropComments && Tok.is(tok::comment)) {
700 // Skip comments. Normally the preprocessor does not generate
701 // tok::comment nodes at all when not keeping comments, but under
702 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
703 SourceLocation StartLoc = Tok.getLocation();
704 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
705 } else if (Tok.is(tok::annot_module_include)) {
706 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
707 // appropriate output here. Ignore this token entirely.
710 } else if (Tok.is(tok::annot_module_begin)) {
711 // FIXME: We retrieve this token after the FileChanged callback, and
712 // retrieve the module_end token before the FileChanged callback, so
713 // we render this within the file and render the module end outside the
714 // file, but this is backwards from the token locations: the module_begin
715 // token is at the include location (outside the file) and the module_end
716 // token is at the EOF location (within the file).
717 Callbacks->BeginModule(
718 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
721 } else if (Tok.is(tok::annot_module_end)) {
722 Callbacks->EndModule(
723 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
726 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
728 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
729 Tok.getLiteralData()) {
730 OS.write(Tok.getLiteralData(), Tok.getLength());
731 } else if (Tok.getLength() < 256) {
732 const char *TokPtr = Buffer;
733 unsigned Len = PP.getSpelling(Tok, TokPtr);
734 OS.write(TokPtr, Len);
736 // Tokens that can contain embedded newlines need to adjust our current
738 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
739 Callbacks->HandleNewlinesInToken(TokPtr, Len);
741 std::string S = PP.getSpelling(Tok);
742 OS.write(&S[0], S.size());
744 // Tokens that can contain embedded newlines need to adjust our current
746 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
747 Callbacks->HandleNewlinesInToken(&S[0], S.size());
749 Callbacks->setEmittedTokensOnThisLine();
751 if (Tok.is(tok::eof)) break;
753 PrevPrevTok = PrevTok;
759 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
760 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
761 return LHS->first->getName().compare(RHS->first->getName());
764 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
765 // Ignore unknown pragmas.
768 // -dM mode just scans and ignores all tokens in the files, then dumps out
769 // the macro table at the end.
770 PP.EnterMainSourceFile();
774 while (Tok.isNot(tok::eof));
776 SmallVector<id_macro_pair, 128> MacrosByID;
777 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
779 auto *MD = I->second.getLatest();
780 if (MD && MD->isDefined())
781 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
783 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
785 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
786 MacroInfo &MI = *MacrosByID[i].second;
787 // Ignore computed macros like __LINE__ and friends.
788 if (MI.isBuiltinMacro()) continue;
790 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
795 /// DoPrintPreprocessedInput - This implements -E mode.
797 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
798 const PreprocessorOutputOptions &Opts) {
799 // Show macros with no output is handled specially.
801 assert(Opts.ShowMacros && "Not yet implemented!");
802 DoPrintMacros(PP, OS);
806 // Inform the preprocessor whether we want it to retain comments or not, due
808 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
810 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
811 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
812 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
814 // Expand macros in pragmas with -fms-extensions. The assumption is that
815 // the majority of pragmas in such a file will be Microsoft pragmas.
816 // Remember the handlers we will add so that we can remove them later.
817 std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
818 new UnknownPragmaHandler(
819 "#pragma", Callbacks,
820 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
822 std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
823 "#pragma GCC", Callbacks,
824 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
826 std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
827 "#pragma clang", Callbacks,
828 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
830 PP.AddPragmaHandler(MicrosoftExtHandler.get());
831 PP.AddPragmaHandler("GCC", GCCHandler.get());
832 PP.AddPragmaHandler("clang", ClangHandler.get());
834 // The tokens after pragma omp need to be expanded.
836 // OpenMP [2.1, Directive format]
837 // Preprocessing tokens following the #pragma omp are subject to macro
839 std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
840 new UnknownPragmaHandler("#pragma omp", Callbacks,
841 /*RequireTokenExpansion=*/true));
842 PP.AddPragmaHandler("omp", OpenMPHandler.get());
844 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
846 // After we have configured the preprocessor, enter the main file.
847 PP.EnterMainSourceFile();
849 // Consume all of the tokens that come from the predefines buffer. Those
850 // should not be emitted into the output and are guaranteed to be at the
852 const SourceManager &SourceMgr = PP.getSourceManager();
856 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
859 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
860 if (PLoc.isInvalid())
863 if (strcmp(PLoc.getFilename(), "<built-in>"))
867 // Read all the preprocessed tokens, printing them out to the stream.
868 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
871 // Remove the handlers we just added to leave the preprocessor in a sane state
872 // so that it can be reused (for example by a clang::Parser instance).
873 PP.RemovePragmaHandler(MicrosoftExtHandler.get());
874 PP.RemovePragmaHandler("GCC", GCCHandler.get());
875 PP.RemovePragmaHandler("clang", ClangHandler.get());
876 PP.RemovePragmaHandler("omp", OpenMPHandler.get());