RawCommentList.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. //===--- RawCommentList.cpp - Processing raw comments -----------*- 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. #include "clang/AST/RawCommentList.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/AST/Comment.h"
  12. #include "clang/AST/CommentBriefParser.h"
  13. #include "clang/AST/CommentCommandTraits.h"
  14. #include "clang/AST/CommentLexer.h"
  15. #include "clang/AST/CommentParser.h"
  16. #include "clang/AST/CommentSema.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. using namespace clang;
  19. namespace {
  20. /// Get comment kind and bool describing if it is a trailing comment.
  21. std::pair<RawComment::CommentKind, bool> getCommentKind(StringRef Comment,
  22. bool ParseAllComments) {
  23. const size_t MinCommentLength = ParseAllComments ? 2 : 3;
  24. if ((Comment.size() < MinCommentLength) || Comment[0] != '/')
  25. return std::make_pair(RawComment::RCK_Invalid, false);
  26. RawComment::CommentKind K;
  27. if (Comment[1] == '/') {
  28. if (Comment.size() < 3)
  29. return std::make_pair(RawComment::RCK_OrdinaryBCPL, false);
  30. if (Comment[2] == '/')
  31. K = RawComment::RCK_BCPLSlash;
  32. else if (Comment[2] == '!')
  33. K = RawComment::RCK_BCPLExcl;
  34. else
  35. return std::make_pair(RawComment::RCK_OrdinaryBCPL, false);
  36. } else {
  37. assert(Comment.size() >= 4);
  38. // Comment lexer does not understand escapes in comment markers, so pretend
  39. // that this is not a comment.
  40. if (Comment[1] != '*' ||
  41. Comment[Comment.size() - 2] != '*' ||
  42. Comment[Comment.size() - 1] != '/')
  43. return std::make_pair(RawComment::RCK_Invalid, false);
  44. if (Comment[2] == '*')
  45. K = RawComment::RCK_JavaDoc;
  46. else if (Comment[2] == '!')
  47. K = RawComment::RCK_Qt;
  48. else
  49. return std::make_pair(RawComment::RCK_OrdinaryC, false);
  50. }
  51. const bool TrailingComment = (Comment.size() > 3) && (Comment[3] == '<');
  52. return std::make_pair(K, TrailingComment);
  53. }
  54. bool mergedCommentIsTrailingComment(StringRef Comment) {
  55. return (Comment.size() > 3) && (Comment[3] == '<');
  56. }
  57. } // unnamed namespace
  58. RawComment::RawComment(const SourceManager &SourceMgr, SourceRange SR,
  59. bool Merged, bool ParseAllComments) :
  60. Range(SR), RawTextValid(false), BriefTextValid(false),
  61. IsAttached(false), IsAlmostTrailingComment(false),
  62. ParseAllComments(ParseAllComments) {
  63. // Extract raw comment text, if possible.
  64. if (SR.getBegin() == SR.getEnd() || getRawText(SourceMgr).empty()) {
  65. Kind = RCK_Invalid;
  66. return;
  67. }
  68. if (!Merged) {
  69. // Guess comment kind.
  70. std::pair<CommentKind, bool> K = getCommentKind(RawText, ParseAllComments);
  71. Kind = K.first;
  72. IsTrailingComment = K.second;
  73. IsAlmostTrailingComment = RawText.startswith("//<") ||
  74. RawText.startswith("/*<");
  75. } else {
  76. Kind = RCK_Merged;
  77. IsTrailingComment = mergedCommentIsTrailingComment(RawText);
  78. }
  79. }
  80. StringRef RawComment::getRawTextSlow(const SourceManager &SourceMgr) const {
  81. FileID BeginFileID;
  82. FileID EndFileID;
  83. unsigned BeginOffset;
  84. unsigned EndOffset;
  85. std::tie(BeginFileID, BeginOffset) =
  86. SourceMgr.getDecomposedLoc(Range.getBegin());
  87. std::tie(EndFileID, EndOffset) = SourceMgr.getDecomposedLoc(Range.getEnd());
  88. const unsigned Length = EndOffset - BeginOffset;
  89. if (Length < 2)
  90. return StringRef();
  91. // The comment can't begin in one file and end in another.
  92. assert(BeginFileID == EndFileID);
  93. bool Invalid = false;
  94. const char *BufferStart = SourceMgr.getBufferData(BeginFileID,
  95. &Invalid).data();
  96. if (Invalid)
  97. return StringRef();
  98. return StringRef(BufferStart + BeginOffset, Length);
  99. }
  100. const char *RawComment::extractBriefText(const ASTContext &Context) const {
  101. // Make sure that RawText is valid.
  102. getRawText(Context.getSourceManager());
  103. // Since we will be copying the resulting text, all allocations made during
  104. // parsing are garbage after resulting string is formed. Thus we can use
  105. // a separate allocator for all temporary stuff.
  106. llvm::BumpPtrAllocator Allocator;
  107. comments::Lexer L(Allocator, Context.getDiagnostics(),
  108. Context.getCommentCommandTraits(),
  109. Range.getBegin(),
  110. RawText.begin(), RawText.end());
  111. comments::BriefParser P(L, Context.getCommentCommandTraits());
  112. const std::string Result = P.Parse();
  113. const unsigned BriefTextLength = Result.size();
  114. char *BriefTextPtr = new (Context) char[BriefTextLength + 1];
  115. memcpy(BriefTextPtr, Result.c_str(), BriefTextLength + 1);
  116. BriefText = BriefTextPtr;
  117. BriefTextValid = true;
  118. return BriefTextPtr;
  119. }
  120. comments::FullComment *RawComment::parse(const ASTContext &Context,
  121. const Preprocessor *PP,
  122. const Decl *D) const {
  123. // Make sure that RawText is valid.
  124. getRawText(Context.getSourceManager());
  125. comments::Lexer L(Context.getAllocator(), Context.getDiagnostics(),
  126. Context.getCommentCommandTraits(),
  127. getSourceRange().getBegin(),
  128. RawText.begin(), RawText.end());
  129. comments::Sema S(Context.getAllocator(), Context.getSourceManager(),
  130. Context.getDiagnostics(),
  131. Context.getCommentCommandTraits(),
  132. PP);
  133. S.setDecl(D);
  134. comments::Parser P(L, S, Context.getAllocator(), Context.getSourceManager(),
  135. Context.getDiagnostics(),
  136. Context.getCommentCommandTraits());
  137. return P.parseFullComment();
  138. }
  139. static bool onlyWhitespaceBetween(SourceManager &SM,
  140. SourceLocation Loc1, SourceLocation Loc2,
  141. unsigned MaxNewlinesAllowed) {
  142. std::pair<FileID, unsigned> Loc1Info = SM.getDecomposedLoc(Loc1);
  143. std::pair<FileID, unsigned> Loc2Info = SM.getDecomposedLoc(Loc2);
  144. // Question does not make sense if locations are in different files.
  145. if (Loc1Info.first != Loc2Info.first)
  146. return false;
  147. bool Invalid = false;
  148. const char *Buffer = SM.getBufferData(Loc1Info.first, &Invalid).data();
  149. if (Invalid)
  150. return false;
  151. unsigned NumNewlines = 0;
  152. assert(Loc1Info.second <= Loc2Info.second && "Loc1 after Loc2!");
  153. // Look for non-whitespace characters and remember any newlines seen.
  154. for (unsigned I = Loc1Info.second; I != Loc2Info.second; ++I) {
  155. switch (Buffer[I]) {
  156. default:
  157. return false;
  158. case ' ':
  159. case '\t':
  160. case '\f':
  161. case '\v':
  162. break;
  163. case '\r':
  164. case '\n':
  165. ++NumNewlines;
  166. // Check if we have found more than the maximum allowed number of
  167. // newlines.
  168. if (NumNewlines > MaxNewlinesAllowed)
  169. return false;
  170. // Collapse \r\n and \n\r into a single newline.
  171. if (I + 1 != Loc2Info.second &&
  172. (Buffer[I + 1] == '\n' || Buffer[I + 1] == '\r') &&
  173. Buffer[I] != Buffer[I + 1])
  174. ++I;
  175. break;
  176. }
  177. }
  178. return true;
  179. }
  180. void RawCommentList::addComment(const RawComment &RC,
  181. llvm::BumpPtrAllocator &Allocator) {
  182. if (RC.isInvalid())
  183. return;
  184. // Check if the comments are not in source order.
  185. while (!Comments.empty() &&
  186. !SourceMgr.isBeforeInTranslationUnit(Comments.back()->getLocStart(),
  187. RC.getLocStart())) {
  188. // If they are, just pop a few last comments that don't fit.
  189. // This happens if an \#include directive contains comments.
  190. Comments.pop_back();
  191. }
  192. // Ordinary comments are not interesting for us.
  193. if (RC.isOrdinary())
  194. return;
  195. // If this is the first Doxygen comment, save it (because there isn't
  196. // anything to merge it with).
  197. if (Comments.empty()) {
  198. Comments.push_back(new (Allocator) RawComment(RC));
  199. return;
  200. }
  201. const RawComment &C1 = *Comments.back();
  202. const RawComment &C2 = RC;
  203. // Merge comments only if there is only whitespace between them.
  204. // Can't merge trailing and non-trailing comments.
  205. // Merge comments if they are on same or consecutive lines.
  206. if (C1.isTrailingComment() == C2.isTrailingComment() &&
  207. onlyWhitespaceBetween(SourceMgr, C1.getLocEnd(), C2.getLocStart(),
  208. /*MaxNewlinesAllowed=*/1)) {
  209. SourceRange MergedRange(C1.getLocStart(), C2.getLocEnd());
  210. *Comments.back() = RawComment(SourceMgr, MergedRange, true,
  211. RC.isParseAllComments());
  212. } else {
  213. Comments.push_back(new (Allocator) RawComment(RC));
  214. }
  215. }
  216. void RawCommentList::addDeserializedComments(ArrayRef<RawComment *> DeserializedComments) {
  217. std::vector<RawComment *> MergedComments;
  218. MergedComments.reserve(Comments.size() + DeserializedComments.size());
  219. std::merge(Comments.begin(), Comments.end(),
  220. DeserializedComments.begin(), DeserializedComments.end(),
  221. std::back_inserter(MergedComments),
  222. BeforeThanCompare<RawComment>(SourceMgr));
  223. std::swap(Comments, MergedComments);
  224. }