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