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