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