RawCommentList.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. //===--- RawCommentList.cpp - Processing raw comments -----------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/AST/RawCommentList.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/AST/Comment.h"
  11. #include "clang/AST/CommentBriefParser.h"
  12. #include "clang/AST/CommentCommandTraits.h"
  13. #include "clang/AST/CommentLexer.h"
  14. #include "clang/AST/CommentParser.h"
  15. #include "clang/AST/CommentSema.h"
  16. #include "clang/Basic/CharInfo.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/Support/Allocator.h"
  20. using namespace clang;
  21. namespace {
  22. /// Get comment kind and bool describing if it is a trailing comment.
  23. std::pair<RawComment::CommentKind, bool> getCommentKind(StringRef Comment,
  24. bool ParseAllComments) {
  25. const size_t MinCommentLength = ParseAllComments ? 2 : 3;
  26. if ((Comment.size() < MinCommentLength) || Comment[0] != '/')
  27. return std::make_pair(RawComment::RCK_Invalid, false);
  28. RawComment::CommentKind K;
  29. if (Comment[1] == '/') {
  30. if (Comment.size() < 3)
  31. return std::make_pair(RawComment::RCK_OrdinaryBCPL, false);
  32. if (Comment[2] == '/')
  33. K = RawComment::RCK_BCPLSlash;
  34. else if (Comment[2] == '!')
  35. K = RawComment::RCK_BCPLExcl;
  36. else
  37. return std::make_pair(RawComment::RCK_OrdinaryBCPL, false);
  38. } else {
  39. assert(Comment.size() >= 4);
  40. // Comment lexer does not understand escapes in comment markers, so pretend
  41. // that this is not a comment.
  42. if (Comment[1] != '*' ||
  43. Comment[Comment.size() - 2] != '*' ||
  44. Comment[Comment.size() - 1] != '/')
  45. return std::make_pair(RawComment::RCK_Invalid, false);
  46. if (Comment[2] == '*')
  47. K = RawComment::RCK_JavaDoc;
  48. else if (Comment[2] == '!')
  49. K = RawComment::RCK_Qt;
  50. else
  51. return std::make_pair(RawComment::RCK_OrdinaryC, false);
  52. }
  53. const bool TrailingComment = (Comment.size() > 3) && (Comment[3] == '<');
  54. return std::make_pair(K, TrailingComment);
  55. }
  56. bool mergedCommentIsTrailingComment(StringRef Comment) {
  57. return (Comment.size() > 3) && (Comment[3] == '<');
  58. }
  59. /// Returns true if R1 and R2 both have valid locations that start on the same
  60. /// column.
  61. bool commentsStartOnSameColumn(const SourceManager &SM, const RawComment &R1,
  62. const RawComment &R2) {
  63. SourceLocation L1 = R1.getBeginLoc();
  64. SourceLocation L2 = R2.getBeginLoc();
  65. bool Invalid = false;
  66. unsigned C1 = SM.getPresumedColumnNumber(L1, &Invalid);
  67. if (!Invalid) {
  68. unsigned C2 = SM.getPresumedColumnNumber(L2, &Invalid);
  69. return !Invalid && (C1 == C2);
  70. }
  71. return false;
  72. }
  73. } // unnamed namespace
  74. /// Determines whether there is only whitespace in `Buffer` between `P`
  75. /// and the previous line.
  76. /// \param Buffer The buffer to search in.
  77. /// \param P The offset from the beginning of `Buffer` to start from.
  78. /// \return true if all of the characters in `Buffer` ranging from the closest
  79. /// line-ending character before `P` (or the beginning of `Buffer`) to `P - 1`
  80. /// are whitespace.
  81. static bool onlyWhitespaceOnLineBefore(const char *Buffer, unsigned P) {
  82. // Search backwards until we see linefeed or carriage return.
  83. for (unsigned I = P; I != 0; --I) {
  84. char C = Buffer[I - 1];
  85. if (isVerticalWhitespace(C))
  86. return true;
  87. if (!isHorizontalWhitespace(C))
  88. return false;
  89. }
  90. // We hit the beginning of the buffer.
  91. return true;
  92. }
  93. /// Returns whether `K` is an ordinary comment kind.
  94. static bool isOrdinaryKind(RawComment::CommentKind K) {
  95. return (K == RawComment::RCK_OrdinaryBCPL) ||
  96. (K == RawComment::RCK_OrdinaryC);
  97. }
  98. RawComment::RawComment(const SourceManager &SourceMgr, SourceRange SR,
  99. const CommentOptions &CommentOpts, bool Merged) :
  100. Range(SR), RawTextValid(false), BriefTextValid(false),
  101. IsAttached(false), IsTrailingComment(false),
  102. IsAlmostTrailingComment(false) {
  103. // Extract raw comment text, if possible.
  104. if (SR.getBegin() == SR.getEnd() || getRawText(SourceMgr).empty()) {
  105. Kind = RCK_Invalid;
  106. return;
  107. }
  108. // Guess comment kind.
  109. std::pair<CommentKind, bool> K =
  110. getCommentKind(RawText, CommentOpts.ParseAllComments);
  111. // Guess whether an ordinary comment is trailing.
  112. if (CommentOpts.ParseAllComments && isOrdinaryKind(K.first)) {
  113. FileID BeginFileID;
  114. unsigned BeginOffset;
  115. std::tie(BeginFileID, BeginOffset) =
  116. SourceMgr.getDecomposedLoc(Range.getBegin());
  117. if (BeginOffset != 0) {
  118. bool Invalid = false;
  119. const char *Buffer =
  120. SourceMgr.getBufferData(BeginFileID, &Invalid).data();
  121. IsTrailingComment |=
  122. (!Invalid && !onlyWhitespaceOnLineBefore(Buffer, BeginOffset));
  123. }
  124. }
  125. if (!Merged) {
  126. Kind = K.first;
  127. IsTrailingComment |= K.second;
  128. IsAlmostTrailingComment = RawText.startswith("//<") ||
  129. RawText.startswith("/*<");
  130. } else {
  131. Kind = RCK_Merged;
  132. IsTrailingComment =
  133. IsTrailingComment || mergedCommentIsTrailingComment(RawText);
  134. }
  135. }
  136. StringRef RawComment::getRawTextSlow(const SourceManager &SourceMgr) const {
  137. FileID BeginFileID;
  138. FileID EndFileID;
  139. unsigned BeginOffset;
  140. unsigned EndOffset;
  141. std::tie(BeginFileID, BeginOffset) =
  142. SourceMgr.getDecomposedLoc(Range.getBegin());
  143. std::tie(EndFileID, EndOffset) = SourceMgr.getDecomposedLoc(Range.getEnd());
  144. const unsigned Length = EndOffset - BeginOffset;
  145. if (Length < 2)
  146. return StringRef();
  147. // The comment can't begin in one file and end in another.
  148. assert(BeginFileID == EndFileID);
  149. bool Invalid = false;
  150. const char *BufferStart = SourceMgr.getBufferData(BeginFileID,
  151. &Invalid).data();
  152. if (Invalid)
  153. return StringRef();
  154. return StringRef(BufferStart + BeginOffset, Length);
  155. }
  156. const char *RawComment::extractBriefText(const ASTContext &Context) const {
  157. // Lazily initialize RawText using the accessor before using it.
  158. (void)getRawText(Context.getSourceManager());
  159. // Since we will be copying the resulting text, all allocations made during
  160. // parsing are garbage after resulting string is formed. Thus we can use
  161. // a separate allocator for all temporary stuff.
  162. llvm::BumpPtrAllocator Allocator;
  163. comments::Lexer L(Allocator, Context.getDiagnostics(),
  164. Context.getCommentCommandTraits(),
  165. Range.getBegin(),
  166. RawText.begin(), RawText.end());
  167. comments::BriefParser P(L, Context.getCommentCommandTraits());
  168. const std::string Result = P.Parse();
  169. const unsigned BriefTextLength = Result.size();
  170. char *BriefTextPtr = new (Context) char[BriefTextLength + 1];
  171. memcpy(BriefTextPtr, Result.c_str(), BriefTextLength + 1);
  172. BriefText = BriefTextPtr;
  173. BriefTextValid = true;
  174. return BriefTextPtr;
  175. }
  176. comments::FullComment *RawComment::parse(const ASTContext &Context,
  177. const Preprocessor *PP,
  178. const Decl *D) const {
  179. // Lazily initialize RawText using the accessor before using it.
  180. (void)getRawText(Context.getSourceManager());
  181. comments::Lexer L(Context.getAllocator(), Context.getDiagnostics(),
  182. Context.getCommentCommandTraits(),
  183. getSourceRange().getBegin(),
  184. RawText.begin(), RawText.end());
  185. comments::Sema S(Context.getAllocator(), Context.getSourceManager(),
  186. Context.getDiagnostics(),
  187. Context.getCommentCommandTraits(),
  188. PP);
  189. S.setDecl(D);
  190. comments::Parser P(L, S, Context.getAllocator(), Context.getSourceManager(),
  191. Context.getDiagnostics(),
  192. Context.getCommentCommandTraits());
  193. return P.parseFullComment();
  194. }
  195. static bool onlyWhitespaceBetween(SourceManager &SM,
  196. SourceLocation Loc1, SourceLocation Loc2,
  197. unsigned MaxNewlinesAllowed) {
  198. std::pair<FileID, unsigned> Loc1Info = SM.getDecomposedLoc(Loc1);
  199. std::pair<FileID, unsigned> Loc2Info = SM.getDecomposedLoc(Loc2);
  200. // Question does not make sense if locations are in different files.
  201. if (Loc1Info.first != Loc2Info.first)
  202. return false;
  203. bool Invalid = false;
  204. const char *Buffer = SM.getBufferData(Loc1Info.first, &Invalid).data();
  205. if (Invalid)
  206. return false;
  207. unsigned NumNewlines = 0;
  208. assert(Loc1Info.second <= Loc2Info.second && "Loc1 after Loc2!");
  209. // Look for non-whitespace characters and remember any newlines seen.
  210. for (unsigned I = Loc1Info.second; I != Loc2Info.second; ++I) {
  211. switch (Buffer[I]) {
  212. default:
  213. return false;
  214. case ' ':
  215. case '\t':
  216. case '\f':
  217. case '\v':
  218. break;
  219. case '\r':
  220. case '\n':
  221. ++NumNewlines;
  222. // Check if we have found more than the maximum allowed number of
  223. // newlines.
  224. if (NumNewlines > MaxNewlinesAllowed)
  225. return false;
  226. // Collapse \r\n and \n\r into a single newline.
  227. if (I + 1 != Loc2Info.second &&
  228. (Buffer[I + 1] == '\n' || Buffer[I + 1] == '\r') &&
  229. Buffer[I] != Buffer[I + 1])
  230. ++I;
  231. break;
  232. }
  233. }
  234. return true;
  235. }
  236. void RawCommentList::addComment(const RawComment &RC,
  237. const CommentOptions &CommentOpts,
  238. llvm::BumpPtrAllocator &Allocator) {
  239. if (RC.isInvalid())
  240. return;
  241. // Ordinary comments are not interesting for us.
  242. if (RC.isOrdinary() && !CommentOpts.ParseAllComments)
  243. return;
  244. std::pair<FileID, unsigned> Loc =
  245. SourceMgr.getDecomposedLoc(RC.getBeginLoc());
  246. const FileID CommentFile = Loc.first;
  247. const unsigned CommentOffset = Loc.second;
  248. // If this is the first Doxygen comment, save it (because there isn't
  249. // anything to merge it with).
  250. if (OrderedComments[CommentFile].empty()) {
  251. OrderedComments[CommentFile][CommentOffset] =
  252. new (Allocator) RawComment(RC);
  253. return;
  254. }
  255. const RawComment &C1 = *OrderedComments[CommentFile].rbegin()->second;
  256. const RawComment &C2 = RC;
  257. // Merge comments only if there is only whitespace between them.
  258. // Can't merge trailing and non-trailing comments unless the second is
  259. // non-trailing ordinary in the same column, as in the case:
  260. // int x; // documents x
  261. // // more text
  262. // versus:
  263. // int x; // documents x
  264. // int y; // documents y
  265. // or:
  266. // int x; // documents x
  267. // // documents y
  268. // int y;
  269. // Merge comments if they are on same or consecutive lines.
  270. if ((C1.isTrailingComment() == C2.isTrailingComment() ||
  271. (C1.isTrailingComment() && !C2.isTrailingComment() &&
  272. isOrdinaryKind(C2.getKind()) &&
  273. commentsStartOnSameColumn(SourceMgr, C1, C2))) &&
  274. onlyWhitespaceBetween(SourceMgr, C1.getEndLoc(), C2.getBeginLoc(),
  275. /*MaxNewlinesAllowed=*/1)) {
  276. SourceRange MergedRange(C1.getBeginLoc(), C2.getEndLoc());
  277. *OrderedComments[CommentFile].rbegin()->second =
  278. RawComment(SourceMgr, MergedRange, CommentOpts, true);
  279. } else {
  280. OrderedComments[CommentFile][CommentOffset] =
  281. new (Allocator) RawComment(RC);
  282. }
  283. }
  284. const std::map<unsigned, RawComment *> *
  285. RawCommentList::getCommentsInFile(FileID File) const {
  286. auto CommentsInFile = OrderedComments.find(File);
  287. if (CommentsInFile == OrderedComments.end())
  288. return nullptr;
  289. return &CommentsInFile->second;
  290. }
  291. bool RawCommentList::empty() const { return OrderedComments.empty(); }
  292. unsigned RawCommentList::getCommentBeginLine(RawComment *C, FileID File,
  293. unsigned Offset) const {
  294. auto Cached = CommentBeginLine.find(C);
  295. if (Cached != CommentBeginLine.end())
  296. return Cached->second;
  297. const unsigned Line = SourceMgr.getLineNumber(File, Offset);
  298. CommentBeginLine[C] = Line;
  299. return Line;
  300. }
  301. unsigned RawCommentList::getCommentEndOffset(RawComment *C) const {
  302. auto Cached = CommentEndOffset.find(C);
  303. if (Cached != CommentEndOffset.end())
  304. return Cached->second;
  305. const unsigned Offset =
  306. SourceMgr.getDecomposedLoc(C->getSourceRange().getEnd()).second;
  307. CommentEndOffset[C] = Offset;
  308. return Offset;
  309. }
  310. std::string RawComment::getFormattedText(const SourceManager &SourceMgr,
  311. DiagnosticsEngine &Diags) const {
  312. llvm::StringRef CommentText = getRawText(SourceMgr);
  313. if (CommentText.empty())
  314. return "";
  315. std::string Result;
  316. for (const RawComment::CommentLine &Line :
  317. getFormattedLines(SourceMgr, Diags))
  318. Result += Line.Text + "\n";
  319. auto LastChar = Result.find_last_not_of('\n');
  320. Result.erase(LastChar + 1, Result.size());
  321. return Result;
  322. }
  323. std::vector<RawComment::CommentLine>
  324. RawComment::getFormattedLines(const SourceManager &SourceMgr,
  325. DiagnosticsEngine &Diags) const {
  326. llvm::StringRef CommentText = getRawText(SourceMgr);
  327. if (CommentText.empty())
  328. return {};
  329. llvm::BumpPtrAllocator Allocator;
  330. // We do not parse any commands, so CommentOptions are ignored by
  331. // comments::Lexer. Therefore, we just use default-constructed options.
  332. CommentOptions DefOpts;
  333. comments::CommandTraits EmptyTraits(Allocator, DefOpts);
  334. comments::Lexer L(Allocator, Diags, EmptyTraits, getSourceRange().getBegin(),
  335. CommentText.begin(), CommentText.end(),
  336. /*ParseCommands=*/false);
  337. std::vector<RawComment::CommentLine> Result;
  338. // A column number of the first non-whitespace token in the comment text.
  339. // We skip whitespace up to this column, but keep the whitespace after this
  340. // column. IndentColumn is calculated when lexing the first line and reused
  341. // for the rest of lines.
  342. unsigned IndentColumn = 0;
  343. // Record the line number of the last processed comment line.
  344. // For block-style comments, an extra newline token will be produced after
  345. // the end-comment marker, e.g.:
  346. // /** This is a multi-line comment block.
  347. // The lexer will produce two newline tokens here > */
  348. // previousLine will record the line number when we previously saw a newline
  349. // token and recorded a comment line. If we see another newline token on the
  350. // same line, don't record anything in between.
  351. unsigned PreviousLine = 0;
  352. // Processes one line of the comment and adds it to the result.
  353. // Handles skipping the indent at the start of the line.
  354. // Returns false when eof is reached and true otherwise.
  355. auto LexLine = [&](bool IsFirstLine) -> bool {
  356. comments::Token Tok;
  357. // Lex the first token on the line. We handle it separately, because we to
  358. // fix up its indentation.
  359. L.lex(Tok);
  360. if (Tok.is(comments::tok::eof))
  361. return false;
  362. if (Tok.is(comments::tok::newline)) {
  363. PresumedLoc Loc = SourceMgr.getPresumedLoc(Tok.getLocation());
  364. if (Loc.getLine() != PreviousLine) {
  365. Result.emplace_back("", Loc, Loc);
  366. PreviousLine = Loc.getLine();
  367. }
  368. return true;
  369. }
  370. SmallString<124> Line;
  371. llvm::StringRef TokText = L.getSpelling(Tok, SourceMgr);
  372. bool LocInvalid = false;
  373. unsigned TokColumn =
  374. SourceMgr.getSpellingColumnNumber(Tok.getLocation(), &LocInvalid);
  375. assert(!LocInvalid && "getFormattedText for invalid location");
  376. // Amount of leading whitespace in TokText.
  377. size_t WhitespaceLen = TokText.find_first_not_of(" \t");
  378. if (WhitespaceLen == StringRef::npos)
  379. WhitespaceLen = TokText.size();
  380. // Remember the amount of whitespace we skipped in the first line to remove
  381. // indent up to that column in the following lines.
  382. if (IsFirstLine)
  383. IndentColumn = TokColumn + WhitespaceLen;
  384. // Amount of leading whitespace we actually want to skip.
  385. // For the first line we skip all the whitespace.
  386. // For the rest of the lines, we skip whitespace up to IndentColumn.
  387. unsigned SkipLen =
  388. IsFirstLine
  389. ? WhitespaceLen
  390. : std::min<size_t>(
  391. WhitespaceLen,
  392. std::max<int>(static_cast<int>(IndentColumn) - TokColumn, 0));
  393. llvm::StringRef Trimmed = TokText.drop_front(SkipLen);
  394. Line += Trimmed;
  395. // Get the beginning location of the adjusted comment line.
  396. PresumedLoc Begin =
  397. SourceMgr.getPresumedLoc(Tok.getLocation().getLocWithOffset(SkipLen));
  398. // Lex all tokens in the rest of the line.
  399. for (L.lex(Tok); Tok.isNot(comments::tok::eof); L.lex(Tok)) {
  400. if (Tok.is(comments::tok::newline)) {
  401. // Get the ending location of the comment line.
  402. PresumedLoc End = SourceMgr.getPresumedLoc(Tok.getLocation());
  403. if (End.getLine() != PreviousLine) {
  404. Result.emplace_back(Line, Begin, End);
  405. PreviousLine = End.getLine();
  406. }
  407. return true;
  408. }
  409. Line += L.getSpelling(Tok, SourceMgr);
  410. }
  411. PresumedLoc End = SourceMgr.getPresumedLoc(Tok.getLocation());
  412. Result.emplace_back(Line, Begin, End);
  413. // We've reached the end of file token.
  414. return false;
  415. };
  416. // Process first line separately to remember indent for the following lines.
  417. if (!LexLine(/*IsFirstLine=*/true))
  418. return Result;
  419. // Process the rest of the lines.
  420. while (LexLine(/*IsFirstLine=*/false))
  421. ;
  422. return Result;
  423. }