blob: 8252df65713dd3d6544ade7ed6b4201590082f76 [file] [log] [blame]
Chris Lattner1665a9f2008-05-08 06:52:13 +00001//===--- RewriteMacros.cpp - Rewrite macros into their expansions ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This code rewrites macro invocations into their expansions. This gives you
11// a macro expanded file that retains comments and #includes.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang.h"
16#include "clang/Rewrite/Rewriter.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Basic/SourceManager.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/Support/Streams.h"
21#include "llvm/System/Path.h"
22#include <fstream>
23using namespace clang;
24
25/// RewriteMacrosInInput - Implement -rewrite-macros mode.
Chris Lattner302b0622008-05-09 22:43:24 +000026void clang::RewriteMacrosInInput(Preprocessor &PP,const std::string &InFileName,
Chris Lattner1665a9f2008-05-08 06:52:13 +000027 const std::string &OutFileName) {
28 SourceManager &SM = PP.getSourceManager();
29
30 Rewriter Rewrite;
31 Rewrite.setSourceMgr(SM);
32
Chris Lattner1665a9f2008-05-08 06:52:13 +000033 // Get the ID and start/end of the main file.
34 unsigned MainFileID = SM.getMainFileID();
Chris Lattner302b0622008-05-09 22:43:24 +000035 //const llvm::MemoryBuffer *MainBuf = SM.getBuffer(MainFileID);
36 //const char *MainFileStart = MainBuf->getBufferStart();
37 //const char *MainFileEnd = MainBuf->getBufferEnd();
Chris Lattner1665a9f2008-05-08 06:52:13 +000038
39
40 // Create the output file.
41
42 std::ostream *OutFile;
43 if (OutFileName == "-") {
44 OutFile = llvm::cout.stream();
45 } else if (!OutFileName.empty()) {
46 OutFile = new std::ofstream(OutFileName.c_str(),
47 std::ios_base::binary|std::ios_base::out);
48 } else if (InFileName == "-") {
49 OutFile = llvm::cout.stream();
50 } else {
51 llvm::sys::Path Path(InFileName);
52 Path.eraseSuffix();
53 Path.appendSuffix("cpp");
54 OutFile = new std::ofstream(Path.toString().c_str(),
55 std::ios_base::binary|std::ios_base::out);
56 }
57
58 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
59 // we are done.
60 if (const RewriteBuffer *RewriteBuf =
61 Rewrite.getRewriteBufferFor(MainFileID)) {
62 //printf("Changed:\n");
63 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
64 } else {
65 fprintf(stderr, "No changes\n");
66 }
Chris Lattner1665a9f2008-05-08 06:52:13 +000067}