blob: acb011c2160f5d3247e94bd8f1068b6b19469a2d [file] [log] [blame]
Ted Kremenek5e0020e2008-03-18 22:21:07 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
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// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/Rewrite/Rewriter.h"
17#include "clang/Rewrite/HTMLRewrite.h"
18#include "clang/Basic/SourceManager.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "clang/AST/ASTContext.h"
Ted Kremenek1b3188c2008-03-18 23:55:46 +000021#include <sstream>
Ted Kremenek5e0020e2008-03-18 22:21:07 +000022
23using namespace clang;
24
25namespace {
26 class HTMLPrinter : public ASTConsumer {
27 Rewriter R;
28 public:
29 HTMLPrinter() {}
30 virtual ~HTMLPrinter();
31
32 void Initialize(ASTContext &context);
33 };
34}
35
36ASTConsumer* clang::CreateHTMLPrinter() { return new HTMLPrinter(); }
37
38void HTMLPrinter::Initialize(ASTContext &context) {
39 R.setSourceMgr(context.getSourceManager());
40}
41
42HTMLPrinter::~HTMLPrinter() {
43 unsigned FileID = R.getSourceMgr().getMainFileID();
44
45 const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID);
46 const char* FileStart = Buf->getBufferStart();
47 const char* FileEnd = Buf->getBufferEnd();
48 SourceLocation StartLoc = SourceLocation::getFileLoc(FileID, 0);
49 SourceLocation EndLoc = SourceLocation::getFileLoc(FileID, FileEnd-FileStart);
50
51 html::EscapeText(R, FileID);
52 html::AddLineNumbers(R, FileID);
Ted Kremenek1b3188c2008-03-18 23:55:46 +000053
Ted Kremenekf8309972008-03-19 01:30:02 +000054 // Generate header
Ted Kremenek1b3188c2008-03-18 23:55:46 +000055
Ted Kremenekf8309972008-03-19 01:30:02 +000056 {
57 std::ostringstream os;
Ted Kremenek1b3188c2008-03-18 23:55:46 +000058
Ted Kremenekf8309972008-03-19 01:30:02 +000059 os << "<html>\n<head>\n"
60 << " <style type=\"text/css\">\n"
61 << " .nums, .lines { vertical-align:top }\n"
62 << " .nums { padding-right:.5em; width:2.5em }\n"
63 << " </style>\n"
64 << "</head>\n"
65 << "<body>\n<pre>";
66
67 R.InsertTextBefore(StartLoc, os.str().c_str(), os.str().size());
68 }
Ted Kremenek1b3188c2008-03-18 23:55:46 +000069
Ted Kremenekf8309972008-03-19 01:30:02 +000070 // Generate footer
71
72 {
73 std::ostringstream os;
74
75 os << "</pre>\n</body></html>\n";
76 R.InsertTextAfter(EndLoc, os.str().c_str(), os.str().size());
77 }
78
Ted Kremenek5e0020e2008-03-18 22:21:07 +000079
80 // Emit the HTML.
81
82 if (const RewriteBuffer *RewriteBuf = R.getRewriteBufferFor(FileID)) {
83 std::string S(RewriteBuf->begin(), RewriteBuf->end());
84 printf("%s\n", S.c_str());
85 }
86}