1 //===--- CommentSema.cpp - Doxygen comment semantic analysis --------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/AST/CommentSema.h"
10 #include "clang/AST/Attr.h"
11 #include "clang/AST/CommentCommandTraits.h"
12 #include "clang/AST/CommentDiagnostic.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclTemplate.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"
24 #include "clang/AST/CommentHTMLTagsProperties.inc"
25 } // end anonymous namespace
27 Sema::Sema(llvm::BumpPtrAllocator &Allocator, const SourceManager &SourceMgr,
28 DiagnosticsEngine &Diags, CommandTraits &Traits,
29 const Preprocessor *PP) :
30 Allocator(Allocator), SourceMgr(SourceMgr), Diags(Diags), Traits(Traits),
31 PP(PP), ThisDeclInfo(nullptr), BriefCommand(nullptr),
32 HeaderfileCommand(nullptr) {
35 void Sema::setDecl(const Decl *D) {
39 ThisDeclInfo = new (Allocator) DeclInfo;
40 ThisDeclInfo->CommentDecl = D;
41 ThisDeclInfo->IsFilled = false;
44 ParagraphComment *Sema::actOnParagraphComment(
45 ArrayRef<InlineContentComment *> Content) {
46 return new (Allocator) ParagraphComment(Content);
49 BlockCommandComment *Sema::actOnBlockCommandStart(
50 SourceLocation LocBegin,
51 SourceLocation LocEnd,
53 CommandMarkerKind CommandMarker) {
54 BlockCommandComment *BC = new (Allocator) BlockCommandComment(LocBegin, LocEnd,
57 checkContainerDecl(BC);
61 void Sema::actOnBlockCommandArgs(BlockCommandComment *Command,
62 ArrayRef<BlockCommandComment::Argument> Args) {
63 Command->setArgs(Args);
66 void Sema::actOnBlockCommandFinish(BlockCommandComment *Command,
67 ParagraphComment *Paragraph) {
68 Command->setParagraph(Paragraph);
69 checkBlockCommandEmptyParagraph(Command);
70 checkBlockCommandDuplicate(Command);
72 // These checks only make sense if the comment is attached to a
74 checkReturnsCommand(Command);
75 checkDeprecatedCommand(Command);
79 ParamCommandComment *Sema::actOnParamCommandStart(
80 SourceLocation LocBegin,
81 SourceLocation LocEnd,
83 CommandMarkerKind CommandMarker) {
84 ParamCommandComment *Command =
85 new (Allocator) ParamCommandComment(LocBegin, LocEnd, CommandID,
88 if (!isFunctionDecl() && !isFunctionOrBlockPointerVarLikeDecl())
89 Diag(Command->getLocation(),
90 diag::warn_doc_param_not_attached_to_a_function_decl)
92 << Command->getCommandNameRange(Traits);
97 void Sema::checkFunctionDeclVerbatimLine(const BlockCommandComment *Comment) {
98 const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
99 if (!Info->IsFunctionDeclarationCommand)
103 switch (Comment->getCommandID()) {
104 case CommandTraits::KCI_function:
105 DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl())? 1 : 0;
107 case CommandTraits::KCI_functiongroup:
108 DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl())? 2 : 0;
110 case CommandTraits::KCI_method:
111 DiagSelect = !isObjCMethodDecl() ? 3 : 0;
113 case CommandTraits::KCI_methodgroup:
114 DiagSelect = !isObjCMethodDecl() ? 4 : 0;
116 case CommandTraits::KCI_callback:
117 DiagSelect = !isFunctionPointerVarDecl() ? 5 : 0;
124 Diag(Comment->getLocation(), diag::warn_doc_function_method_decl_mismatch)
125 << Comment->getCommandMarker()
126 << (DiagSelect-1) << (DiagSelect-1)
127 << Comment->getSourceRange();
130 void Sema::checkContainerDeclVerbatimLine(const BlockCommandComment *Comment) {
131 const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
132 if (!Info->IsRecordLikeDeclarationCommand)
135 switch (Comment->getCommandID()) {
136 case CommandTraits::KCI_class:
137 DiagSelect = (!isClassOrStructDecl() && !isClassTemplateDecl()) ? 1 : 0;
138 // Allow @class command on @interface declarations.
139 // FIXME. Currently, \class and @class are indistinguishable. So,
140 // \class is also allowed on an @interface declaration
141 if (DiagSelect && Comment->getCommandMarker() && isObjCInterfaceDecl())
144 case CommandTraits::KCI_interface:
145 DiagSelect = !isObjCInterfaceDecl() ? 2 : 0;
147 case CommandTraits::KCI_protocol:
148 DiagSelect = !isObjCProtocolDecl() ? 3 : 0;
150 case CommandTraits::KCI_struct:
151 DiagSelect = !isClassOrStructDecl() ? 4 : 0;
153 case CommandTraits::KCI_union:
154 DiagSelect = !isUnionDecl() ? 5 : 0;
161 Diag(Comment->getLocation(), diag::warn_doc_api_container_decl_mismatch)
162 << Comment->getCommandMarker()
163 << (DiagSelect-1) << (DiagSelect-1)
164 << Comment->getSourceRange();
167 void Sema::checkContainerDecl(const BlockCommandComment *Comment) {
168 const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
169 if (!Info->IsRecordLikeDetailCommand || isRecordLikeDecl())
172 switch (Comment->getCommandID()) {
173 case CommandTraits::KCI_classdesign:
176 case CommandTraits::KCI_coclass:
179 case CommandTraits::KCI_dependency:
182 case CommandTraits::KCI_helper:
185 case CommandTraits::KCI_helperclass:
188 case CommandTraits::KCI_helps:
191 case CommandTraits::KCI_instancesize:
194 case CommandTraits::KCI_ownership:
197 case CommandTraits::KCI_performance:
200 case CommandTraits::KCI_security:
203 case CommandTraits::KCI_superclass:
211 Diag(Comment->getLocation(), diag::warn_doc_container_decl_mismatch)
212 << Comment->getCommandMarker()
214 << Comment->getSourceRange();
217 /// Turn a string into the corresponding PassDirection or -1 if it's not
219 static int getParamPassDirection(StringRef Arg) {
220 return llvm::StringSwitch<int>(Arg)
221 .Case("[in]", ParamCommandComment::In)
222 .Case("[out]", ParamCommandComment::Out)
223 .Cases("[in,out]", "[out,in]", ParamCommandComment::InOut)
227 void Sema::actOnParamCommandDirectionArg(ParamCommandComment *Command,
228 SourceLocation ArgLocBegin,
229 SourceLocation ArgLocEnd,
231 std::string ArgLower = Arg.lower();
232 int Direction = getParamPassDirection(ArgLower);
234 if (Direction == -1) {
235 // Try again with whitespace removed.
237 std::remove_if(ArgLower.begin(), ArgLower.end(), clang::isWhitespace),
239 Direction = getParamPassDirection(ArgLower);
241 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
242 if (Direction != -1) {
243 const char *FixedName = ParamCommandComment::getDirectionAsString(
244 (ParamCommandComment::PassDirection)Direction);
245 Diag(ArgLocBegin, diag::warn_doc_param_spaces_in_direction)
246 << ArgRange << FixItHint::CreateReplacement(ArgRange, FixedName);
248 Diag(ArgLocBegin, diag::warn_doc_param_invalid_direction) << ArgRange;
249 Direction = ParamCommandComment::In; // Sane fall back.
252 Command->setDirection((ParamCommandComment::PassDirection)Direction,
256 void Sema::actOnParamCommandParamNameArg(ParamCommandComment *Command,
257 SourceLocation ArgLocBegin,
258 SourceLocation ArgLocEnd,
260 // Parser will not feed us more arguments than needed.
261 assert(Command->getNumArgs() == 0);
263 if (!Command->isDirectionExplicit()) {
264 // User didn't provide a direction argument.
265 Command->setDirection(ParamCommandComment::In, /* Explicit = */ false);
267 typedef BlockCommandComment::Argument Argument;
268 Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin,
271 Command->setArgs(llvm::makeArrayRef(A, 1));
274 void Sema::actOnParamCommandFinish(ParamCommandComment *Command,
275 ParagraphComment *Paragraph) {
276 Command->setParagraph(Paragraph);
277 checkBlockCommandEmptyParagraph(Command);
280 TParamCommandComment *Sema::actOnTParamCommandStart(
281 SourceLocation LocBegin,
282 SourceLocation LocEnd,
284 CommandMarkerKind CommandMarker) {
285 TParamCommandComment *Command =
286 new (Allocator) TParamCommandComment(LocBegin, LocEnd, CommandID,
289 if (!isTemplateOrSpecialization())
290 Diag(Command->getLocation(),
291 diag::warn_doc_tparam_not_attached_to_a_template_decl)
293 << Command->getCommandNameRange(Traits);
298 void Sema::actOnTParamCommandParamNameArg(TParamCommandComment *Command,
299 SourceLocation ArgLocBegin,
300 SourceLocation ArgLocEnd,
302 // Parser will not feed us more arguments than needed.
303 assert(Command->getNumArgs() == 0);
305 typedef BlockCommandComment::Argument Argument;
306 Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin,
309 Command->setArgs(llvm::makeArrayRef(A, 1));
311 if (!isTemplateOrSpecialization()) {
312 // We already warned that this \\tparam is not attached to a template decl.
316 const TemplateParameterList *TemplateParameters =
317 ThisDeclInfo->TemplateParameters;
318 SmallVector<unsigned, 2> Position;
319 if (resolveTParamReference(Arg, TemplateParameters, &Position)) {
320 Command->setPosition(copyArray(llvm::makeArrayRef(Position)));
321 TParamCommandComment *&PrevCommand = TemplateParameterDocs[Arg];
323 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
324 Diag(ArgLocBegin, diag::warn_doc_tparam_duplicate)
326 Diag(PrevCommand->getLocation(), diag::note_doc_tparam_previous)
327 << PrevCommand->getParamNameRange();
329 PrevCommand = Command;
333 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
334 Diag(ArgLocBegin, diag::warn_doc_tparam_not_found)
337 if (!TemplateParameters || TemplateParameters->size() == 0)
340 StringRef CorrectedName;
341 if (TemplateParameters->size() == 1) {
342 const NamedDecl *Param = TemplateParameters->getParam(0);
343 const IdentifierInfo *II = Param->getIdentifier();
345 CorrectedName = II->getName();
347 CorrectedName = correctTypoInTParamReference(Arg, TemplateParameters);
350 if (!CorrectedName.empty()) {
351 Diag(ArgLocBegin, diag::note_doc_tparam_name_suggestion)
353 << FixItHint::CreateReplacement(ArgRange, CorrectedName);
357 void Sema::actOnTParamCommandFinish(TParamCommandComment *Command,
358 ParagraphComment *Paragraph) {
359 Command->setParagraph(Paragraph);
360 checkBlockCommandEmptyParagraph(Command);
363 InlineCommandComment *Sema::actOnInlineCommand(SourceLocation CommandLocBegin,
364 SourceLocation CommandLocEnd,
365 unsigned CommandID) {
366 ArrayRef<InlineCommandComment::Argument> Args;
367 StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
368 return new (Allocator) InlineCommandComment(
372 getInlineCommandRenderKind(CommandName),
376 InlineCommandComment *Sema::actOnInlineCommand(SourceLocation CommandLocBegin,
377 SourceLocation CommandLocEnd,
379 SourceLocation ArgLocBegin,
380 SourceLocation ArgLocEnd,
382 typedef InlineCommandComment::Argument Argument;
383 Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin,
386 StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
388 return new (Allocator) InlineCommandComment(
392 getInlineCommandRenderKind(CommandName),
393 llvm::makeArrayRef(A, 1));
396 InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin,
397 SourceLocation LocEnd,
398 StringRef CommandName) {
399 unsigned CommandID = Traits.registerUnknownCommand(CommandName)->getID();
400 return actOnUnknownCommand(LocBegin, LocEnd, CommandID);
403 InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin,
404 SourceLocation LocEnd,
405 unsigned CommandID) {
406 ArrayRef<InlineCommandComment::Argument> Args;
407 return new (Allocator) InlineCommandComment(
408 LocBegin, LocEnd, CommandID,
409 InlineCommandComment::RenderNormal,
413 TextComment *Sema::actOnText(SourceLocation LocBegin,
414 SourceLocation LocEnd,
416 return new (Allocator) TextComment(LocBegin, LocEnd, Text);
419 VerbatimBlockComment *Sema::actOnVerbatimBlockStart(SourceLocation Loc,
420 unsigned CommandID) {
421 StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
422 return new (Allocator) VerbatimBlockComment(
424 Loc.getLocWithOffset(1 + CommandName.size()),
428 VerbatimBlockLineComment *Sema::actOnVerbatimBlockLine(SourceLocation Loc,
430 return new (Allocator) VerbatimBlockLineComment(Loc, Text);
433 void Sema::actOnVerbatimBlockFinish(
434 VerbatimBlockComment *Block,
435 SourceLocation CloseNameLocBegin,
437 ArrayRef<VerbatimBlockLineComment *> Lines) {
438 Block->setCloseName(CloseName, CloseNameLocBegin);
439 Block->setLines(Lines);
442 VerbatimLineComment *Sema::actOnVerbatimLine(SourceLocation LocBegin,
444 SourceLocation TextBegin,
446 VerbatimLineComment *VL = new (Allocator) VerbatimLineComment(
448 TextBegin.getLocWithOffset(Text.size()),
452 checkFunctionDeclVerbatimLine(VL);
453 checkContainerDeclVerbatimLine(VL);
457 HTMLStartTagComment *Sema::actOnHTMLStartTagStart(SourceLocation LocBegin,
459 return new (Allocator) HTMLStartTagComment(LocBegin, TagName);
462 void Sema::actOnHTMLStartTagFinish(
463 HTMLStartTagComment *Tag,
464 ArrayRef<HTMLStartTagComment::Attribute> Attrs,
465 SourceLocation GreaterLoc,
466 bool IsSelfClosing) {
467 Tag->setAttrs(Attrs);
468 Tag->setGreaterLoc(GreaterLoc);
470 Tag->setSelfClosing();
471 else if (!isHTMLEndTagForbidden(Tag->getTagName()))
472 HTMLOpenTags.push_back(Tag);
475 HTMLEndTagComment *Sema::actOnHTMLEndTag(SourceLocation LocBegin,
476 SourceLocation LocEnd,
478 HTMLEndTagComment *HET =
479 new (Allocator) HTMLEndTagComment(LocBegin, LocEnd, TagName);
480 if (isHTMLEndTagForbidden(TagName)) {
481 Diag(HET->getLocation(), diag::warn_doc_html_end_forbidden)
482 << TagName << HET->getSourceRange();
483 HET->setIsMalformed();
487 bool FoundOpen = false;
488 for (SmallVectorImpl<HTMLStartTagComment *>::const_reverse_iterator
489 I = HTMLOpenTags.rbegin(), E = HTMLOpenTags.rend();
491 if ((*I)->getTagName() == TagName) {
497 Diag(HET->getLocation(), diag::warn_doc_html_end_unbalanced)
498 << HET->getSourceRange();
499 HET->setIsMalformed();
503 while (!HTMLOpenTags.empty()) {
504 HTMLStartTagComment *HST = HTMLOpenTags.pop_back_val();
505 StringRef LastNotClosedTagName = HST->getTagName();
506 if (LastNotClosedTagName == TagName) {
507 // If the start tag is malformed, end tag is malformed as well.
508 if (HST->isMalformed())
509 HET->setIsMalformed();
513 if (isHTMLEndTagOptional(LastNotClosedTagName))
516 bool OpenLineInvalid;
517 const unsigned OpenLine = SourceMgr.getPresumedLineNumber(
520 bool CloseLineInvalid;
521 const unsigned CloseLine = SourceMgr.getPresumedLineNumber(
525 if (OpenLineInvalid || CloseLineInvalid || OpenLine == CloseLine) {
526 Diag(HST->getLocation(), diag::warn_doc_html_start_end_mismatch)
527 << HST->getTagName() << HET->getTagName()
528 << HST->getSourceRange() << HET->getSourceRange();
529 HST->setIsMalformed();
531 Diag(HST->getLocation(), diag::warn_doc_html_start_end_mismatch)
532 << HST->getTagName() << HET->getTagName()
533 << HST->getSourceRange();
534 Diag(HET->getLocation(), diag::note_doc_html_end_tag)
535 << HET->getSourceRange();
536 HST->setIsMalformed();
543 FullComment *Sema::actOnFullComment(
544 ArrayRef<BlockContentComment *> Blocks) {
545 FullComment *FC = new (Allocator) FullComment(Blocks, ThisDeclInfo);
546 resolveParamCommandIndexes(FC);
548 // Complain about HTML tags that are not closed.
549 while (!HTMLOpenTags.empty()) {
550 HTMLStartTagComment *HST = HTMLOpenTags.pop_back_val();
551 if (isHTMLEndTagOptional(HST->getTagName()))
554 Diag(HST->getLocation(), diag::warn_doc_html_missing_end_tag)
555 << HST->getTagName() << HST->getSourceRange();
556 HST->setIsMalformed();
562 void Sema::checkBlockCommandEmptyParagraph(BlockCommandComment *Command) {
563 if (Traits.getCommandInfo(Command->getCommandID())->IsEmptyParagraphAllowed)
566 ParagraphComment *Paragraph = Command->getParagraph();
567 if (Paragraph->isWhitespace()) {
568 SourceLocation DiagLoc;
569 if (Command->getNumArgs() > 0)
570 DiagLoc = Command->getArgRange(Command->getNumArgs() - 1).getEnd();
571 if (!DiagLoc.isValid())
572 DiagLoc = Command->getCommandNameRange(Traits).getEnd();
573 Diag(DiagLoc, diag::warn_doc_block_command_empty_paragraph)
574 << Command->getCommandMarker()
575 << Command->getCommandName(Traits)
576 << Command->getSourceRange();
580 void Sema::checkReturnsCommand(const BlockCommandComment *Command) {
581 if (!Traits.getCommandInfo(Command->getCommandID())->IsReturnsCommand)
584 assert(ThisDeclInfo && "should not call this check on a bare comment");
586 // We allow the return command for all @properties because it can be used
587 // to document the value that the property getter returns.
588 if (isObjCPropertyDecl())
590 if (isFunctionDecl() || isFunctionOrBlockPointerVarLikeDecl()) {
591 assert(!ThisDeclInfo->ReturnType.isNull() &&
592 "should have a valid return type");
593 if (ThisDeclInfo->ReturnType->isVoidType()) {
595 switch (ThisDeclInfo->CommentDecl->getKind()) {
597 if (ThisDeclInfo->IsObjCMethod)
602 case Decl::CXXConstructor:
605 case Decl::CXXDestructor:
609 Diag(Command->getLocation(),
610 diag::warn_doc_returns_attached_to_a_void_function)
611 << Command->getCommandMarker()
612 << Command->getCommandName(Traits)
614 << Command->getSourceRange();
619 Diag(Command->getLocation(),
620 diag::warn_doc_returns_not_attached_to_a_function_decl)
621 << Command->getCommandMarker()
622 << Command->getCommandName(Traits)
623 << Command->getSourceRange();
626 void Sema::checkBlockCommandDuplicate(const BlockCommandComment *Command) {
627 const CommandInfo *Info = Traits.getCommandInfo(Command->getCommandID());
628 const BlockCommandComment *PrevCommand = nullptr;
629 if (Info->IsBriefCommand) {
631 BriefCommand = Command;
634 PrevCommand = BriefCommand;
635 } else if (Info->IsHeaderfileCommand) {
636 if (!HeaderfileCommand) {
637 HeaderfileCommand = Command;
640 PrevCommand = HeaderfileCommand;
642 // We don't want to check this command for duplicates.
645 StringRef CommandName = Command->getCommandName(Traits);
646 StringRef PrevCommandName = PrevCommand->getCommandName(Traits);
647 Diag(Command->getLocation(), diag::warn_doc_block_command_duplicate)
648 << Command->getCommandMarker()
650 << Command->getSourceRange();
651 if (CommandName == PrevCommandName)
652 Diag(PrevCommand->getLocation(), diag::note_doc_block_command_previous)
653 << PrevCommand->getCommandMarker()
655 << PrevCommand->getSourceRange();
657 Diag(PrevCommand->getLocation(),
658 diag::note_doc_block_command_previous_alias)
659 << PrevCommand->getCommandMarker()
664 void Sema::checkDeprecatedCommand(const BlockCommandComment *Command) {
665 if (!Traits.getCommandInfo(Command->getCommandID())->IsDeprecatedCommand)
668 assert(ThisDeclInfo && "should not call this check on a bare comment");
670 const Decl *D = ThisDeclInfo->CommentDecl;
674 if (D->hasAttr<DeprecatedAttr>() ||
675 D->hasAttr<AvailabilityAttr>() ||
676 D->hasAttr<UnavailableAttr>())
679 Diag(Command->getLocation(), diag::warn_doc_deprecated_not_sync)
680 << Command->getSourceRange() << Command->getCommandMarker();
682 // Try to emit a fixit with a deprecation attribute.
683 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
684 // Don't emit a Fix-It for non-member function definitions. GCC does not
685 // accept attributes on them.
686 const DeclContext *Ctx = FD->getDeclContext();
687 if ((!Ctx || !Ctx->isRecord()) &&
688 FD->doesThisDeclarationHaveABody())
691 const LangOptions &LO = FD->getASTContext().getLangOpts();
692 const bool DoubleSquareBracket = LO.CPlusPlus14 || LO.C2x;
693 StringRef AttributeSpelling =
694 DoubleSquareBracket ? "[[deprecated]]" : "__attribute__((deprecated))";
696 // Try to find a replacement macro:
697 // - In C2x/C++14 we prefer [[deprecated]].
698 // - If not found or an older C/C++ look for __attribute__((deprecated)).
700 if (DoubleSquareBracket) {
701 TokenValue Tokens[] = {tok::l_square, tok::l_square,
702 PP->getIdentifierInfo("deprecated"),
703 tok::r_square, tok::r_square};
704 MacroName = PP->getLastMacroWithSpelling(FD->getLocation(), Tokens);
705 if (!MacroName.empty())
706 AttributeSpelling = MacroName;
709 if (MacroName.empty()) {
710 TokenValue Tokens[] = {
711 tok::kw___attribute, tok::l_paren,
712 tok::l_paren, PP->getIdentifierInfo("deprecated"),
713 tok::r_paren, tok::r_paren};
714 StringRef MacroName =
715 PP->getLastMacroWithSpelling(FD->getLocation(), Tokens);
716 if (!MacroName.empty())
717 AttributeSpelling = MacroName;
721 SmallString<64> TextToInsert = AttributeSpelling;
723 SourceLocation Loc = FD->getSourceRange().getBegin();
724 Diag(Loc, diag::note_add_deprecation_attr)
725 << FixItHint::CreateInsertion(Loc, TextToInsert);
729 void Sema::resolveParamCommandIndexes(const FullComment *FC) {
730 if (!isFunctionDecl()) {
731 // We already warned that \\param commands are not attached to a function
736 SmallVector<ParamCommandComment *, 8> UnresolvedParamCommands;
738 // Comment AST nodes that correspond to \c ParamVars for which we have
739 // found a \\param command or NULL if no documentation was found so far.
740 SmallVector<ParamCommandComment *, 8> ParamVarDocs;
742 ArrayRef<const ParmVarDecl *> ParamVars = getParamVars();
743 ParamVarDocs.resize(ParamVars.size(), nullptr);
745 // First pass over all \\param commands: resolve all parameter names.
746 for (Comment::child_iterator I = FC->child_begin(), E = FC->child_end();
748 ParamCommandComment *PCC = dyn_cast<ParamCommandComment>(*I);
749 if (!PCC || !PCC->hasParamName())
751 StringRef ParamName = PCC->getParamNameAsWritten();
753 // Check that referenced parameter name is in the function decl.
754 const unsigned ResolvedParamIndex = resolveParmVarReference(ParamName,
756 if (ResolvedParamIndex == ParamCommandComment::VarArgParamIndex) {
757 PCC->setIsVarArgParam();
760 if (ResolvedParamIndex == ParamCommandComment::InvalidParamIndex) {
761 UnresolvedParamCommands.push_back(PCC);
764 PCC->setParamIndex(ResolvedParamIndex);
765 if (ParamVarDocs[ResolvedParamIndex]) {
766 SourceRange ArgRange = PCC->getParamNameRange();
767 Diag(ArgRange.getBegin(), diag::warn_doc_param_duplicate)
768 << ParamName << ArgRange;
769 ParamCommandComment *PrevCommand = ParamVarDocs[ResolvedParamIndex];
770 Diag(PrevCommand->getLocation(), diag::note_doc_param_previous)
771 << PrevCommand->getParamNameRange();
773 ParamVarDocs[ResolvedParamIndex] = PCC;
776 // Find parameter declarations that have no corresponding \\param.
777 SmallVector<const ParmVarDecl *, 8> OrphanedParamDecls;
778 for (unsigned i = 0, e = ParamVarDocs.size(); i != e; ++i) {
779 if (!ParamVarDocs[i])
780 OrphanedParamDecls.push_back(ParamVars[i]);
783 // Second pass over unresolved \\param commands: do typo correction.
784 // Suggest corrections from a set of parameter declarations that have no
785 // corresponding \\param.
786 for (unsigned i = 0, e = UnresolvedParamCommands.size(); i != e; ++i) {
787 const ParamCommandComment *PCC = UnresolvedParamCommands[i];
789 SourceRange ArgRange = PCC->getParamNameRange();
790 StringRef ParamName = PCC->getParamNameAsWritten();
791 Diag(ArgRange.getBegin(), diag::warn_doc_param_not_found)
792 << ParamName << ArgRange;
794 // All parameters documented -- can't suggest a correction.
795 if (OrphanedParamDecls.size() == 0)
798 unsigned CorrectedParamIndex = ParamCommandComment::InvalidParamIndex;
799 if (OrphanedParamDecls.size() == 1) {
800 // If one parameter is not documented then that parameter is the only
801 // possible suggestion.
802 CorrectedParamIndex = 0;
804 // Do typo correction.
805 CorrectedParamIndex = correctTypoInParmVarReference(ParamName,
808 if (CorrectedParamIndex != ParamCommandComment::InvalidParamIndex) {
809 const ParmVarDecl *CorrectedPVD = OrphanedParamDecls[CorrectedParamIndex];
810 if (const IdentifierInfo *CorrectedII = CorrectedPVD->getIdentifier())
811 Diag(ArgRange.getBegin(), diag::note_doc_param_name_suggestion)
812 << CorrectedII->getName()
813 << FixItHint::CreateReplacement(ArgRange, CorrectedII->getName());
818 bool Sema::isFunctionDecl() {
821 if (!ThisDeclInfo->IsFilled)
823 return ThisDeclInfo->getKind() == DeclInfo::FunctionKind;
826 bool Sema::isAnyFunctionDecl() {
827 return isFunctionDecl() && ThisDeclInfo->CurrentDecl &&
828 isa<FunctionDecl>(ThisDeclInfo->CurrentDecl);
831 bool Sema::isFunctionOrMethodVariadic() {
832 if (!isFunctionDecl() || !ThisDeclInfo->CurrentDecl)
834 if (const FunctionDecl *FD =
835 dyn_cast<FunctionDecl>(ThisDeclInfo->CurrentDecl))
836 return FD->isVariadic();
837 if (const FunctionTemplateDecl *FTD =
838 dyn_cast<FunctionTemplateDecl>(ThisDeclInfo->CurrentDecl))
839 return FTD->getTemplatedDecl()->isVariadic();
840 if (const ObjCMethodDecl *MD =
841 dyn_cast<ObjCMethodDecl>(ThisDeclInfo->CurrentDecl))
842 return MD->isVariadic();
843 if (const TypedefNameDecl *TD =
844 dyn_cast<TypedefNameDecl>(ThisDeclInfo->CurrentDecl)) {
845 QualType Type = TD->getUnderlyingType();
846 if (Type->isFunctionPointerType() || Type->isBlockPointerType())
847 Type = Type->getPointeeType();
848 if (const auto *FT = Type->getAs<FunctionProtoType>())
849 return FT->isVariadic();
854 bool Sema::isObjCMethodDecl() {
855 return isFunctionDecl() && ThisDeclInfo->CurrentDecl &&
856 isa<ObjCMethodDecl>(ThisDeclInfo->CurrentDecl);
859 bool Sema::isFunctionPointerVarDecl() {
862 if (!ThisDeclInfo->IsFilled)
864 if (ThisDeclInfo->getKind() == DeclInfo::VariableKind) {
865 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDeclInfo->CurrentDecl)) {
866 QualType QT = VD->getType();
867 return QT->isFunctionPointerType();
873 bool Sema::isFunctionOrBlockPointerVarLikeDecl() {
876 if (!ThisDeclInfo->IsFilled)
878 if (ThisDeclInfo->getKind() != DeclInfo::VariableKind ||
879 !ThisDeclInfo->CurrentDecl)
882 if (const auto *VD = dyn_cast<DeclaratorDecl>(ThisDeclInfo->CurrentDecl))
884 else if (const auto *PD =
885 dyn_cast<ObjCPropertyDecl>(ThisDeclInfo->CurrentDecl))
889 // We would like to warn about the 'returns'/'param' commands for
890 // variables that don't directly specify the function type, so type aliases
892 if (QT->getAs<TypedefType>())
894 if (const auto *P = QT->getAs<PointerType>())
895 if (P->getPointeeType()->getAs<TypedefType>())
897 if (const auto *P = QT->getAs<BlockPointerType>())
898 if (P->getPointeeType()->getAs<TypedefType>())
900 return QT->isFunctionPointerType() || QT->isBlockPointerType();
903 bool Sema::isObjCPropertyDecl() {
906 if (!ThisDeclInfo->IsFilled)
908 return ThisDeclInfo->CurrentDecl->getKind() == Decl::ObjCProperty;
911 bool Sema::isTemplateOrSpecialization() {
914 if (!ThisDeclInfo->IsFilled)
916 return ThisDeclInfo->getTemplateKind() != DeclInfo::NotTemplate;
919 bool Sema::isRecordLikeDecl() {
922 if (!ThisDeclInfo->IsFilled)
924 return isUnionDecl() || isClassOrStructDecl() || isObjCInterfaceDecl() ||
925 isObjCProtocolDecl();
928 bool Sema::isUnionDecl() {
931 if (!ThisDeclInfo->IsFilled)
933 if (const RecordDecl *RD =
934 dyn_cast_or_null<RecordDecl>(ThisDeclInfo->CurrentDecl))
935 return RD->isUnion();
939 bool Sema::isClassOrStructDecl() {
942 if (!ThisDeclInfo->IsFilled)
944 return ThisDeclInfo->CurrentDecl &&
945 isa<RecordDecl>(ThisDeclInfo->CurrentDecl) &&
949 bool Sema::isClassTemplateDecl() {
952 if (!ThisDeclInfo->IsFilled)
954 return ThisDeclInfo->CurrentDecl &&
955 (isa<ClassTemplateDecl>(ThisDeclInfo->CurrentDecl));
958 bool Sema::isFunctionTemplateDecl() {
961 if (!ThisDeclInfo->IsFilled)
963 return ThisDeclInfo->CurrentDecl &&
964 (isa<FunctionTemplateDecl>(ThisDeclInfo->CurrentDecl));
967 bool Sema::isObjCInterfaceDecl() {
970 if (!ThisDeclInfo->IsFilled)
972 return ThisDeclInfo->CurrentDecl &&
973 isa<ObjCInterfaceDecl>(ThisDeclInfo->CurrentDecl);
976 bool Sema::isObjCProtocolDecl() {
979 if (!ThisDeclInfo->IsFilled)
981 return ThisDeclInfo->CurrentDecl &&
982 isa<ObjCProtocolDecl>(ThisDeclInfo->CurrentDecl);
985 ArrayRef<const ParmVarDecl *> Sema::getParamVars() {
986 if (!ThisDeclInfo->IsFilled)
988 return ThisDeclInfo->ParamVars;
991 void Sema::inspectThisDecl() {
992 ThisDeclInfo->fill();
995 unsigned Sema::resolveParmVarReference(StringRef Name,
996 ArrayRef<const ParmVarDecl *> ParamVars) {
997 for (unsigned i = 0, e = ParamVars.size(); i != e; ++i) {
998 const IdentifierInfo *II = ParamVars[i]->getIdentifier();
999 if (II && II->getName() == Name)
1002 if (Name == "..." && isFunctionOrMethodVariadic())
1003 return ParamCommandComment::VarArgParamIndex;
1004 return ParamCommandComment::InvalidParamIndex;
1008 class SimpleTypoCorrector {
1009 const NamedDecl *BestDecl;
1012 const unsigned MaxEditDistance;
1014 unsigned BestEditDistance;
1019 explicit SimpleTypoCorrector(StringRef Typo)
1020 : BestDecl(nullptr), Typo(Typo), MaxEditDistance((Typo.size() + 2) / 3),
1021 BestEditDistance(MaxEditDistance + 1), BestIndex(0), NextIndex(0) {}
1023 void addDecl(const NamedDecl *ND);
1025 const NamedDecl *getBestDecl() const {
1026 if (BestEditDistance > MaxEditDistance)
1032 unsigned getBestDeclIndex() const {
1033 assert(getBestDecl());
1038 void SimpleTypoCorrector::addDecl(const NamedDecl *ND) {
1039 unsigned CurrIndex = NextIndex++;
1041 const IdentifierInfo *II = ND->getIdentifier();
1045 StringRef Name = II->getName();
1046 unsigned MinPossibleEditDistance = abs((int)Name.size() - (int)Typo.size());
1047 if (MinPossibleEditDistance > 0 &&
1048 Typo.size() / MinPossibleEditDistance < 3)
1051 unsigned EditDistance = Typo.edit_distance(Name, true, MaxEditDistance);
1052 if (EditDistance < BestEditDistance) {
1053 BestEditDistance = EditDistance;
1055 BestIndex = CurrIndex;
1058 } // end anonymous namespace
1060 unsigned Sema::correctTypoInParmVarReference(
1062 ArrayRef<const ParmVarDecl *> ParamVars) {
1063 SimpleTypoCorrector Corrector(Typo);
1064 for (unsigned i = 0, e = ParamVars.size(); i != e; ++i)
1065 Corrector.addDecl(ParamVars[i]);
1066 if (Corrector.getBestDecl())
1067 return Corrector.getBestDeclIndex();
1069 return ParamCommandComment::InvalidParamIndex;
1073 bool ResolveTParamReferenceHelper(
1075 const TemplateParameterList *TemplateParameters,
1076 SmallVectorImpl<unsigned> *Position) {
1077 for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
1078 const NamedDecl *Param = TemplateParameters->getParam(i);
1079 const IdentifierInfo *II = Param->getIdentifier();
1080 if (II && II->getName() == Name) {
1081 Position->push_back(i);
1085 if (const TemplateTemplateParmDecl *TTP =
1086 dyn_cast<TemplateTemplateParmDecl>(Param)) {
1087 Position->push_back(i);
1088 if (ResolveTParamReferenceHelper(Name, TTP->getTemplateParameters(),
1091 Position->pop_back();
1096 } // end anonymous namespace
1098 bool Sema::resolveTParamReference(
1100 const TemplateParameterList *TemplateParameters,
1101 SmallVectorImpl<unsigned> *Position) {
1103 if (!TemplateParameters)
1106 return ResolveTParamReferenceHelper(Name, TemplateParameters, Position);
1110 void CorrectTypoInTParamReferenceHelper(
1111 const TemplateParameterList *TemplateParameters,
1112 SimpleTypoCorrector &Corrector) {
1113 for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
1114 const NamedDecl *Param = TemplateParameters->getParam(i);
1115 Corrector.addDecl(Param);
1117 if (const TemplateTemplateParmDecl *TTP =
1118 dyn_cast<TemplateTemplateParmDecl>(Param))
1119 CorrectTypoInTParamReferenceHelper(TTP->getTemplateParameters(),
1123 } // end anonymous namespace
1125 StringRef Sema::correctTypoInTParamReference(
1127 const TemplateParameterList *TemplateParameters) {
1128 SimpleTypoCorrector Corrector(Typo);
1129 CorrectTypoInTParamReferenceHelper(TemplateParameters, Corrector);
1130 if (const NamedDecl *ND = Corrector.getBestDecl()) {
1131 const IdentifierInfo *II = ND->getIdentifier();
1132 assert(II && "SimpleTypoCorrector should not return this decl");
1133 return II->getName();
1138 InlineCommandComment::RenderKind
1139 Sema::getInlineCommandRenderKind(StringRef Name) const {
1140 assert(Traits.getCommandInfo(Name)->IsInlineCommand);
1142 return llvm::StringSwitch<InlineCommandComment::RenderKind>(Name)
1143 .Case("b", InlineCommandComment::RenderBold)
1144 .Cases("c", "p", InlineCommandComment::RenderMonospaced)
1145 .Cases("a", "e", "em", InlineCommandComment::RenderEmphasized)
1146 .Case("anchor", InlineCommandComment::RenderAnchor)
1147 .Default(InlineCommandComment::RenderNormal);
1150 } // end namespace comments
1151 } // end namespace clang