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, StringRef 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                                              StringRef WarningSpec,
584                                              ArrayRef<int> Ids) {
585   MoveToLine(Loc, /*RequireStartOfLine=*/true);
586   OS << "#pragma warning(" << WarningSpec << ':';
587   for (ArrayRef<int>::iterator I = Ids.begin(), E = Ids.end(); I != E; ++I)
588     OS << ' ' << *I;
589   OS << ')';
590   setEmittedDirectiveOnThisLine();
591 }
592 
593 void PrintPPOutputPPCallbacks::PragmaWarningPush(SourceLocation Loc,
594                                                  int Level) {
595   MoveToLine(Loc, /*RequireStartOfLine=*/true);
596   OS << "#pragma warning(push";
597   if (Level >= 0)
598     OS << ", " << Level;
599   OS << ')';
600   setEmittedDirectiveOnThisLine();
601 }
602 
603 void PrintPPOutputPPCallbacks::PragmaWarningPop(SourceLocation Loc) {
604   MoveToLine(Loc, /*RequireStartOfLine=*/true);
605   OS << "#pragma warning(pop)";
606   setEmittedDirectiveOnThisLine();
607 }
608 
609 void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
610                                                      StringRef Str) {
611   MoveToLine(Loc, /*RequireStartOfLine=*/true);
612   OS << "#pragma character_execution_set(push";
613   if (!Str.empty())
614     OS << ", " << Str;
615   OS << ')';
616   setEmittedDirectiveOnThisLine();
617 }
618 
619 void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
620   MoveToLine(Loc, /*RequireStartOfLine=*/true);
621   OS << "#pragma character_execution_set(pop)";
622   setEmittedDirectiveOnThisLine();
623 }
624 
625 void PrintPPOutputPPCallbacks::
626 PragmaAssumeNonNullBegin(SourceLocation Loc) {
627   MoveToLine(Loc, /*RequireStartOfLine=*/true);
628   OS << "#pragma clang assume_nonnull begin";
629   setEmittedDirectiveOnThisLine();
630 }
631 
632 void PrintPPOutputPPCallbacks::
633 PragmaAssumeNonNullEnd(SourceLocation Loc) {
634   MoveToLine(Loc, /*RequireStartOfLine=*/true);
635   OS << "#pragma clang assume_nonnull end";
636   setEmittedDirectiveOnThisLine();
637 }
638 
639 void PrintPPOutputPPCallbacks::HandleWhitespaceBeforeTok(const Token &Tok,
640                                                          bool RequireSpace,
641                                                          bool RequireSameLine) {
642   // These tokens are not expanded to anything and don't need whitespace before
643   // them.
644   if (Tok.is(tok::eof) ||
645       (Tok.isAnnotation() && !Tok.is(tok::annot_header_unit) &&
646        !Tok.is(tok::annot_module_begin) && !Tok.is(tok::annot_module_end)))
647     return;
648 
649   // EmittedDirectiveOnThisLine takes priority over RequireSameLine.
650   if ((!RequireSameLine || EmittedDirectiveOnThisLine) &&
651       MoveToLine(Tok, /*RequireStartOfLine=*/EmittedDirectiveOnThisLine)) {
652     if (MinimizeWhitespace) {
653       // Avoid interpreting hash as a directive under -fpreprocessed.
654       if (Tok.is(tok::hash))
655         OS << ' ';
656     } else {
657       // Print out space characters so that the first token on a line is
658       // indented for easy reading.
659       unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
660 
661       // The first token on a line can have a column number of 1, yet still
662       // expect leading white space, if a macro expansion in column 1 starts
663       // with an empty macro argument, or an empty nested macro expansion. In
664       // this case, move the token to column 2.
665       if (ColNo == 1 && Tok.hasLeadingSpace())
666         ColNo = 2;
667 
668       // This hack prevents stuff like:
669       // #define HASH #
670       // HASH define foo bar
671       // From having the # character end up at column 1, which makes it so it
672       // is not handled as a #define next time through the preprocessor if in
673       // -fpreprocessed mode.
674       if (ColNo <= 1 && Tok.is(tok::hash))
675         OS << ' ';
676 
677       // Otherwise, indent the appropriate number of spaces.
678       for (; ColNo > 1; --ColNo)
679         OS << ' ';
680     }
681   } else {
682     // Insert whitespace between the previous and next token if either
683     // - The caller requires it
684     // - The input had whitespace between them and we are not in
685     //   whitespace-minimization mode
686     // - The whitespace is necessary to keep the tokens apart and there is not
687     //   already a newline between them
688     if (RequireSpace || (!MinimizeWhitespace && Tok.hasLeadingSpace()) ||
689         ((EmittedTokensOnThisLine || EmittedTokensOnThisLine) &&
690          AvoidConcat(PrevPrevTok, PrevTok, Tok)))
691       OS << ' ';
692   }
693 
694   PrevPrevTok = PrevTok;
695   PrevTok = Tok;
696 }
697 
698 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
699                                                      unsigned Len) {
700   unsigned NumNewlines = 0;
701   for (; Len; --Len, ++TokStr) {
702     if (*TokStr != '\n' &&
703         *TokStr != '\r')
704       continue;
705 
706     ++NumNewlines;
707 
708     // If we have \n\r or \r\n, skip both and count as one line.
709     if (Len != 1 &&
710         (TokStr[1] == '\n' || TokStr[1] == '\r') &&
711         TokStr[0] != TokStr[1]) {
712       ++TokStr;
713       --Len;
714     }
715   }
716 
717   if (NumNewlines == 0) return;
718 
719   CurLine += NumNewlines;
720 }
721 
722 
723 namespace {
724 struct UnknownPragmaHandler : public PragmaHandler {
725   const char *Prefix;
726   PrintPPOutputPPCallbacks *Callbacks;
727 
728   // Set to true if tokens should be expanded
729   bool ShouldExpandTokens;
730 
731   UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks,
732                        bool RequireTokenExpansion)
733       : Prefix(prefix), Callbacks(callbacks),
734         ShouldExpandTokens(RequireTokenExpansion) {}
735   void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
736                     Token &PragmaTok) override {
737     // Figure out what line we went to and insert the appropriate number of
738     // newline characters.
739     Callbacks->MoveToLine(PragmaTok.getLocation(), /*RequireStartOfLine=*/true);
740     Callbacks->OS.write(Prefix, strlen(Prefix));
741     Callbacks->setEmittedTokensOnThisLine();
742 
743     if (ShouldExpandTokens) {
744       // The first token does not have expanded macros. Expand them, if
745       // required.
746       auto Toks = std::make_unique<Token[]>(1);
747       Toks[0] = PragmaTok;
748       PP.EnterTokenStream(std::move(Toks), /*NumToks=*/1,
749                           /*DisableMacroExpansion=*/false,
750                           /*IsReinject=*/false);
751       PP.Lex(PragmaTok);
752     }
753 
754     // Read and print all of the pragma tokens.
755     bool IsFirst = true;
756     while (PragmaTok.isNot(tok::eod)) {
757       Callbacks->HandleWhitespaceBeforeTok(PragmaTok, /*RequireSpace=*/IsFirst,
758                                            /*RequireSameLine=*/true);
759       IsFirst = false;
760       std::string TokSpell = PP.getSpelling(PragmaTok);
761       Callbacks->OS.write(&TokSpell[0], TokSpell.size());
762       Callbacks->setEmittedTokensOnThisLine();
763 
764       if (ShouldExpandTokens)
765         PP.Lex(PragmaTok);
766       else
767         PP.LexUnexpandedToken(PragmaTok);
768     }
769     Callbacks->setEmittedDirectiveOnThisLine();
770   }
771 };
772 } // end anonymous namespace
773 
774 
775 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
776                                     PrintPPOutputPPCallbacks *Callbacks,
777                                     raw_ostream &OS) {
778   bool DropComments = PP.getLangOpts().TraditionalCPP &&
779                       !PP.getCommentRetentionState();
780 
781   bool IsStartOfLine = false;
782   char Buffer[256];
783   while (1) {
784     // Two lines joined with line continuation ('\' as last character on the
785     // line) must be emitted as one line even though Tok.getLine() returns two
786     // different values. In this situation Tok.isAtStartOfLine() is false even
787     // though it may be the first token on the lexical line. When
788     // dropping/skipping a token that is at the start of a line, propagate the
789     // start-of-line-ness to the next token to not append it to the previous
790     // line.
791     IsStartOfLine = IsStartOfLine || Tok.isAtStartOfLine();
792 
793     Callbacks->HandleWhitespaceBeforeTok(Tok, /*RequireSpace=*/false,
794                                          /*RequireSameLine=*/!IsStartOfLine);
795 
796     if (DropComments && Tok.is(tok::comment)) {
797       // Skip comments. Normally the preprocessor does not generate
798       // tok::comment nodes at all when not keeping comments, but under
799       // -traditional-cpp the lexer keeps /all/ whitespace, including comments.
800       PP.Lex(Tok);
801       continue;
802     } else if (Tok.is(tok::eod)) {
803       // Don't print end of directive tokens, since they are typically newlines
804       // that mess up our line tracking. These come from unknown pre-processor
805       // directives or hash-prefixed comments in standalone assembly files.
806       PP.Lex(Tok);
807       // FIXME: The token on the next line after #include should have
808       // Tok.isAtStartOfLine() set.
809       IsStartOfLine = true;
810       continue;
811     } else if (Tok.is(tok::annot_module_include)) {
812       // PrintPPOutputPPCallbacks::InclusionDirective handles producing
813       // appropriate output here. Ignore this token entirely.
814       PP.Lex(Tok);
815       IsStartOfLine = true;
816       continue;
817     } else if (Tok.is(tok::annot_module_begin)) {
818       // FIXME: We retrieve this token after the FileChanged callback, and
819       // retrieve the module_end token before the FileChanged callback, so
820       // we render this within the file and render the module end outside the
821       // file, but this is backwards from the token locations: the module_begin
822       // token is at the include location (outside the file) and the module_end
823       // token is at the EOF location (within the file).
824       Callbacks->BeginModule(
825           reinterpret_cast<Module *>(Tok.getAnnotationValue()));
826       PP.Lex(Tok);
827       IsStartOfLine = true;
828       continue;
829     } else if (Tok.is(tok::annot_module_end)) {
830       Callbacks->EndModule(
831           reinterpret_cast<Module *>(Tok.getAnnotationValue()));
832       PP.Lex(Tok);
833       IsStartOfLine = true;
834       continue;
835     } else if (Tok.is(tok::annot_header_unit)) {
836       // This is a header-name that has been (effectively) converted into a
837       // module-name.
838       // FIXME: The module name could contain non-identifier module name
839       // components. We don't have a good way to round-trip those.
840       Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
841       std::string Name = M->getFullModuleName();
842       OS.write(Name.data(), Name.size());
843       Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
844     } else if (Tok.isAnnotation()) {
845       // Ignore annotation tokens created by pragmas - the pragmas themselves
846       // will be reproduced in the preprocessed output.
847       PP.Lex(Tok);
848       continue;
849     } else if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
850       OS << II->getName();
851     } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
852                Tok.getLiteralData()) {
853       OS.write(Tok.getLiteralData(), Tok.getLength());
854     } else if (Tok.getLength() < llvm::array_lengthof(Buffer)) {
855       const char *TokPtr = Buffer;
856       unsigned Len = PP.getSpelling(Tok, TokPtr);
857       OS.write(TokPtr, Len);
858 
859       // Tokens that can contain embedded newlines need to adjust our current
860       // line number.
861       // FIXME: The token may end with a newline in which case
862       // setEmittedDirectiveOnThisLine/setEmittedTokensOnThisLine afterwards is
863       // wrong.
864       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
865         Callbacks->HandleNewlinesInToken(TokPtr, Len);
866       if (Tok.is(tok::comment) && Len >= 2 && TokPtr[0] == '/' &&
867           TokPtr[1] == '/') {
868         // It's a line comment;
869         // Ensure that we don't concatenate anything behind it.
870         Callbacks->setEmittedDirectiveOnThisLine();
871       }
872     } else {
873       std::string S = PP.getSpelling(Tok);
874       OS.write(S.data(), S.size());
875 
876       // Tokens that can contain embedded newlines need to adjust our current
877       // line number.
878       if (Tok.getKind() == tok::comment || Tok.getKind() == tok::unknown)
879         Callbacks->HandleNewlinesInToken(S.data(), S.size());
880       if (Tok.is(tok::comment) && S.size() >= 2 && S[0] == '/' && S[1] == '/') {
881         // It's a line comment;
882         // Ensure that we don't concatenate anything behind it.
883         Callbacks->setEmittedDirectiveOnThisLine();
884       }
885     }
886     Callbacks->setEmittedTokensOnThisLine();
887     IsStartOfLine = false;
888 
889     if (Tok.is(tok::eof)) break;
890 
891     PP.Lex(Tok);
892   }
893 }
894 
895 typedef std::pair<const IdentifierInfo *, MacroInfo *> id_macro_pair;
896 static int MacroIDCompare(const id_macro_pair *LHS, const id_macro_pair *RHS) {
897   return LHS->first->getName().compare(RHS->first->getName());
898 }
899 
900 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
901   // Ignore unknown pragmas.
902   PP.IgnorePragmas();
903 
904   // -dM mode just scans and ignores all tokens in the files, then dumps out
905   // the macro table at the end.
906   PP.EnterMainSourceFile();
907 
908   Token Tok;
909   do PP.Lex(Tok);
910   while (Tok.isNot(tok::eof));
911 
912   SmallVector<id_macro_pair, 128> MacrosByID;
913   for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
914        I != E; ++I) {
915     auto *MD = I->second.getLatest();
916     if (MD && MD->isDefined())
917       MacrosByID.push_back(id_macro_pair(I->first, MD->getMacroInfo()));
918   }
919   llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
920 
921   for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
922     MacroInfo &MI = *MacrosByID[i].second;
923     // Ignore computed macros like __LINE__ and friends.
924     if (MI.isBuiltinMacro()) continue;
925 
926     PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
927     *OS << '\n';
928   }
929 }
930 
931 /// DoPrintPreprocessedInput - This implements -E mode.
932 ///
933 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
934                                      const PreprocessorOutputOptions &Opts) {
935   // Show macros with no output is handled specially.
936   if (!Opts.ShowCPP) {
937     assert(Opts.ShowMacros && "Not yet implemented!");
938     DoPrintMacros(PP, OS);
939     return;
940   }
941 
942   // Inform the preprocessor whether we want it to retain comments or not, due
943   // to -C or -CC.
944   PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
945 
946   PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(
947       PP, *OS, !Opts.ShowLineMarkers, Opts.ShowMacros,
948       Opts.ShowIncludeDirectives, Opts.UseLineDirectives,
949       Opts.MinimizeWhitespace);
950 
951   // Expand macros in pragmas with -fms-extensions.  The assumption is that
952   // the majority of pragmas in such a file will be Microsoft pragmas.
953   // Remember the handlers we will add so that we can remove them later.
954   std::unique_ptr<UnknownPragmaHandler> MicrosoftExtHandler(
955       new UnknownPragmaHandler(
956           "#pragma", Callbacks,
957           /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
958 
959   std::unique_ptr<UnknownPragmaHandler> GCCHandler(new UnknownPragmaHandler(
960       "#pragma GCC", Callbacks,
961       /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
962 
963   std::unique_ptr<UnknownPragmaHandler> ClangHandler(new UnknownPragmaHandler(
964       "#pragma clang", Callbacks,
965       /*RequireTokenExpansion=*/PP.getLangOpts().MicrosoftExt));
966 
967   PP.AddPragmaHandler(MicrosoftExtHandler.get());
968   PP.AddPragmaHandler("GCC", GCCHandler.get());
969   PP.AddPragmaHandler("clang", ClangHandler.get());
970 
971   // The tokens after pragma omp need to be expanded.
972   //
973   //  OpenMP [2.1, Directive format]
974   //  Preprocessing tokens following the #pragma omp are subject to macro
975   //  replacement.
976   std::unique_ptr<UnknownPragmaHandler> OpenMPHandler(
977       new UnknownPragmaHandler("#pragma omp", Callbacks,
978                                /*RequireTokenExpansion=*/true));
979   PP.AddPragmaHandler("omp", OpenMPHandler.get());
980 
981   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callbacks));
982 
983   // After we have configured the preprocessor, enter the main file.
984   PP.EnterMainSourceFile();
985 
986   // Consume all of the tokens that come from the predefines buffer.  Those
987   // should not be emitted into the output and are guaranteed to be at the
988   // start.
989   const SourceManager &SourceMgr = PP.getSourceManager();
990   Token Tok;
991   do {
992     PP.Lex(Tok);
993     if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
994       break;
995 
996     PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
997     if (PLoc.isInvalid())
998       break;
999 
1000     if (strcmp(PLoc.getFilename(), "<built-in>"))
1001       break;
1002   } while (true);
1003 
1004   // Read all the preprocessed tokens, printing them out to the stream.
1005   PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);
1006   *OS << '\n';
1007 
1008   // Remove the handlers we just added to leave the preprocessor in a sane state
1009   // so that it can be reused (for example by a clang::Parser instance).
1010   PP.RemovePragmaHandler(MicrosoftExtHandler.get());
1011   PP.RemovePragmaHandler("GCC", GCCHandler.get());
1012   PP.RemovePragmaHandler("clang", ClangHandler.get());
1013   PP.RemovePragmaHandler("omp", OpenMPHandler.get());
1014 }
1015