1 //===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This code simply runs the preprocessor on the input file and prints out the
11 // result. This is the traditional behavior of the -E option.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Frontend/Utils.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/SmallString.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Config/config.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/ErrorHandling.h"
31 using namespace clang;
33 /// PrintMacroDefinition - Print a macro definition in a form that will be
34 /// properly accepted back as a definition.
35 static void PrintMacroDefinition(const IdentifierInfo &II, const MacroInfo &MI,
36 Preprocessor &PP, raw_ostream &OS) {
37 OS << "#define " << II.getName();
39 if (MI.isFunctionLike()) {
41 if (!MI.arg_empty()) {
42 MacroInfo::arg_iterator AI = MI.arg_begin(), E = MI.arg_end();
43 for (; AI+1 != E; ++AI) {
44 OS << (*AI)->getName();
49 if ((*AI)->getName() == "__VA_ARGS__")
52 OS << (*AI)->getName();
55 if (MI.isGNUVarargs())
56 OS << "..."; // #define foo(x...)
61 // GCC always emits a space, even if the macro body is empty. However, do not
62 // want to emit two spaces if the first token has a leading space.
63 if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
66 llvm::SmallString<128> SpellingBuffer;
67 for (MacroInfo::tokens_iterator I = MI.tokens_begin(), E = MI.tokens_end();
69 if (I->hasLeadingSpace())
72 OS << PP.getSpelling(*I, SpellingBuffer);
76 //===----------------------------------------------------------------------===//
77 // Preprocessed token printer
78 //===----------------------------------------------------------------------===//
81 class PrintPPOutputPPCallbacks : public PPCallbacks {
84 TokenConcatenation ConcatInfo;
90 bool EmittedTokensOnThisLine;
91 bool EmittedMacroOnThisLine;
92 SrcMgr::CharacteristicKind FileType;
93 llvm::SmallString<512> CurFilename;
95 bool DisableLineMarkers;
97 bool UseLineDirective;
99 PrintPPOutputPPCallbacks(Preprocessor &pp, raw_ostream &os,
100 bool lineMarkers, bool defines)
101 : PP(pp), SM(PP.getSourceManager()),
102 ConcatInfo(PP), OS(os), DisableLineMarkers(lineMarkers),
103 DumpDefines(defines) {
105 CurFilename += "<uninit>";
106 EmittedTokensOnThisLine = false;
107 EmittedMacroOnThisLine = false;
108 FileType = SrcMgr::C_User;
111 // If we're in microsoft mode, use normal #line instead of line markers.
112 UseLineDirective = PP.getLangOptions().MicrosoftExt;
115 void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
116 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
118 bool StartNewLineIfNeeded();
120 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
121 SrcMgr::CharacteristicKind FileType,
123 virtual void Ident(SourceLocation Loc, const std::string &str);
124 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
125 const std::string &Str);
126 virtual void PragmaMessage(SourceLocation Loc, StringRef Str);
127 virtual void PragmaDiagnosticPush(SourceLocation Loc,
128 StringRef Namespace);
129 virtual void PragmaDiagnosticPop(SourceLocation Loc,
130 StringRef Namespace);
131 virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
132 diag::Mapping Map, StringRef Str);
134 bool HandleFirstTokOnLine(Token &Tok);
135 bool MoveToLine(SourceLocation Loc) {
136 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
137 if (PLoc.isInvalid())
139 return MoveToLine(PLoc.getLine());
141 bool MoveToLine(unsigned LineNo);
143 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
145 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
147 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
148 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
149 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
151 /// MacroDefined - This hook is called whenever a macro definition is seen.
152 void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI);
154 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
155 void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI);
157 } // end anonymous namespace
159 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
162 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
164 EmittedTokensOnThisLine = false;
165 EmittedMacroOnThisLine = false;
168 // Emit #line directives or GNU line markers depending on what mode we're in.
169 if (UseLineDirective) {
170 OS << "#line" << ' ' << LineNo << ' ' << '"';
171 OS.write(CurFilename.data(), CurFilename.size());
174 OS << '#' << ' ' << LineNo << ' ' << '"';
175 OS.write(CurFilename.data(), CurFilename.size());
179 OS.write(Extra, ExtraLen);
181 if (FileType == SrcMgr::C_System)
183 else if (FileType == SrcMgr::C_ExternCSystem)
189 /// MoveToLine - Move the output to the source line specified by the location
190 /// object. We can do this by emitting some number of \n's, or be emitting a
191 /// #line directive. This returns false if already at the specified line, true
192 /// if some newlines were emitted.
193 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
194 // If this line is "close enough" to the original line, just print newlines,
195 // otherwise print a #line directive.
196 if (LineNo-CurLine <= 8) {
197 if (LineNo-CurLine == 1)
199 else if (LineNo == CurLine)
200 return false; // Spelling line moved, but expansion line didn't.
202 const char *NewLines = "\n\n\n\n\n\n\n\n";
203 OS.write(NewLines, LineNo-CurLine);
205 } else if (!DisableLineMarkers) {
206 // Emit a #line or line marker.
207 WriteLineInfo(LineNo, 0, 0);
209 // Okay, we're in -P mode, which turns off line markers. However, we still
210 // need to emit a newline between tokens on different lines.
211 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
213 EmittedTokensOnThisLine = false;
214 EmittedMacroOnThisLine = false;
222 bool PrintPPOutputPPCallbacks::StartNewLineIfNeeded() {
223 if (EmittedTokensOnThisLine || EmittedMacroOnThisLine) {
225 EmittedTokensOnThisLine = false;
226 EmittedMacroOnThisLine = false;
234 /// FileChanged - Whenever the preprocessor enters or exits a #include file
235 /// it invokes this handler. Update our conception of the current source
237 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
238 FileChangeReason Reason,
239 SrcMgr::CharacteristicKind NewFileType,
241 // Unless we are exiting a #include, make sure to skip ahead to the line the
242 // #include directive was at.
243 SourceManager &SourceMgr = SM;
245 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
246 if (UserLoc.isInvalid())
249 unsigned NewLine = UserLoc.getLine();
251 if (Reason == PPCallbacks::EnterFile) {
252 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
253 if (IncludeLoc.isValid())
254 MoveToLine(IncludeLoc);
255 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
258 // TODO GCC emits the # directive for this directive on the line AFTER the
259 // directive and emits a bunch of spaces that aren't needed. Emulate this
266 CurFilename += UserLoc.getFilename();
267 Lexer::Stringify(CurFilename);
268 FileType = NewFileType;
270 if (DisableLineMarkers) return;
273 WriteLineInfo(CurLine);
278 case PPCallbacks::EnterFile:
279 WriteLineInfo(CurLine, " 1", 2);
281 case PPCallbacks::ExitFile:
282 WriteLineInfo(CurLine, " 2", 2);
284 case PPCallbacks::SystemHeaderPragma:
285 case PPCallbacks::RenameFile:
286 WriteLineInfo(CurLine);
291 /// Ident - Handle #ident directives when read by the preprocessor.
293 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
296 OS.write("#ident ", strlen("#ident "));
297 OS.write(&S[0], S.size());
298 EmittedTokensOnThisLine = true;
301 /// MacroDefined - This hook is called whenever a macro definition is seen.
302 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
303 const MacroInfo *MI) {
304 // Only print out macro definitions in -dD mode.
306 // Ignore __FILE__ etc.
307 MI->isBuiltinMacro()) return;
309 MoveToLine(MI->getDefinitionLoc());
310 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
311 EmittedMacroOnThisLine = true;
314 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
315 const MacroInfo *MI) {
316 // Only print out macro definitions in -dD mode.
317 if (!DumpDefines) return;
319 MoveToLine(MacroNameTok.getLocation());
320 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
321 EmittedMacroOnThisLine = true;
324 void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
325 const IdentifierInfo *Kind,
326 const std::string &Str) {
328 OS << "#pragma comment(" << Kind->getName();
333 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
334 unsigned char Char = Str[i];
335 if (isprint(Char) && Char != '\\' && Char != '"')
337 else // Output anything hard as an octal escape.
339 << (char)('0'+ ((Char >> 6) & 7))
340 << (char)('0'+ ((Char >> 3) & 7))
341 << (char)('0'+ ((Char >> 0) & 7));
347 EmittedTokensOnThisLine = true;
350 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
353 OS << "#pragma message(";
357 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
358 unsigned char Char = Str[i];
359 if (isprint(Char) && Char != '\\' && Char != '"')
361 else // Output anything hard as an octal escape.
363 << (char)('0'+ ((Char >> 6) & 7))
364 << (char)('0'+ ((Char >> 3) & 7))
365 << (char)('0'+ ((Char >> 0) & 7));
370 EmittedTokensOnThisLine = true;
373 void PrintPPOutputPPCallbacks::
374 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
376 OS << "#pragma " << Namespace << " diagnostic push";
377 EmittedTokensOnThisLine = true;
380 void PrintPPOutputPPCallbacks::
381 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
383 OS << "#pragma " << Namespace << " diagnostic pop";
384 EmittedTokensOnThisLine = true;
387 void PrintPPOutputPPCallbacks::
388 PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
389 diag::Mapping Map, StringRef Str) {
391 OS << "#pragma " << Namespace << " diagnostic ";
393 default: llvm_unreachable("unexpected diagnostic kind");
394 case diag::MAP_WARNING:
397 case diag::MAP_ERROR:
400 case diag::MAP_IGNORE:
403 case diag::MAP_FATAL:
407 OS << " \"" << Str << '"';
408 EmittedTokensOnThisLine = true;
411 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
412 /// is called for the first token on each new line. If this really is the start
413 /// of a new logical line, handle it and return true, otherwise return false.
414 /// This may not be the start of a logical line because the "start of line"
415 /// marker is set for spelling lines, not expansion ones.
416 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
417 // Figure out what line we went to and insert the appropriate number of
418 // newline characters.
419 if (!MoveToLine(Tok.getLocation()))
422 // Print out space characters so that the first token on a line is
423 // indented for easy reading.
424 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
426 // This hack prevents stuff like:
428 // HASH define foo bar
429 // From having the # character end up at column 1, which makes it so it
430 // is not handled as a #define next time through the preprocessor if in
431 // -fpreprocessed mode.
432 if (ColNo <= 1 && Tok.is(tok::hash))
435 // Otherwise, indent the appropriate number of spaces.
436 for (; ColNo > 1; --ColNo)
442 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
444 unsigned NumNewlines = 0;
445 for (; Len; --Len, ++TokStr) {
446 if (*TokStr != '\n' &&
452 // If we have \n\r or \r\n, skip both and count as one line.
454 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
455 TokStr[0] != TokStr[1])
459 if (NumNewlines == 0) return;
461 CurLine += NumNewlines;
466 struct UnknownPragmaHandler : public PragmaHandler {
468 PrintPPOutputPPCallbacks *Callbacks;
470 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
471 : Prefix(prefix), Callbacks(callbacks) {}
472 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
474 // Figure out what line we went to and insert the appropriate number of
475 // newline characters.
476 Callbacks->StartNewLineIfNeeded();
477 Callbacks->MoveToLine(PragmaTok.getLocation());
478 Callbacks->OS.write(Prefix, strlen(Prefix));
479 Callbacks->SetEmittedTokensOnThisLine();
480 // Read and print all of the pragma tokens.
481 while (PragmaTok.isNot(tok::eod)) {
482 if (PragmaTok.hasLeadingSpace())
483 Callbacks->OS << ' ';
484 std::string TokSpell = PP.getSpelling(PragmaTok);
485 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
486 PP.LexUnexpandedToken(PragmaTok);
488 Callbacks->StartNewLineIfNeeded();
491 } // end anonymous namespace
494 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
495 PrintPPOutputPPCallbacks *Callbacks,
498 Token PrevPrevTok, PrevTok;
499 PrevPrevTok.startToken();
500 PrevTok.startToken();
503 // If this token is at the start of a line, emit newlines if needed.
504 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
506 } else if (Tok.hasLeadingSpace() ||
507 // If we haven't emitted a token on this line yet, PrevTok isn't
508 // useful to look at and no concatenation could happen anyway.
509 (Callbacks->hasEmittedTokensOnThisLine() &&
510 // Don't print "-" next to "-", it would form "--".
511 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
515 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
517 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
518 Tok.getLiteralData()) {
519 OS.write(Tok.getLiteralData(), Tok.getLength());
520 } else if (Tok.getLength() < 256) {
521 const char *TokPtr = Buffer;
522 unsigned Len = PP.getSpelling(Tok, TokPtr);
523 OS.write(TokPtr, Len);
525 // Tokens that can contain embedded newlines need to adjust our current
527 if (Tok.getKind() == tok::comment)
528 Callbacks->HandleNewlinesInToken(TokPtr, Len);
530 std::string S = PP.getSpelling(Tok);
531 OS.write(&S[0], S.size());
533 // Tokens that can contain embedded newlines need to adjust our current
535 if (Tok.getKind() == tok::comment)
536 Callbacks->HandleNewlinesInToken(&S[0], S.size());
538 Callbacks->SetEmittedTokensOnThisLine();
540 if (Tok.is(tok::eof)) break;
542 PrevPrevTok = PrevTok;
548 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
549 static int MacroIDCompare(const void* a, const void* b) {
550 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
551 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
552 return LHS->first->getName().compare(RHS->first->getName());
555 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
556 // Ignore unknown pragmas.
557 PP.AddPragmaHandler(new EmptyPragmaHandler());
559 // -dM mode just scans and ignores all tokens in the files, then dumps out
560 // the macro table at the end.
561 PP.EnterMainSourceFile();
565 while (Tok.isNot(tok::eof));
567 SmallVector<id_macro_pair, 128>
568 MacrosByID(PP.macro_begin(), PP.macro_end());
569 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
571 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
572 MacroInfo &MI = *MacrosByID[i].second;
573 // Ignore computed macros like __LINE__ and friends.
574 if (MI.isBuiltinMacro()) continue;
576 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
581 /// DoPrintPreprocessedInput - This implements -E mode.
583 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
584 const PreprocessorOutputOptions &Opts) {
585 // Show macros with no output is handled specially.
587 assert(Opts.ShowMacros && "Not yet implemented!");
588 DoPrintMacros(PP, OS);
592 // Inform the preprocessor whether we want it to retain comments or not, due
594 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
596 PrintPPOutputPPCallbacks *Callbacks =
597 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
599 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
600 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
601 PP.AddPragmaHandler("clang",
602 new UnknownPragmaHandler("#pragma clang", Callbacks));
604 PP.addPPCallbacks(Callbacks);
606 // After we have configured the preprocessor, enter the main file.
607 PP.EnterMainSourceFile();
609 // Consume all of the tokens that come from the predefines buffer. Those
610 // should not be emitted into the output and are guaranteed to be at the
612 const SourceManager &SourceMgr = PP.getSourceManager();
616 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
619 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
620 if (PLoc.isInvalid())
623 if (strcmp(PLoc.getFilename(), "<built-in>"))
627 // Read all the preprocessed tokens, printing them out to the stream.
628 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);