HTMLRewrite.cpp 19 KB

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