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