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.param_empty()) {
42 MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_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;
146 void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
147 void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
149 bool HandleFirstTokOnLine(Token &Tok);
151 /// Move to the line of the provided source location. This will
152 /// return true if the output stream required adjustment or if
153 /// the requested location is on the first line.
154 bool MoveToLine(SourceLocation Loc) {
155 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
156 if (PLoc.isInvalid())
158 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
160 bool MoveToLine(unsigned LineNo);
162 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
164 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
166 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
167 unsigned ExtraLen=0);
168 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
169 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
171 /// MacroDefined - This hook is called whenever a macro definition is seen.
172 void MacroDefined(const Token &MacroNameTok,
173 const MacroDirective *MD) override;
175 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
176 void MacroUndefined(const Token &MacroNameTok,
177 const MacroDefinition &MD,
178 const MacroDirective *Undef) override;
180 void BeginModule(const Module *M);
181 void EndModule(const Module *M);
183 } // end anonymous namespace
185 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
188 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
190 // Emit #line directives or GNU line markers depending on what mode we're in.
191 if (UseLineDirectives) {
192 OS << "#line" << ' ' << LineNo << ' ' << '"';
193 OS.write_escaped(CurFilename);
196 OS << '#' << ' ' << LineNo << ' ' << '"';
197 OS.write_escaped(CurFilename);
201 OS.write(Extra, ExtraLen);
203 if (FileType == SrcMgr::C_System)
205 else if (FileType == SrcMgr::C_ExternCSystem)
211 /// MoveToLine - Move the output to the source line specified by the location
212 /// object. We can do this by emitting some number of \n's, or be emitting a
213 /// #line directive. This returns false if already at the specified line, true
214 /// if some newlines were emitted.
215 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
216 // If this line is "close enough" to the original line, just print newlines,
217 // otherwise print a #line directive.
218 if (LineNo-CurLine <= 8) {
219 if (LineNo-CurLine == 1)
221 else if (LineNo == CurLine)
222 return false; // Spelling line moved, but expansion line didn't.
224 const char *NewLines = "\n\n\n\n\n\n\n\n";
225 OS.write(NewLines, LineNo-CurLine);
227 } else if (!DisableLineMarkers) {
228 // Emit a #line or line marker.
229 WriteLineInfo(LineNo, nullptr, 0);
231 // Okay, we're in -P mode, which turns off line markers. However, we still
232 // need to emit a newline between tokens on different lines.
233 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
241 PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
242 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
244 EmittedTokensOnThisLine = false;
245 EmittedDirectiveOnThisLine = false;
246 if (ShouldUpdateCurrentLine)
254 /// FileChanged - Whenever the preprocessor enters or exits a #include file
255 /// it invokes this handler. Update our conception of the current source
257 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
258 FileChangeReason Reason,
259 SrcMgr::CharacteristicKind NewFileType,
261 // Unless we are exiting a #include, make sure to skip ahead to the line the
262 // #include directive was at.
263 SourceManager &SourceMgr = SM;
265 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
266 if (UserLoc.isInvalid())
269 unsigned NewLine = UserLoc.getLine();
271 if (Reason == PPCallbacks::EnterFile) {
272 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
273 if (IncludeLoc.isValid())
274 MoveToLine(IncludeLoc);
275 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
276 // GCC emits the # directive for this directive on the line AFTER the
277 // directive and emits a bunch of spaces that aren't needed. This is because
278 // otherwise we will emit a line marker for THIS line, which requires an
279 // extra blank line after the directive to avoid making all following lines
280 // off by one. We can do better by simply incrementing NewLine here.
287 CurFilename += UserLoc.getFilename();
288 FileType = NewFileType;
290 if (DisableLineMarkers) {
291 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
296 WriteLineInfo(CurLine);
300 // Do not emit an enter marker for the main file (which we expect is the first
301 // entered file). This matches gcc, and improves compatibility with some tools
302 // which track the # line markers as a way to determine when the preprocessed
303 // output is in the context of the main file.
304 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
305 IsFirstFileEntered = true;
310 case PPCallbacks::EnterFile:
311 WriteLineInfo(CurLine, " 1", 2);
313 case PPCallbacks::ExitFile:
314 WriteLineInfo(CurLine, " 2", 2);
316 case PPCallbacks::SystemHeaderPragma:
317 case PPCallbacks::RenameFile:
318 WriteLineInfo(CurLine);
323 void PrintPPOutputPPCallbacks::InclusionDirective(SourceLocation HashLoc,
324 const Token &IncludeTok,
327 CharSourceRange FilenameRange,
328 const FileEntry *File,
329 StringRef SearchPath,
330 StringRef RelativePath,
331 const Module *Imported) {
332 // In -dI mode, dump #include directives prior to dumping their content or
334 if (DumpIncludeDirectives) {
335 startNewLineIfNeeded();
337 const std::string TokenText = PP.getSpelling(IncludeTok);
338 assert(!TokenText.empty());
339 OS << "#" << TokenText << " "
340 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
341 << " /* clang -E -dI */";
342 setEmittedDirectiveOnThisLine();
343 startNewLineIfNeeded();
346 // When preprocessing, turn implicit imports into module import pragmas.
348 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
349 case tok::pp_include:
351 case tok::pp_include_next:
352 startNewLineIfNeeded();
354 OS << "#pragma clang module import " << Imported->getFullModuleName(true)
355 << " /* clang -E: implicit import for "
356 << "#" << PP.getSpelling(IncludeTok) << " "
357 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
359 // Since we want a newline after the pragma, but not a #<line>, start a
360 // new line immediately.
361 EmittedTokensOnThisLine = true;
362 startNewLineIfNeeded();
365 case tok::pp___include_macros:
366 // #__include_macros has no effect on a user of a preprocessed source
367 // file; the only effect is on preprocessing.
369 // FIXME: That's not *quite* true: it causes the module in question to
370 // be loaded, which can affect downstream diagnostics.
374 llvm_unreachable("unknown include directive kind");
380 /// Handle entering the scope of a module during a module compilation.
381 void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
382 startNewLineIfNeeded();
383 OS << "#pragma clang module begin " << M->getFullModuleName(true);
384 setEmittedDirectiveOnThisLine();
387 /// Handle leaving the scope of a module during a module compilation.
388 void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
389 startNewLineIfNeeded();
390 OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
391 setEmittedDirectiveOnThisLine();
394 /// Ident - Handle #ident directives when read by the preprocessor.
396 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
399 OS.write("#ident ", strlen("#ident "));
400 OS.write(S.begin(), S.size());
401 EmittedTokensOnThisLine = true;
404 /// MacroDefined - This hook is called whenever a macro definition is seen.
405 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
406 const MacroDirective *MD) {
407 const MacroInfo *MI = MD->getMacroInfo();
408 // Only print out macro definitions in -dD mode.
410 // Ignore __FILE__ etc.
411 MI->isBuiltinMacro()) return;
413 MoveToLine(MI->getDefinitionLoc());
414 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
415 setEmittedDirectiveOnThisLine();
418 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
419 const MacroDefinition &MD,
420 const MacroDirective *Undef) {
421 // Only print out macro definitions in -dD mode.
422 if (!DumpDefines) return;
424 MoveToLine(MacroNameTok.getLocation());
425 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
426 setEmittedDirectiveOnThisLine();
429 static void outputPrintable(raw_ostream &OS, StringRef Str) {
430 for (unsigned char Char : Str) {
431 if (isPrintable(Char) && Char != '\\' && Char != '"')
433 else // Output anything hard as an octal escape.
435 << (char)('0' + ((Char >> 6) & 7))
436 << (char)('0' + ((Char >> 3) & 7))
437 << (char)('0' + ((Char >> 0) & 7));
441 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
443 PragmaMessageKind Kind,
445 startNewLineIfNeeded();
448 if (!Namespace.empty())
449 OS << Namespace << ' ';
462 outputPrintable(OS, Str);
464 if (Kind == PMK_Message)
466 setEmittedDirectiveOnThisLine();
469 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
470 StringRef DebugType) {
471 startNewLineIfNeeded();
474 OS << "#pragma clang __debug ";
477 setEmittedDirectiveOnThisLine();
480 void PrintPPOutputPPCallbacks::
481 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
482 startNewLineIfNeeded();
484 OS << "#pragma " << Namespace << " diagnostic push";
485 setEmittedDirectiveOnThisLine();
488 void PrintPPOutputPPCallbacks::
489 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
490 startNewLineIfNeeded();
492 OS << "#pragma " << Namespace << " diagnostic pop";
493 setEmittedDirectiveOnThisLine();
496 void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
500 startNewLineIfNeeded();
502 OS << "#pragma " << Namespace << " diagnostic ";
504 case diag::Severity::Remark:
507 case diag::Severity::Warning:
510 case diag::Severity::Error:
513 case diag::Severity::Ignored:
516 case diag::Severity::Fatal:
520 OS << " \"" << Str << '"';
521 setEmittedDirectiveOnThisLine();
524 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
525 StringRef WarningSpec,
527 startNewLineIfNeeded();
529 OS << "#pragma warning(" << WarningSpec << ':';
530 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
533 setEmittedDirectiveOnThisLine();
536 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
538 startNewLineIfNeeded();
540 OS << "#pragma warning(push";
544 setEmittedDirectiveOnThisLine();
547 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
548 startNewLineIfNeeded();
550 OS << "#pragma warning(pop)";
551 setEmittedDirectiveOnThisLine();
554 void PrintPPOutputPPCallbacks::
555 PragmaAssumeNonNullBegin(SourceLocation Loc) {
556 startNewLineIfNeeded();
558 OS << "#pragma clang assume_nonnull begin";
559 setEmittedDirectiveOnThisLine();
562 void PrintPPOutputPPCallbacks::
563 PragmaAssumeNonNullEnd(SourceLocation Loc) {
564 startNewLineIfNeeded();
566 OS << "#pragma clang assume_nonnull end";
567 setEmittedDirectiveOnThisLine();
570 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
571 /// is called for the first token on each new line. If this really is the start
572 /// of a new logical line, handle it and return true, otherwise return false.
573 /// This may not be the start of a logical line because the "start of line"
574 /// marker is set for spelling lines, not expansion ones.
575 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
576 // Figure out what line we went to and insert the appropriate number of
577 // newline characters.
578 if (!MoveToLine(Tok.getLocation()))
581 // Print out space characters so that the first token on a line is
582 // indented for easy reading.
583 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
585 // The first token on a line can have a column number of 1, yet still expect
586 // leading white space, if a macro expansion in column 1 starts with an empty
587 // macro argument, or an empty nested macro expansion. In this case, move the
588 // token to column 2.
589 if (ColNo == 1 && Tok.hasLeadingSpace())
592 // This hack prevents stuff like:
594 // HASH define foo bar
595 // From having the # character end up at column 1, which makes it so it
596 // is not handled as a #define next time through the preprocessor if in
597 // -fpreprocessed mode.
598 if (ColNo <= 1 && Tok.is(tok::hash))
601 // Otherwise, indent the appropriate number of spaces.
602 for (; ColNo > 1; --ColNo)
608 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
610 unsigned NumNewlines = 0;
611 for (; Len; --Len, ++TokStr) {
612 if (*TokStr != '\n' &&
618 // If we have \n\r or \r\n, skip both and count as one line.
620 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
621 TokStr[0] != TokStr[1]) {
627 if (NumNewlines == 0) return;
629 CurLine += NumNewlines;
634 struct UnknownPragmaHandler : public PragmaHandler {
636 PrintPPOutputPPCallbacks *Callbacks;
638 // Set to true if tokens should be expanded
639 bool ShouldExpandTokens;
641 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
642 bool RequireTokenExpansion)
643 : Prefix(prefix), Callbacks(callbacks),
644 ShouldExpandTokens(RequireTokenExpansion) {}
645 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
646 Token &PragmaTok) override {
647 // Figure out what line we went to and insert the appropriate number of
648 // newline characters.
649 Callbacks->startNewLineIfNeeded();
650 Callbacks->MoveToLine(PragmaTok.getLocation());
651 Callbacks->OS.write(Prefix, strlen(Prefix));
653 if (ShouldExpandTokens) {
654 // The first token does not have expanded macros. Expand them, if
656 auto Toks = llvm::make_unique<Token[]>(1);
658 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
659 /*DisableMacroExpansion=*/false);
664 PrevToken.startToken();
665 PrevPrevToken.startToken();
667 // Read and print all of the pragma tokens.
668 while (PragmaTok.isNot(tok::eod)) {
669 if (PragmaTok.hasLeadingSpace() ||
670 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
671 Callbacks->OS << ' ';
672 std::string TokSpell = PP.getSpelling(PragmaTok);
673 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
675 PrevPrevToken = PrevToken;
676 PrevToken = PragmaTok;
678 if (ShouldExpandTokens)
681 PP.LexUnexpandedToken(PragmaTok);
683 Callbacks->setEmittedDirectiveOnThisLine();
686 } // end anonymous namespace
689 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
690 PrintPPOutputPPCallbacks *Callbacks,
692 bool DropComments = PP.getLangOpts().TraditionalCPP &&
693 !PP.getCommentRetentionState();
696 Token PrevPrevTok, PrevTok;
697 PrevPrevTok.startToken();
698 PrevTok.startToken();
700 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
701 Callbacks->startNewLineIfNeeded();
702 Callbacks->MoveToLine(Tok.getLocation());
705 // If this token is at the start of a line, emit newlines if needed.
706 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
708 } else if (Tok.hasLeadingSpace() ||
709 // If we haven't emitted a token on this line yet, PrevTok isn't
710 // useful to look at and no concatenation could happen anyway.
711 (Callbacks->hasEmittedTokensOnThisLine() &&
712 // Don't print "-" next to "-", it would form "--".
713 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
717 if (DropComments && Tok.is(tok::comment)) {
718 // Skip comments. Normally the preprocessor does not generate
719 // tok::comment nodes at all when not keeping comments, but under
720 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
721 SourceLocation StartLoc = Tok.getLocation();
722 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
723 } else if (Tok.is(tok::eod)) {
724 // Don't print end of directive tokens, since they are typically newlines
725 // that mess up our line tracking. These come from unknown pre-processor
726 // directives or hash-prefixed comments in standalone assembly files.
729 } else if (Tok.is(tok::annot_module_include)) {
730 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
731 // appropriate output here. Ignore this token entirely.
734 } else if (Tok.is(tok::annot_module_begin)) {
735 // FIXME: We retrieve this token after the FileChanged callback, and
736 // retrieve the module_end token before the FileChanged callback, so
737 // we render this within the file and render the module end outside the
738 // file, but this is backwards from the token locations: the module_begin
739 // token is at the include location (outside the file) and the module_end
740 // token is at the EOF location (within the file).
741 Callbacks->BeginModule(
742 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
745 } else if (Tok.is(tok::annot_module_end)) {
746 Callbacks->EndModule(
747 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
750 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
752 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
753 Tok.getLiteralData()) {
754 OS.write(Tok.getLiteralData(), Tok.getLength());
755 } else if (Tok.getLength() < 256) {
756 const char *TokPtr = Buffer;
757 unsigned Len = PP.getSpelling(Tok, TokPtr);
758 OS.write(TokPtr, Len);
760 // Tokens that can contain embedded newlines need to adjust our current
762 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
763 Callbacks->HandleNewlinesInToken(TokPtr, Len);
765 std::string S = PP.getSpelling(Tok);
766 OS.write(&S[0], S.size());
768 // Tokens that can contain embedded newlines need to adjust our current
770 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
771 Callbacks->HandleNewlinesInToken(&S[0], S.size());
773 Callbacks->setEmittedTokensOnThisLine();
775 if (Tok.is(tok::eof)) break;
777 PrevPrevTok = PrevTok;
783 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
784 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
785 return LHS->first->getName().compare(RHS->first->getName());
788 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
789 // Ignore unknown pragmas.
792 // -dM mode just scans and ignores all tokens in the files, then dumps out
793 // the macro table at the end.
794 PP.EnterMainSourceFile();
798 while (Tok.isNot(tok::eof));
800 SmallVector<id_macro_pair, 128> MacrosByID;
801 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
803 auto *MD = I->second.getLatest();
804 if (MD && MD->isDefined())
805 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
807 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
809 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
810 MacroInfo &MI = *MacrosByID[i].second;
811 // Ignore computed macros like __LINE__ and friends.
812 if (MI.isBuiltinMacro()) continue;
814 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
819 /// DoPrintPreprocessedInput - This implements -E mode.
821 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
822 const PreprocessorOutputOptions &Opts) {
823 // Show macros with no output is handled specially.
825 assert(Opts.ShowMacros && "Not yet implemented!");
826 DoPrintMacros(PP, OS);
830 // Inform the preprocessor whether we want it to retain comments or not, due
832 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
834 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
835 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
836 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
838 // Expand macros in pragmas with -fms-extensions. The assumption is that
839 // the majority of pragmas in such a file will be Microsoft pragmas.
840 // Remember the handlers we will add so that we can remove them later.
841 std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
842 new UnknownPragmaHandler(
843 "#pragma", Callbacks,
844 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
846 std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
847 "#pragma GCC", Callbacks,
848 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
850 std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
851 "#pragma clang", Callbacks,
852 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
854 PP.AddPragmaHandler(MicrosoftExtHandler.get());
855 PP.AddPragmaHandler("GCC", GCCHandler.get());
856 PP.AddPragmaHandler("clang", ClangHandler.get());
858 // The tokens after pragma omp need to be expanded.
860 // OpenMP [2.1, Directive format]
861 // Preprocessing tokens following the #pragma omp are subject to macro
863 std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
864 new UnknownPragmaHandler("#pragma omp", Callbacks,
865 /*RequireTokenExpansion=*/true));
866 PP.AddPragmaHandler("omp", OpenMPHandler.get());
868 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
870 // After we have configured the preprocessor, enter the main file.
871 PP.EnterMainSourceFile();
873 // Consume all of the tokens that come from the predefines buffer. Those
874 // should not be emitted into the output and are guaranteed to be at the
876 const SourceManager &SourceMgr = PP.getSourceManager();
880 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
883 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
884 if (PLoc.isInvalid())
887 if (strcmp(PLoc.getFilename(), "<built-in>"))
891 // Read all the preprocessed tokens, printing them out to the stream.
892 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
895 // Remove the handlers we just added to leave the preprocessor in a sane state
896 // so that it can be reused (for example by a clang::Parser instance).
897 PP.RemovePragmaHandler(MicrosoftExtHandler.get());
898 PP.RemovePragmaHandler("GCC", GCCHandler.get());
899 PP.RemovePragmaHandler("clang", ClangHandler.get());
900 PP.RemovePragmaHandler("omp", OpenMPHandler.get());