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