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