clang API Documentation

RawCommentList.cpp
Go to the documentation of this file.
00001 //===--- RawCommentList.cpp - Processing raw comments -----------*- 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 #include "clang/AST/RawCommentList.h"
00011 #include "clang/AST/ASTContext.h"
00012 #include "clang/AST/Comment.h"
00013 #include "clang/AST/CommentBriefParser.h"
00014 #include "clang/AST/CommentCommandTraits.h"
00015 #include "clang/AST/CommentLexer.h"
00016 #include "clang/AST/CommentParser.h"
00017 #include "clang/AST/CommentSema.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 
00020 using namespace clang;
00021 
00022 namespace {
00023 /// Get comment kind and bool describing if it is a trailing comment.
00024 std::pair<RawComment::CommentKind, bool> getCommentKind(StringRef Comment,
00025                                                         bool ParseAllComments) {
00026   const size_t MinCommentLength = ParseAllComments ? 2 : 3;
00027   if ((Comment.size() < MinCommentLength) || Comment[0] != '/')
00028     return std::make_pair(RawComment::RCK_Invalid, false);
00029 
00030   RawComment::CommentKind K;
00031   if (Comment[1] == '/') {
00032     if (Comment.size() < 3)
00033       return std::make_pair(RawComment::RCK_OrdinaryBCPL, false);
00034 
00035     if (Comment[2] == '/')
00036       K = RawComment::RCK_BCPLSlash;
00037     else if (Comment[2] == '!')
00038       K = RawComment::RCK_BCPLExcl;
00039     else
00040       return std::make_pair(RawComment::RCK_OrdinaryBCPL, false);
00041   } else {
00042     assert(Comment.size() >= 4);
00043 
00044     // Comment lexer does not understand escapes in comment markers, so pretend
00045     // that this is not a comment.
00046     if (Comment[1] != '*' ||
00047         Comment[Comment.size() - 2] != '*' ||
00048         Comment[Comment.size() - 1] != '/')
00049       return std::make_pair(RawComment::RCK_Invalid, false);
00050 
00051     if (Comment[2] == '*')
00052       K = RawComment::RCK_JavaDoc;
00053     else if (Comment[2] == '!')
00054       K = RawComment::RCK_Qt;
00055     else
00056       return std::make_pair(RawComment::RCK_OrdinaryC, false);
00057   }
00058   const bool TrailingComment = (Comment.size() > 3) && (Comment[3] == '<');
00059   return std::make_pair(K, TrailingComment);
00060 }
00061 
00062 bool mergedCommentIsTrailingComment(StringRef Comment) {
00063   return (Comment.size() > 3) && (Comment[3] == '<');
00064 }
00065 } // unnamed namespace
00066 
00067 RawComment::RawComment(const SourceManager &SourceMgr, SourceRange SR,
00068                        bool Merged, bool ParseAllComments) :
00069     Range(SR), RawTextValid(false), BriefTextValid(false),
00070     IsAttached(false), IsAlmostTrailingComment(false),
00071     ParseAllComments(ParseAllComments) {
00072   // Extract raw comment text, if possible.
00073   if (SR.getBegin() == SR.getEnd() || getRawText(SourceMgr).empty()) {
00074     Kind = RCK_Invalid;
00075     return;
00076   }
00077 
00078   if (!Merged) {
00079     // Guess comment kind.
00080     std::pair<CommentKind, bool> K = getCommentKind(RawText, ParseAllComments);
00081     Kind = K.first;
00082     IsTrailingComment = K.second;
00083 
00084     IsAlmostTrailingComment = RawText.startswith("//<") ||
00085                                  RawText.startswith("/*<");
00086   } else {
00087     Kind = RCK_Merged;
00088     IsTrailingComment = mergedCommentIsTrailingComment(RawText);
00089   }
00090 }
00091 
00092 StringRef RawComment::getRawTextSlow(const SourceManager &SourceMgr) const {
00093   FileID BeginFileID;
00094   FileID EndFileID;
00095   unsigned BeginOffset;
00096   unsigned EndOffset;
00097 
00098   std::tie(BeginFileID, BeginOffset) =
00099       SourceMgr.getDecomposedLoc(Range.getBegin());
00100   std::tie(EndFileID, EndOffset) = SourceMgr.getDecomposedLoc(Range.getEnd());
00101 
00102   const unsigned Length = EndOffset - BeginOffset;
00103   if (Length < 2)
00104     return StringRef();
00105 
00106   // The comment can't begin in one file and end in another.
00107   assert(BeginFileID == EndFileID);
00108 
00109   bool Invalid = false;
00110   const char *BufferStart = SourceMgr.getBufferData(BeginFileID,
00111                                                     &Invalid).data();
00112   if (Invalid)
00113     return StringRef();
00114 
00115   return StringRef(BufferStart + BeginOffset, Length);
00116 }
00117 
00118 const char *RawComment::extractBriefText(const ASTContext &Context) const {
00119   // Make sure that RawText is valid.
00120   getRawText(Context.getSourceManager());
00121 
00122   // Since we will be copying the resulting text, all allocations made during
00123   // parsing are garbage after resulting string is formed.  Thus we can use
00124   // a separate allocator for all temporary stuff.
00125   llvm::BumpPtrAllocator Allocator;
00126 
00127   comments::Lexer L(Allocator, Context.getDiagnostics(),
00128                     Context.getCommentCommandTraits(),
00129                     Range.getBegin(),
00130                     RawText.begin(), RawText.end());
00131   comments::BriefParser P(L, Context.getCommentCommandTraits());
00132 
00133   const std::string Result = P.Parse();
00134   const unsigned BriefTextLength = Result.size();
00135   char *BriefTextPtr = new (Context) char[BriefTextLength + 1];
00136   memcpy(BriefTextPtr, Result.c_str(), BriefTextLength + 1);
00137   BriefText = BriefTextPtr;
00138   BriefTextValid = true;
00139 
00140   return BriefTextPtr;
00141 }
00142 
00143 comments::FullComment *RawComment::parse(const ASTContext &Context,
00144                                          const Preprocessor *PP,
00145                                          const Decl *D) const {
00146   // Make sure that RawText is valid.
00147   getRawText(Context.getSourceManager());
00148 
00149   comments::Lexer L(Context.getAllocator(), Context.getDiagnostics(),
00150                     Context.getCommentCommandTraits(),
00151                     getSourceRange().getBegin(),
00152                     RawText.begin(), RawText.end());
00153   comments::Sema S(Context.getAllocator(), Context.getSourceManager(),
00154                    Context.getDiagnostics(),
00155                    Context.getCommentCommandTraits(),
00156                    PP);
00157   S.setDecl(D);
00158   comments::Parser P(L, S, Context.getAllocator(), Context.getSourceManager(),
00159                      Context.getDiagnostics(),
00160                      Context.getCommentCommandTraits());
00161 
00162   return P.parseFullComment();
00163 }
00164 
00165 static bool onlyWhitespaceBetween(SourceManager &SM,
00166                                   SourceLocation Loc1, SourceLocation Loc2,
00167                                   unsigned MaxNewlinesAllowed) {
00168   std::pair<FileID, unsigned> Loc1Info = SM.getDecomposedLoc(Loc1);
00169   std::pair<FileID, unsigned> Loc2Info = SM.getDecomposedLoc(Loc2);
00170 
00171   // Question does not make sense if locations are in different files.
00172   if (Loc1Info.first != Loc2Info.first)
00173     return false;
00174 
00175   bool Invalid = false;
00176   const char *Buffer = SM.getBufferData(Loc1Info.first, &Invalid).data();
00177   if (Invalid)
00178     return false;
00179 
00180   unsigned NumNewlines = 0;
00181   assert(Loc1Info.second <= Loc2Info.second && "Loc1 after Loc2!");
00182   // Look for non-whitespace characters and remember any newlines seen.
00183   for (unsigned I = Loc1Info.second; I != Loc2Info.second; ++I) {
00184     switch (Buffer[I]) {
00185     default:
00186       return false;
00187     case ' ':
00188     case '\t':
00189     case '\f':
00190     case '\v':
00191       break;
00192     case '\r':
00193     case '\n':
00194       ++NumNewlines;
00195 
00196       // Check if we have found more than the maximum allowed number of
00197       // newlines.
00198       if (NumNewlines > MaxNewlinesAllowed)
00199         return false;
00200 
00201       // Collapse \r\n and \n\r into a single newline.
00202       if (I + 1 != Loc2Info.second &&
00203           (Buffer[I + 1] == '\n' || Buffer[I + 1] == '\r') &&
00204           Buffer[I] != Buffer[I + 1])
00205         ++I;
00206       break;
00207     }
00208   }
00209 
00210   return true;
00211 }
00212 
00213 void RawCommentList::addComment(const RawComment &RC,
00214                                 llvm::BumpPtrAllocator &Allocator) {
00215   if (RC.isInvalid())
00216     return;
00217 
00218   // Check if the comments are not in source order.
00219   while (!Comments.empty() &&
00220          !SourceMgr.isBeforeInTranslationUnit(Comments.back()->getLocStart(),
00221                                               RC.getLocStart())) {
00222     // If they are, just pop a few last comments that don't fit.
00223     // This happens if an \#include directive contains comments.
00224     Comments.pop_back();
00225   }
00226 
00227   // Ordinary comments are not interesting for us.
00228   if (RC.isOrdinary())
00229     return;
00230 
00231   // If this is the first Doxygen comment, save it (because there isn't
00232   // anything to merge it with).
00233   if (Comments.empty()) {
00234     Comments.push_back(new (Allocator) RawComment(RC));
00235     return;
00236   }
00237 
00238   const RawComment &C1 = *Comments.back();
00239   const RawComment &C2 = RC;
00240 
00241   // Merge comments only if there is only whitespace between them.
00242   // Can't merge trailing and non-trailing comments.
00243   // Merge comments if they are on same or consecutive lines.
00244   if (C1.isTrailingComment() == C2.isTrailingComment() &&
00245       onlyWhitespaceBetween(SourceMgr, C1.getLocEnd(), C2.getLocStart(),
00246                             /*MaxNewlinesAllowed=*/1)) {
00247     SourceRange MergedRange(C1.getLocStart(), C2.getLocEnd());
00248     *Comments.back() = RawComment(SourceMgr, MergedRange, true,
00249                                   RC.isParseAllComments());
00250   } else {
00251     Comments.push_back(new (Allocator) RawComment(RC));
00252   }
00253 }
00254 
00255 void RawCommentList::addDeserializedComments(ArrayRef<RawComment *> DeserializedComments) {
00256   std::vector<RawComment *> MergedComments;
00257   MergedComments.reserve(Comments.size() + DeserializedComments.size());
00258 
00259   std::merge(Comments.begin(), Comments.end(),
00260              DeserializedComments.begin(), DeserializedComments.end(),
00261              std::back_inserter(MergedComments),
00262              BeforeThanCompare<RawComment>(SourceMgr));
00263   std::swap(Comments, MergedComments);
00264 }
00265