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/Support/raw_ostream.h"
28 #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 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 EmittedDirectiveOnThisLine;
92 SrcMgr::CharacteristicKind FileType;
93 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 EmittedDirectiveOnThisLine = false;
108 FileType = SrcMgr::C_User;
111 // If we're in microsoft mode, use normal #line instead of line markers.
112 UseLineDirective = PP.getLangOpts().MicrosoftExt;
115 void setEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
116 bool hasEmittedTokensOnThisLine() const { return EmittedTokensOnThisLine; }
118 void setEmittedDirectiveOnThisLine() { EmittedDirectiveOnThisLine = true; }
119 bool hasEmittedDirectiveOnThisLine() const {
120 return EmittedDirectiveOnThisLine;
123 bool startNewLineIfNeeded(bool ShouldUpdateCurrentLine = true);
125 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
126 SrcMgr::CharacteristicKind FileType,
128 virtual void Ident(SourceLocation Loc, const std::string &str);
129 virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind,
130 const std::string &Str);
131 virtual void PragmaMessage(SourceLocation Loc, StringRef Str);
132 virtual void PragmaDiagnosticPush(SourceLocation Loc,
133 StringRef Namespace);
134 virtual void PragmaDiagnosticPop(SourceLocation Loc,
135 StringRef Namespace);
136 virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
137 diag::Mapping Map, StringRef Str);
139 bool HandleFirstTokOnLine(Token &Tok);
140 bool MoveToLine(SourceLocation Loc) {
141 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
142 if (PLoc.isInvalid())
144 return MoveToLine(PLoc.getLine());
146 bool MoveToLine(unsigned LineNo);
148 bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok,
150 return ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok);
152 void WriteLineInfo(unsigned LineNo, const char *Extra=0, unsigned ExtraLen=0);
153 bool LineMarkersAreDisabled() const { return DisableLineMarkers; }
154 void HandleNewlinesInToken(const char *TokStr, unsigned Len);
156 /// MacroDefined - This hook is called whenever a macro definition is seen.
157 void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI);
159 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
160 void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI);
162 } // end anonymous namespace
164 void PrintPPOutputPPCallbacks::WriteLineInfo(unsigned LineNo,
167 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
169 // Emit #line directives or GNU line markers depending on what mode we're in.
170 if (UseLineDirective) {
171 OS << "#line" << ' ' << LineNo << ' ' << '"';
172 OS.write(CurFilename.data(), CurFilename.size());
175 OS << '#' << ' ' << LineNo << ' ' << '"';
176 OS.write(CurFilename.data(), CurFilename.size());
180 OS.write(Extra, ExtraLen);
182 if (FileType == SrcMgr::C_System)
184 else if (FileType == SrcMgr::C_ExternCSystem)
190 /// MoveToLine - Move the output to the source line specified by the location
191 /// object. We can do this by emitting some number of \n's, or be emitting a
192 /// #line directive. This returns false if already at the specified line, true
193 /// if some newlines were emitted.
194 bool PrintPPOutputPPCallbacks::MoveToLine(unsigned LineNo) {
195 // If this line is "close enough" to the original line, just print newlines,
196 // otherwise print a #line directive.
197 if (LineNo-CurLine <= 8) {
198 if (LineNo-CurLine == 1)
200 else if (LineNo == CurLine)
201 return false; // Spelling line moved, but expansion line didn't.
203 const char *NewLines = "\n\n\n\n\n\n\n\n";
204 OS.write(NewLines, LineNo-CurLine);
206 } else if (!DisableLineMarkers) {
207 // Emit a #line or line marker.
208 WriteLineInfo(LineNo, 0, 0);
210 // Okay, we're in -P mode, which turns off line markers. However, we still
211 // need to emit a newline between tokens on different lines.
212 startNewLineIfNeeded(/*ShouldUpdateCurrentLine=*/false);
220 PrintPPOutputPPCallbacks::startNewLineIfNeeded(bool ShouldUpdateCurrentLine) {
221 if (EmittedTokensOnThisLine || EmittedDirectiveOnThisLine) {
223 EmittedTokensOnThisLine = false;
224 EmittedDirectiveOnThisLine = false;
225 if (ShouldUpdateCurrentLine)
233 /// FileChanged - Whenever the preprocessor enters or exits a #include file
234 /// it invokes this handler. Update our conception of the current source
236 void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
237 FileChangeReason Reason,
238 SrcMgr::CharacteristicKind NewFileType,
240 // Unless we are exiting a #include, make sure to skip ahead to the line the
241 // #include directive was at.
242 SourceManager &SourceMgr = SM;
244 PresumedLoc UserLoc = SourceMgr.getPresumedLoc(Loc);
245 if (UserLoc.isInvalid())
248 unsigned NewLine = UserLoc.getLine();
250 if (Reason == PPCallbacks::EnterFile) {
251 SourceLocation IncludeLoc = UserLoc.getIncludeLoc();
252 if (IncludeLoc.isValid())
253 MoveToLine(IncludeLoc);
254 } else if (Reason == PPCallbacks::SystemHeaderPragma) {
257 // TODO GCC emits the # directive for this directive on the line AFTER the
258 // directive and emits a bunch of spaces that aren't needed. Emulate this
265 CurFilename += UserLoc.getFilename();
266 Lexer::Stringify(CurFilename);
267 FileType = NewFileType;
269 if (DisableLineMarkers) return;
272 WriteLineInfo(CurLine);
277 case PPCallbacks::EnterFile:
278 WriteLineInfo(CurLine, " 1", 2);
280 case PPCallbacks::ExitFile:
281 WriteLineInfo(CurLine, " 2", 2);
283 case PPCallbacks::SystemHeaderPragma:
284 case PPCallbacks::RenameFile:
285 WriteLineInfo(CurLine);
290 /// Ident - Handle #ident directives when read by the preprocessor.
292 void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
295 OS.write("#ident ", strlen("#ident "));
296 OS.write(&S[0], S.size());
297 EmittedTokensOnThisLine = true;
300 /// MacroDefined - This hook is called whenever a macro definition is seen.
301 void PrintPPOutputPPCallbacks::MacroDefined(const Token &MacroNameTok,
302 const MacroInfo *MI) {
303 // Only print out macro definitions in -dD mode.
305 // Ignore __FILE__ etc.
306 MI->isBuiltinMacro()) return;
308 MoveToLine(MI->getDefinitionLoc());
309 PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
310 setEmittedDirectiveOnThisLine();
313 void PrintPPOutputPPCallbacks::MacroUndefined(const Token &MacroNameTok,
314 const MacroInfo *MI) {
315 // Only print out macro definitions in -dD mode.
316 if (!DumpDefines) return;
318 MoveToLine(MacroNameTok.getLocation());
319 OS << "#undef " << MacroNameTok.getIdentifierInfo()->getName();
320 setEmittedDirectiveOnThisLine();
323 void PrintPPOutputPPCallbacks::PragmaComment(SourceLocation Loc,
324 const IdentifierInfo *Kind,
325 const std::string &Str) {
326 startNewLineIfNeeded();
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 setEmittedDirectiveOnThisLine();
350 void PrintPPOutputPPCallbacks::PragmaMessage(SourceLocation Loc,
352 startNewLineIfNeeded();
354 OS << "#pragma message(";
358 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
359 unsigned char Char = Str[i];
360 if (isprint(Char) && Char != '\\' && Char != '"')
362 else // Output anything hard as an octal escape.
364 << (char)('0'+ ((Char >> 6) & 7))
365 << (char)('0'+ ((Char >> 3) & 7))
366 << (char)('0'+ ((Char >> 0) & 7));
371 setEmittedDirectiveOnThisLine();
374 void PrintPPOutputPPCallbacks::
375 PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) {
376 startNewLineIfNeeded();
378 OS << "#pragma " << Namespace << " diagnostic push";
379 setEmittedDirectiveOnThisLine();
382 void PrintPPOutputPPCallbacks::
383 PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) {
384 startNewLineIfNeeded();
386 OS << "#pragma " << Namespace << " diagnostic pop";
387 setEmittedDirectiveOnThisLine();
390 void PrintPPOutputPPCallbacks::
391 PragmaDiagnostic(SourceLocation Loc, StringRef Namespace,
392 diag::Mapping Map, StringRef Str) {
393 startNewLineIfNeeded();
395 OS << "#pragma " << Namespace << " diagnostic ";
397 case diag::MAP_WARNING:
400 case diag::MAP_ERROR:
403 case diag::MAP_IGNORE:
406 case diag::MAP_FATAL:
410 OS << " \"" << Str << '"';
411 setEmittedDirectiveOnThisLine();
414 /// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
415 /// is called for the first token on each new line. If this really is the start
416 /// of a new logical line, handle it and return true, otherwise return false.
417 /// This may not be the start of a logical line because the "start of line"
418 /// marker is set for spelling lines, not expansion ones.
419 bool PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
420 // Figure out what line we went to and insert the appropriate number of
421 // newline characters.
422 if (!MoveToLine(Tok.getLocation()))
425 // Print out space characters so that the first token on a line is
426 // indented for easy reading.
427 unsigned ColNo = SM.getExpansionColumnNumber(Tok.getLocation());
429 // This hack prevents stuff like:
431 // HASH define foo bar
432 // From having the # character end up at column 1, which makes it so it
433 // is not handled as a #define next time through the preprocessor if in
434 // -fpreprocessed mode.
435 if (ColNo <= 1 && Tok.is(tok::hash))
438 // Otherwise, indent the appropriate number of spaces.
439 for (; ColNo > 1; --ColNo)
445 void PrintPPOutputPPCallbacks::HandleNewlinesInToken(const char *TokStr,
447 unsigned NumNewlines = 0;
448 for (; Len; --Len, ++TokStr) {
449 if (*TokStr != '\n' &&
455 // If we have \n\r or \r\n, skip both and count as one line.
457 (TokStr[1] == '\n' || TokStr[1] == '\r') &&
458 TokStr[0] != TokStr[1])
462 if (NumNewlines == 0) return;
464 CurLine += NumNewlines;
469 struct UnknownPragmaHandler : public PragmaHandler {
471 PrintPPOutputPPCallbacks *Callbacks;
473 UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
474 : Prefix(prefix), Callbacks(callbacks) {}
475 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
477 // Figure out what line we went to and insert the appropriate number of
478 // newline characters.
479 Callbacks->startNewLineIfNeeded();
480 Callbacks->MoveToLine(PragmaTok.getLocation());
481 Callbacks->OS.write(Prefix, strlen(Prefix));
482 // Read and print all of the pragma tokens.
483 while (PragmaTok.isNot(tok::eod)) {
484 if (PragmaTok.hasLeadingSpace())
485 Callbacks->OS << ' ';
486 std::string TokSpell = PP.getSpelling(PragmaTok);
487 Callbacks->OS.write(&TokSpell[0], TokSpell.size());
488 PP.LexUnexpandedToken(PragmaTok);
490 Callbacks->setEmittedDirectiveOnThisLine();
493 } // end anonymous namespace
496 static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
497 PrintPPOutputPPCallbacks *Callbacks,
500 Token PrevPrevTok, PrevTok;
501 PrevPrevTok.startToken();
502 PrevTok.startToken();
504 if (Callbacks->hasEmittedDirectiveOnThisLine()) {
505 Callbacks->startNewLineIfNeeded();
506 Callbacks->MoveToLine(Tok.getLocation());
509 // If this token is at the start of a line, emit newlines if needed.
510 if (Tok.isAtStartOfLine() && Callbacks->HandleFirstTokOnLine(Tok)) {
512 } else if (Tok.hasLeadingSpace() ||
513 // If we haven't emitted a token on this line yet, PrevTok isn't
514 // useful to look at and no concatenation could happen anyway.
515 (Callbacks->hasEmittedTokensOnThisLine() &&
516 // Don't print "-" next to "-", it would form "--".
517 Callbacks->AvoidConcat(PrevPrevTok, PrevTok, Tok))) {
521 if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
523 } else if (Tok.isLiteral() && !Tok.needsCleaning() &&
524 Tok.getLiteralData()) {
525 OS.write(Tok.getLiteralData(), Tok.getLength());
526 } else if (Tok.getLength() < 256) {
527 const char *TokPtr = Buffer;
528 unsigned Len = PP.getSpelling(Tok, TokPtr);
529 OS.write(TokPtr, Len);
531 // Tokens that can contain embedded newlines need to adjust our current
533 if (Tok.getKind() == tok::comment)
534 Callbacks->HandleNewlinesInToken(TokPtr, Len);
536 std::string S = PP.getSpelling(Tok);
537 OS.write(&S[0], S.size());
539 // Tokens that can contain embedded newlines need to adjust our current
541 if (Tok.getKind() == tok::comment)
542 Callbacks->HandleNewlinesInToken(&S[0], S.size());
544 Callbacks->setEmittedTokensOnThisLine();
546 if (Tok.is(tok::eof)) break;
548 PrevPrevTok = PrevTok;
554 typedef std::pair<IdentifierInfo*, MacroInfo*> id_macro_pair;
555 static int MacroIDCompare(const void* a, const void* b) {
556 const id_macro_pair *LHS = static_cast<const id_macro_pair*>(a);
557 const id_macro_pair *RHS = static_cast<const id_macro_pair*>(b);
558 return LHS->first->getName().compare(RHS->first->getName());
561 static void DoPrintMacros(Preprocessor &PP, raw_ostream *OS) {
562 // Ignore unknown pragmas.
563 PP.AddPragmaHandler(new EmptyPragmaHandler());
565 // -dM mode just scans and ignores all tokens in the files, then dumps out
566 // the macro table at the end.
567 PP.EnterMainSourceFile();
571 while (Tok.isNot(tok::eof));
573 SmallVector<id_macro_pair, 128> MacrosByID;
574 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
576 if (I->first->hasMacroDefinition())
577 MacrosByID.push_back(id_macro_pair(I->first, I->second));
579 llvm::array_pod_sort(MacrosByID.begin(), MacrosByID.end(), MacroIDCompare);
581 for (unsigned i = 0, e = MacrosByID.size(); i != e; ++i) {
582 MacroInfo &MI = *MacrosByID[i].second;
583 // Ignore computed macros like __LINE__ and friends.
584 if (MI.isBuiltinMacro()) continue;
586 PrintMacroDefinition(*MacrosByID[i].first, MI, PP, *OS);
591 /// DoPrintPreprocessedInput - This implements -E mode.
593 void clang::DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS,
594 const PreprocessorOutputOptions &Opts) {
595 // Show macros with no output is handled specially.
597 assert(Opts.ShowMacros && "Not yet implemented!");
598 DoPrintMacros(PP, OS);
602 // Inform the preprocessor whether we want it to retain comments or not, due
604 PP.SetCommentRetentionState(Opts.ShowComments, Opts.ShowMacroComments);
606 PrintPPOutputPPCallbacks *Callbacks =
607 new PrintPPOutputPPCallbacks(PP, *OS, !Opts.ShowLineMarkers,
609 PP.AddPragmaHandler(new UnknownPragmaHandler("#pragma", Callbacks));
610 PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
611 PP.AddPragmaHandler("clang",
612 new UnknownPragmaHandler("#pragma clang", Callbacks));
614 PP.addPPCallbacks(Callbacks);
616 // After we have configured the preprocessor, enter the main file.
617 PP.EnterMainSourceFile();
619 // Consume all of the tokens that come from the predefines buffer. Those
620 // should not be emitted into the output and are guaranteed to be at the
622 const SourceManager &SourceMgr = PP.getSourceManager();
626 if (Tok.is(tok::eof) || !Tok.getLocation().isFileID())
629 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
630 if (PLoc.isInvalid())
633 if (strcmp(PLoc.getFilename(), "<built-in>"))
637 // Read all the preprocessed tokens, printing them out to the stream.
638 PrintPreprocessedTokens(PP, Tok, Callbacks, *OS);