HTMLRewrite.cpp 18 KB

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