HTMLRewrite.cpp 16 KB

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