HTMLRewrite.cpp 19 KB

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