HTMLRewrite.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. //== HTMLRewrite.cpp - Translate source code into prettified HTML --*- C++ -*-//
  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 file defines the HTMLRewriter clas, which is used to translate the
  11. // text of a source file into prettified HTML.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Rewrite/Rewriter.h"
  15. #include "clang/Rewrite/HTMLRewrite.h"
  16. #include "clang/Lex/Preprocessor.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/Support/MemoryBuffer.h"
  20. #include <sstream>
  21. using namespace clang;
  22. /// HighlightRange - Highlight a range in the source code with the specified
  23. /// start/end tags. B/E must be in the same file. This ensures that
  24. /// start/end tags are placed at the start/end of each line if the range is
  25. /// multiline.
  26. void html::HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E,
  27. const char *StartTag, const char *EndTag) {
  28. SourceManager &SM = R.getSourceMgr();
  29. B = SM.getLogicalLoc(B);
  30. E = SM.getLogicalLoc(E);
  31. unsigned FileID = SM.getCanonicalFileID(B);
  32. assert(SM.getCanonicalFileID(E) == FileID && "B/E not in the same file!");
  33. unsigned BOffset = SM.getFullFilePos(B);
  34. unsigned EOffset = SM.getFullFilePos(E);
  35. // Include the whole end token in the range.
  36. EOffset += Lexer::MeasureTokenLength(E, R.getSourceMgr());
  37. HighlightRange(R.getEditBuffer(FileID), BOffset, EOffset,
  38. SM.getBufferData(FileID).first, StartTag, EndTag);
  39. }
  40. /// HighlightRange - This is the same as the above method, but takes
  41. /// decomposed file locations.
  42. void html::HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E,
  43. const char *BufferStart,
  44. const char *StartTag, const char *EndTag) {
  45. // Insert the tag at the absolute start/end of the range.
  46. RB.InsertTextAfter(B, StartTag, strlen(StartTag));
  47. RB.InsertTextBefore(E, EndTag, strlen(EndTag));
  48. // Scan the range to see if there is a \r or \n. If so, and if the line is
  49. // not blank, insert tags on that line as well.
  50. bool HadOpenTag = true;
  51. unsigned LastNonWhiteSpace = B;
  52. for (unsigned i = B; i != E; ++i) {
  53. switch (BufferStart[i]) {
  54. case '\r':
  55. case '\n':
  56. // Okay, we found a newline in the range. If we have an open tag, we need
  57. // to insert a close tag at the first non-whitespace before the newline.
  58. if (HadOpenTag)
  59. RB.InsertTextBefore(LastNonWhiteSpace+1, EndTag, strlen(EndTag));
  60. // Instead of inserting an open tag immediately after the newline, we
  61. // wait until we see a non-whitespace character. This prevents us from
  62. // inserting tags around blank lines, and also allows the open tag to
  63. // be put *after* whitespace on a non-blank line.
  64. HadOpenTag = false;
  65. break;
  66. case '\0':
  67. case ' ':
  68. case '\t':
  69. case '\f':
  70. case '\v':
  71. // Ignore whitespace.
  72. break;
  73. default:
  74. // If there is no tag open, do it now.
  75. if (!HadOpenTag) {
  76. RB.InsertTextAfter(i, StartTag, strlen(StartTag));
  77. HadOpenTag = true;
  78. }
  79. // Remember this character.
  80. LastNonWhiteSpace = i;
  81. break;
  82. }
  83. }
  84. }
  85. void html::EscapeText(Rewriter& R, unsigned FileID,
  86. bool EscapeSpaces, bool ReplaceTabs) {
  87. const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID);
  88. const char* C = Buf->getBufferStart();
  89. const char* FileEnd = Buf->getBufferEnd();
  90. assert (C <= FileEnd);
  91. RewriteBuffer &RB = R.getEditBuffer(FileID);
  92. for (unsigned FilePos = 0; C != FileEnd ; ++C, ++FilePos) {
  93. switch (*C) {
  94. default: break;
  95. case ' ':
  96. if (EscapeSpaces)
  97. RB.ReplaceText(FilePos, 1, "&nbsp;", 6);
  98. break;
  99. case '\t':
  100. if (!ReplaceTabs)
  101. break;
  102. if (EscapeSpaces)
  103. RB.ReplaceText(FilePos, 1, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", 6*8);
  104. else
  105. RB.ReplaceText(FilePos, 1, " ", 8);
  106. break;
  107. case '<':
  108. RB.ReplaceText(FilePos, 1, "&lt;", 4);
  109. break;
  110. case '>':
  111. RB.ReplaceText(FilePos, 1, "&gt;", 4);
  112. break;
  113. case '&':
  114. RB.ReplaceText(FilePos, 1, "&amp;", 5);
  115. break;
  116. }
  117. }
  118. }
  119. std::string html::EscapeText(const std::string& s, bool EscapeSpaces,
  120. bool ReplaceTabs) {
  121. unsigned len = s.size();
  122. std::ostringstream os;
  123. for (unsigned i = 0 ; i < len; ++i) {
  124. char c = s[i];
  125. switch (c) {
  126. default:
  127. os << c; break;
  128. case ' ':
  129. if (EscapeSpaces) os << "&nbsp;";
  130. else os << ' ';
  131. break;
  132. case '\t':
  133. if (ReplaceTabs)
  134. for (unsigned i = 0; i < 4; ++i)
  135. os << "&nbsp;";
  136. else
  137. os << c;
  138. break;
  139. case '<': os << "&lt;"; break;
  140. case '>': os << "&gt;"; break;
  141. case '&': os << "&amp;"; break;
  142. }
  143. }
  144. return os.str();
  145. }
  146. static void AddLineNumber(RewriteBuffer &RB, unsigned LineNo,
  147. unsigned B, unsigned E) {
  148. llvm::SmallString<100> Str;
  149. Str += "<tr><td class=\"num\" id=\"LN";
  150. Str.append_uint(LineNo);
  151. Str += "\">";
  152. Str.append_uint(LineNo);
  153. Str += "</td><td class=\"line\">";
  154. if (B == E) { // Handle empty lines.
  155. Str += " </td></tr>";
  156. RB.InsertTextBefore(B, &Str[0], Str.size());
  157. } else {
  158. RB.InsertTextBefore(B, &Str[0], Str.size());
  159. RB.InsertTextBefore(E, "</td></tr>", strlen("</td></tr>"));
  160. }
  161. }
  162. void html::AddLineNumbers(Rewriter& R, unsigned FileID) {
  163. const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID);
  164. const char* FileBeg = Buf->getBufferStart();
  165. const char* FileEnd = Buf->getBufferEnd();
  166. const char* C = FileBeg;
  167. RewriteBuffer &RB = R.getEditBuffer(FileID);
  168. assert (C <= FileEnd);
  169. unsigned LineNo = 0;
  170. unsigned FilePos = 0;
  171. while (C != FileEnd) {
  172. ++LineNo;
  173. unsigned LineStartPos = FilePos;
  174. unsigned LineEndPos = FileEnd - FileBeg;
  175. assert (FilePos <= LineEndPos);
  176. assert (C < FileEnd);
  177. // Scan until the newline (or end-of-file).
  178. while (C != FileEnd) {
  179. char c = *C;
  180. ++C;
  181. if (c == '\n') {
  182. LineEndPos = FilePos++;
  183. break;
  184. }
  185. ++FilePos;
  186. }
  187. AddLineNumber(RB, LineNo, LineStartPos, LineEndPos);
  188. }
  189. // Add one big table tag that surrounds all of the code.
  190. RB.InsertTextBefore(0, "<table class=\"code\">\n",
  191. strlen("<table class=\"code\">\n"));
  192. RB.InsertTextAfter(FileEnd - FileBeg, "</table>", strlen("</table>"));
  193. }
  194. void html::AddHeaderFooterInternalBuiltinCSS(Rewriter& R, unsigned FileID) {
  195. const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FileID);
  196. const char* FileStart = Buf->getBufferStart();
  197. const char* FileEnd = Buf->getBufferEnd();
  198. SourceLocation StartLoc = SourceLocation::getFileLoc(FileID, 0);
  199. SourceLocation EndLoc = SourceLocation::getFileLoc(FileID, FileEnd-FileStart);
  200. // Generate header
  201. R.InsertCStrBefore(StartLoc,
  202. "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" "
  203. "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
  204. "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n"
  205. "<style type=\"text/css\">\n"
  206. " body { color:#000000; background-color:#ffffff }\n"
  207. " body { font-family:Helvetica, sans-serif; font-size:10pt }\n"
  208. " h1 { font-size:14pt }\n"
  209. " .code { border-spacing:0px; width:100%; }\n"
  210. " .code { font-family: \"Andale Mono\", monospace; font-size:10pt }\n"
  211. " .code { line-height: 1.2em }\n"
  212. " .comment { color: #A0A0A0; font-style: oblique }\n"
  213. " .keyword { color: #FF00FF }\n"
  214. " .directive { color: #00A000 }\n"
  215. // Macro expansions.
  216. " .expansion { display: none; }\n"
  217. " .macro:hover .expansion { display: block; border: 2px solid #FF0000; "
  218. "padding: 2px; background-color:#FFF0F0;"
  219. " -webkit-border-radius:5px; -webkit-box-shadow:1px 1px 7px #000; "
  220. "position: absolute; top: -1em; left:10em } \n"
  221. " .macro { color: #FF0000; background-color:#FFC0C0;"
  222. // Macros are position: relative to provide base for expansions.
  223. " position: relative }\n"
  224. " .num { width:2.5em; padding-right:2ex; background-color:#eeeeee }\n"
  225. " .num { text-align:right; font-size: smaller }\n"
  226. " .num { color:#444444 }\n"
  227. " .line { padding-left: 1ex; border-left: 3px solid #ccc }\n"
  228. " .line { white-space: pre }\n"
  229. " .msg { background-color:#fff8b4; color:#000000 }\n"
  230. " .msg { -webkit-box-shadow:1px 1px 7px #000 }\n"
  231. " .msg { -webkit-border-radius:5px }\n"
  232. " .msg { font-family:Helvetica, sans-serif; font-size: smaller }\n"
  233. " .msg { font-weight: bold }\n"
  234. " .msg { float:left }\n"
  235. " .msg { padding:0.5em 1ex 0.5em 1ex }\n"
  236. " .msg { margin-top:10px; margin-bottom:10px }\n"
  237. " .mrange { background-color:#dfddf3 }\n"
  238. " .mrange { border-bottom:1px solid #6F9DBE }\n"
  239. " .PathIndex { font-weight: bold }\n"
  240. " table.simpletable {\n"
  241. " padding: 5px;\n"
  242. " font-size:12pt;\n"
  243. " margin:20px;\n"
  244. " border-collapse: collapse; border-spacing: 0px;\n"
  245. " }\n"
  246. " td.rowname {\n"
  247. " text-align:right; font-weight:bold; color:#444444;\n"
  248. " padding-right:2ex; }\n"
  249. "</style>\n</head>\n<body>");
  250. // Generate footer
  251. R.InsertCStrAfter(EndLoc, "</body></html>\n");
  252. }
  253. /// SyntaxHighlight - Relex the specified FileID and annotate the HTML with
  254. /// information about keywords, macro expansions etc. This uses the macro
  255. /// table state from the end of the file, so it won't be perfectly perfect,
  256. /// but it will be reasonably close.
  257. void html::SyntaxHighlight(Rewriter &R, unsigned FileID, Preprocessor &PP) {
  258. RewriteBuffer &RB = R.getEditBuffer(FileID);
  259. const SourceManager &SourceMgr = PP.getSourceManager();
  260. std::pair<const char*, const char*> File = SourceMgr.getBufferData(FileID);
  261. const char *BufferStart = File.first;
  262. Lexer L(SourceLocation::getFileLoc(FileID, 0), PP.getLangOptions(),
  263. File.first, File.second);
  264. // Inform the preprocessor that we want to retain comments as tokens, so we
  265. // can highlight them.
  266. L.SetCommentRetentionState(true);
  267. // Lex all the tokens in raw mode, to avoid entering #includes or expanding
  268. // macros.
  269. Token Tok;
  270. L.LexRawToken(Tok);
  271. while (Tok.isNot(tok::eof)) {
  272. // Since we are lexing unexpanded tokens, all tokens are from the main
  273. // FileID.
  274. unsigned TokOffs = SourceMgr.getFullFilePos(Tok.getLocation());
  275. unsigned TokLen = Tok.getLength();
  276. switch (Tok.getKind()) {
  277. default: break;
  278. case tok::identifier: {
  279. // Fill in Result.IdentifierInfo, looking up the identifier in the
  280. // identifier table.
  281. IdentifierInfo *II = PP.LookUpIdentifierInfo(Tok, BufferStart+TokOffs);
  282. // If this is a pp-identifier, for a keyword, highlight it as such.
  283. if (II->getTokenID() != tok::identifier)
  284. HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
  285. "<span class='keyword'>", "</span>");
  286. break;
  287. }
  288. case tok::comment:
  289. HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
  290. "<span class='comment'>", "</span>");
  291. break;
  292. case tok::hash: {
  293. // If this is a preprocessor directive, all tokens to end of line are too.
  294. if (!Tok.isAtStartOfLine())
  295. break;
  296. // Eat all of the tokens until we get to the next one at the start of
  297. // line.
  298. unsigned TokEnd = TokOffs+TokLen;
  299. L.LexRawToken(Tok);
  300. while (!Tok.isAtStartOfLine() && Tok.isNot(tok::eof)) {
  301. TokEnd = SourceMgr.getFullFilePos(Tok.getLocation())+Tok.getLength();
  302. L.LexRawToken(Tok);
  303. }
  304. // Find end of line. This is a hack.
  305. HighlightRange(RB, TokOffs, TokEnd, BufferStart,
  306. "<span class='directive'>", "</span>");
  307. // Don't skip the next token.
  308. continue;
  309. }
  310. }
  311. L.LexRawToken(Tok);
  312. }
  313. }
  314. /// HighlightMacros - This uses the macro table state from the end of the
  315. /// file, to reexpand macros and insert (into the HTML) information about the
  316. /// macro expansions. This won't be perfectly perfect, but it will be
  317. /// reasonably close.
  318. void html::HighlightMacros(Rewriter &R, unsigned FileID, Preprocessor &PP) {
  319. RewriteBuffer &RB = R.getEditBuffer(FileID);
  320. // Inform the preprocessor that we don't want comments.
  321. PP.SetCommentRetentionState(false, false);
  322. // Start parsing the specified input file.
  323. PP.EnterMainSourceFile();
  324. // Lex all the tokens.
  325. const SourceManager &SourceMgr = PP.getSourceManager();
  326. Token Tok;
  327. PP.Lex(Tok);
  328. while (Tok.isNot(tok::eof)) {
  329. // Ignore non-macro tokens.
  330. if (!Tok.getLocation().isMacroID()) {
  331. PP.Lex(Tok);
  332. continue;
  333. }
  334. // Ignore tokens whose logical location was not the main file.
  335. SourceLocation LLoc = SourceMgr.getLogicalLoc(Tok.getLocation());
  336. std::pair<unsigned, unsigned> LLocInfo =
  337. SourceMgr.getDecomposedFileLoc(LLoc);
  338. if (LLocInfo.first != FileID) {
  339. PP.Lex(Tok);
  340. continue;
  341. }
  342. // Okay, we have the first token of a macro expansion: highlight the
  343. // instantiation.
  344. // Get the size of current macro call itself.
  345. // FIXME: This should highlight the args of a function-like
  346. // macro, using a heuristic.
  347. unsigned TokLen = Lexer::MeasureTokenLength(LLoc, SourceMgr);
  348. unsigned TokOffs = LLocInfo.second;
  349. // Highlight the macro invocation itself.
  350. RB.InsertTextAfter(TokOffs, "<span class='macro'>",
  351. strlen("<span class='macro'>"));
  352. RB.InsertTextBefore(TokOffs+TokLen, "</span>", strlen("</span>"));
  353. std::string Expansion = PP.getSpelling(Tok);
  354. unsigned LineLen = Expansion.size();
  355. // Okay, eat this token, getting the next one.
  356. PP.Lex(Tok);
  357. // Skip all the rest of the tokens that are part of this macro
  358. // instantiation. It would be really nice to pop up a window with all the
  359. // spelling of the tokens or something.
  360. while (!Tok.is(tok::eof) &&
  361. SourceMgr.getLogicalLoc(Tok.getLocation()) == LLoc) {
  362. // Insert a newline if the macro expansion is getting large.
  363. if (LineLen > 60) {
  364. Expansion += "<br>";
  365. LineLen = 0;
  366. }
  367. LineLen -= Expansion.size();
  368. Expansion += ' ' + PP.getSpelling(Tok);
  369. LineLen += Expansion.size();
  370. PP.Lex(Tok);
  371. }
  372. // Insert the information about the expansion inside the macro span.
  373. Expansion = "<span class='expansion'>" + Expansion + "</span>";
  374. RB.InsertTextBefore(TokOffs+TokLen, Expansion.c_str(), Expansion.size());
  375. }
  376. }