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,
134 SrcMgr::CharacteristicKind FileType) override;
135 void Ident(SourceLocation Loc, StringRef str) override;
136 void PragmaMessage(SourceLocation Loc, StringRef Namespace,
137 PragmaMessageKind Kind, StringRef Str) override;
138 void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
139 void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
140 void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
141 void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
142 diag::Severity Map, StringRef Str) override;
143 void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
144 ArrayRef<int> Ids) override;
145 void PragmaWarningPush(SourceLocation Loc, int Level) override;
146 void PragmaWarningPop(SourceLocation Loc) override;
147 void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
148 void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
150 bool HandleFirstTokOnLine(Token &Tok);
152 /// Move to the line of the provided source location. This will
153 /// return true if the output stream required adjustment or if
154 /// the requested location is on the first line.
155 bool MoveToLine(SourceLocation Loc) {
156 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
157 if (PLoc.isInvalid())
159 return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
161 bool MoveToLine(unsigned LineNo);
163 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
165 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
167 void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
168 unsigned ExtraLen=0);
169 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
170 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
172 /// MacroDefined - This hook is called whenever a macro definition is seen.
173 void MacroDefined(const Token &MacroNameTok,
174 const MacroDirective *MD) override;
176 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
177 void MacroUndefined(const Token &MacroNameTok,
178 const MacroDefinition &MD,
179 const MacroDirective *Undef) override;
181 void BeginModule(const Module *M);
182 void EndModule(const Module *M);
184 } // end anonymous namespace
186 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
189 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
191 // Emit #line directives or GNU line markers depending on what mode we're in.
192 if (UseLineDirectives) {
193 OS << "#line" << ' ' << LineNo << ' ' << '"';
194 OS.write_escaped(CurFilename);
197 OS << '#' << ' ' << LineNo << ' ' << '"';
198 OS.write_escaped(CurFilename);
202 OS.write(Extra, ExtraLen);
204 if (FileType == SrcMgr::C_System)
206 else if (FileType == SrcMgr::C_ExternCSystem)
212 /// MoveToLine - Move the output to the source line specified by the location
213 /// object. We can do this by emitting some number of \n's, or be emitting a
214 /// #line directive. This returns false if already at the specified line, true
215 /// if some newlines were emitted.
216 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
217 // If this line is "close enough" to the original line, just print newlines,
218 // otherwise print a #line directive.
219 if (LineNo-CurLine <= 8) {
220 if (LineNo-CurLine == 1)
222 else if (LineNo == CurLine)
223 return false; // Spelling line moved, but expansion line didn't.
225 const char *NewLines = "\n\n\n\n\n\n\n\n";
226 OS.write(NewLines, LineNo-CurLine);
228 } else if (!DisableLineMarkers) {
229 // Emit a #line or line marker.
230 WriteLineInfo(LineNo, nullptr, 0);
232 // Okay, we're in -P mode, which turns off line markers. However, we still
233 // need to emit a newline between tokens on different lines.
234 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
242 PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
243 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
245 EmittedTokensOnThisLine = false;
246 EmittedDirectiveOnThisLine = false;
247 if (ShouldUpdateCurrentLine)
255 /// FileChanged - Whenever the preprocessor enters or exits a #include file
256 /// it invokes this handler. Update our conception of the current source
258 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
259 FileChangeReason Reason,
260 SrcMgr::CharacteristicKind NewFileType,
262 // Unless we are exiting a #include, make sure to skip ahead to the line the
263 // #include directive was at.
264 SourceManager &SourceMgr = SM;
266 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
267 if (UserLoc.isInvalid())
270 unsigned NewLine = UserLoc.getLine();
272 if (Reason == PPCallbacks::EnterFile) {
273 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
274 if (IncludeLoc.isValid())
275 MoveToLine(IncludeLoc);
276 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
277 // GCC emits the # directive for this directive on the line AFTER the
278 // directive and emits a bunch of spaces that aren't needed. This is because
279 // otherwise we will emit a line marker for THIS line, which requires an
280 // extra blank line after the directive to avoid making all following lines
281 // off by one. We can do better by simply incrementing NewLine here.
288 CurFilename += UserLoc.getFilename();
289 FileType = NewFileType;
291 if (DisableLineMarkers) {
292 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
297 WriteLineInfo(CurLine);
301 // Do not emit an enter marker for the main file (which we expect is the first
302 // entered file). This matches gcc, and improves compatibility with some tools
303 // which track the # line markers as a way to determine when the preprocessed
304 // output is in the context of the main file.
305 if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
306 IsFirstFileEntered = true;
311 case PPCallbacks::EnterFile:
312 WriteLineInfo(CurLine, " 1", 2);
314 case PPCallbacks::ExitFile:
315 WriteLineInfo(CurLine, " 2", 2);
317 case PPCallbacks::SystemHeaderPragma:
318 case PPCallbacks::RenameFile:
319 WriteLineInfo(CurLine);
324 void PrintPPOutputPPCallbacks::InclusionDirective(
325 SourceLocation HashLoc,
326 const Token &IncludeTok,
329 CharSourceRange FilenameRange,
330 const FileEntry *File,
331 StringRef SearchPath,
332 StringRef RelativePath,
333 const Module *Imported,
334 SrcMgr::CharacteristicKind FileType) {
335 // In -dI mode, dump #include directives prior to dumping their content or
337 if (DumpIncludeDirectives) {
338 startNewLineIfNeeded();
340 const std::string TokenText = PP.getSpelling(IncludeTok);
341 assert(!TokenText.empty());
342 OS << "#" << TokenText << " "
343 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
344 << " /* clang -E -dI */";
345 setEmittedDirectiveOnThisLine();
346 startNewLineIfNeeded();
349 // When preprocessing, turn implicit imports into module import pragmas.
351 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
352 case tok::pp_include:
354 case tok::pp_include_next:
355 startNewLineIfNeeded();
357 OS << "#pragma clang module import " << Imported->getFullModuleName(true)
358 << " /* clang -E: implicit import for "
359 << "#" << PP.getSpelling(IncludeTok) << " "
360 << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
362 // Since we want a newline after the pragma, but not a #<line>, start a
363 // new line immediately.
364 EmittedTokensOnThisLine = true;
365 startNewLineIfNeeded();
368 case tok::pp___include_macros:
369 // #__include_macros has no effect on a user of a preprocessed source
370 // file; the only effect is on preprocessing.
372 // FIXME: That's not *quite* true: it causes the module in question to
373 // be loaded, which can affect downstream diagnostics.
377 llvm_unreachable("unknown include directive kind");
383 /// Handle entering the scope of a module during a module compilation.
384 void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
385 startNewLineIfNeeded();
386 OS << "#pragma clang module begin " << M->getFullModuleName(true);
387 setEmittedDirectiveOnThisLine();
390 /// Handle leaving the scope of a module during a module compilation.
391 void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
392 startNewLineIfNeeded();
393 OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
394 setEmittedDirectiveOnThisLine();
397 /// Ident - Handle #ident directives when read by the preprocessor.
399 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
402 OS.write("#ident ", strlen("#ident "));
403 OS.write(S.begin(), S.size());
404 EmittedTokensOnThisLine = true;
407 /// MacroDefined - This hook is called whenever a macro definition is seen.
408 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
409 const MacroDirective *MD) {
410 const MacroInfo *MI = MD->getMacroInfo();
411 // Only print out macro definitions in -dD mode.
413 // Ignore __FILE__ etc.
414 MI->isBuiltinMacro()) return;
416 MoveToLine(MI->getDefinitionLoc());
417 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
418 setEmittedDirectiveOnThisLine();
421 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
422 const MacroDefinition &MD,
423 const MacroDirective *Undef) {
424 // Only print out macro definitions in -dD mode.
425 if (!DumpDefines) return;
427 MoveToLine(MacroNameTok.getLocation());
428 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
429 setEmittedDirectiveOnThisLine();
432 static void outputPrintable(raw_ostream &OS, StringRef Str) {
433 for (unsigned char Char : Str) {
434 if (isPrintable(Char) && Char != '\\' && Char != '"')
436 else // Output anything hard as an octal escape.
438 << (char)('0' + ((Char >> 6) & 7))
439 << (char)('0' + ((Char >> 3) & 7))
440 << (char)('0' + ((Char >> 0) & 7));
444 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
446 PragmaMessageKind Kind,
448 startNewLineIfNeeded();
451 if (!Namespace.empty())
452 OS << Namespace << ' ';
465 outputPrintable(OS, Str);
467 if (Kind == PMK_Message)
469 setEmittedDirectiveOnThisLine();
472 void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
473 StringRef DebugType) {
474 startNewLineIfNeeded();
477 OS << "#pragma clang __debug ";
480 setEmittedDirectiveOnThisLine();
483 void PrintPPOutputPPCallbacks::
484 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
485 startNewLineIfNeeded();
487 OS << "#pragma " << Namespace << " diagnostic push";
488 setEmittedDirectiveOnThisLine();
491 void PrintPPOutputPPCallbacks::
492 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
493 startNewLineIfNeeded();
495 OS << "#pragma " << Namespace << " diagnostic pop";
496 setEmittedDirectiveOnThisLine();
499 void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
503 startNewLineIfNeeded();
505 OS << "#pragma " << Namespace << " diagnostic ";
507 case diag::Severity::Remark:
510 case diag::Severity::Warning:
513 case diag::Severity::Error:
516 case diag::Severity::Ignored:
519 case diag::Severity::Fatal:
523 OS << " \"" << Str << '"';
524 setEmittedDirectiveOnThisLine();
527 void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
528 StringRef WarningSpec,
530 startNewLineIfNeeded();
532 OS << "#pragma warning(" << WarningSpec << ':';
533 for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
536 setEmittedDirectiveOnThisLine();
539 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
541 startNewLineIfNeeded();
543 OS << "#pragma warning(push";
547 setEmittedDirectiveOnThisLine();
550 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
551 startNewLineIfNeeded();
553 OS << "#pragma warning(pop)";
554 setEmittedDirectiveOnThisLine();
557 void PrintPPOutputPPCallbacks::
558 PragmaAssumeNonNullBegin(SourceLocation Loc) {
559 startNewLineIfNeeded();
561 OS << "#pragma clang assume_nonnull begin";
562 setEmittedDirectiveOnThisLine();
565 void PrintPPOutputPPCallbacks::
566 PragmaAssumeNonNullEnd(SourceLocation Loc) {
567 startNewLineIfNeeded();
569 OS << "#pragma clang assume_nonnull end";
570 setEmittedDirectiveOnThisLine();
573 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
574 /// is called for the first token on each new line. If this really is the start
575 /// of a new logical line, handle it and return true, otherwise return false.
576 /// This may not be the start of a logical line because the "start of line"
577 /// marker is set for spelling lines, not expansion ones.
578 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
579 // Figure out what line we went to and insert the appropriate number of
580 // newline characters.
581 if (!MoveToLine(Tok.getLocation()))
584 // Print out space characters so that the first token on a line is
585 // indented for easy reading.
586 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
588 // The first token on a line can have a column number of 1, yet still expect
589 // leading white space, if a macro expansion in column 1 starts with an empty
590 // macro argument, or an empty nested macro expansion. In this case, move the
591 // token to column 2.
592 if (ColNo == 1 && Tok.hasLeadingSpace())
595 // This hack prevents stuff like:
597 // HASH define foo bar
598 // From having the # character end up at column 1, which makes it so it
599 // is not handled as a #define next time through the preprocessor if in
600 // -fpreprocessed mode.
601 if (ColNo <= 1 && Tok.is(tok::hash))
604 // Otherwise, indent the appropriate number of spaces.
605 for (; ColNo > 1; --ColNo)
611 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
613 unsigned NumNewlines = 0;
614 for (; Len; --Len, ++TokStr) {
615 if (*TokStr != '\n' &&
621 // If we have \n\r or \r\n, skip both and count as one line.
623 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
624 TokStr[0] != TokStr[1]) {
630 if (NumNewlines == 0) return;
632 CurLine += NumNewlines;
637 struct UnknownPragmaHandler : public PragmaHandler {
639 PrintPPOutputPPCallbacks *Callbacks;
641 // Set to true if tokens should be expanded
642 bool ShouldExpandTokens;
644 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
645 bool RequireTokenExpansion)
646 : Prefix(prefix), Callbacks(callbacks),
647 ShouldExpandTokens(RequireTokenExpansion) {}
648 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
649 Token &PragmaTok) override {
650 // Figure out what line we went to and insert the appropriate number of
651 // newline characters.
652 Callbacks->startNewLineIfNeeded();
653 Callbacks->MoveToLine(PragmaTok.getLocation());
654 Callbacks->OS.write(Prefix, strlen(Prefix));
656 if (ShouldExpandTokens) {
657 // The first token does not have expanded macros. Expand them, if
659 auto Toks = llvm::make_unique<Token[]>(1);
661 PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
662 /*DisableMacroExpansion=*/false);
667 PrevToken.startToken();
668 PrevPrevToken.startToken();
670 // Read and print all of the pragma tokens.
671 while (PragmaTok.isNot(tok::eod)) {
672 if (PragmaTok.hasLeadingSpace() ||
673 Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
674 Callbacks->OS << ' ';
675 std::string TokSpell = PP.getSpelling(PragmaTok);
676 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
678 PrevPrevToken = PrevToken;
679 PrevToken = PragmaTok;
681 if (ShouldExpandTokens)
684 PP.LexUnexpandedToken(PragmaTok);
686 Callbacks->setEmittedDirectiveOnThisLine();
689 } // end anonymous namespace
692 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
693 PrintPPOutputPPCallbacks *Callbacks,
695 bool DropComments = PP.getLangOpts().TraditionalCPP &&
696 !PP.getCommentRetentionState();
699 Token PrevPrevTok, PrevTok;
700 PrevPrevTok.startToken();
701 PrevTok.startToken();
703 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
704 Callbacks->startNewLineIfNeeded();
705 Callbacks->MoveToLine(Tok.getLocation());
708 // If this token is at the start of a line, emit newlines if needed.
709 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
711 } else if (Tok.hasLeadingSpace() ||
712 // If we haven't emitted a token on this line yet, PrevTok isn't
713 // useful to look at and no concatenation could happen anyway.
714 (Callbacks->hasEmittedTokensOnThisLine() &&
715 // Don't print "-" next to "-", it would form "--".
716 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
720 if (DropComments && Tok.is(tok::comment)) {
721 // Skip comments. Normally the preprocessor does not generate
722 // tok::comment nodes at all when not keeping comments, but under
723 // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
724 SourceLocation StartLoc = Tok.getLocation();
725 Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
726 } else if (Tok.is(tok::eod)) {
727 // Don't print end of directive tokens, since they are typically newlines
728 // that mess up our line tracking. These come from unknown pre-processor
729 // directives or hash-prefixed comments in standalone assembly files.
732 } else if (Tok.is(tok::annot_module_include)) {
733 // PrintPPOutputPPCallbacks::InclusionDirective handles producing
734 // appropriate output here. Ignore this token entirely.
737 } else if (Tok.is(tok::annot_module_begin)) {
738 // FIXME: We retrieve this token after the FileChanged callback, and
739 // retrieve the module_end token before the FileChanged callback, so
740 // we render this within the file and render the module end outside the
741 // file, but this is backwards from the token locations: the module_begin
742 // token is at the include location (outside the file) and the module_end
743 // token is at the EOF location (within the file).
744 Callbacks->BeginModule(
745 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
748 } else if (Tok.is(tok::annot_module_end)) {
749 Callbacks->EndModule(
750 reinterpret_cast<Module *>(Tok.getAnnotationValue()));
753 } else if (Tok.isAnnotation()) {
754 // Ignore annotation tokens created by pragmas - the pragmas themselves
755 // will be reproduced in the preprocessed output.
758 } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
760 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
761 Tok.getLiteralData()) {
762 OS.write(Tok.getLiteralData(), Tok.getLength());
763 } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
764 const char *TokPtr = Buffer;
765 unsigned Len = PP.getSpelling(Tok, TokPtr);
766 OS.write(TokPtr, Len);
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(TokPtr, Len);
773 std::string S = PP.getSpelling(Tok);
774 OS.write(&S[0], S.size());
776 // Tokens that can contain embedded newlines need to adjust our current
778 if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
779 Callbacks->HandleNewlinesInToken(&S[0], S.size());
781 Callbacks->setEmittedTokensOnThisLine();
783 if (Tok.is(tok::eof)) break;
785 PrevPrevTok = PrevTok;
791 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
792 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
793 return LHS->first->getName().compare(RHS->first->getName());
796 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
797 // Ignore unknown pragmas.
800 // -dM mode just scans and ignores all tokens in the files, then dumps out
801 // the macro table at the end.
802 PP.EnterMainSourceFile();
806 while (Tok.isNot(tok::eof));
808 SmallVector<id_macro_pair, 128> MacrosByID;
809 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
811 auto *MD = I->second.getLatest();
812 if (MD && MD->isDefined())
813 MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
815 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
817 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
818 MacroInfo &MI = *MacrosByID[i].second;
819 // Ignore computed macros like __LINE__ and friends.
820 if (MI.isBuiltinMacro()) continue;
822 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
827 /// DoPrintPreprocessedInput - This implements -E mode.
829 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
830 const PreprocessorOutputOptions &Opts) {
831 // Show macros with no output is handled specially.
833 assert(Opts.ShowMacros && "Not yet implemented!");
834 DoPrintMacros(PP, OS);
838 // Inform the preprocessor whether we want it to retain comments or not, due
840 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
842 PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
843 PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
844 Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
846 // Expand macros in pragmas with -fms-extensions. The assumption is that
847 // the majority of pragmas in such a file will be Microsoft pragmas.
848 // Remember the handlers we will add so that we can remove them later.
849 std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
850 new UnknownPragmaHandler(
851 "#pragma", Callbacks,
852 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
854 std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
855 "#pragma GCC", Callbacks,
856 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
858 std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
859 "#pragma clang", Callbacks,
860 /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
862 PP.AddPragmaHandler(MicrosoftExtHandler.get());
863 PP.AddPragmaHandler("GCC", GCCHandler.get());
864 PP.AddPragmaHandler("clang", ClangHandler.get());
866 // The tokens after pragma omp need to be expanded.
868 // OpenMP [2.1, Directive format]
869 // Preprocessing tokens following the #pragma omp are subject to macro
871 std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
872 new UnknownPragmaHandler("#pragma omp", Callbacks,
873 /*RequireTokenExpansion=*/true));
874 PP.AddPragmaHandler("omp", OpenMPHandler.get());
876 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
878 // After we have configured the preprocessor, enter the main file.
879 PP.EnterMainSourceFile();
881 // Consume all of the tokens that come from the predefines buffer. Those
882 // should not be emitted into the output and are guaranteed to be at the
884 const SourceManager &SourceMgr = PP.getSourceManager();
888 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
891 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
892 if (PLoc.isInvalid())
895 if (strcmp(PLoc.getFilename(), "<built-in>"))
899 // Read all the preprocessed tokens, printing them out to the stream.
900 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
903 // Remove the handlers we just added to leave the preprocessor in a sane state
904 // so that it can be reused (for example by a clang::Parser instance).
905 PP.RemovePragmaHandler(MicrosoftExtHandler.get());
906 PP.RemovePragmaHandler("GCC", GCCHandler.get());
907 PP.RemovePragmaHandler("clang", ClangHandler.get());
908 PP.RemovePragmaHandler("omp", OpenMPHandler.get());