CommentSema.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. //===--- CommentSema.cpp - Doxygen comment semantic analysis --------------===//
  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/CommentSema.h"
  9. #include "clang/AST/Attr.h"
  10. #include "clang/AST/CommentCommandTraits.h"
  11. #include "clang/AST/CommentDiagnostic.h"
  12. #include "clang/AST/Decl.h"
  13. #include "clang/AST/DeclTemplate.h"
  14. #include "clang/Basic/LLVM.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Lex/Preprocessor.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/StringSwitch.h"
  19. namespace clang {
  20. namespace comments {
  21. namespace {
  22. #include "clang/AST/CommentHTMLTagsProperties.inc"
  23. } // end anonymous namespace
  24. Sema::Sema(llvm::BumpPtrAllocator &Allocator, const SourceManager &SourceMgr,
  25. DiagnosticsEngine &Diags, CommandTraits &Traits,
  26. const Preprocessor *PP) :
  27. Allocator(Allocator), SourceMgr(SourceMgr), Diags(Diags), Traits(Traits),
  28. PP(PP), ThisDeclInfo(nullptr), BriefCommand(nullptr),
  29. HeaderfileCommand(nullptr) {
  30. }
  31. void Sema::setDecl(const Decl *D) {
  32. if (!D)
  33. return;
  34. ThisDeclInfo = new (Allocator) DeclInfo;
  35. ThisDeclInfo->CommentDecl = D;
  36. ThisDeclInfo->IsFilled = false;
  37. }
  38. ParagraphComment *Sema::actOnParagraphComment(
  39. ArrayRef<InlineContentComment *> Content) {
  40. return new (Allocator) ParagraphComment(Content);
  41. }
  42. BlockCommandComment *Sema::actOnBlockCommandStart(
  43. SourceLocation LocBegin,
  44. SourceLocation LocEnd,
  45. unsigned CommandID,
  46. CommandMarkerKind CommandMarker) {
  47. BlockCommandComment *BC = new (Allocator) BlockCommandComment(LocBegin, LocEnd,
  48. CommandID,
  49. CommandMarker);
  50. checkContainerDecl(BC);
  51. return BC;
  52. }
  53. void Sema::actOnBlockCommandArgs(BlockCommandComment *Command,
  54. ArrayRef<BlockCommandComment::Argument> Args) {
  55. Command->setArgs(Args);
  56. }
  57. void Sema::actOnBlockCommandFinish(BlockCommandComment *Command,
  58. ParagraphComment *Paragraph) {
  59. Command->setParagraph(Paragraph);
  60. checkBlockCommandEmptyParagraph(Command);
  61. checkBlockCommandDuplicate(Command);
  62. if (ThisDeclInfo) {
  63. // These checks only make sense if the comment is attached to a
  64. // declaration.
  65. checkReturnsCommand(Command);
  66. checkDeprecatedCommand(Command);
  67. }
  68. }
  69. ParamCommandComment *Sema::actOnParamCommandStart(
  70. SourceLocation LocBegin,
  71. SourceLocation LocEnd,
  72. unsigned CommandID,
  73. CommandMarkerKind CommandMarker) {
  74. ParamCommandComment *Command =
  75. new (Allocator) ParamCommandComment(LocBegin, LocEnd, CommandID,
  76. CommandMarker);
  77. if (!involvesFunctionType())
  78. Diag(Command->getLocation(),
  79. diag::warn_doc_param_not_attached_to_a_function_decl)
  80. << CommandMarker
  81. << Command->getCommandNameRange(Traits);
  82. return Command;
  83. }
  84. void Sema::checkFunctionDeclVerbatimLine(const BlockCommandComment *Comment) {
  85. const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
  86. if (!Info->IsFunctionDeclarationCommand)
  87. return;
  88. unsigned DiagSelect;
  89. switch (Comment->getCommandID()) {
  90. case CommandTraits::KCI_function:
  91. DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl())? 1 : 0;
  92. break;
  93. case CommandTraits::KCI_functiongroup:
  94. DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl())? 2 : 0;
  95. break;
  96. case CommandTraits::KCI_method:
  97. DiagSelect = !isObjCMethodDecl() ? 3 : 0;
  98. break;
  99. case CommandTraits::KCI_methodgroup:
  100. DiagSelect = !isObjCMethodDecl() ? 4 : 0;
  101. break;
  102. case CommandTraits::KCI_callback:
  103. DiagSelect = !isFunctionPointerVarDecl() ? 5 : 0;
  104. break;
  105. default:
  106. DiagSelect = 0;
  107. break;
  108. }
  109. if (DiagSelect)
  110. Diag(Comment->getLocation(), diag::warn_doc_function_method_decl_mismatch)
  111. << Comment->getCommandMarker()
  112. << (DiagSelect-1) << (DiagSelect-1)
  113. << Comment->getSourceRange();
  114. }
  115. void Sema::checkContainerDeclVerbatimLine(const BlockCommandComment *Comment) {
  116. const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
  117. if (!Info->IsRecordLikeDeclarationCommand)
  118. return;
  119. unsigned DiagSelect;
  120. switch (Comment->getCommandID()) {
  121. case CommandTraits::KCI_class:
  122. DiagSelect =
  123. (!isClassOrStructOrTagTypedefDecl() && !isClassTemplateDecl()) ? 1
  124. : 0;
  125. // Allow @class command on @interface declarations.
  126. // FIXME. Currently, \class and @class are indistinguishable. So,
  127. // \class is also allowed on an @interface declaration
  128. if (DiagSelect && Comment->getCommandMarker() && isObjCInterfaceDecl())
  129. DiagSelect = 0;
  130. break;
  131. case CommandTraits::KCI_interface:
  132. DiagSelect = !isObjCInterfaceDecl() ? 2 : 0;
  133. break;
  134. case CommandTraits::KCI_protocol:
  135. DiagSelect = !isObjCProtocolDecl() ? 3 : 0;
  136. break;
  137. case CommandTraits::KCI_struct:
  138. DiagSelect = !isClassOrStructOrTagTypedefDecl() ? 4 : 0;
  139. break;
  140. case CommandTraits::KCI_union:
  141. DiagSelect = !isUnionDecl() ? 5 : 0;
  142. break;
  143. default:
  144. DiagSelect = 0;
  145. break;
  146. }
  147. if (DiagSelect)
  148. Diag(Comment->getLocation(), diag::warn_doc_api_container_decl_mismatch)
  149. << Comment->getCommandMarker()
  150. << (DiagSelect-1) << (DiagSelect-1)
  151. << Comment->getSourceRange();
  152. }
  153. void Sema::checkContainerDecl(const BlockCommandComment *Comment) {
  154. const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
  155. if (!Info->IsRecordLikeDetailCommand || isRecordLikeDecl())
  156. return;
  157. unsigned DiagSelect;
  158. switch (Comment->getCommandID()) {
  159. case CommandTraits::KCI_classdesign:
  160. DiagSelect = 1;
  161. break;
  162. case CommandTraits::KCI_coclass:
  163. DiagSelect = 2;
  164. break;
  165. case CommandTraits::KCI_dependency:
  166. DiagSelect = 3;
  167. break;
  168. case CommandTraits::KCI_helper:
  169. DiagSelect = 4;
  170. break;
  171. case CommandTraits::KCI_helperclass:
  172. DiagSelect = 5;
  173. break;
  174. case CommandTraits::KCI_helps:
  175. DiagSelect = 6;
  176. break;
  177. case CommandTraits::KCI_instancesize:
  178. DiagSelect = 7;
  179. break;
  180. case CommandTraits::KCI_ownership:
  181. DiagSelect = 8;
  182. break;
  183. case CommandTraits::KCI_performance:
  184. DiagSelect = 9;
  185. break;
  186. case CommandTraits::KCI_security:
  187. DiagSelect = 10;
  188. break;
  189. case CommandTraits::KCI_superclass:
  190. DiagSelect = 11;
  191. break;
  192. default:
  193. DiagSelect = 0;
  194. break;
  195. }
  196. if (DiagSelect)
  197. Diag(Comment->getLocation(), diag::warn_doc_container_decl_mismatch)
  198. << Comment->getCommandMarker()
  199. << (DiagSelect-1)
  200. << Comment->getSourceRange();
  201. }
  202. /// Turn a string into the corresponding PassDirection or -1 if it's not
  203. /// valid.
  204. static int getParamPassDirection(StringRef Arg) {
  205. return llvm::StringSwitch<int>(Arg)
  206. .Case("[in]", ParamCommandComment::In)
  207. .Case("[out]", ParamCommandComment::Out)
  208. .Cases("[in,out]", "[out,in]", ParamCommandComment::InOut)
  209. .Default(-1);
  210. }
  211. void Sema::actOnParamCommandDirectionArg(ParamCommandComment *Command,
  212. SourceLocation ArgLocBegin,
  213. SourceLocation ArgLocEnd,
  214. StringRef Arg) {
  215. std::string ArgLower = Arg.lower();
  216. int Direction = getParamPassDirection(ArgLower);
  217. if (Direction == -1) {
  218. // Try again with whitespace removed.
  219. llvm::erase_if(ArgLower, clang::isWhitespace);
  220. Direction = getParamPassDirection(ArgLower);
  221. SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
  222. if (Direction != -1) {
  223. const char *FixedName = ParamCommandComment::getDirectionAsString(
  224. (ParamCommandComment::PassDirection)Direction);
  225. Diag(ArgLocBegin, diag::warn_doc_param_spaces_in_direction)
  226. << ArgRange << FixItHint::CreateReplacement(ArgRange, FixedName);
  227. } else {
  228. Diag(ArgLocBegin, diag::warn_doc_param_invalid_direction) << ArgRange;
  229. Direction = ParamCommandComment::In; // Sane fall back.
  230. }
  231. }
  232. Command->setDirection((ParamCommandComment::PassDirection)Direction,
  233. /*Explicit=*/true);
  234. }
  235. void Sema::actOnParamCommandParamNameArg(ParamCommandComment *Command,
  236. SourceLocation ArgLocBegin,
  237. SourceLocation ArgLocEnd,
  238. StringRef Arg) {
  239. // Parser will not feed us more arguments than needed.
  240. assert(Command->getNumArgs() == 0);
  241. if (!Command->isDirectionExplicit()) {
  242. // User didn't provide a direction argument.
  243. Command->setDirection(ParamCommandComment::In, /* Explicit = */ false);
  244. }
  245. auto *A = new (Allocator)
  246. Comment::Argument{SourceRange(ArgLocBegin, ArgLocEnd), Arg};
  247. Command->setArgs(llvm::ArrayRef(A, 1));
  248. }
  249. void Sema::actOnParamCommandFinish(ParamCommandComment *Command,
  250. ParagraphComment *Paragraph) {
  251. Command->setParagraph(Paragraph);
  252. checkBlockCommandEmptyParagraph(Command);
  253. }
  254. TParamCommandComment *Sema::actOnTParamCommandStart(
  255. SourceLocation LocBegin,
  256. SourceLocation LocEnd,
  257. unsigned CommandID,
  258. CommandMarkerKind CommandMarker) {
  259. TParamCommandComment *Command =
  260. new (Allocator) TParamCommandComment(LocBegin, LocEnd, CommandID,
  261. CommandMarker);
  262. if (!isTemplateOrSpecialization())
  263. Diag(Command->getLocation(),
  264. diag::warn_doc_tparam_not_attached_to_a_template_decl)
  265. << CommandMarker
  266. << Command->getCommandNameRange(Traits);
  267. return Command;
  268. }
  269. void Sema::actOnTParamCommandParamNameArg(TParamCommandComment *Command,
  270. SourceLocation ArgLocBegin,
  271. SourceLocation ArgLocEnd,
  272. StringRef Arg) {
  273. // Parser will not feed us more arguments than needed.
  274. assert(Command->getNumArgs() == 0);
  275. auto *A = new (Allocator)
  276. Comment::Argument{SourceRange(ArgLocBegin, ArgLocEnd), Arg};
  277. Command->setArgs(llvm::ArrayRef(A, 1));
  278. if (!isTemplateOrSpecialization()) {
  279. // We already warned that this \\tparam is not attached to a template decl.
  280. return;
  281. }
  282. const TemplateParameterList *TemplateParameters =
  283. ThisDeclInfo->TemplateParameters;
  284. SmallVector<unsigned, 2> Position;
  285. if (resolveTParamReference(Arg, TemplateParameters, &Position)) {
  286. Command->setPosition(copyArray(llvm::ArrayRef(Position)));
  287. TParamCommandComment *&PrevCommand = TemplateParameterDocs[Arg];
  288. if (PrevCommand) {
  289. SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
  290. Diag(ArgLocBegin, diag::warn_doc_tparam_duplicate)
  291. << Arg << ArgRange;
  292. Diag(PrevCommand->getLocation(), diag::note_doc_tparam_previous)
  293. << PrevCommand->getParamNameRange();
  294. }
  295. PrevCommand = Command;
  296. return;
  297. }
  298. SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
  299. Diag(ArgLocBegin, diag::warn_doc_tparam_not_found)
  300. << Arg << ArgRange;
  301. if (!TemplateParameters || TemplateParameters->size() == 0)
  302. return;
  303. StringRef CorrectedName;
  304. if (TemplateParameters->size() == 1) {
  305. const NamedDecl *Param = TemplateParameters->getParam(0);
  306. const IdentifierInfo *II = Param->getIdentifier();
  307. if (II)
  308. CorrectedName = II->getName();
  309. } else {
  310. CorrectedName = correctTypoInTParamReference(Arg, TemplateParameters);
  311. }
  312. if (!CorrectedName.empty()) {
  313. Diag(ArgLocBegin, diag::note_doc_tparam_name_suggestion)
  314. << CorrectedName
  315. << FixItHint::CreateReplacement(ArgRange, CorrectedName);
  316. }
  317. }
  318. void Sema::actOnTParamCommandFinish(TParamCommandComment *Command,
  319. ParagraphComment *Paragraph) {
  320. Command->setParagraph(Paragraph);
  321. checkBlockCommandEmptyParagraph(Command);
  322. }
  323. InlineCommandComment *
  324. Sema::actOnInlineCommand(SourceLocation CommandLocBegin,
  325. SourceLocation CommandLocEnd, unsigned CommandID,
  326. ArrayRef<Comment::Argument> Args) {
  327. StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
  328. return new (Allocator)
  329. InlineCommandComment(CommandLocBegin, CommandLocEnd, CommandID,
  330. getInlineCommandRenderKind(CommandName), Args);
  331. }
  332. InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin,
  333. SourceLocation LocEnd,
  334. StringRef CommandName) {
  335. unsigned CommandID = Traits.registerUnknownCommand(CommandName)->getID();
  336. return actOnUnknownCommand(LocBegin, LocEnd, CommandID);
  337. }
  338. InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin,
  339. SourceLocation LocEnd,
  340. unsigned CommandID) {
  341. ArrayRef<InlineCommandComment::Argument> Args;
  342. return new (Allocator) InlineCommandComment(
  343. LocBegin, LocEnd, CommandID,
  344. InlineCommandComment::RenderNormal,
  345. Args);
  346. }
  347. TextComment *Sema::actOnText(SourceLocation LocBegin,
  348. SourceLocation LocEnd,
  349. StringRef Text) {
  350. return new (Allocator) TextComment(LocBegin, LocEnd, Text);
  351. }
  352. VerbatimBlockComment *Sema::actOnVerbatimBlockStart(SourceLocation Loc,
  353. unsigned CommandID) {
  354. StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
  355. return new (Allocator) VerbatimBlockComment(
  356. Loc,
  357. Loc.getLocWithOffset(1 + CommandName.size()),
  358. CommandID);
  359. }
  360. VerbatimBlockLineComment *Sema::actOnVerbatimBlockLine(SourceLocation Loc,
  361. StringRef Text) {
  362. return new (Allocator) VerbatimBlockLineComment(Loc, Text);
  363. }
  364. void Sema::actOnVerbatimBlockFinish(
  365. VerbatimBlockComment *Block,
  366. SourceLocation CloseNameLocBegin,
  367. StringRef CloseName,
  368. ArrayRef<VerbatimBlockLineComment *> Lines) {
  369. Block->setCloseName(CloseName, CloseNameLocBegin);
  370. Block->setLines(Lines);
  371. }
  372. VerbatimLineComment *Sema::actOnVerbatimLine(SourceLocation LocBegin,
  373. unsigned CommandID,
  374. SourceLocation TextBegin,
  375. StringRef Text) {
  376. VerbatimLineComment *VL = new (Allocator) VerbatimLineComment(
  377. LocBegin,
  378. TextBegin.getLocWithOffset(Text.size()),
  379. CommandID,
  380. TextBegin,
  381. Text);
  382. checkFunctionDeclVerbatimLine(VL);
  383. checkContainerDeclVerbatimLine(VL);
  384. return VL;
  385. }
  386. HTMLStartTagComment *Sema::actOnHTMLStartTagStart(SourceLocation LocBegin,
  387. StringRef TagName) {
  388. return new (Allocator) HTMLStartTagComment(LocBegin, TagName);
  389. }
  390. void Sema::actOnHTMLStartTagFinish(
  391. HTMLStartTagComment *Tag,
  392. ArrayRef<HTMLStartTagComment::Attribute> Attrs,
  393. SourceLocation GreaterLoc,
  394. bool IsSelfClosing) {
  395. Tag->setAttrs(Attrs);
  396. Tag->setGreaterLoc(GreaterLoc);
  397. if (IsSelfClosing)
  398. Tag->setSelfClosing();
  399. else if (!isHTMLEndTagForbidden(Tag->getTagName()))
  400. HTMLOpenTags.push_back(Tag);
  401. }
  402. HTMLEndTagComment *Sema::actOnHTMLEndTag(SourceLocation LocBegin,
  403. SourceLocation LocEnd,
  404. StringRef TagName) {
  405. HTMLEndTagComment *HET =
  406. new (Allocator) HTMLEndTagComment(LocBegin, LocEnd, TagName);
  407. if (isHTMLEndTagForbidden(TagName)) {
  408. Diag(HET->getLocation(), diag::warn_doc_html_end_forbidden)
  409. << TagName << HET->getSourceRange();
  410. HET->setIsMalformed();
  411. return HET;
  412. }
  413. bool FoundOpen = false;
  414. for (SmallVectorImpl<HTMLStartTagComment *>::const_reverse_iterator
  415. I = HTMLOpenTags.rbegin(), E = HTMLOpenTags.rend();
  416. I != E; ++I) {
  417. if ((*I)->getTagName() == TagName) {
  418. FoundOpen = true;
  419. break;
  420. }
  421. }
  422. if (!FoundOpen) {
  423. Diag(HET->getLocation(), diag::warn_doc_html_end_unbalanced)
  424. << HET->getSourceRange();
  425. HET->setIsMalformed();
  426. return HET;
  427. }
  428. while (!HTMLOpenTags.empty()) {
  429. HTMLStartTagComment *HST = HTMLOpenTags.pop_back_val();
  430. StringRef LastNotClosedTagName = HST->getTagName();
  431. if (LastNotClosedTagName == TagName) {
  432. // If the start tag is malformed, end tag is malformed as well.
  433. if (HST->isMalformed())
  434. HET->setIsMalformed();
  435. break;
  436. }
  437. if (isHTMLEndTagOptional(LastNotClosedTagName))
  438. continue;
  439. bool OpenLineInvalid;
  440. const unsigned OpenLine = SourceMgr.getPresumedLineNumber(
  441. HST->getLocation(),
  442. &OpenLineInvalid);
  443. bool CloseLineInvalid;
  444. const unsigned CloseLine = SourceMgr.getPresumedLineNumber(
  445. HET->getLocation(),
  446. &CloseLineInvalid);
  447. if (OpenLineInvalid || CloseLineInvalid || OpenLine == CloseLine) {
  448. Diag(HST->getLocation(), diag::warn_doc_html_start_end_mismatch)
  449. << HST->getTagName() << HET->getTagName()
  450. << HST->getSourceRange() << HET->getSourceRange();
  451. HST->setIsMalformed();
  452. } else {
  453. Diag(HST->getLocation(), diag::warn_doc_html_start_end_mismatch)
  454. << HST->getTagName() << HET->getTagName()
  455. << HST->getSourceRange();
  456. Diag(HET->getLocation(), diag::note_doc_html_end_tag)
  457. << HET->getSourceRange();
  458. HST->setIsMalformed();
  459. }
  460. }
  461. return HET;
  462. }
  463. FullComment *Sema::actOnFullComment(
  464. ArrayRef<BlockContentComment *> Blocks) {
  465. FullComment *FC = new (Allocator) FullComment(Blocks, ThisDeclInfo);
  466. resolveParamCommandIndexes(FC);
  467. // Complain about HTML tags that are not closed.
  468. while (!HTMLOpenTags.empty()) {
  469. HTMLStartTagComment *HST = HTMLOpenTags.pop_back_val();
  470. if (isHTMLEndTagOptional(HST->getTagName()))
  471. continue;
  472. Diag(HST->getLocation(), diag::warn_doc_html_missing_end_tag)
  473. << HST->getTagName() << HST->getSourceRange();
  474. HST->setIsMalformed();
  475. }
  476. return FC;
  477. }
  478. void Sema::checkBlockCommandEmptyParagraph(BlockCommandComment *Command) {
  479. if (Traits.getCommandInfo(Command->getCommandID())->IsEmptyParagraphAllowed)
  480. return;
  481. ParagraphComment *Paragraph = Command->getParagraph();
  482. if (Paragraph->isWhitespace()) {
  483. SourceLocation DiagLoc;
  484. if (Command->getNumArgs() > 0)
  485. DiagLoc = Command->getArgRange(Command->getNumArgs() - 1).getEnd();
  486. if (!DiagLoc.isValid())
  487. DiagLoc = Command->getCommandNameRange(Traits).getEnd();
  488. Diag(DiagLoc, diag::warn_doc_block_command_empty_paragraph)
  489. << Command->getCommandMarker()
  490. << Command->getCommandName(Traits)
  491. << Command->getSourceRange();
  492. }
  493. }
  494. void Sema::checkReturnsCommand(const BlockCommandComment *Command) {
  495. if (!Traits.getCommandInfo(Command->getCommandID())->IsReturnsCommand)
  496. return;
  497. assert(ThisDeclInfo && "should not call this check on a bare comment");
  498. // We allow the return command for all @properties because it can be used
  499. // to document the value that the property getter returns.
  500. if (isObjCPropertyDecl())
  501. return;
  502. if (involvesFunctionType()) {
  503. assert(!ThisDeclInfo->ReturnType.isNull() &&
  504. "should have a valid return type");
  505. if (ThisDeclInfo->ReturnType->isVoidType()) {
  506. unsigned DiagKind;
  507. switch (ThisDeclInfo->CommentDecl->getKind()) {
  508. default:
  509. if (ThisDeclInfo->IsObjCMethod)
  510. DiagKind = 3;
  511. else
  512. DiagKind = 0;
  513. break;
  514. case Decl::CXXConstructor:
  515. DiagKind = 1;
  516. break;
  517. case Decl::CXXDestructor:
  518. DiagKind = 2;
  519. break;
  520. }
  521. Diag(Command->getLocation(),
  522. diag::warn_doc_returns_attached_to_a_void_function)
  523. << Command->getCommandMarker()
  524. << Command->getCommandName(Traits)
  525. << DiagKind
  526. << Command->getSourceRange();
  527. }
  528. return;
  529. }
  530. Diag(Command->getLocation(),
  531. diag::warn_doc_returns_not_attached_to_a_function_decl)
  532. << Command->getCommandMarker()
  533. << Command->getCommandName(Traits)
  534. << Command->getSourceRange();
  535. }
  536. void Sema::checkBlockCommandDuplicate(const BlockCommandComment *Command) {
  537. const CommandInfo *Info = Traits.getCommandInfo(Command->getCommandID());
  538. const BlockCommandComment *PrevCommand = nullptr;
  539. if (Info->IsBriefCommand) {
  540. if (!BriefCommand) {
  541. BriefCommand = Command;
  542. return;
  543. }
  544. PrevCommand = BriefCommand;
  545. } else if (Info->IsHeaderfileCommand) {
  546. if (!HeaderfileCommand) {
  547. HeaderfileCommand = Command;
  548. return;
  549. }
  550. PrevCommand = HeaderfileCommand;
  551. } else {
  552. // We don't want to check this command for duplicates.
  553. return;
  554. }
  555. StringRef CommandName = Command->getCommandName(Traits);
  556. StringRef PrevCommandName = PrevCommand->getCommandName(Traits);
  557. Diag(Command->getLocation(), diag::warn_doc_block_command_duplicate)
  558. << Command->getCommandMarker()
  559. << CommandName
  560. << Command->getSourceRange();
  561. if (CommandName == PrevCommandName)
  562. Diag(PrevCommand->getLocation(), diag::note_doc_block_command_previous)
  563. << PrevCommand->getCommandMarker()
  564. << PrevCommandName
  565. << PrevCommand->getSourceRange();
  566. else
  567. Diag(PrevCommand->getLocation(),
  568. diag::note_doc_block_command_previous_alias)
  569. << PrevCommand->getCommandMarker()
  570. << PrevCommandName
  571. << CommandName;
  572. }
  573. void Sema::checkDeprecatedCommand(const BlockCommandComment *Command) {
  574. if (!Traits.getCommandInfo(Command->getCommandID())->IsDeprecatedCommand)
  575. return;
  576. assert(ThisDeclInfo && "should not call this check on a bare comment");
  577. const Decl *D = ThisDeclInfo->CommentDecl;
  578. if (!D)
  579. return;
  580. if (D->hasAttr<DeprecatedAttr>() ||
  581. D->hasAttr<AvailabilityAttr>() ||
  582. D->hasAttr<UnavailableAttr>())
  583. return;
  584. Diag(Command->getLocation(), diag::warn_doc_deprecated_not_sync)
  585. << Command->getSourceRange() << Command->getCommandMarker();
  586. // Try to emit a fixit with a deprecation attribute.
  587. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  588. // Don't emit a Fix-It for non-member function definitions. GCC does not
  589. // accept attributes on them.
  590. const DeclContext *Ctx = FD->getDeclContext();
  591. if ((!Ctx || !Ctx->isRecord()) &&
  592. FD->doesThisDeclarationHaveABody())
  593. return;
  594. const LangOptions &LO = FD->getLangOpts();
  595. const bool DoubleSquareBracket = LO.CPlusPlus14 || LO.C2x;
  596. StringRef AttributeSpelling =
  597. DoubleSquareBracket ? "[[deprecated]]" : "__attribute__((deprecated))";
  598. if (PP) {
  599. // Try to find a replacement macro:
  600. // - In C2x/C++14 we prefer [[deprecated]].
  601. // - If not found or an older C/C++ look for __attribute__((deprecated)).
  602. StringRef MacroName;
  603. if (DoubleSquareBracket) {
  604. TokenValue Tokens[] = {tok::l_square, tok::l_square,
  605. PP->getIdentifierInfo("deprecated"),
  606. tok::r_square, tok::r_square};
  607. MacroName = PP->getLastMacroWithSpelling(FD->getLocation(), Tokens);
  608. if (!MacroName.empty())
  609. AttributeSpelling = MacroName;
  610. }
  611. if (MacroName.empty()) {
  612. TokenValue Tokens[] = {
  613. tok::kw___attribute, tok::l_paren,
  614. tok::l_paren, PP->getIdentifierInfo("deprecated"),
  615. tok::r_paren, tok::r_paren};
  616. StringRef MacroName =
  617. PP->getLastMacroWithSpelling(FD->getLocation(), Tokens);
  618. if (!MacroName.empty())
  619. AttributeSpelling = MacroName;
  620. }
  621. }
  622. SmallString<64> TextToInsert = AttributeSpelling;
  623. TextToInsert += " ";
  624. SourceLocation Loc = FD->getSourceRange().getBegin();
  625. Diag(Loc, diag::note_add_deprecation_attr)
  626. << FixItHint::CreateInsertion(Loc, TextToInsert);
  627. }
  628. }
  629. void Sema::resolveParamCommandIndexes(const FullComment *FC) {
  630. if (!involvesFunctionType()) {
  631. // We already warned that \\param commands are not attached to a function
  632. // decl.
  633. return;
  634. }
  635. SmallVector<ParamCommandComment *, 8> UnresolvedParamCommands;
  636. // Comment AST nodes that correspond to \c ParamVars for which we have
  637. // found a \\param command or NULL if no documentation was found so far.
  638. SmallVector<ParamCommandComment *, 8> ParamVarDocs;
  639. ArrayRef<const ParmVarDecl *> ParamVars = getParamVars();
  640. ParamVarDocs.resize(ParamVars.size(), nullptr);
  641. // First pass over all \\param commands: resolve all parameter names.
  642. for (Comment::child_iterator I = FC->child_begin(), E = FC->child_end();
  643. I != E; ++I) {
  644. ParamCommandComment *PCC = dyn_cast<ParamCommandComment>(*I);
  645. if (!PCC || !PCC->hasParamName())
  646. continue;
  647. StringRef ParamName = PCC->getParamNameAsWritten();
  648. // Check that referenced parameter name is in the function decl.
  649. const unsigned ResolvedParamIndex = resolveParmVarReference(ParamName,
  650. ParamVars);
  651. if (ResolvedParamIndex == ParamCommandComment::VarArgParamIndex) {
  652. PCC->setIsVarArgParam();
  653. continue;
  654. }
  655. if (ResolvedParamIndex == ParamCommandComment::InvalidParamIndex) {
  656. UnresolvedParamCommands.push_back(PCC);
  657. continue;
  658. }
  659. PCC->setParamIndex(ResolvedParamIndex);
  660. if (ParamVarDocs[ResolvedParamIndex]) {
  661. SourceRange ArgRange = PCC->getParamNameRange();
  662. Diag(ArgRange.getBegin(), diag::warn_doc_param_duplicate)
  663. << ParamName << ArgRange;
  664. ParamCommandComment *PrevCommand = ParamVarDocs[ResolvedParamIndex];
  665. Diag(PrevCommand->getLocation(), diag::note_doc_param_previous)
  666. << PrevCommand->getParamNameRange();
  667. }
  668. ParamVarDocs[ResolvedParamIndex] = PCC;
  669. }
  670. // Find parameter declarations that have no corresponding \\param.
  671. SmallVector<const ParmVarDecl *, 8> OrphanedParamDecls;
  672. for (unsigned i = 0, e = ParamVarDocs.size(); i != e; ++i) {
  673. if (!ParamVarDocs[i])
  674. OrphanedParamDecls.push_back(ParamVars[i]);
  675. }
  676. // Second pass over unresolved \\param commands: do typo correction.
  677. // Suggest corrections from a set of parameter declarations that have no
  678. // corresponding \\param.
  679. for (unsigned i = 0, e = UnresolvedParamCommands.size(); i != e; ++i) {
  680. const ParamCommandComment *PCC = UnresolvedParamCommands[i];
  681. SourceRange ArgRange = PCC->getParamNameRange();
  682. StringRef ParamName = PCC->getParamNameAsWritten();
  683. Diag(ArgRange.getBegin(), diag::warn_doc_param_not_found)
  684. << ParamName << ArgRange;
  685. // All parameters documented -- can't suggest a correction.
  686. if (OrphanedParamDecls.size() == 0)
  687. continue;
  688. unsigned CorrectedParamIndex = ParamCommandComment::InvalidParamIndex;
  689. if (OrphanedParamDecls.size() == 1) {
  690. // If one parameter is not documented then that parameter is the only
  691. // possible suggestion.
  692. CorrectedParamIndex = 0;
  693. } else {
  694. // Do typo correction.
  695. CorrectedParamIndex = correctTypoInParmVarReference(ParamName,
  696. OrphanedParamDecls);
  697. }
  698. if (CorrectedParamIndex != ParamCommandComment::InvalidParamIndex) {
  699. const ParmVarDecl *CorrectedPVD = OrphanedParamDecls[CorrectedParamIndex];
  700. if (const IdentifierInfo *CorrectedII = CorrectedPVD->getIdentifier())
  701. Diag(ArgRange.getBegin(), diag::note_doc_param_name_suggestion)
  702. << CorrectedII->getName()
  703. << FixItHint::CreateReplacement(ArgRange, CorrectedII->getName());
  704. }
  705. }
  706. }
  707. bool Sema::involvesFunctionType() {
  708. if (!ThisDeclInfo)
  709. return false;
  710. if (!ThisDeclInfo->IsFilled)
  711. inspectThisDecl();
  712. return ThisDeclInfo->involvesFunctionType();
  713. }
  714. bool Sema::isFunctionDecl() {
  715. if (!ThisDeclInfo)
  716. return false;
  717. if (!ThisDeclInfo->IsFilled)
  718. inspectThisDecl();
  719. return ThisDeclInfo->getKind() == DeclInfo::FunctionKind;
  720. }
  721. bool Sema::isAnyFunctionDecl() {
  722. return isFunctionDecl() && ThisDeclInfo->CurrentDecl &&
  723. isa<FunctionDecl>(ThisDeclInfo->CurrentDecl);
  724. }
  725. bool Sema::isFunctionOrMethodVariadic() {
  726. if (!ThisDeclInfo)
  727. return false;
  728. if (!ThisDeclInfo->IsFilled)
  729. inspectThisDecl();
  730. return ThisDeclInfo->IsVariadic;
  731. }
  732. bool Sema::isObjCMethodDecl() {
  733. return isFunctionDecl() && ThisDeclInfo->CurrentDecl &&
  734. isa<ObjCMethodDecl>(ThisDeclInfo->CurrentDecl);
  735. }
  736. bool Sema::isFunctionPointerVarDecl() {
  737. if (!ThisDeclInfo)
  738. return false;
  739. if (!ThisDeclInfo->IsFilled)
  740. inspectThisDecl();
  741. if (ThisDeclInfo->getKind() == DeclInfo::VariableKind) {
  742. if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDeclInfo->CurrentDecl)) {
  743. QualType QT = VD->getType();
  744. return QT->isFunctionPointerType();
  745. }
  746. }
  747. return false;
  748. }
  749. bool Sema::isObjCPropertyDecl() {
  750. if (!ThisDeclInfo)
  751. return false;
  752. if (!ThisDeclInfo->IsFilled)
  753. inspectThisDecl();
  754. return ThisDeclInfo->CurrentDecl->getKind() == Decl::ObjCProperty;
  755. }
  756. bool Sema::isTemplateOrSpecialization() {
  757. if (!ThisDeclInfo)
  758. return false;
  759. if (!ThisDeclInfo->IsFilled)
  760. inspectThisDecl();
  761. return ThisDeclInfo->getTemplateKind() != DeclInfo::NotTemplate;
  762. }
  763. bool Sema::isRecordLikeDecl() {
  764. if (!ThisDeclInfo)
  765. return false;
  766. if (!ThisDeclInfo->IsFilled)
  767. inspectThisDecl();
  768. return isUnionDecl() || isClassOrStructDecl() || isObjCInterfaceDecl() ||
  769. isObjCProtocolDecl();
  770. }
  771. bool Sema::isUnionDecl() {
  772. if (!ThisDeclInfo)
  773. return false;
  774. if (!ThisDeclInfo->IsFilled)
  775. inspectThisDecl();
  776. if (const RecordDecl *RD =
  777. dyn_cast_or_null<RecordDecl>(ThisDeclInfo->CurrentDecl))
  778. return RD->isUnion();
  779. return false;
  780. }
  781. static bool isClassOrStructDeclImpl(const Decl *D) {
  782. if (auto *record = dyn_cast_or_null<RecordDecl>(D))
  783. return !record->isUnion();
  784. return false;
  785. }
  786. bool Sema::isClassOrStructDecl() {
  787. if (!ThisDeclInfo)
  788. return false;
  789. if (!ThisDeclInfo->IsFilled)
  790. inspectThisDecl();
  791. if (!ThisDeclInfo->CurrentDecl)
  792. return false;
  793. return isClassOrStructDeclImpl(ThisDeclInfo->CurrentDecl);
  794. }
  795. bool Sema::isClassOrStructOrTagTypedefDecl() {
  796. if (!ThisDeclInfo)
  797. return false;
  798. if (!ThisDeclInfo->IsFilled)
  799. inspectThisDecl();
  800. if (!ThisDeclInfo->CurrentDecl)
  801. return false;
  802. if (isClassOrStructDeclImpl(ThisDeclInfo->CurrentDecl))
  803. return true;
  804. if (auto *ThisTypedefDecl = dyn_cast<TypedefDecl>(ThisDeclInfo->CurrentDecl)) {
  805. auto UnderlyingType = ThisTypedefDecl->getUnderlyingType();
  806. if (auto ThisElaboratedType = dyn_cast<ElaboratedType>(UnderlyingType)) {
  807. auto DesugaredType = ThisElaboratedType->desugar();
  808. if (auto *DesugaredTypePtr = DesugaredType.getTypePtrOrNull()) {
  809. if (auto *ThisRecordType = dyn_cast<RecordType>(DesugaredTypePtr)) {
  810. return isClassOrStructDeclImpl(ThisRecordType->getAsRecordDecl());
  811. }
  812. }
  813. }
  814. }
  815. return false;
  816. }
  817. bool Sema::isClassTemplateDecl() {
  818. if (!ThisDeclInfo)
  819. return false;
  820. if (!ThisDeclInfo->IsFilled)
  821. inspectThisDecl();
  822. return ThisDeclInfo->CurrentDecl &&
  823. (isa<ClassTemplateDecl>(ThisDeclInfo->CurrentDecl));
  824. }
  825. bool Sema::isFunctionTemplateDecl() {
  826. if (!ThisDeclInfo)
  827. return false;
  828. if (!ThisDeclInfo->IsFilled)
  829. inspectThisDecl();
  830. return ThisDeclInfo->CurrentDecl &&
  831. (isa<FunctionTemplateDecl>(ThisDeclInfo->CurrentDecl));
  832. }
  833. bool Sema::isObjCInterfaceDecl() {
  834. if (!ThisDeclInfo)
  835. return false;
  836. if (!ThisDeclInfo->IsFilled)
  837. inspectThisDecl();
  838. return ThisDeclInfo->CurrentDecl &&
  839. isa<ObjCInterfaceDecl>(ThisDeclInfo->CurrentDecl);
  840. }
  841. bool Sema::isObjCProtocolDecl() {
  842. if (!ThisDeclInfo)
  843. return false;
  844. if (!ThisDeclInfo->IsFilled)
  845. inspectThisDecl();
  846. return ThisDeclInfo->CurrentDecl &&
  847. isa<ObjCProtocolDecl>(ThisDeclInfo->CurrentDecl);
  848. }
  849. ArrayRef<const ParmVarDecl *> Sema::getParamVars() {
  850. if (!ThisDeclInfo->IsFilled)
  851. inspectThisDecl();
  852. return ThisDeclInfo->ParamVars;
  853. }
  854. void Sema::inspectThisDecl() {
  855. ThisDeclInfo->fill();
  856. }
  857. unsigned Sema::resolveParmVarReference(StringRef Name,
  858. ArrayRef<const ParmVarDecl *> ParamVars) {
  859. for (unsigned i = 0, e = ParamVars.size(); i != e; ++i) {
  860. const IdentifierInfo *II = ParamVars[i]->getIdentifier();
  861. if (II && II->getName() == Name)
  862. return i;
  863. }
  864. if (Name == "..." && isFunctionOrMethodVariadic())
  865. return ParamCommandComment::VarArgParamIndex;
  866. return ParamCommandComment::InvalidParamIndex;
  867. }
  868. namespace {
  869. class SimpleTypoCorrector {
  870. const NamedDecl *BestDecl;
  871. StringRef Typo;
  872. const unsigned MaxEditDistance;
  873. unsigned BestEditDistance;
  874. unsigned BestIndex;
  875. unsigned NextIndex;
  876. public:
  877. explicit SimpleTypoCorrector(StringRef Typo)
  878. : BestDecl(nullptr), Typo(Typo), MaxEditDistance((Typo.size() + 2) / 3),
  879. BestEditDistance(MaxEditDistance + 1), BestIndex(0), NextIndex(0) {}
  880. void addDecl(const NamedDecl *ND);
  881. const NamedDecl *getBestDecl() const {
  882. if (BestEditDistance > MaxEditDistance)
  883. return nullptr;
  884. return BestDecl;
  885. }
  886. unsigned getBestDeclIndex() const {
  887. assert(getBestDecl());
  888. return BestIndex;
  889. }
  890. };
  891. void SimpleTypoCorrector::addDecl(const NamedDecl *ND) {
  892. unsigned CurrIndex = NextIndex++;
  893. const IdentifierInfo *II = ND->getIdentifier();
  894. if (!II)
  895. return;
  896. StringRef Name = II->getName();
  897. unsigned MinPossibleEditDistance = abs((int)Name.size() - (int)Typo.size());
  898. if (MinPossibleEditDistance > 0 &&
  899. Typo.size() / MinPossibleEditDistance < 3)
  900. return;
  901. unsigned EditDistance = Typo.edit_distance(Name, true, MaxEditDistance);
  902. if (EditDistance < BestEditDistance) {
  903. BestEditDistance = EditDistance;
  904. BestDecl = ND;
  905. BestIndex = CurrIndex;
  906. }
  907. }
  908. } // end anonymous namespace
  909. unsigned Sema::correctTypoInParmVarReference(
  910. StringRef Typo,
  911. ArrayRef<const ParmVarDecl *> ParamVars) {
  912. SimpleTypoCorrector Corrector(Typo);
  913. for (unsigned i = 0, e = ParamVars.size(); i != e; ++i)
  914. Corrector.addDecl(ParamVars[i]);
  915. if (Corrector.getBestDecl())
  916. return Corrector.getBestDeclIndex();
  917. else
  918. return ParamCommandComment::InvalidParamIndex;
  919. }
  920. namespace {
  921. bool ResolveTParamReferenceHelper(
  922. StringRef Name,
  923. const TemplateParameterList *TemplateParameters,
  924. SmallVectorImpl<unsigned> *Position) {
  925. for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
  926. const NamedDecl *Param = TemplateParameters->getParam(i);
  927. const IdentifierInfo *II = Param->getIdentifier();
  928. if (II && II->getName() == Name) {
  929. Position->push_back(i);
  930. return true;
  931. }
  932. if (const TemplateTemplateParmDecl *TTP =
  933. dyn_cast<TemplateTemplateParmDecl>(Param)) {
  934. Position->push_back(i);
  935. if (ResolveTParamReferenceHelper(Name, TTP->getTemplateParameters(),
  936. Position))
  937. return true;
  938. Position->pop_back();
  939. }
  940. }
  941. return false;
  942. }
  943. } // end anonymous namespace
  944. bool Sema::resolveTParamReference(
  945. StringRef Name,
  946. const TemplateParameterList *TemplateParameters,
  947. SmallVectorImpl<unsigned> *Position) {
  948. Position->clear();
  949. if (!TemplateParameters)
  950. return false;
  951. return ResolveTParamReferenceHelper(Name, TemplateParameters, Position);
  952. }
  953. namespace {
  954. void CorrectTypoInTParamReferenceHelper(
  955. const TemplateParameterList *TemplateParameters,
  956. SimpleTypoCorrector &Corrector) {
  957. for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
  958. const NamedDecl *Param = TemplateParameters->getParam(i);
  959. Corrector.addDecl(Param);
  960. if (const TemplateTemplateParmDecl *TTP =
  961. dyn_cast<TemplateTemplateParmDecl>(Param))
  962. CorrectTypoInTParamReferenceHelper(TTP->getTemplateParameters(),
  963. Corrector);
  964. }
  965. }
  966. } // end anonymous namespace
  967. StringRef Sema::correctTypoInTParamReference(
  968. StringRef Typo,
  969. const TemplateParameterList *TemplateParameters) {
  970. SimpleTypoCorrector Corrector(Typo);
  971. CorrectTypoInTParamReferenceHelper(TemplateParameters, Corrector);
  972. if (const NamedDecl *ND = Corrector.getBestDecl()) {
  973. const IdentifierInfo *II = ND->getIdentifier();
  974. assert(II && "SimpleTypoCorrector should not return this decl");
  975. return II->getName();
  976. }
  977. return StringRef();
  978. }
  979. InlineCommandComment::RenderKind
  980. Sema::getInlineCommandRenderKind(StringRef Name) const {
  981. assert(Traits.getCommandInfo(Name)->IsInlineCommand);
  982. return llvm::StringSwitch<InlineCommandComment::RenderKind>(Name)
  983. .Case("b", InlineCommandComment::RenderBold)
  984. .Cases("c", "p", InlineCommandComment::RenderMonospaced)
  985. .Cases("a", "e", "em", InlineCommandComment::RenderEmphasized)
  986. .Case("anchor", InlineCommandComment::RenderAnchor)
  987. .Default(InlineCommandComment::RenderNormal);
  988. }
  989. } // end namespace comments
  990. } // end namespace clang