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
9#include "clang/AST/CommentSema.h"
10#include "clang/AST/Attr.h"
11#include "clang/AST/CommentCommandTraits.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclTemplate.h"
14#include "clang/Basic/DiagnosticComment.h"
15#include "clang/Basic/LLVM.h"
16#include "clang/Basic/SimpleTypoCorrection.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Lex/Preprocessor.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
45ParagraphComment *Sema::actOnParagraphComment(
46 ArrayRef<InlineContentComment *> Content) {
47 return new (Allocator) ParagraphComment(Content);
48}
49
50BlockCommandComment *Sema::actOnBlockCommandStart(
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(Comment: BC);
59 return BC;
60}
61
62void Sema::actOnBlockCommandArgs(BlockCommandComment *Command,
63 ArrayRef<BlockCommandComment::Argument> Args) {
64 Command->setArgs(Args);
65}
66
67void Sema::actOnBlockCommandFinish(BlockCommandComment *Command,
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(Comment: Command);
77 }
78}
79
80ParamCommandComment *Sema::actOnParamCommandStart(
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(Loc: Command->getLocation(),
91 DiagID: 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(CommandID: Comment->getCommandID());
100 if (!Info->IsFunctionDeclarationCommand)
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(Loc: Comment->getLocation(), DiagID: 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(CommandID: 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(Loc: Comment->getLocation(), DiagID: 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(CommandID: 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(Loc: Comment->getLocation(), DiagID: 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.
222static ParamCommandPassDirection getParamPassDirection(StringRef Arg) {
223 return llvm::StringSwitch<ParamCommandPassDirection>(Arg)
224 .Case(S: "[in]", Value: ParamCommandPassDirection::In)
225 .Case(S: "[out]", Value: ParamCommandPassDirection::Out)
226 .Cases(CaseStrings: {"[in,out]", "[out,in]"}, Value: ParamCommandPassDirection::InOut)
227 .Default(Value: static_cast<ParamCommandPassDirection>(-1));
228}
229
230void Sema::actOnParamCommandDirectionArg(ParamCommandComment *Command,
231 SourceLocation ArgLocBegin,
232 SourceLocation ArgLocEnd,
233 StringRef Arg) {
234 std::string ArgLower = Arg.lower();
235 ParamCommandPassDirection Direction = getParamPassDirection(Arg: ArgLower);
236
237 if (Direction == static_cast<ParamCommandPassDirection>(-1)) {
238 // Try again with whitespace removed.
239 llvm::erase_if(C&: ArgLower, P: clang::isWhitespace);
240 Direction = getParamPassDirection(Arg: ArgLower);
241
242 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
243 if (Direction != static_cast<ParamCommandPassDirection>(-1)) {
244 const char *FixedName =
245 ParamCommandComment::getDirectionAsString(D: Direction);
246 Diag(Loc: ArgLocBegin, DiagID: diag::warn_doc_param_spaces_in_direction)
247 << ArgRange << FixItHint::CreateReplacement(RemoveRange: ArgRange, Code: FixedName);
248 } else {
249 Diag(Loc: ArgLocBegin, DiagID: 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
257void Sema::actOnParamCommandParamNameArg(ParamCommandComment *Command,
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.
266 Command->setDirection(Direction: ParamCommandPassDirection::In,
267 /* Explicit = */ false);
268 }
269 auto *A = new (Allocator)
270 Comment::Argument{.Range: SourceRange(ArgLocBegin, ArgLocEnd), .Text: Arg};
271 Command->setArgs(ArrayRef(A, 1));
272}
273
274void Sema::actOnParamCommandFinish(ParamCommandComment *Command,
275 ParagraphComment *Paragraph) {
276 Command->setParagraph(Paragraph);
277 checkBlockCommandEmptyParagraph(Command);
278}
279
280TParamCommandComment *Sema::actOnTParamCommandStart(
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(Loc: Command->getLocation(),
291 DiagID: diag::warn_doc_tparam_not_attached_to_a_template_decl)
292 << CommandMarker
293 << Command->getCommandNameRange(Traits);
294
295 return Command;
296}
297
298void Sema::actOnTParamCommandParamNameArg(TParamCommandComment *Command,
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{.Range: SourceRange(ArgLocBegin, ArgLocEnd), .Text: 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;
316 SmallVector<unsigned, 2> Position;
317 if (resolveTParamReference(Name: Arg, TemplateParameters, Position: &Position)) {
318 Command->setPosition(copyArray(Source: ArrayRef(Position)));
319 TParamCommandComment *&PrevCommand = TemplateParameterDocs[Arg];
320 if (PrevCommand) {
321 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
322 Diag(Loc: ArgLocBegin, DiagID: diag::warn_doc_tparam_duplicate)
323 << Arg << ArgRange;
324 Diag(Loc: PrevCommand->getLocation(), DiagID: diag::note_doc_tparam_previous)
325 << PrevCommand->getParamNameRange();
326 }
327 PrevCommand = Command;
328 return;
329 }
330
331 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
332 Diag(Loc: ArgLocBegin, DiagID: 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(Idx: 0);
341 const IdentifierInfo *II = Param->getIdentifier();
342 if (II)
343 CorrectedName = II->getName();
344 } else {
345 CorrectedName = correctTypoInTParamReference(Typo: Arg, TemplateParameters);
346 }
347
348 if (!CorrectedName.empty()) {
349 Diag(Loc: ArgLocBegin, DiagID: diag::note_doc_tparam_name_suggestion)
350 << CorrectedName
351 << FixItHint::CreateReplacement(RemoveRange: ArgRange, Code: CorrectedName);
352 }
353}
354
355void Sema::actOnTParamCommandFinish(TParamCommandComment *Command,
356 ParagraphComment *Paragraph) {
357 Command->setParagraph(Paragraph);
358 checkBlockCommandEmptyParagraph(Command);
359}
360
361InlineCommandComment *
362Sema::actOnInlineCommand(SourceLocation CommandLocBegin,
363 SourceLocation CommandLocEnd, unsigned CommandID,
364 CommandMarkerKind CommandMarker,
365 ArrayRef<Comment::Argument> Args) {
366 StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
367
368 return new (Allocator) InlineCommandComment(
369 CommandLocBegin, CommandLocEnd, CommandID,
370 getInlineCommandRenderKind(Name: CommandName), CommandMarker, Args);
371}
372
373InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin,
374 SourceLocation LocEnd,
375 StringRef CommandName) {
376 unsigned CommandID = Traits.registerUnknownCommand(CommandName)->getID();
377 return actOnUnknownCommand(LocBegin, LocEnd, CommandID);
378}
379
380InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin,
381 SourceLocation LocEnd,
382 unsigned CommandID) {
383 ArrayRef<InlineCommandComment::Argument> Args;
384 return new (Allocator) InlineCommandComment(
385 LocBegin, LocEnd, CommandID, InlineCommandRenderKind::Normal, Args);
386}
387
388TextComment *Sema::actOnText(SourceLocation LocBegin,
389 SourceLocation LocEnd,
390 StringRef Text) {
391 return new (Allocator) TextComment(LocBegin, LocEnd, Text);
392}
393
394VerbatimBlockComment *Sema::actOnVerbatimBlockStart(SourceLocation Loc,
395 unsigned CommandID) {
396 StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
397 return new (Allocator) VerbatimBlockComment(
398 Loc,
399 Loc.getLocWithOffset(Offset: 1 + CommandName.size()),
400 CommandID);
401}
402
403VerbatimBlockLineComment *Sema::actOnVerbatimBlockLine(SourceLocation Loc,
404 StringRef Text) {
405 return new (Allocator) VerbatimBlockLineComment(Loc, Text);
406}
407
408void Sema::actOnVerbatimBlockFinish(
409 VerbatimBlockComment *Block,
410 SourceLocation CloseNameLocBegin,
411 StringRef CloseName,
412 ArrayRef<VerbatimBlockLineComment *> Lines) {
413 Block->setCloseName(Name: CloseName, LocBegin: CloseNameLocBegin);
414 Block->setLines(Lines);
415}
416
417VerbatimLineComment *Sema::actOnVerbatimLine(SourceLocation LocBegin,
418 unsigned CommandID,
419 SourceLocation TextBegin,
420 StringRef Text) {
421 VerbatimLineComment *VL = new (Allocator) VerbatimLineComment(
422 LocBegin,
423 TextBegin.getLocWithOffset(Offset: Text.size()),
424 CommandID,
425 TextBegin,
426 Text);
427 checkFunctionDeclVerbatimLine(Comment: VL);
428 checkContainerDeclVerbatimLine(Comment: VL);
429 return VL;
430}
431
432HTMLStartTagComment *Sema::actOnHTMLStartTagStart(SourceLocation LocBegin,
433 StringRef TagName) {
434 return new (Allocator) HTMLStartTagComment(LocBegin, TagName);
435}
436
437void Sema::actOnHTMLStartTagFinish(
438 HTMLStartTagComment *Tag,
439 ArrayRef<HTMLStartTagComment::Attribute> Attrs,
440 SourceLocation GreaterLoc,
441 bool IsSelfClosing) {
442 Tag->setAttrs(Attrs);
443 Tag->setGreaterLoc(GreaterLoc);
444 if (IsSelfClosing)
445 Tag->setSelfClosing();
446 else if (!isHTMLEndTagForbidden(Name: Tag->getTagName()))
447 HTMLOpenTags.push_back(Elt: Tag);
448}
449
450HTMLEndTagComment *Sema::actOnHTMLEndTag(SourceLocation LocBegin,
451 SourceLocation LocEnd,
452 StringRef TagName) {
453 HTMLEndTagComment *HET =
454 new (Allocator) HTMLEndTagComment(LocBegin, LocEnd, TagName);
455 if (isHTMLEndTagForbidden(Name: TagName)) {
456 Diag(Loc: HET->getLocation(), DiagID: diag::warn_doc_html_end_forbidden)
457 << TagName << HET->getSourceRange();
458 HET->setIsMalformed();
459 return HET;
460 }
461
462 bool FoundOpen = false;
463 for (SmallVectorImpl<HTMLStartTagComment *>::const_reverse_iterator
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(Loc: HET->getLocation(), DiagID: 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(Name: LastNotClosedTagName))
489 continue;
490
491 bool OpenLineInvalid;
492 const unsigned OpenLine = SourceMgr.getPresumedLineNumber(
493 Loc: HST->getLocation(),
494 Invalid: &OpenLineInvalid);
495 bool CloseLineInvalid;
496 const unsigned CloseLine = SourceMgr.getPresumedLineNumber(
497 Loc: HET->getLocation(),
498 Invalid: &CloseLineInvalid);
499
500 if (OpenLineInvalid || CloseLineInvalid || OpenLine == CloseLine) {
501 Diag(Loc: HST->getLocation(), DiagID: diag::warn_doc_html_start_end_mismatch)
502 << HST->getTagName() << HET->getTagName()
503 << HST->getSourceRange() << HET->getSourceRange();
504 HST->setIsMalformed();
505 } else {
506 Diag(Loc: HST->getLocation(), DiagID: diag::warn_doc_html_start_end_mismatch)
507 << HST->getTagName() << HET->getTagName()
508 << HST->getSourceRange();
509 Diag(Loc: HET->getLocation(), DiagID: diag::note_doc_html_end_tag)
510 << HET->getSourceRange();
511 HST->setIsMalformed();
512 }
513 }
514
515 return HET;
516}
517
518FullComment *Sema::actOnFullComment(
519 ArrayRef<BlockContentComment *> Blocks) {
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(Name: HST->getTagName()))
527 continue;
528
529 Diag(Loc: HST->getLocation(), DiagID: 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(CommandID: 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(Idx: Command->getNumArgs() - 1).getEnd();
546 if (!DiagLoc.isValid())
547 DiagLoc = Command->getCommandNameRange(Traits).getEnd();
548 Diag(Loc: DiagLoc, DiagID: 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(CommandID: 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(Loc: Command->getLocation(),
585 DiagID: 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(Loc: Command->getLocation(),
595 DiagID: 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(CommandID: 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(Loc: Command->getLocation(), DiagID: diag::warn_doc_block_command_duplicate)
623 << Command->getCommandMarker()
624 << CommandName
625 << Command->getSourceRange();
626 if (CommandName == PrevCommandName)
627 Diag(Loc: PrevCommand->getLocation(), DiagID: diag::note_doc_block_command_previous)
628 << PrevCommand->getCommandMarker()
629 << PrevCommandName
630 << PrevCommand->getSourceRange();
631 else
632 Diag(Loc: PrevCommand->getLocation(),
633 DiagID: 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(CommandID: 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(Loc: Command->getLocation(), DiagID: 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>(Val: 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(Name: "deprecated"),
678 tok::r_square, tok::r_square};
679 MacroName = PP->getLastMacroWithSpelling(Loc: 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(Name: "deprecated"),
688 tok::r_paren, tok::r_paren};
689 StringRef MacroName =
690 PP->getLastMacroWithSpelling(Loc: 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, DiagID: diag::note_add_deprecation_attr)
700 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: 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(N: ParamVars.size(), NV: 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>(Val: *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(Name: ParamName,
730 ParamVars);
731 if (ResolvedParamIndex == ParamCommandComment::VarArgParamIndex) {
732 PCC->setIsVarArgParam();
733 continue;
734 }
735 if (ResolvedParamIndex == ParamCommandComment::InvalidParamIndex) {
736 UnresolvedParamCommands.push_back(Elt: PCC);
737 continue;
738 }
739 PCC->setParamIndex(ResolvedParamIndex);
740 if (ParamVarDocs[ResolvedParamIndex]) {
741 SourceRange ArgRange = PCC->getParamNameRange();
742 Diag(Loc: ArgRange.getBegin(), DiagID: diag::warn_doc_param_duplicate)
743 << ParamName << ArgRange;
744 ParamCommandComment *PrevCommand = ParamVarDocs[ResolvedParamIndex];
745 Diag(Loc: PrevCommand->getLocation(), DiagID: 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(Elt: 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(Loc: ArgRange.getBegin(), DiagID: 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(Typo: ParamName,
781 ParamVars: OrphanedParamDecls);
782 }
783 if (CorrectedParamIndex != ParamCommandComment::InvalidParamIndex) {
784 const ParmVarDecl *CorrectedPVD = OrphanedParamDecls[CorrectedParamIndex];
785 if (const IdentifierInfo *CorrectedII = CorrectedPVD->getIdentifier())
786 Diag(Loc: ArgRange.getBegin(), DiagID: diag::note_doc_param_name_suggestion)
787 << CorrectedII->getName()
788 << FixItHint::CreateReplacement(RemoveRange: ArgRange, Code: 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>(Val: 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>(Val: 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>(Val: 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>(Val: 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>(Val: 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(D: 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(D: ThisDeclInfo->CurrentDecl))
905 return true;
906
907 if (auto *ThisTypedefDecl = dyn_cast<TypedefDecl>(Val: 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>(Val: 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>(Val: 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>(Val: 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>(Val: 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())
968 return ParamCommandComment::VarArgParamIndex;
969 return ParamCommandComment::InvalidParamIndex;
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(Candidate: Param->getIdentifier());
982 }
983
984 if (STC.hasCorrection())
985 return STC.getCorrectionIndex();
986
987 return ParamCommandComment::InvalidParamIndex;
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(Idx: i);
997 const IdentifierInfo *II = Param->getIdentifier();
998 if (II && II->getName() == Name) {
999 Position->push_back(Elt: i);
1000 return true;
1001 }
1002
1003 if (const TemplateTemplateParmDecl *TTP =
1004 dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
1005 Position->push_back(Elt: i);
1006 if (ResolveTParamReferenceHelper(Name, TemplateParameters: 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(Idx: i);
1033 if (!Param)
1034 continue;
1035
1036 STC.add(Candidate: Param->getIdentifier());
1037
1038 if (const TemplateTemplateParmDecl *TTP =
1039 dyn_cast<TemplateTemplateParmDecl>(Val: Param))
1040 CorrectTypoInTParamReferenceHelper(TemplateParameters: 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)
1061 .Case(S: "b", Value: InlineCommandRenderKind::Bold)
1062 .Cases(CaseStrings: {"c", "p"}, Value: InlineCommandRenderKind::Monospaced)
1063 .Cases(CaseStrings: {"a", "e", "em"}, Value: InlineCommandRenderKind::Emphasized)
1064 .Case(S: "anchor", Value: InlineCommandRenderKind::Anchor)
1065 .Default(Value: InlineCommandRenderKind::Normal);
1066}
1067
1068} // end namespace comments
1069} // end namespace clang
1070