18#include "llvm/ADT/StringSwitch.h"
24#include "clang/AST/CommentHTMLTagsProperties.inc"
27Sema::Sema(llvm::BumpPtrAllocator &Allocator,
const SourceManager &SourceMgr,
30 Allocator(Allocator), SourceMgr(SourceMgr), Diags(Diags), Traits(Traits),
31 PP(PP), ThisDeclInfo(nullptr), BriefCommand(nullptr),
32 HeaderfileCommand(nullptr) {
39 ThisDeclInfo =
new (Allocator)
DeclInfo;
57 checkContainerDecl(BC);
69 checkBlockCommandEmptyParagraph(Command);
70 checkBlockCommandDuplicate(Command);
74 checkReturnsCommand(Command);
75 checkDeprecatedCommand(Command);
88 if (!involvesFunctionType())
90 diag::warn_doc_param_not_attached_to_a_function_decl)
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)
126 << (DiagSelect-1) << (DiagSelect-1)
130void 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:
138 (!isClassOrStructOrTagTypedefDecl() && !isClassTemplateDecl()) ? 1
143 if (DiagSelect && Comment->getCommandMarker() && isObjCInterfaceDecl())
146 case CommandTraits::KCI_interface:
147 DiagSelect = !isObjCInterfaceDecl() ? 2 : 0;
149 case CommandTraits::KCI_protocol:
150 DiagSelect = !isObjCProtocolDecl() ? 3 : 0;
152 case CommandTraits::KCI_struct:
153 DiagSelect = !isClassOrStructOrTagTypedefDecl() ? 4 : 0;
155 case CommandTraits::KCI_union:
156 DiagSelect = !isUnionDecl() ? 5 : 0;
163 Diag(Comment->getLocation(), diag::warn_doc_api_container_decl_mismatch)
164 << Comment->getCommandMarker()
165 << (DiagSelect-1) << (DiagSelect-1)
166 << Comment->getSourceRange();
169void Sema::checkContainerDecl(
const BlockCommandComment *Comment) {
170 const CommandInfo *Info = Traits.
getCommandInfo(Comment->getCommandID());
171 if (!Info->IsRecordLikeDetailCommand || isRecordLikeDecl())
174 switch (Comment->getCommandID()) {
175 case CommandTraits::KCI_classdesign:
178 case CommandTraits::KCI_coclass:
181 case CommandTraits::KCI_dependency:
184 case CommandTraits::KCI_helper:
187 case CommandTraits::KCI_helperclass:
190 case CommandTraits::KCI_helps:
193 case CommandTraits::KCI_instancesize:
196 case CommandTraits::KCI_ownership:
199 case CommandTraits::KCI_performance:
202 case CommandTraits::KCI_security:
205 case CommandTraits::KCI_superclass:
213 Diag(Comment->getLocation(), diag::warn_doc_container_decl_mismatch)
214 << Comment->getCommandMarker()
216 << Comment->getSourceRange();
222 return llvm::StringSwitch<ParamCommandPassDirection>(Arg)
233 std::string ArgLower = Arg.lower();
243 const char *FixedName =
245 Diag(ArgLocBegin, diag::warn_doc_param_spaces_in_direction)
248 Diag(ArgLocBegin, diag::warn_doc_param_invalid_direction) << ArgRange;
268 auto *A =
new (Allocator)
276 checkBlockCommandEmptyParagraph(Command);
288 if (!isTemplateOrSpecialization())
290 diag::warn_doc_tparam_not_attached_to_a_template_decl)
304 auto *A =
new (Allocator)
308 if (!isTemplateOrSpecialization()) {
316 if (resolveTParamReference(Arg, TemplateParameters, &Position)) {
321 Diag(ArgLocBegin, diag::warn_doc_tparam_duplicate)
323 Diag(PrevCommand->
getLocation(), diag::note_doc_tparam_previous)
326 PrevCommand = Command;
331 Diag(ArgLocBegin, diag::warn_doc_tparam_not_found)
334 if (!TemplateParameters || TemplateParameters->
size() == 0)
337 StringRef CorrectedName;
338 if (TemplateParameters->
size() == 1) {
344 CorrectedName = correctTypoInTParamReference(Arg, TemplateParameters);
347 if (!CorrectedName.empty()) {
348 Diag(ArgLocBegin, diag::note_doc_tparam_name_suggestion)
357 checkBlockCommandEmptyParagraph(Command);
366 return new (Allocator)
368 getInlineCommandRenderKind(CommandName), Args);
373 StringRef CommandName) {
380 unsigned CommandID) {
393 unsigned CommandID) {
397 Loc.getLocWithOffset(1 + CommandName.size()),
411 Block->setCloseName(CloseName, CloseNameLocBegin);
412 Block->setLines(Lines);
425 checkFunctionDeclVerbatimLine(VL);
426 checkContainerDeclVerbatimLine(VL);
439 bool IsSelfClosing) {
440 Tag->setAttrs(Attrs);
441 Tag->setGreaterLoc(GreaterLoc);
443 Tag->setSelfClosing();
444 else if (!isHTMLEndTagForbidden(Tag->getTagName()))
445 HTMLOpenTags.push_back(Tag);
453 if (isHTMLEndTagForbidden(TagName)) {
454 Diag(HET->
getLocation(), diag::warn_doc_html_end_forbidden)
460 bool FoundOpen =
false;
462 I = HTMLOpenTags.rbegin(),
E = HTMLOpenTags.rend();
464 if ((*I)->getTagName() == TagName) {
470 Diag(HET->
getLocation(), diag::warn_doc_html_end_unbalanced)
476 while (!HTMLOpenTags.empty()) {
478 StringRef LastNotClosedTagName = HST->
getTagName();
479 if (LastNotClosedTagName == TagName) {
486 if (isHTMLEndTagOptional(LastNotClosedTagName))
489 bool OpenLineInvalid;
493 bool CloseLineInvalid;
498 if (OpenLineInvalid || CloseLineInvalid || OpenLine == CloseLine) {
499 Diag(HST->
getLocation(), diag::warn_doc_html_start_end_mismatch)
504 Diag(HST->
getLocation(), diag::warn_doc_html_start_end_mismatch)
507 Diag(HET->
getLocation(), diag::note_doc_html_end_tag)
519 resolveParamCommandIndexes(FC);
522 while (!HTMLOpenTags.empty()) {
527 Diag(HST->
getLocation(), diag::warn_doc_html_missing_end_tag)
546 Diag(DiagLoc, diag::warn_doc_block_command_empty_paragraph)
553void Sema::checkReturnsCommand(
const BlockCommandComment *Command) {
557 assert(ThisDeclInfo &&
"should not call this check on a bare comment");
561 if (isObjCPropertyDecl())
563 if (involvesFunctionType()) {
565 "should have a valid return type");
575 case Decl::CXXConstructor:
578 case Decl::CXXDestructor:
582 Diag(Command->getLocation(),
583 diag::warn_doc_returns_attached_to_a_void_function)
584 << Command->getCommandMarker()
585 << Command->getCommandName(Traits)
587 << Command->getSourceRange();
592 Diag(Command->getLocation(),
593 diag::warn_doc_returns_not_attached_to_a_function_decl)
594 << Command->getCommandMarker()
595 << Command->getCommandName(Traits)
596 << Command->getSourceRange();
599void Sema::checkBlockCommandDuplicate(
const BlockCommandComment *Command) {
600 const CommandInfo *Info = Traits.
getCommandInfo(Command->getCommandID());
601 const BlockCommandComment *PrevCommand =
nullptr;
602 if (Info->IsBriefCommand) {
604 BriefCommand = Command;
607 PrevCommand = BriefCommand;
608 }
else if (Info->IsHeaderfileCommand) {
609 if (!HeaderfileCommand) {
610 HeaderfileCommand = Command;
613 PrevCommand = HeaderfileCommand;
619 StringRef PrevCommandName = PrevCommand->getCommandName(Traits);
620 Diag(Command->getLocation(), diag::warn_doc_block_command_duplicate)
621 << Command->getCommandMarker()
623 << Command->getSourceRange();
624 if (CommandName == PrevCommandName)
625 Diag(PrevCommand->getLocation(), diag::note_doc_block_command_previous)
626 << PrevCommand->getCommandMarker()
628 << PrevCommand->getSourceRange();
630 Diag(PrevCommand->getLocation(),
631 diag::note_doc_block_command_previous_alias)
632 << PrevCommand->getCommandMarker()
637void Sema::checkDeprecatedCommand(
const BlockCommandComment *Command) {
641 assert(ThisDeclInfo &&
"should not call this check on a bare comment");
647 if (
D->hasAttr<DeprecatedAttr>() ||
648 D->hasAttr<AvailabilityAttr>() ||
649 D->hasAttr<UnavailableAttr>())
652 Diag(Command->getLocation(), diag::warn_doc_deprecated_not_sync)
653 << Command->getSourceRange() << Command->getCommandMarker();
656 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(
D)) {
659 const DeclContext *Ctx = FD->getDeclContext();
660 if ((!Ctx || !Ctx->isRecord()) &&
661 FD->doesThisDeclarationHaveABody())
664 const LangOptions &LO = FD->getLangOpts();
665 const bool DoubleSquareBracket = LO.CPlusPlus14 || LO.C23;
666 StringRef AttributeSpelling =
667 DoubleSquareBracket ?
"[[deprecated]]" :
"__attribute__((deprecated))";
673 if (DoubleSquareBracket) {
674 TokenValue Tokens[] = {tok::l_square, tok::l_square,
676 tok::r_square, tok::r_square};
678 if (!MacroName.empty())
679 AttributeSpelling = MacroName;
682 if (MacroName.empty()) {
683 TokenValue Tokens[] = {
684 tok::kw___attribute, tok::l_paren,
686 tok::r_paren, tok::r_paren};
687 StringRef MacroName =
689 if (!MacroName.empty())
690 AttributeSpelling = MacroName;
694 SmallString<64> TextToInsert = AttributeSpelling;
696 SourceLocation
Loc = FD->getSourceRange().getBegin();
697 Diag(
Loc, diag::note_add_deprecation_attr)
702void Sema::resolveParamCommandIndexes(
const FullComment *FC) {
703 if (!involvesFunctionType()) {
709 SmallVector<ParamCommandComment *, 8> UnresolvedParamCommands;
713 SmallVector<ParamCommandComment *, 8> ParamVarDocs;
715 ArrayRef<const ParmVarDecl *> ParamVars = getParamVars();
716 ParamVarDocs.resize(ParamVars.size(),
nullptr);
721 ParamCommandComment *PCC = dyn_cast<ParamCommandComment>(*I);
722 if (!PCC || !PCC->hasParamName())
724 StringRef ParamName = PCC->getParamNameAsWritten();
727 const unsigned ResolvedParamIndex = resolveParmVarReference(ParamName,
730 PCC->setIsVarArgParam();
734 UnresolvedParamCommands.push_back(PCC);
737 PCC->setParamIndex(ResolvedParamIndex);
738 if (ParamVarDocs[ResolvedParamIndex]) {
739 SourceRange ArgRange = PCC->getParamNameRange();
740 Diag(ArgRange.getBegin(), diag::warn_doc_param_duplicate)
741 << ParamName << ArgRange;
742 ParamCommandComment *PrevCommand = ParamVarDocs[ResolvedParamIndex];
743 Diag(PrevCommand->getLocation(), diag::note_doc_param_previous)
744 << PrevCommand->getParamNameRange();
746 ParamVarDocs[ResolvedParamIndex] = PCC;
750 SmallVector<const ParmVarDecl *, 8> OrphanedParamDecls;
751 for (
unsigned i = 0, e = ParamVarDocs.size(); i != e; ++i) {
752 if (!ParamVarDocs[i])
753 OrphanedParamDecls.push_back(ParamVars[i]);
759 for (
unsigned i = 0, e = UnresolvedParamCommands.size(); i != e; ++i) {
760 const ParamCommandComment *PCC = UnresolvedParamCommands[i];
762 SourceRange ArgRange = PCC->getParamNameRange();
763 StringRef ParamName = PCC->getParamNameAsWritten();
764 Diag(ArgRange.getBegin(), diag::warn_doc_param_not_found)
765 << ParamName << ArgRange;
768 if (OrphanedParamDecls.size() == 0)
772 if (OrphanedParamDecls.size() == 1) {
775 CorrectedParamIndex = 0;
778 CorrectedParamIndex = correctTypoInParmVarReference(ParamName,
782 const ParmVarDecl *CorrectedPVD = OrphanedParamDecls[CorrectedParamIndex];
783 if (
const IdentifierInfo *CorrectedII = CorrectedPVD->getIdentifier())
784 Diag(ArgRange.getBegin(), diag::note_doc_param_name_suggestion)
785 << CorrectedII->getName()
791bool Sema::involvesFunctionType() {
799bool Sema::isFunctionDecl() {
807bool Sema::isAnyFunctionDecl() {
808 return isFunctionDecl() && ThisDeclInfo->
CurrentDecl &&
812bool Sema::isFunctionOrMethodVariadic() {
820bool Sema::isObjCMethodDecl() {
821 return isFunctionDecl() && ThisDeclInfo->
CurrentDecl &&
825bool Sema::isFunctionPointerVarDecl() {
831 if (
const VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDeclInfo->
CurrentDecl)) {
832 QualType QT = VD->getType();
833 return QT->isFunctionPointerType();
839bool Sema::isObjCPropertyDecl() {
847bool Sema::isTemplateOrSpecialization() {
855bool Sema::isRecordLikeDecl() {
860 return isUnionDecl() || isClassOrStructDecl() || isObjCInterfaceDecl() ||
861 isObjCProtocolDecl();
864bool Sema::isUnionDecl() {
869 if (
const RecordDecl *RD =
870 dyn_cast_or_null<RecordDecl>(ThisDeclInfo->
CurrentDecl))
871 return RD->isUnion();
875 if (
auto *record = dyn_cast_or_null<RecordDecl>(
D))
876 return !record->isUnion();
881bool Sema::isClassOrStructDecl() {
893bool Sema::isClassOrStructOrTagTypedefDecl() {
905 if (
auto *ThisTypedefDecl = dyn_cast<TypedefDecl>(ThisDeclInfo->
CurrentDecl)) {
906 auto UnderlyingType = ThisTypedefDecl->getUnderlyingType();
907 if (
auto ThisElaboratedType = dyn_cast<ElaboratedType>(UnderlyingType)) {
908 auto DesugaredType = ThisElaboratedType->desugar();
909 if (
auto *DesugaredTypePtr = DesugaredType.getTypePtrOrNull()) {
910 if (
auto *ThisRecordType = dyn_cast<RecordType>(DesugaredTypePtr)) {
920bool Sema::isClassTemplateDecl() {
926 (isa<ClassTemplateDecl>(ThisDeclInfo->
CurrentDecl));
929bool Sema::isFunctionTemplateDecl() {
935 (isa<FunctionTemplateDecl>(ThisDeclInfo->
CurrentDecl));
938bool Sema::isObjCInterfaceDecl() {
947bool Sema::isObjCProtocolDecl() {
956ArrayRef<const ParmVarDecl *> Sema::getParamVars() {
962void Sema::inspectThisDecl() {
963 ThisDeclInfo->
fill();
966unsigned Sema::resolveParmVarReference(StringRef Name,
967 ArrayRef<const ParmVarDecl *> ParamVars) {
968 for (
unsigned i = 0, e = ParamVars.size(); i != e; ++i) {
969 const IdentifierInfo *II = ParamVars[i]->getIdentifier();
970 if (II && II->getName() == Name)
973 if (Name ==
"..." && isFunctionOrMethodVariadic())
979class SimpleTypoCorrector {
980 const NamedDecl *BestDecl;
983 const unsigned MaxEditDistance;
985 unsigned BestEditDistance;
990 explicit SimpleTypoCorrector(StringRef Typo)
991 : BestDecl(nullptr), Typo(Typo), MaxEditDistance((Typo.size() + 2) / 3),
992 BestEditDistance(MaxEditDistance + 1), BestIndex(0), NextIndex(0) {}
994 void addDecl(
const NamedDecl *ND);
996 const NamedDecl *getBestDecl()
const {
997 if (BestEditDistance > MaxEditDistance)
1003 unsigned getBestDeclIndex()
const {
1004 assert(getBestDecl());
1009void SimpleTypoCorrector::addDecl(
const NamedDecl *ND) {
1010 unsigned CurrIndex = NextIndex++;
1012 const IdentifierInfo *II = ND->getIdentifier();
1016 StringRef Name = II->getName();
1017 unsigned MinPossibleEditDistance =
abs((
int)Name.size() - (
int)Typo.size());
1018 if (MinPossibleEditDistance > 0 &&
1019 Typo.size() / MinPossibleEditDistance < 3)
1022 unsigned EditDistance = Typo.edit_distance(Name,
true, MaxEditDistance);
1023 if (EditDistance < BestEditDistance) {
1024 BestEditDistance = EditDistance;
1026 BestIndex = CurrIndex;
1031unsigned Sema::correctTypoInParmVarReference(
1033 ArrayRef<const ParmVarDecl *> ParamVars) {
1034 SimpleTypoCorrector Corrector(Typo);
1035 for (
unsigned i = 0, e = ParamVars.size(); i != e; ++i)
1036 Corrector.addDecl(ParamVars[i]);
1037 if (Corrector.getBestDecl())
1038 return Corrector.getBestDeclIndex();
1044bool ResolveTParamReferenceHelper(
1046 const TemplateParameterList *TemplateParameters,
1047 SmallVectorImpl<unsigned> *Position) {
1048 for (
unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
1049 const NamedDecl *Param = TemplateParameters->getParam(i);
1050 const IdentifierInfo *II = Param->getIdentifier();
1051 if (II && II->getName() == Name) {
1052 Position->push_back(i);
1056 if (
const TemplateTemplateParmDecl *TTP =
1057 dyn_cast<TemplateTemplateParmDecl>(Param)) {
1058 Position->push_back(i);
1059 if (ResolveTParamReferenceHelper(Name, TTP->getTemplateParameters(),
1062 Position->pop_back();
1069bool Sema::resolveTParamReference(
1071 const TemplateParameterList *TemplateParameters,
1072 SmallVectorImpl<unsigned> *Position) {
1074 if (!TemplateParameters)
1077 return ResolveTParamReferenceHelper(Name, TemplateParameters, Position);
1081void CorrectTypoInTParamReferenceHelper(
1082 const TemplateParameterList *TemplateParameters,
1083 SimpleTypoCorrector &Corrector) {
1084 for (
unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
1085 const NamedDecl *Param = TemplateParameters->getParam(i);
1086 Corrector.addDecl(Param);
1088 if (
const TemplateTemplateParmDecl *TTP =
1089 dyn_cast<TemplateTemplateParmDecl>(Param))
1090 CorrectTypoInTParamReferenceHelper(TTP->getTemplateParameters(),
1096StringRef Sema::correctTypoInTParamReference(
1098 const TemplateParameterList *TemplateParameters) {
1099 SimpleTypoCorrector Corrector(Typo);
1100 CorrectTypoInTParamReferenceHelper(TemplateParameters, Corrector);
1101 if (
const NamedDecl *ND = Corrector.getBestDecl()) {
1102 const IdentifierInfo *II = ND->getIdentifier();
1103 assert(II &&
"SimpleTypoCorrector should not return this decl");
1104 return II->getName();
1112 return llvm::StringSwitch<InlineCommandRenderKind>(Name)
Defines the C++ template declaration subclasses.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
__DEVICE__ long long abs(long long __n)
Decl - This represents one declaration (or definition), e.g.
Concrete class used by the front-end to report problems and issues.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
The JSON file list parser is used to communicate input to InstallAPI.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...