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