Path: blob/main/contrib/llvm-project/clang/lib/Frontend/PrintPreprocessedOutput.cpp
35233 views
//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This code simply runs the preprocessor on the input file and prints out the9// result. This is the traditional behavior of the -E option.10//11//===----------------------------------------------------------------------===//1213#include "clang/Basic/CharInfo.h"14#include "clang/Basic/Diagnostic.h"15#include "clang/Basic/SourceManager.h"16#include "clang/Frontend/PreprocessorOutputOptions.h"17#include "clang/Frontend/Utils.h"18#include "clang/Lex/MacroInfo.h"19#include "clang/Lex/PPCallbacks.h"20#include "clang/Lex/Pragma.h"21#include "clang/Lex/Preprocessor.h"22#include "clang/Lex/TokenConcatenation.h"23#include "llvm/ADT/STLExtras.h"24#include "llvm/ADT/SmallString.h"25#include "llvm/ADT/StringRef.h"26#include "llvm/Support/ErrorHandling.h"27#include "llvm/Support/raw_ostream.h"28#include <cstdio>29using namespace clang;3031/// PrintMacroDefinition - Print a macro definition in a form that will be32/// properly accepted back as a definition.33static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,34Preprocessor &PP, raw_ostream *OS) {35*OS << "#define " << II.getName();3637if (MI.isFunctionLike()) {38*OS << '(';39if (!MI.param_empty()) {40MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_end();41for (; AI+1 != E; ++AI) {42*OS << (*AI)->getName();43*OS << ',';44}4546// Last argument.47if ((*AI)->getName() == "__VA_ARGS__")48*OS << "...";49else50*OS << (*AI)->getName();51}5253if (MI.isGNUVarargs())54*OS << "..."; // #define foo(x...)5556*OS << ')';57}5859// GCC always emits a space, even if the macro body is empty. However, do not60// want to emit two spaces if the first token has a leading space.61if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())62*OS << ' ';6364SmallString<128> SpellingBuffer;65for (const auto &T : MI.tokens()) {66if (T.hasLeadingSpace())67*OS << ' ';6869*OS << PP.getSpelling(T, SpellingBuffer);70}71}7273//===----------------------------------------------------------------------===//74// Preprocessed token printer75//===----------------------------------------------------------------------===//7677namespace {78class PrintPPOutputPPCallbacks : public PPCallbacks {79Preprocessor &PP;80SourceManager &SM;81TokenConcatenation ConcatInfo;82public:83raw_ostream *OS;84private:85unsigned CurLine;8687bool EmittedTokensOnThisLine;88bool EmittedDirectiveOnThisLine;89SrcMgr::CharacteristicKind FileType;90SmallString<512> CurFilename;91bool Initialized;92bool DisableLineMarkers;93bool DumpDefines;94bool DumpIncludeDirectives;95bool DumpEmbedDirectives;96bool UseLineDirectives;97bool IsFirstFileEntered;98bool MinimizeWhitespace;99bool DirectivesOnly;100bool KeepSystemIncludes;101raw_ostream *OrigOS;102std::unique_ptr<llvm::raw_null_ostream> NullOS;103unsigned NumToksToSkip;104105Token PrevTok;106Token PrevPrevTok;107108public:109PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream *os, bool lineMarkers,110bool defines, bool DumpIncludeDirectives,111bool DumpEmbedDirectives, bool UseLineDirectives,112bool MinimizeWhitespace, bool DirectivesOnly,113bool KeepSystemIncludes)114: PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),115DisableLineMarkers(lineMarkers), DumpDefines(defines),116DumpIncludeDirectives(DumpIncludeDirectives),117DumpEmbedDirectives(DumpEmbedDirectives),118UseLineDirectives(UseLineDirectives),119MinimizeWhitespace(MinimizeWhitespace), DirectivesOnly(DirectivesOnly),120KeepSystemIncludes(KeepSystemIncludes), OrigOS(os), NumToksToSkip(0) {121CurLine = 0;122CurFilename += "<uninit>";123EmittedTokensOnThisLine = false;124EmittedDirectiveOnThisLine = false;125FileType = SrcMgr::C_User;126Initialized = false;127IsFirstFileEntered = false;128if (KeepSystemIncludes)129NullOS = std::make_unique<llvm::raw_null_ostream>();130131PrevTok.startToken();132PrevPrevTok.startToken();133}134135/// Returns true if #embed directives should be expanded into a comma-136/// delimited list of integer constants or not.137bool expandEmbedContents() const { return !DumpEmbedDirectives; }138139bool isMinimizeWhitespace() const { return MinimizeWhitespace; }140141void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }142bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }143144void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }145bool hasEmittedDirectiveOnThisLine() const {146return EmittedDirectiveOnThisLine;147}148149/// Ensure that the output stream position is at the beginning of a new line150/// and inserts one if it does not. It is intended to ensure that directives151/// inserted by the directives not from the input source (such as #line) are152/// in the first column. To insert newlines that represent the input, use153/// MoveToLine(/*...*/, /*RequireStartOfLine=*/true).154void startNewLineIfNeeded();155156void FileChanged(SourceLocation Loc, FileChangeReason Reason,157SrcMgr::CharacteristicKind FileType,158FileID PrevFID) override;159void EmbedDirective(SourceLocation HashLoc, StringRef FileName, bool IsAngled,160OptionalFileEntryRef File,161const LexEmbedParametersResult &Params) override;162void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,163StringRef FileName, bool IsAngled,164CharSourceRange FilenameRange,165OptionalFileEntryRef File, StringRef SearchPath,166StringRef RelativePath, const Module *SuggestedModule,167bool ModuleImported,168SrcMgr::CharacteristicKind FileType) override;169void Ident(SourceLocation Loc, StringRef str) override;170void PragmaMessage(SourceLocation Loc, StringRef Namespace,171PragmaMessageKind Kind, StringRef Str) override;172void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;173void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;174void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;175void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,176diag::Severity Map, StringRef Str) override;177void PragmaWarning(SourceLocation Loc, PragmaWarningSpecifier WarningSpec,178ArrayRef<int> Ids) override;179void PragmaWarningPush(SourceLocation Loc, int Level) override;180void PragmaWarningPop(SourceLocation Loc) override;181void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;182void PragmaExecCharsetPop(SourceLocation Loc) override;183void PragmaAssumeNonNullBegin(SourceLocation Loc) override;184void PragmaAssumeNonNullEnd(SourceLocation Loc) override;185186/// Insert whitespace before emitting the next token.187///188/// @param Tok Next token to be emitted.189/// @param RequireSpace Ensure at least one whitespace is emitted. Useful190/// if non-tokens have been emitted to the stream.191/// @param RequireSameLine Never emit newlines. Useful when semantics depend192/// on being on the same line, such as directives.193void HandleWhitespaceBeforeTok(const Token &Tok, bool RequireSpace,194bool RequireSameLine);195196/// Move to the line of the provided source location. This will197/// return true if a newline was inserted or if198/// the requested location is the first token on the first line.199/// In these cases the next output will be the first column on the line and200/// make it possible to insert indention. The newline was inserted201/// implicitly when at the beginning of the file.202///203/// @param Tok Token where to move to.204/// @param RequireStartOfLine Whether the next line depends on being in the205/// first column, such as a directive.206///207/// @return Whether column adjustments are necessary.208bool MoveToLine(const Token &Tok, bool RequireStartOfLine) {209PresumedLoc PLoc = SM.getPresumedLoc(Tok.getLocation());210unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;211bool IsFirstInFile =212Tok.isAtStartOfLine() && PLoc.isValid() && PLoc.getLine() == 1;213return MoveToLine(TargetLine, RequireStartOfLine) || IsFirstInFile;214}215216/// Move to the line of the provided source location. Returns true if a new217/// line was inserted.218bool MoveToLine(SourceLocation Loc, bool RequireStartOfLine) {219PresumedLoc PLoc = SM.getPresumedLoc(Loc);220unsigned TargetLine = PLoc.isValid() ? PLoc.getLine() : CurLine;221return MoveToLine(TargetLine, RequireStartOfLine);222}223bool MoveToLine(unsigned LineNo, bool RequireStartOfLine);224225bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,226const Token &Tok) {227return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);228}229void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,230unsigned ExtraLen=0);231bool LineMarkersAreDisabled() const { return DisableLineMarkers; }232void HandleNewlinesInToken(const char *TokStr, unsigned Len);233234/// MacroDefined - This hook is called whenever a macro definition is seen.235void MacroDefined(const Token &MacroNameTok,236const MacroDirective *MD) override;237238/// MacroUndefined - This hook is called whenever a macro #undef is seen.239void MacroUndefined(const Token &MacroNameTok,240const MacroDefinition &MD,241const MacroDirective *Undef) override;242243void BeginModule(const Module *M);244void EndModule(const Module *M);245246unsigned GetNumToksToSkip() const { return NumToksToSkip; }247void ResetSkipToks() { NumToksToSkip = 0; }248};249} // end anonymous namespace250251void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,252const char *Extra,253unsigned ExtraLen) {254startNewLineIfNeeded();255256// Emit #line directives or GNU line markers depending on what mode we're in.257if (UseLineDirectives) {258*OS << "#line" << ' ' << LineNo << ' ' << '"';259OS->write_escaped(CurFilename);260*OS << '"';261} else {262*OS << '#' << ' ' << LineNo << ' ' << '"';263OS->write_escaped(CurFilename);264*OS << '"';265266if (ExtraLen)267OS->write(Extra, ExtraLen);268269if (FileType == SrcMgr::C_System)270OS->write(" 3", 2);271else if (FileType == SrcMgr::C_ExternCSystem)272OS->write(" 3 4", 4);273}274*OS << '\n';275}276277/// MoveToLine - Move the output to the source line specified by the location278/// object. We can do this by emitting some number of \n's, or be emitting a279/// #line directive. This returns false if already at the specified line, true280/// if some newlines were emitted.281bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo,282bool RequireStartOfLine) {283// If it is required to start a new line or finish the current, insert284// vertical whitespace now and take it into account when moving to the285// expected line.286bool StartedNewLine = false;287if ((RequireStartOfLine && EmittedTokensOnThisLine) ||288EmittedDirectiveOnThisLine) {289*OS << '\n';290StartedNewLine = true;291CurLine += 1;292EmittedTokensOnThisLine = false;293EmittedDirectiveOnThisLine = false;294}295296// If this line is "close enough" to the original line, just print newlines,297// otherwise print a #line directive.298if (CurLine == LineNo) {299// Nothing to do if we are already on the correct line.300} else if (MinimizeWhitespace && DisableLineMarkers) {301// With -E -P -fminimize-whitespace, don't emit anything if not necessary.302} else if (!StartedNewLine && LineNo - CurLine == 1) {303// Printing a single line has priority over printing a #line directive, even304// when minimizing whitespace which otherwise would print #line directives305// for every single line.306*OS << '\n';307StartedNewLine = true;308} else if (!DisableLineMarkers) {309if (LineNo - CurLine <= 8) {310const char *NewLines = "\n\n\n\n\n\n\n\n";311OS->write(NewLines, LineNo - CurLine);312} else {313// Emit a #line or line marker.314WriteLineInfo(LineNo, nullptr, 0);315}316StartedNewLine = true;317} else if (EmittedTokensOnThisLine) {318// If we are not on the correct line and don't need to be line-correct,319// at least ensure we start on a new line.320*OS << '\n';321StartedNewLine = true;322}323324if (StartedNewLine) {325EmittedTokensOnThisLine = false;326EmittedDirectiveOnThisLine = false;327}328329CurLine = LineNo;330return StartedNewLine;331}332333void PrintPPOutputPPCallbacks::startNewLineIfNeeded() {334if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {335*OS << '\n';336EmittedTokensOnThisLine = false;337EmittedDirectiveOnThisLine = false;338}339}340341/// FileChanged - Whenever the preprocessor enters or exits a #include file342/// it invokes this handler. Update our conception of the current source343/// position.344void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,345FileChangeReason Reason,346SrcMgr::CharacteristicKind NewFileType,347FileID PrevFID) {348// Unless we are exiting a #include, make sure to skip ahead to the line the349// #include directive was at.350SourceManager &SourceMgr = SM;351352PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);353if (UserLoc.isInvalid())354return;355356unsigned NewLine = UserLoc.getLine();357358if (Reason == PPCallbacks::EnterFile) {359SourceLocation IncludeLoc = UserLoc.getIncludeLoc();360if (IncludeLoc.isValid())361MoveToLine(IncludeLoc, /*RequireStartOfLine=*/false);362} else if (Reason == PPCallbacks::SystemHeaderPragma) {363// GCC emits the # directive for this directive on the line AFTER the364// directive and emits a bunch of spaces that aren't needed. This is because365// otherwise we will emit a line marker for THIS line, which requires an366// extra blank line after the directive to avoid making all following lines367// off by one. We can do better by simply incrementing NewLine here.368NewLine += 1;369}370371CurLine = NewLine;372373// In KeepSystemIncludes mode, redirect OS as needed.374if (KeepSystemIncludes && (isSystem(FileType) != isSystem(NewFileType)))375OS = isSystem(FileType) ? OrigOS : NullOS.get();376377CurFilename.clear();378CurFilename += UserLoc.getFilename();379FileType = NewFileType;380381if (DisableLineMarkers) {382if (!MinimizeWhitespace)383startNewLineIfNeeded();384return;385}386387if (!Initialized) {388WriteLineInfo(CurLine);389Initialized = true;390}391392// Do not emit an enter marker for the main file (which we expect is the first393// entered file). This matches gcc, and improves compatibility with some tools394// which track the # line markers as a way to determine when the preprocessed395// output is in the context of the main file.396if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {397IsFirstFileEntered = true;398return;399}400401switch (Reason) {402case PPCallbacks::EnterFile:403WriteLineInfo(CurLine, " 1", 2);404break;405case PPCallbacks::ExitFile:406WriteLineInfo(CurLine, " 2", 2);407break;408case PPCallbacks::SystemHeaderPragma:409case PPCallbacks::RenameFile:410WriteLineInfo(CurLine);411break;412}413}414415void PrintPPOutputPPCallbacks::EmbedDirective(416SourceLocation HashLoc, StringRef FileName, bool IsAngled,417OptionalFileEntryRef File, const LexEmbedParametersResult &Params) {418if (!DumpEmbedDirectives)419return;420421// The EmbedDirective() callback is called before we produce the annotation422// token stream for the directive. We skip printing the annotation tokens423// within PrintPreprocessedTokens(), but we also need to skip the prefix,424// suffix, and if_empty tokens as those are inserted directly into the token425// stream and would otherwise be printed immediately after printing the426// #embed directive.427//428// FIXME: counting tokens to skip is a kludge but we have no way to know429// which tokens were inserted as part of the embed and which ones were430// explicitly written by the user.431MoveToLine(HashLoc, /*RequireStartOfLine=*/true);432*OS << "#embed " << (IsAngled ? '<' : '"') << FileName433<< (IsAngled ? '>' : '"');434435auto PrintToks = [&](llvm::ArrayRef<Token> Toks) {436SmallString<128> SpellingBuffer;437for (const Token &T : Toks) {438if (T.hasLeadingSpace())439*OS << " ";440*OS << PP.getSpelling(T, SpellingBuffer);441}442};443bool SkipAnnotToks = true;444if (Params.MaybeIfEmptyParam) {445*OS << " if_empty(";446PrintToks(Params.MaybeIfEmptyParam->Tokens);447*OS << ")";448// If the file is empty, we can skip those tokens. If the file is not449// empty, we skip the annotation tokens.450if (File && !File->getSize()) {451NumToksToSkip += Params.MaybeIfEmptyParam->Tokens.size();452SkipAnnotToks = false;453}454}455456if (Params.MaybeLimitParam) {457*OS << " limit(" << Params.MaybeLimitParam->Limit << ")";458}459if (Params.MaybeOffsetParam) {460*OS << " clang::offset(" << Params.MaybeOffsetParam->Offset << ")";461}462if (Params.MaybePrefixParam) {463*OS << " prefix(";464PrintToks(Params.MaybePrefixParam->Tokens);465*OS << ")";466NumToksToSkip += Params.MaybePrefixParam->Tokens.size();467}468if (Params.MaybeSuffixParam) {469*OS << " suffix(";470PrintToks(Params.MaybeSuffixParam->Tokens);471*OS << ")";472NumToksToSkip += Params.MaybeSuffixParam->Tokens.size();473}474475// We may need to skip the annotation token.476if (SkipAnnotToks)477NumToksToSkip++;478479*OS << " /* clang -E -dE */";480setEmittedDirectiveOnThisLine();481}482483void PrintPPOutputPPCallbacks::InclusionDirective(484SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,485bool IsAngled, CharSourceRange FilenameRange, OptionalFileEntryRef File,486StringRef SearchPath, StringRef RelativePath, const Module *SuggestedModule,487bool ModuleImported, SrcMgr::CharacteristicKind FileType) {488// In -dI mode, dump #include directives prior to dumping their content or489// interpretation. Similar for -fkeep-system-includes.490if (DumpIncludeDirectives || (KeepSystemIncludes && isSystem(FileType))) {491MoveToLine(HashLoc, /*RequireStartOfLine=*/true);492const std::string TokenText = PP.getSpelling(IncludeTok);493assert(!TokenText.empty());494*OS << "#" << TokenText << " "495<< (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')496<< " /* clang -E "497<< (DumpIncludeDirectives ? "-dI" : "-fkeep-system-includes")498<< " */";499setEmittedDirectiveOnThisLine();500}501502// When preprocessing, turn implicit imports into module import pragmas.503if (ModuleImported) {504switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {505case tok::pp_include:506case tok::pp_import:507case tok::pp_include_next:508MoveToLine(HashLoc, /*RequireStartOfLine=*/true);509*OS << "#pragma clang module import "510<< SuggestedModule->getFullModuleName(true)511<< " /* clang -E: implicit import for "512<< "#" << PP.getSpelling(IncludeTok) << " "513<< (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')514<< " */";515setEmittedDirectiveOnThisLine();516break;517518case tok::pp___include_macros:519// #__include_macros has no effect on a user of a preprocessed source520// file; the only effect is on preprocessing.521//522// FIXME: That's not *quite* true: it causes the module in question to523// be loaded, which can affect downstream diagnostics.524break;525526default:527llvm_unreachable("unknown include directive kind");528break;529}530}531}532533/// Handle entering the scope of a module during a module compilation.534void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {535startNewLineIfNeeded();536*OS << "#pragma clang module begin " << M->getFullModuleName(true);537setEmittedDirectiveOnThisLine();538}539540/// Handle leaving the scope of a module during a module compilation.541void PrintPPOutputPPCallbacks::EndModule(const Module *M) {542startNewLineIfNeeded();543*OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";544setEmittedDirectiveOnThisLine();545}546547/// Ident - Handle #ident directives when read by the preprocessor.548///549void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {550MoveToLine(Loc, /*RequireStartOfLine=*/true);551552OS->write("#ident ", strlen("#ident "));553OS->write(S.begin(), S.size());554setEmittedTokensOnThisLine();555}556557/// MacroDefined - This hook is called whenever a macro definition is seen.558void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,559const MacroDirective *MD) {560const MacroInfo *MI = MD->getMacroInfo();561// Print out macro definitions in -dD mode and when we have -fdirectives-only562// for C++20 header units.563if ((!DumpDefines && !DirectivesOnly) ||564// Ignore __FILE__ etc.565MI->isBuiltinMacro())566return;567568SourceLocation DefLoc = MI->getDefinitionLoc();569if (DirectivesOnly && !MI->isUsed()) {570SourceManager &SM = PP.getSourceManager();571if (SM.isWrittenInBuiltinFile(DefLoc) ||572SM.isWrittenInCommandLineFile(DefLoc))573return;574}575MoveToLine(DefLoc, /*RequireStartOfLine=*/true);576PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);577setEmittedDirectiveOnThisLine();578}579580void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,581const MacroDefinition &MD,582const MacroDirective *Undef) {583// Print out macro definitions in -dD mode and when we have -fdirectives-only584// for C++20 header units.585if (!DumpDefines && !DirectivesOnly)586return;587588MoveToLine(MacroNameTok.getLocation(), /*RequireStartOfLine=*/true);589*OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();590setEmittedDirectiveOnThisLine();591}592593static void outputPrintable(raw_ostream *OS, StringRef Str) {594for (unsigned char Char : Str) {595if (isPrintable(Char) && Char != '\\' && Char != '"')596*OS << (char)Char;597else // Output anything hard as an octal escape.598*OS << '\\'599<< (char)('0' + ((Char >> 6) & 7))600<< (char)('0' + ((Char >> 3) & 7))601<< (char)('0' + ((Char >> 0) & 7));602}603}604605void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,606StringRef Namespace,607PragmaMessageKind Kind,608StringRef Str) {609MoveToLine(Loc, /*RequireStartOfLine=*/true);610*OS << "#pragma ";611if (!Namespace.empty())612*OS << Namespace << ' ';613switch (Kind) {614case PMK_Message:615*OS << "message(\"";616break;617case PMK_Warning:618*OS << "warning \"";619break;620case PMK_Error:621*OS << "error \"";622break;623}624625outputPrintable(OS, Str);626*OS << '"';627if (Kind == PMK_Message)628*OS << ')';629setEmittedDirectiveOnThisLine();630}631632void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,633StringRef DebugType) {634MoveToLine(Loc, /*RequireStartOfLine=*/true);635636*OS << "#pragma clang __debug ";637*OS << DebugType;638639setEmittedDirectiveOnThisLine();640}641642void PrintPPOutputPPCallbacks::643PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {644MoveToLine(Loc, /*RequireStartOfLine=*/true);645*OS << "#pragma " << Namespace << " diagnostic push";646setEmittedDirectiveOnThisLine();647}648649void PrintPPOutputPPCallbacks::650PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {651MoveToLine(Loc, /*RequireStartOfLine=*/true);652*OS << "#pragma " << Namespace << " diagnostic pop";653setEmittedDirectiveOnThisLine();654}655656void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,657StringRef Namespace,658diag::Severity Map,659StringRef Str) {660MoveToLine(Loc, /*RequireStartOfLine=*/true);661*OS << "#pragma " << Namespace << " diagnostic ";662switch (Map) {663case diag::Severity::Remark:664*OS << "remark";665break;666case diag::Severity::Warning:667*OS << "warning";668break;669case diag::Severity::Error:670*OS << "error";671break;672case diag::Severity::Ignored:673*OS << "ignored";674break;675case diag::Severity::Fatal:676*OS << "fatal";677break;678}679*OS << " \"" << Str << '"';680setEmittedDirectiveOnThisLine();681}682683void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,684PragmaWarningSpecifier WarningSpec,685ArrayRef<int> Ids) {686MoveToLine(Loc, /*RequireStartOfLine=*/true);687688*OS << "#pragma warning(";689switch(WarningSpec) {690case PWS_Default: *OS << "default"; break;691case PWS_Disable: *OS << "disable"; break;692case PWS_Error: *OS << "error"; break;693case PWS_Once: *OS << "once"; break;694case PWS_Suppress: *OS << "suppress"; break;695case PWS_Level1: *OS << '1'; break;696case PWS_Level2: *OS << '2'; break;697case PWS_Level3: *OS << '3'; break;698case PWS_Level4: *OS << '4'; break;699}700*OS << ':';701702for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)703*OS << ' ' << *I;704*OS << ')';705setEmittedDirectiveOnThisLine();706}707708void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,709int Level) {710MoveToLine(Loc, /*RequireStartOfLine=*/true);711*OS << "#pragma warning(push";712if (Level >= 0)713*OS << ", " << Level;714*OS << ')';715setEmittedDirectiveOnThisLine();716}717718void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {719MoveToLine(Loc, /*RequireStartOfLine=*/true);720*OS << "#pragma warning(pop)";721setEmittedDirectiveOnThisLine();722}723724void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,725StringRef Str) {726MoveToLine(Loc, /*RequireStartOfLine=*/true);727*OS << "#pragma character_execution_set(push";728if (!Str.empty())729*OS << ", " << Str;730*OS << ')';731setEmittedDirectiveOnThisLine();732}733734void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {735MoveToLine(Loc, /*RequireStartOfLine=*/true);736*OS << "#pragma character_execution_set(pop)";737setEmittedDirectiveOnThisLine();738}739740void PrintPPOutputPPCallbacks::741PragmaAssumeNonNullBegin(SourceLocation Loc) {742MoveToLine(Loc, /*RequireStartOfLine=*/true);743*OS << "#pragma clang assume_nonnull begin";744setEmittedDirectiveOnThisLine();745}746747void PrintPPOutputPPCallbacks::748PragmaAssumeNonNullEnd(SourceLocation Loc) {749MoveToLine(Loc, /*RequireStartOfLine=*/true);750*OS << "#pragma clang assume_nonnull end";751setEmittedDirectiveOnThisLine();752}753754void PrintPPOutputPPCallbacks::HandleWhitespaceBeforeTok(const Token &Tok,755bool RequireSpace,756bool RequireSameLine) {757// These tokens are not expanded to anything and don't need whitespace before758// them.759if (Tok.is(tok::eof) ||760(Tok.isAnnotation() && !Tok.is(tok::annot_header_unit) &&761!Tok.is(tok::annot_module_begin) && !Tok.is(tok::annot_module_end) &&762!Tok.is(tok::annot_repl_input_end) && !Tok.is(tok::annot_embed)))763return;764765// EmittedDirectiveOnThisLine takes priority over RequireSameLine.766if ((!RequireSameLine || EmittedDirectiveOnThisLine) &&767MoveToLine(Tok, /*RequireStartOfLine=*/EmittedDirectiveOnThisLine)) {768if (MinimizeWhitespace) {769// Avoid interpreting hash as a directive under -fpreprocessed.770if (Tok.is(tok::hash))771*OS << ' ';772} else {773// Print out space characters so that the first token on a line is774// indented for easy reading.775unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());776777// The first token on a line can have a column number of 1, yet still778// expect leading white space, if a macro expansion in column 1 starts779// with an empty macro argument, or an empty nested macro expansion. In780// this case, move the token to column 2.781if (ColNo == 1 && Tok.hasLeadingSpace())782ColNo = 2;783784// This hack prevents stuff like:785// #define HASH #786// HASH define foo bar787// From having the # character end up at column 1, which makes it so it788// is not handled as a #define next time through the preprocessor if in789// -fpreprocessed mode.790if (ColNo <= 1 && Tok.is(tok::hash))791*OS << ' ';792793// Otherwise, indent the appropriate number of spaces.794for (; ColNo > 1; --ColNo)795*OS << ' ';796}797} else {798// Insert whitespace between the previous and next token if either799// - The caller requires it800// - The input had whitespace between them and we are not in801// whitespace-minimization mode802// - The whitespace is necessary to keep the tokens apart and there is not803// already a newline between them804if (RequireSpace || (!MinimizeWhitespace && Tok.hasLeadingSpace()) ||805((EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) &&806AvoidConcat(PrevPrevTok, PrevTok, Tok)))807*OS << ' ';808}809810PrevPrevTok = PrevTok;811PrevTok = Tok;812}813814void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,815unsigned Len) {816unsigned NumNewlines = 0;817for (; Len; --Len, ++TokStr) {818if (*TokStr != '\n' &&819*TokStr != '\r')820continue;821822++NumNewlines;823824// If we have \n\r or \r\n, skip both and count as one line.825if (Len != 1 &&826(TokStr[1] == '\n' || TokStr[1] == '\r') &&827TokStr[0] != TokStr[1]) {828++TokStr;829--Len;830}831}832833if (NumNewlines == 0) return;834835CurLine += NumNewlines;836}837838839namespace {840struct UnknownPragmaHandler : public PragmaHandler {841const char *Prefix;842PrintPPOutputPPCallbacks *Callbacks;843844// Set to true if tokens should be expanded845bool ShouldExpandTokens;846847UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,848bool RequireTokenExpansion)849: Prefix(prefix), Callbacks(callbacks),850ShouldExpandTokens(RequireTokenExpansion) {}851void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,852Token &PragmaTok) override {853// Figure out what line we went to and insert the appropriate number of854// newline characters.855Callbacks->MoveToLine(PragmaTok.getLocation(), /*RequireStartOfLine=*/true);856Callbacks->OS->write(Prefix, strlen(Prefix));857Callbacks->setEmittedTokensOnThisLine();858859if (ShouldExpandTokens) {860// The first token does not have expanded macros. Expand them, if861// required.862auto Toks = std::make_unique<Token[]>(1);863Toks[0] = PragmaTok;864PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,865/*DisableMacroExpansion=*/false,866/*IsReinject=*/false);867PP.Lex(PragmaTok);868}869870// Read and print all of the pragma tokens.871bool IsFirst = true;872while (PragmaTok.isNot(tok::eod)) {873Callbacks->HandleWhitespaceBeforeTok(PragmaTok, /*RequireSpace=*/IsFirst,874/*RequireSameLine=*/true);875IsFirst = false;876std::string TokSpell = PP.getSpelling(PragmaTok);877Callbacks->OS->write(&TokSpell[0], TokSpell.size());878Callbacks->setEmittedTokensOnThisLine();879880if (ShouldExpandTokens)881PP.Lex(PragmaTok);882else883PP.LexUnexpandedToken(PragmaTok);884}885Callbacks->setEmittedDirectiveOnThisLine();886}887};888} // end anonymous namespace889890891static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,892PrintPPOutputPPCallbacks *Callbacks) {893bool DropComments = PP.getLangOpts().TraditionalCPP &&894!PP.getCommentRetentionState();895896bool IsStartOfLine = false;897char Buffer[256];898while (true) {899// Two lines joined with line continuation ('\' as last character on the900// line) must be emitted as one line even though Tok.getLine() returns two901// different values. In this situation Tok.isAtStartOfLine() is false even902// though it may be the first token on the lexical line. When903// dropping/skipping a token that is at the start of a line, propagate the904// start-of-line-ness to the next token to not append it to the previous905// line.906IsStartOfLine = IsStartOfLine || Tok.isAtStartOfLine();907908Callbacks->HandleWhitespaceBeforeTok(Tok, /*RequireSpace=*/false,909/*RequireSameLine=*/!IsStartOfLine);910911if (DropComments && Tok.is(tok::comment)) {912// Skip comments. Normally the preprocessor does not generate913// tok::comment nodes at all when not keeping comments, but under914// -traditional-cpp the lexer keeps /all/ whitespace, including comments.915PP.Lex(Tok);916continue;917} else if (Tok.is(tok::annot_repl_input_end)) {918PP.Lex(Tok);919continue;920} else if (Tok.is(tok::eod)) {921// Don't print end of directive tokens, since they are typically newlines922// that mess up our line tracking. These come from unknown pre-processor923// directives or hash-prefixed comments in standalone assembly files.924PP.Lex(Tok);925// FIXME: The token on the next line after #include should have926// Tok.isAtStartOfLine() set.927IsStartOfLine = true;928continue;929} else if (Tok.is(tok::annot_module_include)) {930// PrintPPOutputPPCallbacks::InclusionDirective handles producing931// appropriate output here. Ignore this token entirely.932PP.Lex(Tok);933IsStartOfLine = true;934continue;935} else if (Tok.is(tok::annot_module_begin)) {936// FIXME: We retrieve this token after the FileChanged callback, and937// retrieve the module_end token before the FileChanged callback, so938// we render this within the file and render the module end outside the939// file, but this is backwards from the token locations: the module_begin940// token is at the include location (outside the file) and the module_end941// token is at the EOF location (within the file).942Callbacks->BeginModule(943reinterpret_cast<Module *>(Tok.getAnnotationValue()));944PP.Lex(Tok);945IsStartOfLine = true;946continue;947} else if (Tok.is(tok::annot_module_end)) {948Callbacks->EndModule(949reinterpret_cast<Module *>(Tok.getAnnotationValue()));950PP.Lex(Tok);951IsStartOfLine = true;952continue;953} else if (Tok.is(tok::annot_header_unit)) {954// This is a header-name that has been (effectively) converted into a955// module-name.956// FIXME: The module name could contain non-identifier module name957// components. We don't have a good way to round-trip those.958Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());959std::string Name = M->getFullModuleName();960Callbacks->OS->write(Name.data(), Name.size());961Callbacks->HandleNewlinesInToken(Name.data(), Name.size());962} else if (Tok.is(tok::annot_embed)) {963// Manually explode the binary data out to a stream of comma-delimited964// integer values. If the user passed -dE, that is handled by the965// EmbedDirective() callback. We should only get here if the user did not966// pass -dE.967assert(Callbacks->expandEmbedContents() &&968"did not expect an embed annotation");969auto *Data =970reinterpret_cast<EmbedAnnotationData *>(Tok.getAnnotationValue());971972// Loop over the contents and print them as a comma-delimited list of973// values.974bool PrintComma = false;975for (auto Iter = Data->BinaryData.begin(), End = Data->BinaryData.end();976Iter != End; ++Iter) {977if (PrintComma)978*Callbacks->OS << ", ";979*Callbacks->OS << static_cast<unsigned>(*Iter);980PrintComma = true;981}982IsStartOfLine = true;983} else if (Tok.isAnnotation()) {984// Ignore annotation tokens created by pragmas - the pragmas themselves985// will be reproduced in the preprocessed output.986PP.Lex(Tok);987continue;988} else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {989*Callbacks->OS << II->getName();990} else if (Tok.isLiteral() && !Tok.needsCleaning() &&991Tok.getLiteralData()) {992Callbacks->OS->write(Tok.getLiteralData(), Tok.getLength());993} else if (Tok.getLength() < std::size(Buffer)) {994const char *TokPtr = Buffer;995unsigned Len = PP.getSpelling(Tok, TokPtr);996Callbacks->OS->write(TokPtr, Len);997998// Tokens that can contain embedded newlines need to adjust our current999// line number.1000// FIXME: The token may end with a newline in which case1001// setEmittedDirectiveOnThisLine/setEmittedTokensOnThisLine afterwards is1002// wrong.1003if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)1004Callbacks->HandleNewlinesInToken(TokPtr, Len);1005if (Tok.is(tok::comment) && Len >= 2 && TokPtr[0] == '/' &&1006TokPtr[1] == '/') {1007// It's a line comment;1008// Ensure that we don't concatenate anything behind it.1009Callbacks->setEmittedDirectiveOnThisLine();1010}1011} else {1012std::string S = PP.getSpelling(Tok);1013Callbacks->OS->write(S.data(), S.size());10141015// Tokens that can contain embedded newlines need to adjust our current1016// line number.1017if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)1018Callbacks->HandleNewlinesInToken(S.data(), S.size());1019if (Tok.is(tok::comment) && S.size() >= 2 && S[0] == '/' && S[1] == '/') {1020// It's a line comment;1021// Ensure that we don't concatenate anything behind it.1022Callbacks->setEmittedDirectiveOnThisLine();1023}1024}1025Callbacks->setEmittedTokensOnThisLine();1026IsStartOfLine = false;10271028if (Tok.is(tok::eof)) break;10291030PP.Lex(Tok);1031// If lexing that token causes us to need to skip future tokens, do so now.1032for (unsigned I = 0, Skip = Callbacks->GetNumToksToSkip(); I < Skip; ++I)1033PP.Lex(Tok);1034Callbacks->ResetSkipToks();1035}1036}10371038typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;1039static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {1040return LHS->first->getName().compare(RHS->first->getName());1041}10421043static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {1044// Ignore unknown pragmas.1045PP.IgnorePragmas();10461047// -dM mode just scans and ignores all tokens in the files, then dumps out1048// the macro table at the end.1049PP.EnterMainSourceFile();10501051Token Tok;1052do PP.Lex(Tok);1053while (Tok.isNot(tok::eof));10541055SmallVector<id_macro_pair, 128> MacrosByID;1056for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();1057I != E; ++I) {1058auto *MD = I->second.getLatest();1059if (MD && MD->isDefined())1060MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));1061}1062llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);10631064for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {1065MacroInfo &MI = *MacrosByID[i].second;1066// Ignore computed macros like __LINE__ and friends.1067if (MI.isBuiltinMacro()) continue;10681069PrintMacroDefinition(*MacrosByID[i].first, MI, PP, OS);1070*OS << '\n';1071}1072}10731074/// DoPrintPreprocessedInput - This implements -E mode.1075///1076void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,1077const PreprocessorOutputOptions &Opts) {1078// Show macros with no output is handled specially.1079if (!Opts.ShowCPP) {1080assert(Opts.ShowMacros && "Not yet implemented!");1081DoPrintMacros(PP, OS);1082return;1083}10841085// Inform the preprocessor whether we want it to retain comments or not, due1086// to -C or -CC.1087PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);10881089PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(1090PP, OS, !Opts.ShowLineMarkers, Opts.ShowMacros,1091Opts.ShowIncludeDirectives, Opts.ShowEmbedDirectives,1092Opts.UseLineDirectives, Opts.MinimizeWhitespace, Opts.DirectivesOnly,1093Opts.KeepSystemIncludes);10941095// Expand macros in pragmas with -fms-extensions. The assumption is that1096// the majority of pragmas in such a file will be Microsoft pragmas.1097// Remember the handlers we will add so that we can remove them later.1098std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(1099new UnknownPragmaHandler(1100"#pragma", Callbacks,1101/*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));11021103std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(1104"#pragma GCC", Callbacks,1105/*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));11061107std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(1108"#pragma clang", Callbacks,1109/*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));11101111PP.AddPragmaHandler(MicrosoftExtHandler.get());1112PP.AddPragmaHandler("GCC", GCCHandler.get());1113PP.AddPragmaHandler("clang", ClangHandler.get());11141115// The tokens after pragma omp need to be expanded.1116//1117// OpenMP [2.1, Directive format]1118// Preprocessing tokens following the #pragma omp are subject to macro1119// replacement.1120std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(1121new UnknownPragmaHandler("#pragma omp", Callbacks,1122/*RequireTokenExpansion=*/true));1123PP.AddPragmaHandler("omp", OpenMPHandler.get());11241125PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));11261127// After we have configured the preprocessor, enter the main file.1128PP.EnterMainSourceFile();1129if (Opts.DirectivesOnly)1130PP.SetMacroExpansionOnlyInDirectives();11311132// Consume all of the tokens that come from the predefines buffer. Those1133// should not be emitted into the output and are guaranteed to be at the1134// start.1135const SourceManager &SourceMgr = PP.getSourceManager();1136Token Tok;1137do {1138PP.Lex(Tok);1139if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())1140break;11411142PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());1143if (PLoc.isInvalid())1144break;11451146if (strcmp(PLoc.getFilename(), "<built-in>"))1147break;1148} while (true);11491150// Read all the preprocessed tokens, printing them out to the stream.1151PrintPreprocessedTokens(PP, Tok, Callbacks);1152*OS << '\n';11531154// Remove the handlers we just added to leave the preprocessor in a sane state1155// so that it can be reused (for example by a clang::Parser instance).1156PP.RemovePragmaHandler(MicrosoftExtHandler.get());1157PP.RemovePragmaHandler("GCC", GCCHandler.get());1158PP.RemovePragmaHandler("clang", ClangHandler.get());1159PP.RemovePragmaHandler("omp", OpenMPHandler.get());1160}116111621163