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