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 (!isFunctionDecl())
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 (isFunctionDecl()) {
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 (!isFunctionDecl()) {
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::isFunctionDecl() {
820   if (!ThisDeclInfo)
821     return false;
822   if (!ThisDeclInfo->IsFilled)
823     inspectThisDecl();
824   return ThisDeclInfo->getKind() == DeclInfo::FunctionKind;
825 }
826 
827 bool Sema::isAnyFunctionDecl() {
828   return isFunctionDecl() && ThisDeclInfo->CurrentDecl &&
829          isa<FunctionDecl>(ThisDeclInfo->CurrentDecl);
830 }
831 
832 bool Sema::isFunctionOrMethodVariadic() {
833   if (!isFunctionDecl() || !ThisDeclInfo->CurrentDecl)
834     return false;
835   if (const FunctionDecl *FD =
836         dyn_cast<FunctionDecl>(ThisDeclInfo->CurrentDecl))
837     return FD->isVariadic();
838   if (const FunctionTemplateDecl *FTD =
839         dyn_cast<FunctionTemplateDecl>(ThisDeclInfo->CurrentDecl))
840     return FTD->getTemplatedDecl()->isVariadic();
841   if (const ObjCMethodDecl *MD =
842         dyn_cast<ObjCMethodDecl>(ThisDeclInfo->CurrentDecl))
843     return MD->isVariadic();
844   if (const TypedefNameDecl *TD =
845           dyn_cast<TypedefNameDecl>(ThisDeclInfo->CurrentDecl)) {
846     QualType Type = TD->getUnderlyingType();
847     if (Type->isFunctionPointerType() || Type->isBlockPointerType())
848       Type = Type->getPointeeType();
849     if (const auto *FT = Type->getAs<FunctionProtoType>())
850       return FT->isVariadic();
851   }
852   return false;
853 }
854 
855 bool Sema::isObjCMethodDecl() {
856   return isFunctionDecl() && ThisDeclInfo->CurrentDecl &&
857          isa<ObjCMethodDecl>(ThisDeclInfo->CurrentDecl);
858 }
859 
860 bool Sema::isFunctionPointerVarDecl() {
861   if (!ThisDeclInfo)
862     return false;
863   if (!ThisDeclInfo->IsFilled)
864     inspectThisDecl();
865   if (ThisDeclInfo->getKind() == DeclInfo::VariableKind) {
866     if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDeclInfo->CurrentDecl)) {
867       QualType QT = VD->getType();
868       return QT->isFunctionPointerType();
869     }
870   }
871   return false;
872 }
873 
874 bool Sema::isObjCPropertyDecl() {
875   if (!ThisDeclInfo)
876     return false;
877   if (!ThisDeclInfo->IsFilled)
878     inspectThisDecl();
879   return ThisDeclInfo->CurrentDecl->getKind() == Decl::ObjCProperty;
880 }
881 
882 bool Sema::isTemplateOrSpecialization() {
883   if (!ThisDeclInfo)
884     return false;
885   if (!ThisDeclInfo->IsFilled)
886     inspectThisDecl();
887   return ThisDeclInfo->getTemplateKind() != DeclInfo::NotTemplate;
888 }
889 
890 bool Sema::isRecordLikeDecl() {
891   if (!ThisDeclInfo)
892     return false;
893   if (!ThisDeclInfo->IsFilled)
894     inspectThisDecl();
895   return isUnionDecl() || isClassOrStructDecl() || isObjCInterfaceDecl() ||
896          isObjCProtocolDecl();
897 }
898 
899 bool Sema::isUnionDecl() {
900   if (!ThisDeclInfo)
901     return false;
902   if (!ThisDeclInfo->IsFilled)
903     inspectThisDecl();
904   if (const RecordDecl *RD =
905         dyn_cast_or_null<RecordDecl>(ThisDeclInfo->CurrentDecl))
906     return RD->isUnion();
907   return false;
908 }
909 static bool isClassOrStructDeclImpl(const Decl *D) {
910   if (auto *record = dyn_cast_or_null<RecordDecl>(D))
911     return !record->isUnion();
912 
913   return false;
914 }
915 
916 bool Sema::isClassOrStructDecl() {
917   if (!ThisDeclInfo)
918     return false;
919   if (!ThisDeclInfo->IsFilled)
920     inspectThisDecl();
921 
922   if (!ThisDeclInfo->CurrentDecl)
923     return false;
924 
925   return isClassOrStructDeclImpl(ThisDeclInfo->CurrentDecl);
926 }
927 
928 bool Sema::isClassOrStructOrTagTypedefDecl() {
929   if (!ThisDeclInfo)
930     return false;
931   if (!ThisDeclInfo->IsFilled)
932     inspectThisDecl();
933 
934   if (!ThisDeclInfo->CurrentDecl)
935     return false;
936 
937   if (isClassOrStructDeclImpl(ThisDeclInfo->CurrentDecl))
938     return true;
939 
940   if (auto *ThisTypedefDecl = dyn_cast<TypedefDecl>(ThisDeclInfo->CurrentDecl)) {
941     auto UnderlyingType = ThisTypedefDecl->getUnderlyingType();
942     if (auto ThisElaboratedType = dyn_cast<ElaboratedType>(UnderlyingType)) {
943       auto DesugaredType = ThisElaboratedType->desugar();
944       if (auto *DesugaredTypePtr = DesugaredType.getTypePtrOrNull()) {
945         if (auto *ThisRecordType = dyn_cast<RecordType>(DesugaredTypePtr)) {
946           return isClassOrStructDeclImpl(ThisRecordType->getAsRecordDecl());
947         }
948       }
949     }
950   }
951 
952   return false;
953 }
954 
955 bool Sema::isClassTemplateDecl() {
956   if (!ThisDeclInfo)
957     return false;
958   if (!ThisDeclInfo->IsFilled)
959     inspectThisDecl();
960   return ThisDeclInfo->CurrentDecl &&
961           (isa<ClassTemplateDecl>(ThisDeclInfo->CurrentDecl));
962 }
963 
964 bool Sema::isFunctionTemplateDecl() {
965   if (!ThisDeclInfo)
966     return false;
967   if (!ThisDeclInfo->IsFilled)
968     inspectThisDecl();
969   return ThisDeclInfo->CurrentDecl &&
970          (isa<FunctionTemplateDecl>(ThisDeclInfo->CurrentDecl));
971 }
972 
973 bool Sema::isObjCInterfaceDecl() {
974   if (!ThisDeclInfo)
975     return false;
976   if (!ThisDeclInfo->IsFilled)
977     inspectThisDecl();
978   return ThisDeclInfo->CurrentDecl &&
979          isa<ObjCInterfaceDecl>(ThisDeclInfo->CurrentDecl);
980 }
981 
982 bool Sema::isObjCProtocolDecl() {
983   if (!ThisDeclInfo)
984     return false;
985   if (!ThisDeclInfo->IsFilled)
986     inspectThisDecl();
987   return ThisDeclInfo->CurrentDecl &&
988          isa<ObjCProtocolDecl>(ThisDeclInfo->CurrentDecl);
989 }
990 
991 ArrayRef<const ParmVarDecl *> Sema::getParamVars() {
992   if (!ThisDeclInfo->IsFilled)
993     inspectThisDecl();
994   return ThisDeclInfo->ParamVars;
995 }
996 
997 void Sema::inspectThisDecl() {
998   ThisDeclInfo->fill();
999 }
1000 
1001 unsigned Sema::resolveParmVarReference(StringRef Name,
1002                                        ArrayRef<const ParmVarDecl *> ParamVars) {
1003   for (unsigned i = 0, e = ParamVars.size(); i != e; ++i) {
1004     const IdentifierInfo *II = ParamVars[i]->getIdentifier();
1005     if (II && II->getName() == Name)
1006       return i;
1007   }
1008   if (Name == "..." && isFunctionOrMethodVariadic())
1009     return ParamCommandComment::VarArgParamIndex;
1010   return ParamCommandComment::InvalidParamIndex;
1011 }
1012 
1013 namespace {
1014 class SimpleTypoCorrector {
1015   const NamedDecl *BestDecl;
1016 
1017   StringRef Typo;
1018   const unsigned MaxEditDistance;
1019 
1020   unsigned BestEditDistance;
1021   unsigned BestIndex;
1022   unsigned NextIndex;
1023 
1024 public:
1025   explicit SimpleTypoCorrector(StringRef Typo)
1026       : BestDecl(nullptr), Typo(Typo), MaxEditDistance((Typo.size() + 2) / 3),
1027         BestEditDistance(MaxEditDistance + 1), BestIndex(0), NextIndex(0) {}
1028 
1029   void addDecl(const NamedDecl *ND);
1030 
1031   const NamedDecl *getBestDecl() const {
1032     if (BestEditDistance > MaxEditDistance)
1033       return nullptr;
1034 
1035     return BestDecl;
1036   }
1037 
1038   unsigned getBestDeclIndex() const {
1039     assert(getBestDecl());
1040     return BestIndex;
1041   }
1042 };
1043 
1044 void SimpleTypoCorrector::addDecl(const NamedDecl *ND) {
1045   unsigned CurrIndex = NextIndex++;
1046 
1047   const IdentifierInfo *II = ND->getIdentifier();
1048   if (!II)
1049     return;
1050 
1051   StringRef Name = II->getName();
1052   unsigned MinPossibleEditDistance = abs((int)Name.size() - (int)Typo.size());
1053   if (MinPossibleEditDistance > 0 &&
1054       Typo.size() / MinPossibleEditDistance < 3)
1055     return;
1056 
1057   unsigned EditDistance = Typo.edit_distance(Name, true, MaxEditDistance);
1058   if (EditDistance < BestEditDistance) {
1059     BestEditDistance = EditDistance;
1060     BestDecl = ND;
1061     BestIndex = CurrIndex;
1062   }
1063 }
1064 } // end anonymous namespace
1065 
1066 unsigned Sema::correctTypoInParmVarReference(
1067                                     StringRef Typo,
1068                                     ArrayRef<const ParmVarDecl *> ParamVars) {
1069   SimpleTypoCorrector Corrector(Typo);
1070   for (unsigned i = 0, e = ParamVars.size(); i != e; ++i)
1071     Corrector.addDecl(ParamVars[i]);
1072   if (Corrector.getBestDecl())
1073     return Corrector.getBestDeclIndex();
1074   else
1075     return ParamCommandComment::InvalidParamIndex;
1076 }
1077 
1078 namespace {
1079 bool ResolveTParamReferenceHelper(
1080                             StringRef Name,
1081                             const TemplateParameterList *TemplateParameters,
1082                             SmallVectorImpl<unsigned> *Position) {
1083   for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
1084     const NamedDecl *Param = TemplateParameters->getParam(i);
1085     const IdentifierInfo *II = Param->getIdentifier();
1086     if (II && II->getName() == Name) {
1087       Position->push_back(i);
1088       return true;
1089     }
1090 
1091     if (const TemplateTemplateParmDecl *TTP =
1092             dyn_cast<TemplateTemplateParmDecl>(Param)) {
1093       Position->push_back(i);
1094       if (ResolveTParamReferenceHelper(Name, TTP->getTemplateParameters(),
1095                                        Position))
1096         return true;
1097       Position->pop_back();
1098     }
1099   }
1100   return false;
1101 }
1102 } // end anonymous namespace
1103 
1104 bool Sema::resolveTParamReference(
1105                             StringRef Name,
1106                             const TemplateParameterList *TemplateParameters,
1107                             SmallVectorImpl<unsigned> *Position) {
1108   Position->clear();
1109   if (!TemplateParameters)
1110     return false;
1111 
1112   return ResolveTParamReferenceHelper(Name, TemplateParameters, Position);
1113 }
1114 
1115 namespace {
1116 void CorrectTypoInTParamReferenceHelper(
1117                             const TemplateParameterList *TemplateParameters,
1118                             SimpleTypoCorrector &Corrector) {
1119   for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
1120     const NamedDecl *Param = TemplateParameters->getParam(i);
1121     Corrector.addDecl(Param);
1122 
1123     if (const TemplateTemplateParmDecl *TTP =
1124             dyn_cast<TemplateTemplateParmDecl>(Param))
1125       CorrectTypoInTParamReferenceHelper(TTP->getTemplateParameters(),
1126                                          Corrector);
1127   }
1128 }
1129 } // end anonymous namespace
1130 
1131 StringRef Sema::correctTypoInTParamReference(
1132                             StringRef Typo,
1133                             const TemplateParameterList *TemplateParameters) {
1134   SimpleTypoCorrector Corrector(Typo);
1135   CorrectTypoInTParamReferenceHelper(TemplateParameters, Corrector);
1136   if (const NamedDecl *ND = Corrector.getBestDecl()) {
1137     const IdentifierInfo *II = ND->getIdentifier();
1138     assert(II && "SimpleTypoCorrector should not return this decl");
1139     return II->getName();
1140   }
1141   return StringRef();
1142 }
1143 
1144 InlineCommandComment::RenderKind
1145 Sema::getInlineCommandRenderKind(StringRef Name) const {
1146   assert(Traits.getCommandInfo(Name)->IsInlineCommand);
1147 
1148   return llvm::StringSwitch<InlineCommandComment::RenderKind>(Name)
1149       .Case("b", InlineCommandComment::RenderBold)
1150       .Cases("c", "p", InlineCommandComment::RenderMonospaced)
1151       .Cases("a", "e", "em", InlineCommandComment::RenderEmphasized)
1152       .Case("anchor", InlineCommandComment::RenderAnchor)
1153       .Default(InlineCommandComment::RenderNormal);
1154 }
1155 
1156 } // end namespace comments
1157 } // end namespace clang
1158