HTMLRewrite.cpp 19 KB

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