1*7330f729Sjoerg //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
2*7330f729Sjoerg //
3*7330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*7330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
5*7330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*7330f729Sjoerg //
7*7330f729Sjoerg //===----------------------------------------------------------------------===//
8*7330f729Sjoerg //
9*7330f729Sjoerg // This code simply runs the preprocessor on the input file and prints out the
10*7330f729Sjoerg // result. This is the traditional behavior of the -E option.
11*7330f729Sjoerg //
12*7330f729Sjoerg //===----------------------------------------------------------------------===//
13*7330f729Sjoerg
14*7330f729Sjoerg #include "clang/Frontend/Utils.h"
15*7330f729Sjoerg #include "clang/Basic/CharInfo.h"
16*7330f729Sjoerg #include "clang/Basic/Diagnostic.h"
17*7330f729Sjoerg #include "clang/Basic/SourceManager.h"
18*7330f729Sjoerg #include "clang/Frontend/PreprocessorOutputOptions.h"
19*7330f729Sjoerg #include "clang/Lex/MacroInfo.h"
20*7330f729Sjoerg #include "clang/Lex/PPCallbacks.h"
21*7330f729Sjoerg #include "clang/Lex/Pragma.h"
22*7330f729Sjoerg #include "clang/Lex/Preprocessor.h"
23*7330f729Sjoerg #include "clang/Lex/TokenConcatenation.h"
24*7330f729Sjoerg #include "llvm/ADT/STLExtras.h"
25*7330f729Sjoerg #include "llvm/ADT/SmallString.h"
26*7330f729Sjoerg #include "llvm/ADT/StringRef.h"
27*7330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
28*7330f729Sjoerg #include "llvm/Support/raw_ostream.h"
29*7330f729Sjoerg #include <cstdio>
30*7330f729Sjoerg using namespace clang;
31*7330f729Sjoerg
32*7330f729Sjoerg /// PrintMacroDefinition - Print a macro definition in a form that will be
33*7330f729Sjoerg /// properly accepted back as a definition.
PrintMacroDefinition(const IdentifierInfo & II,const MacroInfo & MI,Preprocessor & PP,raw_ostream & OS)34*7330f729Sjoerg static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
35*7330f729Sjoerg Preprocessor &PP, raw_ostream &OS) {
36*7330f729Sjoerg OS << "#define " << II.getName();
37*7330f729Sjoerg
38*7330f729Sjoerg if (MI.isFunctionLike()) {
39*7330f729Sjoerg OS << '(';
40*7330f729Sjoerg if (!MI.param_empty()) {
41*7330f729Sjoerg MacroInfo::param_iterator AI = MI.param_begin(), E = MI.param_end();
42*7330f729Sjoerg for (; AI+1 != E; ++AI) {
43*7330f729Sjoerg OS << (*AI)->getName();
44*7330f729Sjoerg OS << ',';
45*7330f729Sjoerg }
46*7330f729Sjoerg
47*7330f729Sjoerg // Last argument.
48*7330f729Sjoerg if ((*AI)->getName() == "__VA_ARGS__")
49*7330f729Sjoerg OS << "...";
50*7330f729Sjoerg else
51*7330f729Sjoerg OS << (*AI)->getName();
52*7330f729Sjoerg }
53*7330f729Sjoerg
54*7330f729Sjoerg if (MI.isGNUVarargs())
55*7330f729Sjoerg OS << "..."; // #define foo(x...)
56*7330f729Sjoerg
57*7330f729Sjoerg OS << ')';
58*7330f729Sjoerg }
59*7330f729Sjoerg
60*7330f729Sjoerg // GCC always emits a space, even if the macro body is empty. However, do not
61*7330f729Sjoerg // want to emit two spaces if the first token has a leading space.
62*7330f729Sjoerg if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
63*7330f729Sjoerg OS << ' ';
64*7330f729Sjoerg
65*7330f729Sjoerg SmallString<128> SpellingBuffer;
66*7330f729Sjoerg for (const auto &T : MI.tokens()) {
67*7330f729Sjoerg if (T.hasLeadingSpace())
68*7330f729Sjoerg OS << ' ';
69*7330f729Sjoerg
70*7330f729Sjoerg OS << PP.getSpelling(T, SpellingBuffer);
71*7330f729Sjoerg }
72*7330f729Sjoerg }
73*7330f729Sjoerg
74*7330f729Sjoerg //===----------------------------------------------------------------------===//
75*7330f729Sjoerg // Preprocessed token printer
76*7330f729Sjoerg //===----------------------------------------------------------------------===//
77*7330f729Sjoerg
78*7330f729Sjoerg namespace {
79*7330f729Sjoerg class PrintPPOutputPPCallbacks : public PPCallbacks {
80*7330f729Sjoerg Preprocessor &PP;
81*7330f729Sjoerg SourceManager &SM;
82*7330f729Sjoerg TokenConcatenation ConcatInfo;
83*7330f729Sjoerg public:
84*7330f729Sjoerg raw_ostream &OS;
85*7330f729Sjoerg private:
86*7330f729Sjoerg unsigned CurLine;
87*7330f729Sjoerg
88*7330f729Sjoerg bool EmittedTokensOnThisLine;
89*7330f729Sjoerg bool EmittedDirectiveOnThisLine;
90*7330f729Sjoerg SrcMgr::CharacteristicKind FileType;
91*7330f729Sjoerg SmallString<512> CurFilename;
92*7330f729Sjoerg bool Initialized;
93*7330f729Sjoerg bool DisableLineMarkers;
94*7330f729Sjoerg bool DumpDefines;
95*7330f729Sjoerg bool DumpIncludeDirectives;
96*7330f729Sjoerg bool UseLineDirectives;
97*7330f729Sjoerg bool IsFirstFileEntered;
98*7330f729Sjoerg public:
PrintPPOutputPPCallbacks(Preprocessor & pp,raw_ostream & os,bool lineMarkers,bool defines,bool DumpIncludeDirectives,bool UseLineDirectives)99*7330f729Sjoerg PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os, bool lineMarkers,
100*7330f729Sjoerg bool defines, bool DumpIncludeDirectives,
101*7330f729Sjoerg bool UseLineDirectives)
102*7330f729Sjoerg : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
103*7330f729Sjoerg DisableLineMarkers(lineMarkers), DumpDefines(defines),
104*7330f729Sjoerg DumpIncludeDirectives(DumpIncludeDirectives),
105*7330f729Sjoerg UseLineDirectives(UseLineDirectives) {
106*7330f729Sjoerg CurLine = 0;
107*7330f729Sjoerg CurFilename += "<uninit>";
108*7330f729Sjoerg EmittedTokensOnThisLine = false;
109*7330f729Sjoerg EmittedDirectiveOnThisLine = false;
110*7330f729Sjoerg FileType = SrcMgr::C_User;
111*7330f729Sjoerg Initialized = false;
112*7330f729Sjoerg IsFirstFileEntered = false;
113*7330f729Sjoerg }
114*7330f729Sjoerg
setEmittedTokensOnThisLine()115*7330f729Sjoerg void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
hasEmittedTokensOnThisLine() const116*7330f729Sjoerg bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
117*7330f729Sjoerg
setEmittedDirectiveOnThisLine()118*7330f729Sjoerg void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
hasEmittedDirectiveOnThisLine() const119*7330f729Sjoerg bool hasEmittedDirectiveOnThisLine() const {
120*7330f729Sjoerg return EmittedDirectiveOnThisLine;
121*7330f729Sjoerg }
122*7330f729Sjoerg
123*7330f729Sjoerg bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
124*7330f729Sjoerg
125*7330f729Sjoerg void FileChanged(SourceLocation Loc, FileChangeReason Reason,
126*7330f729Sjoerg SrcMgr::CharacteristicKind FileType,
127*7330f729Sjoerg FileID PrevFID) override;
128*7330f729Sjoerg void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
129*7330f729Sjoerg StringRef FileName, bool IsAngled,
130*7330f729Sjoerg CharSourceRange FilenameRange, const FileEntry *File,
131*7330f729Sjoerg StringRef SearchPath, StringRef RelativePath,
132*7330f729Sjoerg const Module *Imported,
133*7330f729Sjoerg SrcMgr::CharacteristicKind FileType) override;
134*7330f729Sjoerg void Ident(SourceLocation Loc, StringRef str) override;
135*7330f729Sjoerg void PragmaMessage(SourceLocation Loc, StringRef Namespace,
136*7330f729Sjoerg PragmaMessageKind Kind, StringRef Str) override;
137*7330f729Sjoerg void PragmaDebug(SourceLocation Loc, StringRef DebugType) override;
138*7330f729Sjoerg void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override;
139*7330f729Sjoerg void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override;
140*7330f729Sjoerg void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
141*7330f729Sjoerg diag::Severity Map, StringRef Str) override;
142*7330f729Sjoerg void PragmaWarning(SourceLocation Loc, StringRef WarningSpec,
143*7330f729Sjoerg ArrayRef<int> Ids) override;
144*7330f729Sjoerg void PragmaWarningPush(SourceLocation Loc, int Level) override;
145*7330f729Sjoerg void PragmaWarningPop(SourceLocation Loc) override;
146*7330f729Sjoerg void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;
147*7330f729Sjoerg void PragmaExecCharsetPop(SourceLocation Loc) override;
148*7330f729Sjoerg void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
149*7330f729Sjoerg void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
150*7330f729Sjoerg
151*7330f729Sjoerg bool HandleFirstTokOnLine(Token &Tok);
152*7330f729Sjoerg
153*7330f729Sjoerg /// Move to the line of the provided source location. This will
154*7330f729Sjoerg /// return true if the output stream required adjustment or if
155*7330f729Sjoerg /// the requested location is on the first line.
MoveToLine(SourceLocation Loc)156*7330f729Sjoerg bool MoveToLine(SourceLocation Loc) {
157*7330f729Sjoerg PresumedLoc PLoc = SM.getPresumedLoc(Loc);
158*7330f729Sjoerg if (PLoc.isInvalid())
159*7330f729Sjoerg return false;
160*7330f729Sjoerg return MoveToLine(PLoc.getLine()) || (PLoc.getLine() == 1);
161*7330f729Sjoerg }
162*7330f729Sjoerg bool MoveToLine(unsigned LineNo);
163*7330f729Sjoerg
AvoidConcat(const Token & PrevPrevTok,const Token & PrevTok,const Token & Tok)164*7330f729Sjoerg bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
165*7330f729Sjoerg const Token &Tok) {
166*7330f729Sjoerg return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
167*7330f729Sjoerg }
168*7330f729Sjoerg void WriteLineInfo(unsigned LineNo, const char *Extra=nullptr,
169*7330f729Sjoerg unsigned ExtraLen=0);
LineMarkersAreDisabled() const170*7330f729Sjoerg bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
171*7330f729Sjoerg void HandleNewlinesInToken(const char *TokStr, unsigned Len);
172*7330f729Sjoerg
173*7330f729Sjoerg /// MacroDefined - This hook is called whenever a macro definition is seen.
174*7330f729Sjoerg void MacroDefined(const Token &MacroNameTok,
175*7330f729Sjoerg const MacroDirective *MD) override;
176*7330f729Sjoerg
177*7330f729Sjoerg /// MacroUndefined - This hook is called whenever a macro #undef is seen.
178*7330f729Sjoerg void MacroUndefined(const Token &MacroNameTok,
179*7330f729Sjoerg const MacroDefinition &MD,
180*7330f729Sjoerg const MacroDirective *Undef) override;
181*7330f729Sjoerg
182*7330f729Sjoerg void BeginModule(const Module *M);
183*7330f729Sjoerg void EndModule(const Module *M);
184*7330f729Sjoerg };
185*7330f729Sjoerg } // end anonymous namespace
186*7330f729Sjoerg
WriteLineInfo(unsigned LineNo,const char * Extra,unsigned ExtraLen)187*7330f729Sjoerg void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
188*7330f729Sjoerg const char *Extra,
189*7330f729Sjoerg unsigned ExtraLen) {
190*7330f729Sjoerg startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
191*7330f729Sjoerg
192*7330f729Sjoerg // Emit #line directives or GNU line markers depending on what mode we're in.
193*7330f729Sjoerg if (UseLineDirectives) {
194*7330f729Sjoerg OS << "#line" << ' ' << LineNo << ' ' << '"';
195*7330f729Sjoerg OS.write_escaped(CurFilename);
196*7330f729Sjoerg OS << '"';
197*7330f729Sjoerg } else {
198*7330f729Sjoerg OS << '#' << ' ' << LineNo << ' ' << '"';
199*7330f729Sjoerg OS.write_escaped(CurFilename);
200*7330f729Sjoerg OS << '"';
201*7330f729Sjoerg
202*7330f729Sjoerg if (ExtraLen)
203*7330f729Sjoerg OS.write(Extra, ExtraLen);
204*7330f729Sjoerg
205*7330f729Sjoerg if (FileType == SrcMgr::C_System)
206*7330f729Sjoerg OS.write(" 3", 2);
207*7330f729Sjoerg else if (FileType == SrcMgr::C_ExternCSystem)
208*7330f729Sjoerg OS.write(" 3 4", 4);
209*7330f729Sjoerg }
210*7330f729Sjoerg OS << '\n';
211*7330f729Sjoerg }
212*7330f729Sjoerg
213*7330f729Sjoerg /// MoveToLine - Move the output to the source line specified by the location
214*7330f729Sjoerg /// object. We can do this by emitting some number of \n's, or be emitting a
215*7330f729Sjoerg /// #line directive. This returns false if already at the specified line, true
216*7330f729Sjoerg /// if some newlines were emitted.
MoveToLine(unsigned LineNo)217*7330f729Sjoerg bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
218*7330f729Sjoerg // If this line is "close enough" to the original line, just print newlines,
219*7330f729Sjoerg // otherwise print a #line directive.
220*7330f729Sjoerg if (LineNo-CurLine <= 8) {
221*7330f729Sjoerg if (LineNo-CurLine == 1)
222*7330f729Sjoerg OS << '\n';
223*7330f729Sjoerg else if (LineNo == CurLine)
224*7330f729Sjoerg return false; // Spelling line moved, but expansion line didn't.
225*7330f729Sjoerg else {
226*7330f729Sjoerg const char *NewLines = "\n\n\n\n\n\n\n\n";
227*7330f729Sjoerg OS.write(NewLines, LineNo-CurLine);
228*7330f729Sjoerg }
229*7330f729Sjoerg } else if (!DisableLineMarkers) {
230*7330f729Sjoerg // Emit a #line or line marker.
231*7330f729Sjoerg WriteLineInfo(LineNo, nullptr, 0);
232*7330f729Sjoerg } else {
233*7330f729Sjoerg // Okay, we're in -P mode, which turns off line markers. However, we still
234*7330f729Sjoerg // need to emit a newline between tokens on different lines.
235*7330f729Sjoerg startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
236*7330f729Sjoerg }
237*7330f729Sjoerg
238*7330f729Sjoerg CurLine = LineNo;
239*7330f729Sjoerg return true;
240*7330f729Sjoerg }
241*7330f729Sjoerg
242*7330f729Sjoerg bool
startNewLineIfNeeded(bool ShouldUpdateCurrentLine)243*7330f729Sjoerg PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
244*7330f729Sjoerg if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
245*7330f729Sjoerg OS << '\n';
246*7330f729Sjoerg EmittedTokensOnThisLine = false;
247*7330f729Sjoerg EmittedDirectiveOnThisLine = false;
248*7330f729Sjoerg if (ShouldUpdateCurrentLine)
249*7330f729Sjoerg ++CurLine;
250*7330f729Sjoerg return true;
251*7330f729Sjoerg }
252*7330f729Sjoerg
253*7330f729Sjoerg return false;
254*7330f729Sjoerg }
255*7330f729Sjoerg
256*7330f729Sjoerg /// FileChanged - Whenever the preprocessor enters or exits a #include file
257*7330f729Sjoerg /// it invokes this handler. Update our conception of the current source
258*7330f729Sjoerg /// position.
FileChanged(SourceLocation Loc,FileChangeReason Reason,SrcMgr::CharacteristicKind NewFileType,FileID PrevFID)259*7330f729Sjoerg void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
260*7330f729Sjoerg FileChangeReason Reason,
261*7330f729Sjoerg SrcMgr::CharacteristicKind NewFileType,
262*7330f729Sjoerg FileID PrevFID) {
263*7330f729Sjoerg // Unless we are exiting a #include, make sure to skip ahead to the line the
264*7330f729Sjoerg // #include directive was at.
265*7330f729Sjoerg SourceManager &SourceMgr = SM;
266*7330f729Sjoerg
267*7330f729Sjoerg PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
268*7330f729Sjoerg if (UserLoc.isInvalid())
269*7330f729Sjoerg return;
270*7330f729Sjoerg
271*7330f729Sjoerg unsigned NewLine = UserLoc.getLine();
272*7330f729Sjoerg
273*7330f729Sjoerg if (Reason == PPCallbacks::EnterFile) {
274*7330f729Sjoerg SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
275*7330f729Sjoerg if (IncludeLoc.isValid())
276*7330f729Sjoerg MoveToLine(IncludeLoc);
277*7330f729Sjoerg } else if (Reason == PPCallbacks::SystemHeaderPragma) {
278*7330f729Sjoerg // GCC emits the # directive for this directive on the line AFTER the
279*7330f729Sjoerg // directive and emits a bunch of spaces that aren't needed. This is because
280*7330f729Sjoerg // otherwise we will emit a line marker for THIS line, which requires an
281*7330f729Sjoerg // extra blank line after the directive to avoid making all following lines
282*7330f729Sjoerg // off by one. We can do better by simply incrementing NewLine here.
283*7330f729Sjoerg NewLine += 1;
284*7330f729Sjoerg }
285*7330f729Sjoerg
286*7330f729Sjoerg CurLine = NewLine;
287*7330f729Sjoerg
288*7330f729Sjoerg CurFilename.clear();
289*7330f729Sjoerg CurFilename += UserLoc.getFilename();
290*7330f729Sjoerg FileType = NewFileType;
291*7330f729Sjoerg
292*7330f729Sjoerg if (DisableLineMarkers) {
293*7330f729Sjoerg startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
294*7330f729Sjoerg return;
295*7330f729Sjoerg }
296*7330f729Sjoerg
297*7330f729Sjoerg if (!Initialized) {
298*7330f729Sjoerg WriteLineInfo(CurLine);
299*7330f729Sjoerg Initialized = true;
300*7330f729Sjoerg }
301*7330f729Sjoerg
302*7330f729Sjoerg // Do not emit an enter marker for the main file (which we expect is the first
303*7330f729Sjoerg // entered file). This matches gcc, and improves compatibility with some tools
304*7330f729Sjoerg // which track the # line markers as a way to determine when the preprocessed
305*7330f729Sjoerg // output is in the context of the main file.
306*7330f729Sjoerg if (Reason == PPCallbacks::EnterFile && !IsFirstFileEntered) {
307*7330f729Sjoerg IsFirstFileEntered = true;
308*7330f729Sjoerg return;
309*7330f729Sjoerg }
310*7330f729Sjoerg
311*7330f729Sjoerg switch (Reason) {
312*7330f729Sjoerg case PPCallbacks::EnterFile:
313*7330f729Sjoerg WriteLineInfo(CurLine, " 1", 2);
314*7330f729Sjoerg break;
315*7330f729Sjoerg case PPCallbacks::ExitFile:
316*7330f729Sjoerg WriteLineInfo(CurLine, " 2", 2);
317*7330f729Sjoerg break;
318*7330f729Sjoerg case PPCallbacks::SystemHeaderPragma:
319*7330f729Sjoerg case PPCallbacks::RenameFile:
320*7330f729Sjoerg WriteLineInfo(CurLine);
321*7330f729Sjoerg break;
322*7330f729Sjoerg }
323*7330f729Sjoerg }
324*7330f729Sjoerg
InclusionDirective(SourceLocation HashLoc,const Token & IncludeTok,StringRef FileName,bool IsAngled,CharSourceRange FilenameRange,const FileEntry * File,StringRef SearchPath,StringRef RelativePath,const Module * Imported,SrcMgr::CharacteristicKind FileType)325*7330f729Sjoerg void PrintPPOutputPPCallbacks::InclusionDirective(
326*7330f729Sjoerg SourceLocation HashLoc,
327*7330f729Sjoerg const Token &IncludeTok,
328*7330f729Sjoerg StringRef FileName,
329*7330f729Sjoerg bool IsAngled,
330*7330f729Sjoerg CharSourceRange FilenameRange,
331*7330f729Sjoerg const FileEntry *File,
332*7330f729Sjoerg StringRef SearchPath,
333*7330f729Sjoerg StringRef RelativePath,
334*7330f729Sjoerg const Module *Imported,
335*7330f729Sjoerg SrcMgr::CharacteristicKind FileType) {
336*7330f729Sjoerg // In -dI mode, dump #include directives prior to dumping their content or
337*7330f729Sjoerg // interpretation.
338*7330f729Sjoerg if (DumpIncludeDirectives) {
339*7330f729Sjoerg startNewLineIfNeeded();
340*7330f729Sjoerg MoveToLine(HashLoc);
341*7330f729Sjoerg const std::string TokenText = PP.getSpelling(IncludeTok);
342*7330f729Sjoerg assert(!TokenText.empty());
343*7330f729Sjoerg OS << "#" << TokenText << " "
344*7330f729Sjoerg << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
345*7330f729Sjoerg << " /* clang -E -dI */";
346*7330f729Sjoerg setEmittedDirectiveOnThisLine();
347*7330f729Sjoerg startNewLineIfNeeded();
348*7330f729Sjoerg }
349*7330f729Sjoerg
350*7330f729Sjoerg // When preprocessing, turn implicit imports into module import pragmas.
351*7330f729Sjoerg if (Imported) {
352*7330f729Sjoerg switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
353*7330f729Sjoerg case tok::pp_include:
354*7330f729Sjoerg case tok::pp_import:
355*7330f729Sjoerg case tok::pp_include_next:
356*7330f729Sjoerg startNewLineIfNeeded();
357*7330f729Sjoerg MoveToLine(HashLoc);
358*7330f729Sjoerg OS << "#pragma clang module import " << Imported->getFullModuleName(true)
359*7330f729Sjoerg << " /* clang -E: implicit import for "
360*7330f729Sjoerg << "#" << PP.getSpelling(IncludeTok) << " "
361*7330f729Sjoerg << (IsAngled ? '<' : '"') << FileName << (IsAngled ? '>' : '"')
362*7330f729Sjoerg << " */";
363*7330f729Sjoerg // Since we want a newline after the pragma, but not a #<line>, start a
364*7330f729Sjoerg // new line immediately.
365*7330f729Sjoerg EmittedTokensOnThisLine = true;
366*7330f729Sjoerg startNewLineIfNeeded();
367*7330f729Sjoerg break;
368*7330f729Sjoerg
369*7330f729Sjoerg case tok::pp___include_macros:
370*7330f729Sjoerg // #__include_macros has no effect on a user of a preprocessed source
371*7330f729Sjoerg // file; the only effect is on preprocessing.
372*7330f729Sjoerg //
373*7330f729Sjoerg // FIXME: That's not *quite* true: it causes the module in question to
374*7330f729Sjoerg // be loaded, which can affect downstream diagnostics.
375*7330f729Sjoerg break;
376*7330f729Sjoerg
377*7330f729Sjoerg default:
378*7330f729Sjoerg llvm_unreachable("unknown include directive kind");
379*7330f729Sjoerg break;
380*7330f729Sjoerg }
381*7330f729Sjoerg }
382*7330f729Sjoerg }
383*7330f729Sjoerg
384*7330f729Sjoerg /// Handle entering the scope of a module during a module compilation.
BeginModule(const Module * M)385*7330f729Sjoerg void PrintPPOutputPPCallbacks::BeginModule(const Module *M) {
386*7330f729Sjoerg startNewLineIfNeeded();
387*7330f729Sjoerg OS << "#pragma clang module begin " << M->getFullModuleName(true);
388*7330f729Sjoerg setEmittedDirectiveOnThisLine();
389*7330f729Sjoerg }
390*7330f729Sjoerg
391*7330f729Sjoerg /// Handle leaving the scope of a module during a module compilation.
EndModule(const Module * M)392*7330f729Sjoerg void PrintPPOutputPPCallbacks::EndModule(const Module *M) {
393*7330f729Sjoerg startNewLineIfNeeded();
394*7330f729Sjoerg OS << "#pragma clang module end /*" << M->getFullModuleName(true) << "*/";
395*7330f729Sjoerg setEmittedDirectiveOnThisLine();
396*7330f729Sjoerg }
397*7330f729Sjoerg
398*7330f729Sjoerg /// Ident - Handle #ident directives when read by the preprocessor.
399*7330f729Sjoerg ///
Ident(SourceLocation Loc,StringRef S)400*7330f729Sjoerg void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, StringRef S) {
401*7330f729Sjoerg MoveToLine(Loc);
402*7330f729Sjoerg
403*7330f729Sjoerg OS.write("#ident ", strlen("#ident "));
404*7330f729Sjoerg OS.write(S.begin(), S.size());
405*7330f729Sjoerg EmittedTokensOnThisLine = true;
406*7330f729Sjoerg }
407*7330f729Sjoerg
408*7330f729Sjoerg /// MacroDefined - This hook is called whenever a macro definition is seen.
MacroDefined(const Token & MacroNameTok,const MacroDirective * MD)409*7330f729Sjoerg void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
410*7330f729Sjoerg const MacroDirective *MD) {
411*7330f729Sjoerg const MacroInfo *MI = MD->getMacroInfo();
412*7330f729Sjoerg // Only print out macro definitions in -dD mode.
413*7330f729Sjoerg if (!DumpDefines ||
414*7330f729Sjoerg // Ignore __FILE__ etc.
415*7330f729Sjoerg MI->isBuiltinMacro()) return;
416*7330f729Sjoerg
417*7330f729Sjoerg MoveToLine(MI->getDefinitionLoc());
418*7330f729Sjoerg PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
419*7330f729Sjoerg setEmittedDirectiveOnThisLine();
420*7330f729Sjoerg }
421*7330f729Sjoerg
MacroUndefined(const Token & MacroNameTok,const MacroDefinition & MD,const MacroDirective * Undef)422*7330f729Sjoerg void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
423*7330f729Sjoerg const MacroDefinition &MD,
424*7330f729Sjoerg const MacroDirective *Undef) {
425*7330f729Sjoerg // Only print out macro definitions in -dD mode.
426*7330f729Sjoerg if (!DumpDefines) return;
427*7330f729Sjoerg
428*7330f729Sjoerg MoveToLine(MacroNameTok.getLocation());
429*7330f729Sjoerg OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
430*7330f729Sjoerg setEmittedDirectiveOnThisLine();
431*7330f729Sjoerg }
432*7330f729Sjoerg
outputPrintable(raw_ostream & OS,StringRef Str)433*7330f729Sjoerg static void outputPrintable(raw_ostream &OS, StringRef Str) {
434*7330f729Sjoerg for (unsigned char Char : Str) {
435*7330f729Sjoerg if (isPrintable(Char) && Char != '\\' && Char != '"')
436*7330f729Sjoerg OS << (char)Char;
437*7330f729Sjoerg else // Output anything hard as an octal escape.
438*7330f729Sjoerg OS << '\\'
439*7330f729Sjoerg << (char)('0' + ((Char >> 6) & 7))
440*7330f729Sjoerg << (char)('0' + ((Char >> 3) & 7))
441*7330f729Sjoerg << (char)('0' + ((Char >> 0) & 7));
442*7330f729Sjoerg }
443*7330f729Sjoerg }
444*7330f729Sjoerg
PragmaMessage(SourceLocation Loc,StringRef Namespace,PragmaMessageKind Kind,StringRef Str)445*7330f729Sjoerg void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
446*7330f729Sjoerg StringRef Namespace,
447*7330f729Sjoerg PragmaMessageKind Kind,
448*7330f729Sjoerg StringRef Str) {
449*7330f729Sjoerg startNewLineIfNeeded();
450*7330f729Sjoerg MoveToLine(Loc);
451*7330f729Sjoerg OS << "#pragma ";
452*7330f729Sjoerg if (!Namespace.empty())
453*7330f729Sjoerg OS << Namespace << ' ';
454*7330f729Sjoerg switch (Kind) {
455*7330f729Sjoerg case PMK_Message:
456*7330f729Sjoerg OS << "message(\"";
457*7330f729Sjoerg break;
458*7330f729Sjoerg case PMK_Warning:
459*7330f729Sjoerg OS << "warning \"";
460*7330f729Sjoerg break;
461*7330f729Sjoerg case PMK_Error:
462*7330f729Sjoerg OS << "error \"";
463*7330f729Sjoerg break;
464*7330f729Sjoerg }
465*7330f729Sjoerg
466*7330f729Sjoerg outputPrintable(OS, Str);
467*7330f729Sjoerg OS << '"';
468*7330f729Sjoerg if (Kind == PMK_Message)
469*7330f729Sjoerg OS << ')';
470*7330f729Sjoerg setEmittedDirectiveOnThisLine();
471*7330f729Sjoerg }
472*7330f729Sjoerg
PragmaDebug(SourceLocation Loc,StringRef DebugType)473*7330f729Sjoerg void PrintPPOutputPPCallbacks::PragmaDebug(SourceLocation Loc,
474*7330f729Sjoerg StringRef DebugType) {
475*7330f729Sjoerg startNewLineIfNeeded();
476*7330f729Sjoerg MoveToLine(Loc);
477*7330f729Sjoerg
478*7330f729Sjoerg OS << "#pragma clang __debug ";
479*7330f729Sjoerg OS << DebugType;
480*7330f729Sjoerg
481*7330f729Sjoerg setEmittedDirectiveOnThisLine();
482*7330f729Sjoerg }
483*7330f729Sjoerg
484*7330f729Sjoerg void PrintPPOutputPPCallbacks::
PragmaDiagnosticPush(SourceLocation Loc,StringRef Namespace)485*7330f729Sjoerg PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
486*7330f729Sjoerg startNewLineIfNeeded();
487*7330f729Sjoerg MoveToLine(Loc);
488*7330f729Sjoerg OS << "#pragma " << Namespace << " diagnostic push";
489*7330f729Sjoerg setEmittedDirectiveOnThisLine();
490*7330f729Sjoerg }
491*7330f729Sjoerg
492*7330f729Sjoerg void PrintPPOutputPPCallbacks::
PragmaDiagnosticPop(SourceLocation Loc,StringRef Namespace)493*7330f729Sjoerg PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
494*7330f729Sjoerg startNewLineIfNeeded();
495*7330f729Sjoerg MoveToLine(Loc);
496*7330f729Sjoerg OS << "#pragma " << Namespace << " diagnostic pop";
497*7330f729Sjoerg setEmittedDirectiveOnThisLine();
498*7330f729Sjoerg }
499*7330f729Sjoerg
PragmaDiagnostic(SourceLocation Loc,StringRef Namespace,diag::Severity Map,StringRef Str)500*7330f729Sjoerg void PrintPPOutputPPCallbacks::PragmaDiagnostic(SourceLocation Loc,
501*7330f729Sjoerg StringRef Namespace,
502*7330f729Sjoerg diag::Severity Map,
503*7330f729Sjoerg StringRef Str) {
504*7330f729Sjoerg startNewLineIfNeeded();
505*7330f729Sjoerg MoveToLine(Loc);
506*7330f729Sjoerg OS << "#pragma " << Namespace << " diagnostic ";
507*7330f729Sjoerg switch (Map) {
508*7330f729Sjoerg case diag::Severity::Remark:
509*7330f729Sjoerg OS << "remark";
510*7330f729Sjoerg break;
511*7330f729Sjoerg case diag::Severity::Warning:
512*7330f729Sjoerg OS << "warning";
513*7330f729Sjoerg break;
514*7330f729Sjoerg case diag::Severity::Error:
515*7330f729Sjoerg OS << "error";
516*7330f729Sjoerg break;
517*7330f729Sjoerg case diag::Severity::Ignored:
518*7330f729Sjoerg OS << "ignored";
519*7330f729Sjoerg break;
520*7330f729Sjoerg case diag::Severity::Fatal:
521*7330f729Sjoerg OS << "fatal";
522*7330f729Sjoerg break;
523*7330f729Sjoerg }
524*7330f729Sjoerg OS << " \"" << Str << '"';
525*7330f729Sjoerg setEmittedDirectiveOnThisLine();
526*7330f729Sjoerg }
527*7330f729Sjoerg
PragmaWarning(SourceLocation Loc,StringRef WarningSpec,ArrayRef<int> Ids)528*7330f729Sjoerg void PrintPPOutputPPCallbacks::PragmaWarning(SourceLocation Loc,
529*7330f729Sjoerg StringRef WarningSpec,
530*7330f729Sjoerg ArrayRef<int> Ids) {
531*7330f729Sjoerg startNewLineIfNeeded();
532*7330f729Sjoerg MoveToLine(Loc);
533*7330f729Sjoerg OS << "#pragma warning(" << WarningSpec << ':';
534*7330f729Sjoerg for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
535*7330f729Sjoerg OS << ' ' << *I;
536*7330f729Sjoerg OS << ')';
537*7330f729Sjoerg setEmittedDirectiveOnThisLine();
538*7330f729Sjoerg }
539*7330f729Sjoerg
PragmaWarningPush(SourceLocation Loc,int Level)540*7330f729Sjoerg void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
541*7330f729Sjoerg int Level) {
542*7330f729Sjoerg startNewLineIfNeeded();
543*7330f729Sjoerg MoveToLine(Loc);
544*7330f729Sjoerg OS << "#pragma warning(push";
545*7330f729Sjoerg if (Level >= 0)
546*7330f729Sjoerg OS << ", " << Level;
547*7330f729Sjoerg OS << ')';
548*7330f729Sjoerg setEmittedDirectiveOnThisLine();
549*7330f729Sjoerg }
550*7330f729Sjoerg
PragmaWarningPop(SourceLocation Loc)551*7330f729Sjoerg void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
552*7330f729Sjoerg startNewLineIfNeeded();
553*7330f729Sjoerg MoveToLine(Loc);
554*7330f729Sjoerg OS << "#pragma warning(pop)";
555*7330f729Sjoerg setEmittedDirectiveOnThisLine();
556*7330f729Sjoerg }
557*7330f729Sjoerg
PragmaExecCharsetPush(SourceLocation Loc,StringRef Str)558*7330f729Sjoerg void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
559*7330f729Sjoerg StringRef Str) {
560*7330f729Sjoerg startNewLineIfNeeded();
561*7330f729Sjoerg MoveToLine(Loc);
562*7330f729Sjoerg OS << "#pragma character_execution_set(push";
563*7330f729Sjoerg if (!Str.empty())
564*7330f729Sjoerg OS << ", " << Str;
565*7330f729Sjoerg OS << ')';
566*7330f729Sjoerg setEmittedDirectiveOnThisLine();
567*7330f729Sjoerg }
568*7330f729Sjoerg
PragmaExecCharsetPop(SourceLocation Loc)569*7330f729Sjoerg void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
570*7330f729Sjoerg startNewLineIfNeeded();
571*7330f729Sjoerg MoveToLine(Loc);
572*7330f729Sjoerg OS << "#pragma character_execution_set(pop)";
573*7330f729Sjoerg setEmittedDirectiveOnThisLine();
574*7330f729Sjoerg }
575*7330f729Sjoerg
576*7330f729Sjoerg void PrintPPOutputPPCallbacks::
PragmaAssumeNonNullBegin(SourceLocation Loc)577*7330f729Sjoerg PragmaAssumeNonNullBegin(SourceLocation Loc) {
578*7330f729Sjoerg startNewLineIfNeeded();
579*7330f729Sjoerg MoveToLine(Loc);
580*7330f729Sjoerg OS << "#pragma clang assume_nonnull begin";
581*7330f729Sjoerg setEmittedDirectiveOnThisLine();
582*7330f729Sjoerg }
583*7330f729Sjoerg
584*7330f729Sjoerg void PrintPPOutputPPCallbacks::
PragmaAssumeNonNullEnd(SourceLocation Loc)585*7330f729Sjoerg PragmaAssumeNonNullEnd(SourceLocation Loc) {
586*7330f729Sjoerg startNewLineIfNeeded();
587*7330f729Sjoerg MoveToLine(Loc);
588*7330f729Sjoerg OS << "#pragma clang assume_nonnull end";
589*7330f729Sjoerg setEmittedDirectiveOnThisLine();
590*7330f729Sjoerg }
591*7330f729Sjoerg
592*7330f729Sjoerg /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
593*7330f729Sjoerg /// is called for the first token on each new line. If this really is the start
594*7330f729Sjoerg /// of a new logical line, handle it and return true, otherwise return false.
595*7330f729Sjoerg /// This may not be the start of a logical line because the "start of line"
596*7330f729Sjoerg /// marker is set for spelling lines, not expansion ones.
HandleFirstTokOnLine(Token & Tok)597*7330f729Sjoerg bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
598*7330f729Sjoerg // Figure out what line we went to and insert the appropriate number of
599*7330f729Sjoerg // newline characters.
600*7330f729Sjoerg if (!MoveToLine(Tok.getLocation()))
601*7330f729Sjoerg return false;
602*7330f729Sjoerg
603*7330f729Sjoerg // Print out space characters so that the first token on a line is
604*7330f729Sjoerg // indented for easy reading.
605*7330f729Sjoerg unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
606*7330f729Sjoerg
607*7330f729Sjoerg // The first token on a line can have a column number of 1, yet still expect
608*7330f729Sjoerg // leading white space, if a macro expansion in column 1 starts with an empty
609*7330f729Sjoerg // macro argument, or an empty nested macro expansion. In this case, move the
610*7330f729Sjoerg // token to column 2.
611*7330f729Sjoerg if (ColNo == 1 && Tok.hasLeadingSpace())
612*7330f729Sjoerg ColNo = 2;
613*7330f729Sjoerg
614*7330f729Sjoerg // This hack prevents stuff like:
615*7330f729Sjoerg // #define HASH #
616*7330f729Sjoerg // HASH define foo bar
617*7330f729Sjoerg // From having the # character end up at column 1, which makes it so it
618*7330f729Sjoerg // is not handled as a #define next time through the preprocessor if in
619*7330f729Sjoerg // -fpreprocessed mode.
620*7330f729Sjoerg if (ColNo <= 1 && Tok.is(tok::hash))
621*7330f729Sjoerg OS << ' ';
622*7330f729Sjoerg
623*7330f729Sjoerg // Otherwise, indent the appropriate number of spaces.
624*7330f729Sjoerg for (; ColNo > 1; --ColNo)
625*7330f729Sjoerg OS << ' ';
626*7330f729Sjoerg
627*7330f729Sjoerg return true;
628*7330f729Sjoerg }
629*7330f729Sjoerg
HandleNewlinesInToken(const char * TokStr,unsigned Len)630*7330f729Sjoerg void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
631*7330f729Sjoerg unsigned Len) {
632*7330f729Sjoerg unsigned NumNewlines = 0;
633*7330f729Sjoerg for (; Len; --Len, ++TokStr) {
634*7330f729Sjoerg if (*TokStr != '\n' &&
635*7330f729Sjoerg *TokStr != '\r')
636*7330f729Sjoerg continue;
637*7330f729Sjoerg
638*7330f729Sjoerg ++NumNewlines;
639*7330f729Sjoerg
640*7330f729Sjoerg // If we have \n\r or \r\n, skip both and count as one line.
641*7330f729Sjoerg if (Len != 1 &&
642*7330f729Sjoerg (TokStr[1] == '\n' || TokStr[1] == '\r') &&
643*7330f729Sjoerg TokStr[0] != TokStr[1]) {
644*7330f729Sjoerg ++TokStr;
645*7330f729Sjoerg --Len;
646*7330f729Sjoerg }
647*7330f729Sjoerg }
648*7330f729Sjoerg
649*7330f729Sjoerg if (NumNewlines == 0) return;
650*7330f729Sjoerg
651*7330f729Sjoerg CurLine += NumNewlines;
652*7330f729Sjoerg }
653*7330f729Sjoerg
654*7330f729Sjoerg
655*7330f729Sjoerg namespace {
656*7330f729Sjoerg struct UnknownPragmaHandler : public PragmaHandler {
657*7330f729Sjoerg const char *Prefix;
658*7330f729Sjoerg PrintPPOutputPPCallbacks *Callbacks;
659*7330f729Sjoerg
660*7330f729Sjoerg // Set to true if tokens should be expanded
661*7330f729Sjoerg bool ShouldExpandTokens;
662*7330f729Sjoerg
UnknownPragmaHandler__anonc99bc9c10211::UnknownPragmaHandler663*7330f729Sjoerg UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
664*7330f729Sjoerg bool RequireTokenExpansion)
665*7330f729Sjoerg : Prefix(prefix), Callbacks(callbacks),
666*7330f729Sjoerg ShouldExpandTokens(RequireTokenExpansion) {}
HandlePragma__anonc99bc9c10211::UnknownPragmaHandler667*7330f729Sjoerg void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
668*7330f729Sjoerg Token &PragmaTok) override {
669*7330f729Sjoerg // Figure out what line we went to and insert the appropriate number of
670*7330f729Sjoerg // newline characters.
671*7330f729Sjoerg Callbacks->startNewLineIfNeeded();
672*7330f729Sjoerg Callbacks->MoveToLine(PragmaTok.getLocation());
673*7330f729Sjoerg Callbacks->OS.write(Prefix, strlen(Prefix));
674*7330f729Sjoerg
675*7330f729Sjoerg if (ShouldExpandTokens) {
676*7330f729Sjoerg // The first token does not have expanded macros. Expand them, if
677*7330f729Sjoerg // required.
678*7330f729Sjoerg auto Toks = std::make_unique<Token[]>(1);
679*7330f729Sjoerg Toks[0] = PragmaTok;
680*7330f729Sjoerg PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
681*7330f729Sjoerg /*DisableMacroExpansion=*/false,
682*7330f729Sjoerg /*IsReinject=*/false);
683*7330f729Sjoerg PP.Lex(PragmaTok);
684*7330f729Sjoerg }
685*7330f729Sjoerg Token PrevToken;
686*7330f729Sjoerg Token PrevPrevToken;
687*7330f729Sjoerg PrevToken.startToken();
688*7330f729Sjoerg PrevPrevToken.startToken();
689*7330f729Sjoerg
690*7330f729Sjoerg // Read and print all of the pragma tokens.
691*7330f729Sjoerg while (PragmaTok.isNot(tok::eod)) {
692*7330f729Sjoerg if (PragmaTok.hasLeadingSpace() ||
693*7330f729Sjoerg Callbacks->AvoidConcat(PrevPrevToken, PrevToken, PragmaTok))
694*7330f729Sjoerg Callbacks->OS << ' ';
695*7330f729Sjoerg std::string TokSpell = PP.getSpelling(PragmaTok);
696*7330f729Sjoerg Callbacks->OS.write(&TokSpell[0], TokSpell.size());
697*7330f729Sjoerg
698*7330f729Sjoerg PrevPrevToken = PrevToken;
699*7330f729Sjoerg PrevToken = PragmaTok;
700*7330f729Sjoerg
701*7330f729Sjoerg if (ShouldExpandTokens)
702*7330f729Sjoerg PP.Lex(PragmaTok);
703*7330f729Sjoerg else
704*7330f729Sjoerg PP.LexUnexpandedToken(PragmaTok);
705*7330f729Sjoerg }
706*7330f729Sjoerg Callbacks->setEmittedDirectiveOnThisLine();
707*7330f729Sjoerg }
708*7330f729Sjoerg };
709*7330f729Sjoerg } // end anonymous namespace
710*7330f729Sjoerg
711*7330f729Sjoerg
PrintPreprocessedTokens(Preprocessor & PP,Token & Tok,PrintPPOutputPPCallbacks * Callbacks,raw_ostream & OS)712*7330f729Sjoerg static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
713*7330f729Sjoerg PrintPPOutputPPCallbacks *Callbacks,
714*7330f729Sjoerg raw_ostream &OS) {
715*7330f729Sjoerg bool DropComments = PP.getLangOpts().TraditionalCPP &&
716*7330f729Sjoerg !PP.getCommentRetentionState();
717*7330f729Sjoerg
718*7330f729Sjoerg char Buffer[256];
719*7330f729Sjoerg Token PrevPrevTok, PrevTok;
720*7330f729Sjoerg PrevPrevTok.startToken();
721*7330f729Sjoerg PrevTok.startToken();
722*7330f729Sjoerg while (1) {
723*7330f729Sjoerg if (Callbacks->hasEmittedDirectiveOnThisLine()) {
724*7330f729Sjoerg Callbacks->startNewLineIfNeeded();
725*7330f729Sjoerg Callbacks->MoveToLine(Tok.getLocation());
726*7330f729Sjoerg }
727*7330f729Sjoerg
728*7330f729Sjoerg // If this token is at the start of a line, emit newlines if needed.
729*7330f729Sjoerg if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
730*7330f729Sjoerg // done.
731*7330f729Sjoerg } else if (Tok.hasLeadingSpace() ||
732*7330f729Sjoerg // If we haven't emitted a token on this line yet, PrevTok isn't
733*7330f729Sjoerg // useful to look at and no concatenation could happen anyway.
734*7330f729Sjoerg (Callbacks->hasEmittedTokensOnThisLine() &&
735*7330f729Sjoerg // Don't print "-" next to "-", it would form "--".
736*7330f729Sjoerg Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
737*7330f729Sjoerg OS << ' ';
738*7330f729Sjoerg }
739*7330f729Sjoerg
740*7330f729Sjoerg if (DropComments && Tok.is(tok::comment)) {
741*7330f729Sjoerg // Skip comments. Normally the preprocessor does not generate
742*7330f729Sjoerg // tok::comment nodes at all when not keeping comments, but under
743*7330f729Sjoerg // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
744*7330f729Sjoerg SourceLocation StartLoc = Tok.getLocation();
745*7330f729Sjoerg Callbacks->MoveToLine(StartLoc.getLocWithOffset(Tok.getLength()));
746*7330f729Sjoerg } else if (Tok.is(tok::eod)) {
747*7330f729Sjoerg // Don't print end of directive tokens, since they are typically newlines
748*7330f729Sjoerg // that mess up our line tracking. These come from unknown pre-processor
749*7330f729Sjoerg // directives or hash-prefixed comments in standalone assembly files.
750*7330f729Sjoerg PP.Lex(Tok);
751*7330f729Sjoerg continue;
752*7330f729Sjoerg } else if (Tok.is(tok::annot_module_include)) {
753*7330f729Sjoerg // PrintPPOutputPPCallbacks::InclusionDirective handles producing
754*7330f729Sjoerg // appropriate output here. Ignore this token entirely.
755*7330f729Sjoerg PP.Lex(Tok);
756*7330f729Sjoerg continue;
757*7330f729Sjoerg } else if (Tok.is(tok::annot_module_begin)) {
758*7330f729Sjoerg // FIXME: We retrieve this token after the FileChanged callback, and
759*7330f729Sjoerg // retrieve the module_end token before the FileChanged callback, so
760*7330f729Sjoerg // we render this within the file and render the module end outside the
761*7330f729Sjoerg // file, but this is backwards from the token locations: the module_begin
762*7330f729Sjoerg // token is at the include location (outside the file) and the module_end
763*7330f729Sjoerg // token is at the EOF location (within the file).
764*7330f729Sjoerg Callbacks->BeginModule(
765*7330f729Sjoerg reinterpret_cast<Module *>(Tok.getAnnotationValue()));
766*7330f729Sjoerg PP.Lex(Tok);
767*7330f729Sjoerg continue;
768*7330f729Sjoerg } else if (Tok.is(tok::annot_module_end)) {
769*7330f729Sjoerg Callbacks->EndModule(
770*7330f729Sjoerg reinterpret_cast<Module *>(Tok.getAnnotationValue()));
771*7330f729Sjoerg PP.Lex(Tok);
772*7330f729Sjoerg continue;
773*7330f729Sjoerg } else if (Tok.is(tok::annot_header_unit)) {
774*7330f729Sjoerg // This is a header-name that has been (effectively) converted into a
775*7330f729Sjoerg // module-name.
776*7330f729Sjoerg // FIXME: The module name could contain non-identifier module name
777*7330f729Sjoerg // components. We don't have a good way to round-trip those.
778*7330f729Sjoerg Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
779*7330f729Sjoerg std::string Name = M->getFullModuleName();
780*7330f729Sjoerg OS.write(Name.data(), Name.size());
781*7330f729Sjoerg Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
782*7330f729Sjoerg } else if (Tok.isAnnotation()) {
783*7330f729Sjoerg // Ignore annotation tokens created by pragmas - the pragmas themselves
784*7330f729Sjoerg // will be reproduced in the preprocessed output.
785*7330f729Sjoerg PP.Lex(Tok);
786*7330f729Sjoerg continue;
787*7330f729Sjoerg } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
788*7330f729Sjoerg OS << II->getName();
789*7330f729Sjoerg } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
790*7330f729Sjoerg Tok.getLiteralData()) {
791*7330f729Sjoerg OS.write(Tok.getLiteralData(), Tok.getLength());
792*7330f729Sjoerg } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
793*7330f729Sjoerg const char *TokPtr = Buffer;
794*7330f729Sjoerg unsigned Len = PP.getSpelling(Tok, TokPtr);
795*7330f729Sjoerg OS.write(TokPtr, Len);
796*7330f729Sjoerg
797*7330f729Sjoerg // Tokens that can contain embedded newlines need to adjust our current
798*7330f729Sjoerg // line number.
799*7330f729Sjoerg if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
800*7330f729Sjoerg Callbacks->HandleNewlinesInToken(TokPtr, Len);
801*7330f729Sjoerg } else {
802*7330f729Sjoerg std::string S = PP.getSpelling(Tok);
803*7330f729Sjoerg OS.write(S.data(), S.size());
804*7330f729Sjoerg
805*7330f729Sjoerg // Tokens that can contain embedded newlines need to adjust our current
806*7330f729Sjoerg // line number.
807*7330f729Sjoerg if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
808*7330f729Sjoerg Callbacks->HandleNewlinesInToken(S.data(), S.size());
809*7330f729Sjoerg }
810*7330f729Sjoerg Callbacks->setEmittedTokensOnThisLine();
811*7330f729Sjoerg
812*7330f729Sjoerg if (Tok.is(tok::eof)) break;
813*7330f729Sjoerg
814*7330f729Sjoerg PrevPrevTok = PrevTok;
815*7330f729Sjoerg PrevTok = Tok;
816*7330f729Sjoerg PP.Lex(Tok);
817*7330f729Sjoerg }
818*7330f729Sjoerg }
819*7330f729Sjoerg
820*7330f729Sjoerg typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
MacroIDCompare(const id_macro_pair * LHS,const id_macro_pair * RHS)821*7330f729Sjoerg static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
822*7330f729Sjoerg return LHS->first->getName().compare(RHS->first->getName());
823*7330f729Sjoerg }
824*7330f729Sjoerg
DoPrintMacros(Preprocessor & PP,raw_ostream * OS)825*7330f729Sjoerg static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
826*7330f729Sjoerg // Ignore unknown pragmas.
827*7330f729Sjoerg PP.IgnorePragmas();
828*7330f729Sjoerg
829*7330f729Sjoerg // -dM mode just scans and ignores all tokens in the files, then dumps out
830*7330f729Sjoerg // the macro table at the end.
831*7330f729Sjoerg PP.EnterMainSourceFile();
832*7330f729Sjoerg
833*7330f729Sjoerg Token Tok;
834*7330f729Sjoerg do PP.Lex(Tok);
835*7330f729Sjoerg while (Tok.isNot(tok::eof));
836*7330f729Sjoerg
837*7330f729Sjoerg SmallVector<id_macro_pair, 128> MacrosByID;
838*7330f729Sjoerg for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
839*7330f729Sjoerg I != E; ++I) {
840*7330f729Sjoerg auto *MD = I->second.getLatest();
841*7330f729Sjoerg if (MD && MD->isDefined())
842*7330f729Sjoerg MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
843*7330f729Sjoerg }
844*7330f729Sjoerg llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
845*7330f729Sjoerg
846*7330f729Sjoerg for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
847*7330f729Sjoerg MacroInfo &MI = *MacrosByID[i].second;
848*7330f729Sjoerg // Ignore computed macros like __LINE__ and friends.
849*7330f729Sjoerg if (MI.isBuiltinMacro()) continue;
850*7330f729Sjoerg
851*7330f729Sjoerg PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
852*7330f729Sjoerg *OS << '\n';
853*7330f729Sjoerg }
854*7330f729Sjoerg }
855*7330f729Sjoerg
856*7330f729Sjoerg /// DoPrintPreprocessedInput - This implements -E mode.
857*7330f729Sjoerg ///
DoPrintPreprocessedInput(Preprocessor & PP,raw_ostream * OS,const PreprocessorOutputOptions & Opts)858*7330f729Sjoerg void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
859*7330f729Sjoerg const PreprocessorOutputOptions &Opts) {
860*7330f729Sjoerg // Show macros with no output is handled specially.
861*7330f729Sjoerg if (!Opts.ShowCPP) {
862*7330f729Sjoerg assert(Opts.ShowMacros && "Not yet implemented!");
863*7330f729Sjoerg DoPrintMacros(PP, OS);
864*7330f729Sjoerg return;
865*7330f729Sjoerg }
866*7330f729Sjoerg
867*7330f729Sjoerg // Inform the preprocessor whether we want it to retain comments or not, due
868*7330f729Sjoerg // to -C or -CC.
869*7330f729Sjoerg PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
870*7330f729Sjoerg
871*7330f729Sjoerg PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
872*7330f729Sjoerg PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
873*7330f729Sjoerg Opts.ShowIncludeDirectives, Opts.UseLineDirectives);
874*7330f729Sjoerg
875*7330f729Sjoerg // Expand macros in pragmas with -fms-extensions. The assumption is that
876*7330f729Sjoerg // the majority of pragmas in such a file will be Microsoft pragmas.
877*7330f729Sjoerg // Remember the handlers we will add so that we can remove them later.
878*7330f729Sjoerg std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
879*7330f729Sjoerg new UnknownPragmaHandler(
880*7330f729Sjoerg "#pragma", Callbacks,
881*7330f729Sjoerg /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
882*7330f729Sjoerg
883*7330f729Sjoerg std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
884*7330f729Sjoerg "#pragma GCC", Callbacks,
885*7330f729Sjoerg /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
886*7330f729Sjoerg
887*7330f729Sjoerg std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
888*7330f729Sjoerg "#pragma clang", Callbacks,
889*7330f729Sjoerg /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
890*7330f729Sjoerg
891*7330f729Sjoerg PP.AddPragmaHandler(MicrosoftExtHandler.get());
892*7330f729Sjoerg PP.AddPragmaHandler("GCC", GCCHandler.get());
893*7330f729Sjoerg PP.AddPragmaHandler("clang", ClangHandler.get());
894*7330f729Sjoerg
895*7330f729Sjoerg // The tokens after pragma omp need to be expanded.
896*7330f729Sjoerg //
897*7330f729Sjoerg // OpenMP [2.1, Directive format]
898*7330f729Sjoerg // Preprocessing tokens following the #pragma omp are subject to macro
899*7330f729Sjoerg // replacement.
900*7330f729Sjoerg std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
901*7330f729Sjoerg new UnknownPragmaHandler("#pragma omp", Callbacks,
902*7330f729Sjoerg /*RequireTokenExpansion=*/true));
903*7330f729Sjoerg PP.AddPragmaHandler("omp", OpenMPHandler.get());
904*7330f729Sjoerg
905*7330f729Sjoerg PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
906*7330f729Sjoerg
907*7330f729Sjoerg // After we have configured the preprocessor, enter the main file.
908*7330f729Sjoerg PP.EnterMainSourceFile();
909*7330f729Sjoerg
910*7330f729Sjoerg // Consume all of the tokens that come from the predefines buffer. Those
911*7330f729Sjoerg // should not be emitted into the output and are guaranteed to be at the
912*7330f729Sjoerg // start.
913*7330f729Sjoerg const SourceManager &SourceMgr = PP.getSourceManager();
914*7330f729Sjoerg Token Tok;
915*7330f729Sjoerg do {
916*7330f729Sjoerg PP.Lex(Tok);
917*7330f729Sjoerg if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
918*7330f729Sjoerg break;
919*7330f729Sjoerg
920*7330f729Sjoerg PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
921*7330f729Sjoerg if (PLoc.isInvalid())
922*7330f729Sjoerg break;
923*7330f729Sjoerg
924*7330f729Sjoerg if (strcmp(PLoc.getFilename(), "<built-in>"))
925*7330f729Sjoerg break;
926*7330f729Sjoerg } while (true);
927*7330f729Sjoerg
928*7330f729Sjoerg // Read all the preprocessed tokens, printing them out to the stream.
929*7330f729Sjoerg PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
930*7330f729Sjoerg *OS << '\n';
931*7330f729Sjoerg
932*7330f729Sjoerg // Remove the handlers we just added to leave the preprocessor in a sane state
933*7330f729Sjoerg // so that it can be reused (for example by a clang::Parser instance).
934*7330f729Sjoerg PP.RemovePragmaHandler(MicrosoftExtHandler.get());
935*7330f729Sjoerg PP.RemovePragmaHandler("GCC", GCCHandler.get());
936*7330f729Sjoerg PP.RemovePragmaHandler("clang", ClangHandler.get());
937*7330f729Sjoerg PP.RemovePragmaHandler("omp", OpenMPHandler.get());
938*7330f729Sjoerg }
939