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