clang API Documentation

HTMLRewrite.cpp
Go to the documentation of this file.
00001 //== HTMLRewrite.cpp - Translate source code into prettified HTML --*- C++ -*-//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the HTMLRewriter class, which is used to translate the
00011 //  text of a source file into prettified HTML.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Rewrite/Core/HTMLRewrite.h"
00016 #include "clang/Basic/SourceManager.h"
00017 #include "clang/Lex/Preprocessor.h"
00018 #include "clang/Lex/TokenConcatenation.h"
00019 #include "clang/Rewrite/Core/Rewriter.h"
00020 #include "llvm/ADT/SmallString.h"
00021 #include "llvm/Support/ErrorHandling.h"
00022 #include "llvm/Support/MemoryBuffer.h"
00023 #include "llvm/Support/raw_ostream.h"
00024 #include <memory>
00025 using namespace clang;
00026 
00027 
00028 /// HighlightRange - Highlight a range in the source code with the specified
00029 /// start/end tags.  B/E must be in the same file.  This ensures that
00030 /// start/end tags are placed at the start/end of each line if the range is
00031 /// multiline.
00032 void html::HighlightRange(Rewriter &R, SourceLocation B, SourceLocation E,
00033                           const char *StartTag, const char *EndTag) {
00034   SourceManager &SM = R.getSourceMgr();
00035   B = SM.getExpansionLoc(B);
00036   E = SM.getExpansionLoc(E);
00037   FileID FID = SM.getFileID(B);
00038   assert(SM.getFileID(E) == FID && "B/E not in the same file!");
00039 
00040   unsigned BOffset = SM.getFileOffset(B);
00041   unsigned EOffset = SM.getFileOffset(E);
00042 
00043   // Include the whole end token in the range.
00044   EOffset += Lexer::MeasureTokenLength(E, R.getSourceMgr(), R.getLangOpts());
00045 
00046   bool Invalid = false;
00047   const char *BufferStart = SM.getBufferData(FID, &Invalid).data();
00048   if (Invalid)
00049     return;
00050   
00051   HighlightRange(R.getEditBuffer(FID), BOffset, EOffset,
00052                  BufferStart, StartTag, EndTag);
00053 }
00054 
00055 /// HighlightRange - This is the same as the above method, but takes
00056 /// decomposed file locations.
00057 void html::HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E,
00058                           const char *BufferStart,
00059                           const char *StartTag, const char *EndTag) {
00060   // Insert the tag at the absolute start/end of the range.
00061   RB.InsertTextAfter(B, StartTag);
00062   RB.InsertTextBefore(E, EndTag);
00063 
00064   // Scan the range to see if there is a \r or \n.  If so, and if the line is
00065   // not blank, insert tags on that line as well.
00066   bool HadOpenTag = true;
00067 
00068   unsigned LastNonWhiteSpace = B;
00069   for (unsigned i = B; i != E; ++i) {
00070     switch (BufferStart[i]) {
00071     case '\r':
00072     case '\n':
00073       // Okay, we found a newline in the range.  If we have an open tag, we need
00074       // to insert a close tag at the first non-whitespace before the newline.
00075       if (HadOpenTag)
00076         RB.InsertTextBefore(LastNonWhiteSpace+1, EndTag);
00077 
00078       // Instead of inserting an open tag immediately after the newline, we
00079       // wait until we see a non-whitespace character.  This prevents us from
00080       // inserting tags around blank lines, and also allows the open tag to
00081       // be put *after* whitespace on a non-blank line.
00082       HadOpenTag = false;
00083       break;
00084     case '\0':
00085     case ' ':
00086     case '\t':
00087     case '\f':
00088     case '\v':
00089       // Ignore whitespace.
00090       break;
00091 
00092     default:
00093       // If there is no tag open, do it now.
00094       if (!HadOpenTag) {
00095         RB.InsertTextAfter(i, StartTag);
00096         HadOpenTag = true;
00097       }
00098 
00099       // Remember this character.
00100       LastNonWhiteSpace = i;
00101       break;
00102     }
00103   }
00104 }
00105 
00106 void html::EscapeText(Rewriter &R, FileID FID,
00107                       bool EscapeSpaces, bool ReplaceTabs) {
00108 
00109   const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
00110   const char* C = Buf->getBufferStart();
00111   const char* FileEnd = Buf->getBufferEnd();
00112 
00113   assert (C <= FileEnd);
00114 
00115   RewriteBuffer &RB = R.getEditBuffer(FID);
00116 
00117   unsigned ColNo = 0;
00118   for (unsigned FilePos = 0; C != FileEnd ; ++C, ++FilePos) {
00119     switch (*C) {
00120     default: ++ColNo; break;
00121     case '\n':
00122     case '\r':
00123       ColNo = 0;
00124       break;
00125 
00126     case ' ':
00127       if (EscapeSpaces)
00128         RB.ReplaceText(FilePos, 1, "&nbsp;");
00129       ++ColNo;
00130       break;
00131     case '\f':
00132       RB.ReplaceText(FilePos, 1, "<hr>");
00133       ColNo = 0;
00134       break;
00135 
00136     case '\t': {
00137       if (!ReplaceTabs)
00138         break;
00139       unsigned NumSpaces = 8-(ColNo&7);
00140       if (EscapeSpaces)
00141         RB.ReplaceText(FilePos, 1,
00142                        StringRef("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
00143                                        "&nbsp;&nbsp;&nbsp;", 6*NumSpaces));
00144       else
00145         RB.ReplaceText(FilePos, 1, StringRef("        ", NumSpaces));
00146       ColNo += NumSpaces;
00147       break;
00148     }
00149     case '<':
00150       RB.ReplaceText(FilePos, 1, "&lt;");
00151       ++ColNo;
00152       break;
00153 
00154     case '>':
00155       RB.ReplaceText(FilePos, 1, "&gt;");
00156       ++ColNo;
00157       break;
00158 
00159     case '&':
00160       RB.ReplaceText(FilePos, 1, "&amp;");
00161       ++ColNo;
00162       break;
00163     }
00164   }
00165 }
00166 
00167 std::string html::EscapeText(StringRef s, bool EscapeSpaces, bool ReplaceTabs) {
00168 
00169   unsigned len = s.size();
00170   std::string Str;
00171   llvm::raw_string_ostream os(Str);
00172 
00173   for (unsigned i = 0 ; i < len; ++i) {
00174 
00175     char c = s[i];
00176     switch (c) {
00177     default:
00178       os << c; break;
00179 
00180     case ' ':
00181       if (EscapeSpaces) os << "&nbsp;";
00182       else os << ' ';
00183       break;
00184 
00185     case '\t':
00186       if (ReplaceTabs) {
00187         if (EscapeSpaces)
00188           for (unsigned i = 0; i < 4; ++i)
00189             os << "&nbsp;";
00190         else
00191           for (unsigned i = 0; i < 4; ++i)
00192             os << " ";
00193       }
00194       else
00195         os << c;
00196 
00197       break;
00198 
00199     case '<': os << "&lt;"; break;
00200     case '>': os << "&gt;"; break;
00201     case '&': os << "&amp;"; break;
00202     }
00203   }
00204 
00205   return os.str();
00206 }
00207 
00208 static void AddLineNumber(RewriteBuffer &RB, unsigned LineNo,
00209                           unsigned B, unsigned E) {
00210   SmallString<256> Str;
00211   llvm::raw_svector_ostream OS(Str);
00212 
00213   OS << "<tr><td class=\"num\" id=\"LN"
00214      << LineNo << "\">"
00215      << LineNo << "</td><td class=\"line\">";
00216 
00217   if (B == E) { // Handle empty lines.
00218     OS << " </td></tr>";
00219     RB.InsertTextBefore(B, OS.str());
00220   } else {
00221     RB.InsertTextBefore(B, OS.str());
00222     RB.InsertTextBefore(E, "</td></tr>");
00223   }
00224 }
00225 
00226 void html::AddLineNumbers(Rewriter& R, FileID FID) {
00227 
00228   const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
00229   const char* FileBeg = Buf->getBufferStart();
00230   const char* FileEnd = Buf->getBufferEnd();
00231   const char* C = FileBeg;
00232   RewriteBuffer &RB = R.getEditBuffer(FID);
00233 
00234   assert (C <= FileEnd);
00235 
00236   unsigned LineNo = 0;
00237   unsigned FilePos = 0;
00238 
00239   while (C != FileEnd) {
00240 
00241     ++LineNo;
00242     unsigned LineStartPos = FilePos;
00243     unsigned LineEndPos = FileEnd - FileBeg;
00244 
00245     assert (FilePos <= LineEndPos);
00246     assert (C < FileEnd);
00247 
00248     // Scan until the newline (or end-of-file).
00249 
00250     while (C != FileEnd) {
00251       char c = *C;
00252       ++C;
00253 
00254       if (c == '\n') {
00255         LineEndPos = FilePos++;
00256         break;
00257       }
00258 
00259       ++FilePos;
00260     }
00261 
00262     AddLineNumber(RB, LineNo, LineStartPos, LineEndPos);
00263   }
00264 
00265   // Add one big table tag that surrounds all of the code.
00266   RB.InsertTextBefore(0, "<table class=\"code\">\n");
00267   RB.InsertTextAfter(FileEnd - FileBeg, "</table>");
00268 }
00269 
00270 void html::AddHeaderFooterInternalBuiltinCSS(Rewriter& R, FileID FID,
00271                                              const char *title) {
00272 
00273   const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
00274   const char* FileStart = Buf->getBufferStart();
00275   const char* FileEnd = Buf->getBufferEnd();
00276 
00277   SourceLocation StartLoc = R.getSourceMgr().getLocForStartOfFile(FID);
00278   SourceLocation EndLoc = StartLoc.getLocWithOffset(FileEnd-FileStart);
00279 
00280   std::string s;
00281   llvm::raw_string_ostream os(s);
00282   os << "<!doctype html>\n" // Use HTML 5 doctype
00283         "<html>\n<head>\n";
00284 
00285   if (title)
00286     os << "<title>" << html::EscapeText(title) << "</title>\n";
00287 
00288   os << "<style type=\"text/css\">\n"
00289       " body { color:#000000; background-color:#ffffff }\n"
00290       " body { font-family:Helvetica, sans-serif; font-size:10pt }\n"
00291       " h1 { font-size:14pt }\n"
00292       " .code { border-collapse:collapse; width:100%; }\n"
00293       " .code { font-family: \"Monospace\", monospace; font-size:10pt }\n"
00294       " .code { line-height: 1.2em }\n"
00295       " .comment { color: green; font-style: oblique }\n"
00296       " .keyword { color: blue }\n"
00297       " .string_literal { color: red }\n"
00298       " .directive { color: darkmagenta }\n"
00299       // Macro expansions.
00300       " .expansion { display: none; }\n"
00301       " .macro:hover .expansion { display: block; border: 2px solid #FF0000; "
00302           "padding: 2px; background-color:#FFF0F0; font-weight: normal; "
00303           "  -webkit-border-radius:5px;  -webkit-box-shadow:1px 1px 7px #000; "
00304           "position: absolute; top: -1em; left:10em; z-index: 1 } \n"
00305       " .macro { color: darkmagenta; background-color:LemonChiffon;"
00306              // Macros are position: relative to provide base for expansions.
00307              " position: relative }\n"
00308       " .num { width:2.5em; padding-right:2ex; background-color:#eeeeee }\n"
00309       " .num { text-align:right; font-size:8pt }\n"
00310       " .num { color:#444444 }\n"
00311       " .line { padding-left: 1ex; border-left: 3px solid #ccc }\n"
00312       " .line { white-space: pre }\n"
00313       " .msg { -webkit-box-shadow:1px 1px 7px #000 }\n"
00314       " .msg { -webkit-border-radius:5px }\n"
00315       " .msg { font-family:Helvetica, sans-serif; font-size:8pt }\n"
00316       " .msg { float:left }\n"
00317       " .msg { padding:0.25em 1ex 0.25em 1ex }\n"
00318       " .msg { margin-top:10px; margin-bottom:10px }\n"
00319       " .msg { font-weight:bold }\n"
00320       " .msg { max-width:60em; word-wrap: break-word; white-space: pre-wrap }\n"
00321       " .msgT { padding:0x; spacing:0x }\n"
00322       " .msgEvent { background-color:#fff8b4; color:#000000 }\n"
00323       " .msgControl { background-color:#bbbbbb; color:#000000 }\n"
00324       " .mrange { background-color:#dfddf3 }\n"
00325       " .mrange { border-bottom:1px solid #6F9DBE }\n"
00326       " .PathIndex { font-weight: bold; padding:0px 5px; "
00327         "margin-right:5px; }\n"
00328       " .PathIndex { -webkit-border-radius:8px }\n"
00329       " .PathIndexEvent { background-color:#bfba87 }\n"
00330       " .PathIndexControl { background-color:#8c8c8c }\n"
00331       " .PathNav a { text-decoration:none; font-size: larger }\n"
00332       " .CodeInsertionHint { font-weight: bold; background-color: #10dd10 }\n"
00333       " .CodeRemovalHint { background-color:#de1010 }\n"
00334       " .CodeRemovalHint { border-bottom:1px solid #6F9DBE }\n"
00335       " table.simpletable {\n"
00336       "   padding: 5px;\n"
00337       "   font-size:12pt;\n"
00338       "   margin:20px;\n"
00339       "   border-collapse: collapse; border-spacing: 0px;\n"
00340       " }\n"
00341       " td.rowname {\n"
00342       "   text-align:right; font-weight:bold; color:#444444;\n"
00343       "   padding-right:2ex; }\n"
00344       "</style>\n</head>\n<body>";
00345 
00346   // Generate header
00347   R.InsertTextBefore(StartLoc, os.str());
00348   // Generate footer
00349 
00350   R.InsertTextAfter(EndLoc, "</body></html>\n");
00351 }
00352 
00353 /// SyntaxHighlight - Relex the specified FileID and annotate the HTML with
00354 /// information about keywords, macro expansions etc.  This uses the macro
00355 /// table state from the end of the file, so it won't be perfectly perfect,
00356 /// but it will be reasonably close.
00357 void html::SyntaxHighlight(Rewriter &R, FileID FID, const Preprocessor &PP) {
00358   RewriteBuffer &RB = R.getEditBuffer(FID);
00359 
00360   const SourceManager &SM = PP.getSourceManager();
00361   const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
00362   Lexer L(FID, FromFile, SM, PP.getLangOpts());
00363   const char *BufferStart = L.getBuffer().data();
00364 
00365   // Inform the preprocessor that we want to retain comments as tokens, so we
00366   // can highlight them.
00367   L.SetCommentRetentionState(true);
00368 
00369   // Lex all the tokens in raw mode, to avoid entering #includes or expanding
00370   // macros.
00371   Token Tok;
00372   L.LexFromRawLexer(Tok);
00373 
00374   while (Tok.isNot(tok::eof)) {
00375     // Since we are lexing unexpanded tokens, all tokens are from the main
00376     // FileID.
00377     unsigned TokOffs = SM.getFileOffset(Tok.getLocation());
00378     unsigned TokLen = Tok.getLength();
00379     switch (Tok.getKind()) {
00380     default: break;
00381     case tok::identifier:
00382       llvm_unreachable("tok::identifier in raw lexing mode!");
00383     case tok::raw_identifier: {
00384       // Fill in Result.IdentifierInfo and update the token kind,
00385       // looking up the identifier in the identifier table.
00386       PP.LookUpIdentifierInfo(Tok);
00387 
00388       // If this is a pp-identifier, for a keyword, highlight it as such.
00389       if (Tok.isNot(tok::identifier))
00390         HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
00391                        "<span class='keyword'>", "</span>");
00392       break;
00393     }
00394     case tok::comment:
00395       HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
00396                      "<span class='comment'>", "</span>");
00397       break;
00398     case tok::utf8_string_literal:
00399       // Chop off the u part of u8 prefix
00400       ++TokOffs;
00401       --TokLen;
00402       // FALL THROUGH to chop the 8
00403     case tok::wide_string_literal:
00404     case tok::utf16_string_literal:
00405     case tok::utf32_string_literal:
00406       // Chop off the L, u, U or 8 prefix
00407       ++TokOffs;
00408       --TokLen;
00409       // FALL THROUGH.
00410     case tok::string_literal:
00411       // FIXME: Exclude the optional ud-suffix from the highlighted range.
00412       HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
00413                      "<span class='string_literal'>", "</span>");
00414       break;
00415     case tok::hash: {
00416       // If this is a preprocessor directive, all tokens to end of line are too.
00417       if (!Tok.isAtStartOfLine())
00418         break;
00419 
00420       // Eat all of the tokens until we get to the next one at the start of
00421       // line.
00422       unsigned TokEnd = TokOffs+TokLen;
00423       L.LexFromRawLexer(Tok);
00424       while (!Tok.isAtStartOfLine() && Tok.isNot(tok::eof)) {
00425         TokEnd = SM.getFileOffset(Tok.getLocation())+Tok.getLength();
00426         L.LexFromRawLexer(Tok);
00427       }
00428 
00429       // Find end of line.  This is a hack.
00430       HighlightRange(RB, TokOffs, TokEnd, BufferStart,
00431                      "<span class='directive'>", "</span>");
00432 
00433       // Don't skip the next token.
00434       continue;
00435     }
00436     }
00437 
00438     L.LexFromRawLexer(Tok);
00439   }
00440 }
00441 
00442 /// HighlightMacros - This uses the macro table state from the end of the
00443 /// file, to re-expand macros and insert (into the HTML) information about the
00444 /// macro expansions.  This won't be perfectly perfect, but it will be
00445 /// reasonably close.
00446 void html::HighlightMacros(Rewriter &R, FileID FID, const Preprocessor& PP) {
00447   // Re-lex the raw token stream into a token buffer.
00448   const SourceManager &SM = PP.getSourceManager();
00449   std::vector<Token> TokenStream;
00450 
00451   const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
00452   Lexer L(FID, FromFile, SM, PP.getLangOpts());
00453 
00454   // Lex all the tokens in raw mode, to avoid entering #includes or expanding
00455   // macros.
00456   while (1) {
00457     Token Tok;
00458     L.LexFromRawLexer(Tok);
00459 
00460     // If this is a # at the start of a line, discard it from the token stream.
00461     // We don't want the re-preprocess step to see #defines, #includes or other
00462     // preprocessor directives.
00463     if (Tok.is(tok::hash) && Tok.isAtStartOfLine())
00464       continue;
00465 
00466     // If this is a ## token, change its kind to unknown so that repreprocessing
00467     // it will not produce an error.
00468     if (Tok.is(tok::hashhash))
00469       Tok.setKind(tok::unknown);
00470 
00471     // If this raw token is an identifier, the raw lexer won't have looked up
00472     // the corresponding identifier info for it.  Do this now so that it will be
00473     // macro expanded when we re-preprocess it.
00474     if (Tok.is(tok::raw_identifier))
00475       PP.LookUpIdentifierInfo(Tok);
00476 
00477     TokenStream.push_back(Tok);
00478 
00479     if (Tok.is(tok::eof)) break;
00480   }
00481 
00482   // Temporarily change the diagnostics object so that we ignore any generated
00483   // diagnostics from this pass.
00484   DiagnosticsEngine TmpDiags(PP.getDiagnostics().getDiagnosticIDs(),
00485                              &PP.getDiagnostics().getDiagnosticOptions(),
00486                       new IgnoringDiagConsumer);
00487 
00488   // FIXME: This is a huge hack; we reuse the input preprocessor because we want
00489   // its state, but we aren't actually changing it (we hope). This should really
00490   // construct a copy of the preprocessor.
00491   Preprocessor &TmpPP = const_cast<Preprocessor&>(PP);
00492   DiagnosticsEngine *OldDiags = &TmpPP.getDiagnostics();
00493   TmpPP.setDiagnostics(TmpDiags);
00494 
00495   // Inform the preprocessor that we don't want comments.
00496   TmpPP.SetCommentRetentionState(false, false);
00497 
00498   // We don't want pragmas either. Although we filtered out #pragma, removing
00499   // _Pragma and __pragma is much harder.
00500   bool PragmasPreviouslyEnabled = TmpPP.getPragmasEnabled();
00501   TmpPP.setPragmasEnabled(false);
00502 
00503   // Enter the tokens we just lexed.  This will cause them to be macro expanded
00504   // but won't enter sub-files (because we removed #'s).
00505   TmpPP.EnterTokenStream(&TokenStream[0], TokenStream.size(), false, false);
00506 
00507   TokenConcatenation ConcatInfo(TmpPP);
00508 
00509   // Lex all the tokens.
00510   Token Tok;
00511   TmpPP.Lex(Tok);
00512   while (Tok.isNot(tok::eof)) {
00513     // Ignore non-macro tokens.
00514     if (!Tok.getLocation().isMacroID()) {
00515       TmpPP.Lex(Tok);
00516       continue;
00517     }
00518 
00519     // Okay, we have the first token of a macro expansion: highlight the
00520     // expansion by inserting a start tag before the macro expansion and
00521     // end tag after it.
00522     std::pair<SourceLocation, SourceLocation> LLoc =
00523       SM.getExpansionRange(Tok.getLocation());
00524 
00525     // Ignore tokens whose instantiation location was not the main file.
00526     if (SM.getFileID(LLoc.first) != FID) {
00527       TmpPP.Lex(Tok);
00528       continue;
00529     }
00530 
00531     assert(SM.getFileID(LLoc.second) == FID &&
00532            "Start and end of expansion must be in the same ultimate file!");
00533 
00534     std::string Expansion = EscapeText(TmpPP.getSpelling(Tok));
00535     unsigned LineLen = Expansion.size();
00536 
00537     Token PrevPrevTok;
00538     Token PrevTok = Tok;
00539     // Okay, eat this token, getting the next one.
00540     TmpPP.Lex(Tok);
00541 
00542     // Skip all the rest of the tokens that are part of this macro
00543     // instantiation.  It would be really nice to pop up a window with all the
00544     // spelling of the tokens or something.
00545     while (!Tok.is(tok::eof) &&
00546            SM.getExpansionLoc(Tok.getLocation()) == LLoc.first) {
00547       // Insert a newline if the macro expansion is getting large.
00548       if (LineLen > 60) {
00549         Expansion += "<br>";
00550         LineLen = 0;
00551       }
00552 
00553       LineLen -= Expansion.size();
00554 
00555       // If the tokens were already space separated, or if they must be to avoid
00556       // them being implicitly pasted, add a space between them.
00557       if (Tok.hasLeadingSpace() ||
00558           ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok))
00559         Expansion += ' ';
00560 
00561       // Escape any special characters in the token text.
00562       Expansion += EscapeText(TmpPP.getSpelling(Tok));
00563       LineLen += Expansion.size();
00564 
00565       PrevPrevTok = PrevTok;
00566       PrevTok = Tok;
00567       TmpPP.Lex(Tok);
00568     }
00569 
00570 
00571     // Insert the expansion as the end tag, so that multi-line macros all get
00572     // highlighted.
00573     Expansion = "<span class='expansion'>" + Expansion + "</span></span>";
00574 
00575     HighlightRange(R, LLoc.first, LLoc.second,
00576                    "<span class='macro'>", Expansion.c_str());
00577   }
00578 
00579   // Restore the preprocessor's old state.
00580   TmpPP.setDiagnostics(*OldDiags);
00581   TmpPP.setPragmasEnabled(PragmasPreviouslyEnabled);
00582 }