1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 | #include "clang/AST/ASTConsumer.h" |
14 | #include "clang/AST/ASTContext.h" |
15 | #include "clang/AST/Decl.h" |
16 | #include "clang/Basic/Diagnostic.h" |
17 | #include "clang/Basic/FileManager.h" |
18 | #include "clang/Basic/SourceManager.h" |
19 | #include "clang/Lex/Preprocessor.h" |
20 | #include "clang/Rewrite/Core/HTMLRewrite.h" |
21 | #include "clang/Rewrite/Core/Rewriter.h" |
22 | #include "clang/Rewrite/Frontend/ASTConsumers.h" |
23 | #include "llvm/Support/raw_ostream.h" |
24 | using namespace clang; |
25 | |
26 | |
27 | |
28 | |
29 | |
30 | namespace { |
31 | class HTMLPrinter : public ASTConsumer { |
32 | Rewriter R; |
33 | std::unique_ptr<raw_ostream> Out; |
34 | Preprocessor &PP; |
35 | bool SyntaxHighlight, HighlightMacros; |
36 | |
37 | public: |
38 | HTMLPrinter(std::unique_ptr<raw_ostream> OS, Preprocessor &pp, |
39 | bool _SyntaxHighlight, bool _HighlightMacros) |
40 | : Out(std::move(OS)), PP(pp), SyntaxHighlight(_SyntaxHighlight), |
41 | HighlightMacros(_HighlightMacros) {} |
42 | |
43 | void Initialize(ASTContext &context) override; |
44 | void HandleTranslationUnit(ASTContext &Ctx) override; |
45 | }; |
46 | } |
47 | |
48 | std::unique_ptr<ASTConsumer> |
49 | clang::CreateHTMLPrinter(std::unique_ptr<raw_ostream> OS, Preprocessor &PP, |
50 | bool SyntaxHighlight, bool HighlightMacros) { |
51 | return llvm::make_unique<HTMLPrinter>(std::move(OS), PP, SyntaxHighlight, |
52 | HighlightMacros); |
53 | } |
54 | |
55 | void HTMLPrinter::Initialize(ASTContext &context) { |
56 | R.setSourceMgr(context.getSourceManager(), context.getLangOpts()); |
57 | } |
58 | |
59 | void HTMLPrinter::HandleTranslationUnit(ASTContext &Ctx) { |
60 | if (PP.getDiagnostics().hasErrorOccurred()) |
61 | return; |
62 | |
63 | |
64 | FileID FID = R.getSourceMgr().getMainFileID(); |
65 | const FileEntry* Entry = R.getSourceMgr().getFileEntryForID(FID); |
66 | StringRef Name; |
67 | |
68 | |
69 | |
70 | if (Entry) |
71 | Name = Entry->getName(); |
72 | else |
73 | Name = R.getSourceMgr().getBuffer(FID)->getBufferIdentifier(); |
74 | |
75 | html::AddLineNumbers(R, FID); |
76 | html::AddHeaderFooterInternalBuiltinCSS(R, FID, Name); |
77 | |
78 | |
79 | |
80 | |
81 | |
82 | if (SyntaxHighlight) html::SyntaxHighlight(R, FID, PP); |
83 | if (HighlightMacros) html::HighlightMacros(R, FID, PP); |
84 | html::EscapeText(R, FID, false, true); |
85 | |
86 | |
87 | const RewriteBuffer &RewriteBuf = R.getEditBuffer(FID); |
88 | std::unique_ptr<char[]> Buffer(new char[RewriteBuf.size()]); |
89 | std::copy(RewriteBuf.begin(), RewriteBuf.end(), Buffer.get()); |
90 | Out->write(Buffer.get(), RewriteBuf.size()); |
91 | } |
92 | |