1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "FindBadConstructsConsumer.h"
7 #include "clang/Frontend/CompilerInstance.h"
8 #include "clang/AST/Attr.h"
9 #include "clang/Lex/Lexer.h"
10 #include "llvm/Support/raw_ostream.h"
12 using namespace clang;
14 namespace chrome_checker {
18 const char kMethodRequiresOverride[] =
19 "[chromium-style] Overriding method must be marked with 'override' or "
21 const char kRedundantVirtualSpecifier[] =
22 "[chromium-style] %0 is redundant; %1 implies %0.";
23 // http://llvm.org/bugs/show_bug.cgi?id=21051 has been filed to make this a
25 const char kBaseMethodVirtualAndFinal[] =
26 "[chromium-style] The virtual method does not override anything and is "
27 "final; consider making it non-virtual.";
28 const char kNoExplicitDtor[] =
29 "[chromium-style] Classes that are ref-counted should have explicit "
30 "destructors that are declared protected or private.";
31 const char kPublicDtor[] =
32 "[chromium-style] Classes that are ref-counted should have "
33 "destructors that are declared protected or private.";
34 const char kProtectedNonVirtualDtor[] =
35 "[chromium-style] Classes that are ref-counted and have non-private "
36 "destructors should declare their destructor virtual.";
37 const char kWeakPtrFactoryOrder[] =
38 "[chromium-style] WeakPtrFactory members which refer to their outer class "
39 "must be the last member in the outer class definition.";
40 const char kBadLastEnumValue[] =
41 "[chromium-style] _LAST/Last constants of enum types must have the maximal "
42 "value for any constant of that type.";
43 const char kNoteInheritance[] = "[chromium-style] %0 inherits from %1 here";
44 const char kNoteImplicitDtor[] =
45 "[chromium-style] No explicit destructor for %0 defined";
46 const char kNotePublicDtor[] =
47 "[chromium-style] Public destructor declared here";
48 const char kNoteProtectedNonVirtualDtor[] =
49 "[chromium-style] Protected non-virtual destructor declared here";
51 bool TypeHasNonTrivialDtor(const Type* type) {
52 if (const CXXRecordDecl* cxx_r = type->getPointeeCXXRecordDecl())
53 return !cxx_r->hasTrivialDestructor();
58 // Returns the underlying Type for |type| by expanding typedefs and removing
59 // any namespace qualifiers. This is similar to desugaring, except that for
60 // ElaboratedTypes, desugar will unwrap too much.
61 const Type* UnwrapType(const Type* type) {
62 if (const ElaboratedType* elaborated = dyn_cast<ElaboratedType>(type))
63 return UnwrapType(elaborated->getNamedType().getTypePtr());
64 if (const TypedefType* typedefed = dyn_cast<TypedefType>(type))
65 return UnwrapType(typedefed->desugar().getTypePtr());
69 bool IsGtestTestFixture(const CXXRecordDecl* decl) {
70 return decl->getQualifiedNameAsString() == "testing::Test";
73 FixItHint FixItRemovalForVirtual(const SourceManager& manager,
74 const CXXMethodDecl* method) {
75 // Unfortunately, there doesn't seem to be a good way to determine the
76 // location of the 'virtual' keyword. It's available in Declarator, but that
77 // isn't accessible from the AST. So instead, make an educated guess that the
78 // first token is probably the virtual keyword. Strictly speaking, this
79 // doesn't have to be true, but it probably will be.
80 // TODO(dcheng): Add a warning to force virtual to always appear first ;-)
81 SourceRange range(method->getLocStart());
82 // Get the spelling loc just in case it was expanded from a macro.
83 SourceRange spelling_range(manager.getSpellingLoc(range.getBegin()));
84 // Sanity check that the text looks like virtual.
85 StringRef text = clang::Lexer::getSourceText(
86 CharSourceRange::getTokenRange(spelling_range), manager, LangOptions());
87 if (text.trim() != "virtual")
89 return FixItHint::CreateRemoval(range);
94 FindBadConstructsConsumer::FindBadConstructsConsumer(CompilerInstance& instance,
95 const Options& options)
96 : ChromeClassTester(instance), options_(options) {
97 // Messages for virtual method specifiers.
98 diag_method_requires_override_ =
99 diagnostic().getCustomDiagID(getErrorLevel(), kMethodRequiresOverride);
100 diag_redundant_virtual_specifier_ =
101 diagnostic().getCustomDiagID(getErrorLevel(), kRedundantVirtualSpecifier);
102 diag_base_method_virtual_and_final_ =
103 diagnostic().getCustomDiagID(getErrorLevel(), kBaseMethodVirtualAndFinal);
105 // Messages for destructors.
106 diag_no_explicit_dtor_ =
107 diagnostic().getCustomDiagID(getErrorLevel(), kNoExplicitDtor);
109 diagnostic().getCustomDiagID(getErrorLevel(), kPublicDtor);
110 diag_protected_non_virtual_dtor_ =
111 diagnostic().getCustomDiagID(getErrorLevel(), kProtectedNonVirtualDtor);
113 // Miscellaneous messages.
114 diag_weak_ptr_factory_order_ =
115 diagnostic().getCustomDiagID(getErrorLevel(), kWeakPtrFactoryOrder);
116 diag_bad_enum_last_value_ =
117 diagnostic().getCustomDiagID(getErrorLevel(), kBadLastEnumValue);
119 // Registers notes to make it easier to interpret warnings.
120 diag_note_inheritance_ =
121 diagnostic().getCustomDiagID(DiagnosticsEngine::Note, kNoteInheritance);
122 diag_note_implicit_dtor_ =
123 diagnostic().getCustomDiagID(DiagnosticsEngine::Note, kNoteImplicitDtor);
124 diag_note_public_dtor_ =
125 diagnostic().getCustomDiagID(DiagnosticsEngine::Note, kNotePublicDtor);
126 diag_note_protected_non_virtual_dtor_ = diagnostic().getCustomDiagID(
127 DiagnosticsEngine::Note, kNoteProtectedNonVirtualDtor);
130 void FindBadConstructsConsumer::CheckChromeClass(SourceLocation record_location,
131 CXXRecordDecl* record) {
132 bool implementation_file = InImplementationFile(record_location);
134 if (!implementation_file) {
135 // Only check for "heavy" constructors/destructors in header files;
136 // within implementation files, there is no performance cost.
137 CheckCtorDtorWeight(record_location, record);
140 bool warn_on_inline_bodies = !implementation_file;
142 // Check that all virtual methods are annotated with override or final.
143 CheckVirtualMethods(record_location, record, warn_on_inline_bodies);
145 CheckRefCountedDtors(record_location, record);
147 if (options_.check_weak_ptr_factory_order)
148 CheckWeakPtrFactoryMembers(record_location, record);
151 void FindBadConstructsConsumer::CheckChromeEnum(SourceLocation enum_location,
152 EnumDecl* enum_decl) {
153 if (!options_.check_enum_last_value)
156 bool got_one = false;
157 bool is_signed = false;
158 llvm::APSInt max_so_far;
159 EnumDecl::enumerator_iterator iter;
160 for (iter = enum_decl->enumerator_begin();
161 iter != enum_decl->enumerator_end();
163 llvm::APSInt current_value = iter->getInitVal();
165 max_so_far = current_value;
166 is_signed = current_value.isSigned();
169 if (is_signed != current_value.isSigned()) {
170 // This only happens in some cases when compiling C (not C++) files,
171 // so it is OK to bail out here.
174 if (current_value > max_so_far)
175 max_so_far = current_value;
178 for (iter = enum_decl->enumerator_begin();
179 iter != enum_decl->enumerator_end();
181 std::string name = iter->getNameAsString();
182 if (((name.size() > 4 && name.compare(name.size() - 4, 4, "Last") == 0) ||
183 (name.size() > 5 && name.compare(name.size() - 5, 5, "_LAST") == 0)) &&
184 iter->getInitVal() < max_so_far) {
185 diagnostic().Report(iter->getLocation(), diag_bad_enum_last_value_);
190 void FindBadConstructsConsumer::CheckCtorDtorWeight(
191 SourceLocation record_location,
192 CXXRecordDecl* record) {
193 // We don't handle anonymous structs. If this record doesn't have a
194 // name, it's of the form:
199 if (record->getIdentifier() == NULL)
202 // Count the number of templated base classes as a feature of whether the
203 // destructor can be inlined.
204 int templated_base_classes = 0;
205 for (CXXRecordDecl::base_class_const_iterator it = record->bases_begin();
206 it != record->bases_end();
208 if (it->getTypeSourceInfo()->getTypeLoc().getTypeLocClass() ==
209 TypeLoc::TemplateSpecialization) {
210 ++templated_base_classes;
214 // Count the number of trivial and non-trivial member variables.
215 int trivial_member = 0;
216 int non_trivial_member = 0;
217 int templated_non_trivial_member = 0;
218 for (RecordDecl::field_iterator it = record->field_begin();
219 it != record->field_end();
221 CountType(it->getType().getTypePtr(),
224 &templated_non_trivial_member);
227 // Check to see if we need to ban inlined/synthesized constructors. Note
228 // that the cutoffs here are kind of arbitrary. Scores over 10 break.
230 // Deriving from a templated base class shouldn't be enough to trigger
231 // the ctor warning, but if you do *anything* else, it should.
233 // TODO(erg): This is motivated by templated base classes that don't have
234 // any data members. Somehow detect when templated base classes have data
235 // members and treat them differently.
236 dtor_score += templated_base_classes * 9;
237 // Instantiating a template is an insta-hit.
238 dtor_score += templated_non_trivial_member * 10;
239 // The fourth normal class member should trigger the warning.
240 dtor_score += non_trivial_member * 3;
242 int ctor_score = dtor_score;
243 // You should be able to have 9 ints before we warn you.
244 ctor_score += trivial_member;
246 if (ctor_score >= 10) {
247 if (!record->hasUserDeclaredConstructor()) {
248 emitWarning(record_location,
249 "Complex class/struct needs an explicit out-of-line "
252 // Iterate across all the constructors in this file and yell if we
253 // find one that tries to be inline.
254 for (CXXRecordDecl::ctor_iterator it = record->ctor_begin();
255 it != record->ctor_end();
257 if (it->hasInlineBody()) {
258 if (it->isCopyConstructor() &&
259 !record->hasUserDeclaredCopyConstructor()) {
260 emitWarning(record_location,
261 "Complex class/struct needs an explicit out-of-line "
262 "copy constructor.");
264 emitWarning(it->getInnerLocStart(),
265 "Complex constructor has an inlined body.");
272 // The destructor side is equivalent except that we don't check for
273 // trivial members; 20 ints don't need a destructor.
274 if (dtor_score >= 10 && !record->hasTrivialDestructor()) {
275 if (!record->hasUserDeclaredDestructor()) {
276 emitWarning(record_location,
277 "Complex class/struct needs an explicit out-of-line "
279 } else if (CXXDestructorDecl* dtor = record->getDestructor()) {
280 if (dtor->hasInlineBody()) {
281 emitWarning(dtor->getInnerLocStart(),
282 "Complex destructor has an inline body.");
288 bool FindBadConstructsConsumer::InTestingNamespace(const Decl* record) {
289 return GetNamespace(record).find("testing") != std::string::npos;
292 bool FindBadConstructsConsumer::IsMethodInBannedOrTestingNamespace(
293 const CXXMethodDecl* method) {
294 if (InBannedNamespace(method))
296 for (CXXMethodDecl::method_iterator i = method->begin_overridden_methods();
297 i != method->end_overridden_methods();
299 const CXXMethodDecl* overridden = *i;
300 if (IsMethodInBannedOrTestingNamespace(overridden) ||
301 // Provide an exception for ::testing::Test. gtest itself uses some
302 // magic to try to make sure SetUp()/TearDown() aren't capitalized
303 // incorrectly, but having the plugin enforce override is also nice.
304 (InTestingNamespace(overridden) &&
305 (!options_.strict_virtual_specifiers ||
306 !IsGtestTestFixture(overridden->getParent())))) {
314 // Checks that virtual methods are correctly annotated, and have no body in a
316 void FindBadConstructsConsumer::CheckVirtualMethods(
317 SourceLocation record_location,
318 CXXRecordDecl* record,
319 bool warn_on_inline_bodies) {
320 // Gmock objects trigger these for each MOCK_BLAH() macro used. So we have a
321 // trick to get around that. If a class has member variables whose types are
322 // in the "testing" namespace (which is how gmock works behind the scenes),
323 // there's a really high chance we won't care about these errors
324 for (CXXRecordDecl::field_iterator it = record->field_begin();
325 it != record->field_end();
327 CXXRecordDecl* record_type = it->getTypeSourceInfo()
330 ->getAsCXXRecordDecl();
332 if (InTestingNamespace(record_type)) {
338 for (CXXRecordDecl::method_iterator it = record->method_begin();
339 it != record->method_end();
341 if (it->isCopyAssignmentOperator() || isa<CXXConstructorDecl>(*it)) {
342 // Ignore constructors and assignment operators.
343 } else if (isa<CXXDestructorDecl>(*it) &&
344 !record->hasUserDeclaredDestructor()) {
345 // Ignore non-user-declared destructors.
346 } else if (!it->isVirtual()) {
349 CheckVirtualSpecifiers(*it);
350 if (warn_on_inline_bodies)
351 CheckVirtualBodies(*it);
356 // Makes sure that virtual methods use the most appropriate specifier. If a
357 // virtual method overrides a method from a base class, only the override
358 // specifier should be used. If the method should not be overridden by derived
359 // classes, only the final specifier should be used.
360 void FindBadConstructsConsumer::CheckVirtualSpecifiers(
361 const CXXMethodDecl* method) {
362 bool is_override = method->size_overridden_methods() > 0;
363 bool has_virtual = method->isVirtualAsWritten();
364 OverrideAttr* override_attr = method->getAttr<OverrideAttr>();
365 FinalAttr* final_attr = method->getAttr<FinalAttr>();
367 if (method->isPure() && !options_.strict_virtual_specifiers)
370 if (IsMethodInBannedOrTestingNamespace(method))
373 if (isa<CXXDestructorDecl>(method) && !options_.strict_virtual_specifiers)
376 SourceManager& manager = instance().getSourceManager();
378 // Complain if a method is annotated virtual && (override || final).
379 if (has_virtual && (override_attr || final_attr) &&
380 options_.strict_virtual_specifiers) {
381 diagnostic().Report(method->getLocStart(),
382 diag_redundant_virtual_specifier_)
384 << (override_attr ? static_cast<Attr*>(override_attr) : final_attr)
385 << FixItRemovalForVirtual(manager, method);
388 // Complain if a method is an override and is not annotated with override or
390 if (is_override && !override_attr && !final_attr) {
391 SourceRange type_info_range =
392 method->getTypeSourceInfo()->getTypeLoc().getSourceRange();
393 FullSourceLoc loc(type_info_range.getBegin(), manager);
395 // Build the FixIt insertion point after the end of the method definition,
396 // including any const-qualifiers and attributes, and before the opening
397 // of the l-curly-brace (if inline) or the semi-color (if a declaration).
398 SourceLocation spelling_end =
399 manager.getSpellingLoc(type_info_range.getEnd());
400 if (spelling_end.isValid()) {
401 SourceLocation token_end =
402 Lexer::getLocForEndOfToken(spelling_end, 0, manager, LangOptions());
403 diagnostic().Report(token_end, diag_method_requires_override_)
404 << FixItHint::CreateInsertion(token_end, " override");
406 diagnostic().Report(loc, diag_method_requires_override_);
410 if (final_attr && override_attr && options_.strict_virtual_specifiers) {
411 diagnostic().Report(override_attr->getLocation(),
412 diag_redundant_virtual_specifier_)
413 << override_attr << final_attr
414 << FixItHint::CreateRemoval(override_attr->getRange());
417 if (final_attr && !is_override && options_.strict_virtual_specifiers) {
418 diagnostic().Report(method->getLocStart(),
419 diag_base_method_virtual_and_final_)
420 << FixItRemovalForVirtual(manager, method)
421 << FixItHint::CreateRemoval(final_attr->getRange());
425 void FindBadConstructsConsumer::CheckVirtualBodies(
426 const CXXMethodDecl* method) {
427 // Virtual methods should not have inline definitions beyond "{}". This
428 // only matters for header files.
429 if (method->hasBody() && method->hasInlineBody()) {
430 if (CompoundStmt* cs = dyn_cast<CompoundStmt>(method->getBody())) {
432 emitWarning(cs->getLBracLoc(),
433 "virtual methods with non-empty bodies shouldn't be "
440 void FindBadConstructsConsumer::CountType(const Type* type,
442 int* non_trivial_member,
443 int* templated_non_trivial_member) {
444 switch (type->getTypeClass()) {
446 // Simplifying; the whole class isn't trivial if the dtor is, but
447 // we use this as a signal about complexity.
448 if (TypeHasNonTrivialDtor(type))
451 (*non_trivial_member)++;
454 case Type::TemplateSpecialization: {
456 dyn_cast<TemplateSpecializationType>(type)->getTemplateName();
457 bool whitelisted_template = false;
459 // HACK: I'm at a loss about how to get the syntax checker to get
460 // whether a template is exterened or not. For the first pass here,
461 // just do retarded string comparisons.
462 if (TemplateDecl* decl = name.getAsTemplateDecl()) {
463 std::string base_name = decl->getNameAsString();
464 if (base_name == "basic_string")
465 whitelisted_template = true;
468 if (whitelisted_template)
469 (*non_trivial_member)++;
471 (*templated_non_trivial_member)++;
474 case Type::Elaborated: {
475 CountType(dyn_cast<ElaboratedType>(type)->getNamedType().getTypePtr(),
478 templated_non_trivial_member);
481 case Type::Typedef: {
482 while (const TypedefType* TT = dyn_cast<TypedefType>(type)) {
483 type = TT->getDecl()->getUnderlyingType().getTypePtr();
488 templated_non_trivial_member);
492 // Stupid assumption: anything we see that isn't the above is one of
493 // the 20 integer types.
500 // Check |record| for issues that are problematic for ref-counted types.
501 // Note that |record| may not be a ref-counted type, but a base class for
503 // If there are issues, update |loc| with the SourceLocation of the issue
504 // and returns appropriately, or returns None if there are no issues.
505 FindBadConstructsConsumer::RefcountIssue
506 FindBadConstructsConsumer::CheckRecordForRefcountIssue(
507 const CXXRecordDecl* record,
508 SourceLocation& loc) {
509 if (!record->hasUserDeclaredDestructor()) {
510 loc = record->getLocation();
511 return ImplicitDestructor;
514 if (CXXDestructorDecl* dtor = record->getDestructor()) {
515 if (dtor->getAccess() == AS_public) {
516 loc = dtor->getInnerLocStart();
517 return PublicDestructor;
524 // Adds either a warning or error, based on the current handling of
526 DiagnosticsEngine::Level FindBadConstructsConsumer::getErrorLevel() {
527 return diagnostic().getWarningsAsErrors() ? DiagnosticsEngine::Error
528 : DiagnosticsEngine::Warning;
531 // Returns true if |base| specifies one of the Chromium reference counted
532 // classes (base::RefCounted / base::RefCountedThreadSafe).
533 bool FindBadConstructsConsumer::IsRefCountedCallback(
534 const CXXBaseSpecifier* base,
537 FindBadConstructsConsumer* self =
538 static_cast<FindBadConstructsConsumer*>(user_data);
540 const TemplateSpecializationType* base_type =
541 dyn_cast<TemplateSpecializationType>(
542 UnwrapType(base->getType().getTypePtr()));
544 // Base-most definition is not a template, so this cannot derive from
545 // base::RefCounted. However, it may still be possible to use with a
546 // scoped_refptr<> and support ref-counting, so this is not a perfect
547 // guarantee of safety.
551 TemplateName name = base_type->getTemplateName();
552 if (TemplateDecl* decl = name.getAsTemplateDecl()) {
553 std::string base_name = decl->getNameAsString();
555 // Check for both base::RefCounted and base::RefCountedThreadSafe.
556 if (base_name.compare(0, 10, "RefCounted") == 0 &&
557 self->GetNamespace(decl) == "base") {
565 // Returns true if |base| specifies a class that has a public destructor,
566 // either explicitly or implicitly.
567 bool FindBadConstructsConsumer::HasPublicDtorCallback(
568 const CXXBaseSpecifier* base,
571 // Only examine paths that have public inheritance, as they are the
572 // only ones which will result in the destructor potentially being
573 // exposed. This check is largely redundant, as Chromium code should be
574 // exclusively using public inheritance.
575 if (path.Access != AS_public)
578 CXXRecordDecl* record =
579 dyn_cast<CXXRecordDecl>(base->getType()->getAs<RecordType>()->getDecl());
580 SourceLocation unused;
581 return None != CheckRecordForRefcountIssue(record, unused);
584 // Outputs a C++ inheritance chain as a diagnostic aid.
585 void FindBadConstructsConsumer::PrintInheritanceChain(const CXXBasePath& path) {
586 for (CXXBasePath::const_iterator it = path.begin(); it != path.end(); ++it) {
587 diagnostic().Report(it->Base->getLocStart(), diag_note_inheritance_)
588 << it->Class << it->Base->getType();
592 unsigned FindBadConstructsConsumer::DiagnosticForIssue(RefcountIssue issue) {
594 case ImplicitDestructor:
595 return diag_no_explicit_dtor_;
596 case PublicDestructor:
597 return diag_public_dtor_;
599 assert(false && "Do not call DiagnosticForIssue with issue None");
606 // Check |record| to determine if it has any problematic refcounting
607 // issues and, if so, print them as warnings/errors based on the current
608 // value of getErrorLevel().
610 // If |record| is a C++ class, and if it inherits from one of the Chromium
611 // ref-counting classes (base::RefCounted / base::RefCountedThreadSafe),
612 // ensure that there are no public destructors in the class hierarchy. This
613 // is to guard against accidentally stack-allocating a RefCounted class or
614 // sticking it in a non-ref-counted container (like scoped_ptr<>).
615 void FindBadConstructsConsumer::CheckRefCountedDtors(
616 SourceLocation record_location,
617 CXXRecordDecl* record) {
618 // Skip anonymous structs.
619 if (record->getIdentifier() == NULL)
622 // Determine if the current type is even ref-counted.
623 CXXBasePaths refcounted_path;
624 if (!record->lookupInBases(&FindBadConstructsConsumer::IsRefCountedCallback,
627 return; // Class does not derive from a ref-counted base class.
630 // Easy check: Check to see if the current type is problematic.
632 RefcountIssue issue = CheckRecordForRefcountIssue(record, loc);
634 diagnostic().Report(loc, DiagnosticForIssue(issue));
635 PrintInheritanceChain(refcounted_path.front());
638 if (CXXDestructorDecl* dtor =
639 refcounted_path.begin()->back().Class->getDestructor()) {
640 if (dtor->getAccess() == AS_protected && !dtor->isVirtual()) {
641 loc = dtor->getInnerLocStart();
642 diagnostic().Report(loc, diag_protected_non_virtual_dtor_);
647 // Long check: Check all possible base classes for problematic
648 // destructors. This checks for situations involving multiple
649 // inheritance, where the ref-counted class may be implementing an
650 // interface that has a public or implicit destructor.
652 // struct SomeInterface {
653 // virtual void DoFoo();
656 // struct RefCountedInterface
657 // : public base::RefCounted<RefCountedInterface>,
658 // public SomeInterface {
660 // friend class base::Refcounted<RefCountedInterface>;
661 // virtual ~RefCountedInterface() {}
664 // While RefCountedInterface is "safe", in that its destructor is
665 // private, it's possible to do the following "unsafe" code:
666 // scoped_refptr<RefCountedInterface> some_class(
667 // new RefCountedInterface);
668 // // Calls SomeInterface::~SomeInterface(), which is unsafe.
669 // delete static_cast<SomeInterface*>(some_class.get());
670 if (!options_.check_base_classes)
673 // Find all public destructors. This will record the class hierarchy
674 // that leads to the public destructor in |dtor_paths|.
675 CXXBasePaths dtor_paths;
676 if (!record->lookupInBases(&FindBadConstructsConsumer::HasPublicDtorCallback,
682 for (CXXBasePaths::const_paths_iterator it = dtor_paths.begin();
683 it != dtor_paths.end();
685 // The record with the problem will always be the last record
686 // in the path, since it is the record that stopped the search.
687 const CXXRecordDecl* problem_record = dyn_cast<CXXRecordDecl>(
688 it->back().Base->getType()->getAs<RecordType>()->getDecl());
690 issue = CheckRecordForRefcountIssue(problem_record, loc);
692 if (issue == ImplicitDestructor) {
693 diagnostic().Report(record_location, diag_no_explicit_dtor_);
694 PrintInheritanceChain(refcounted_path.front());
695 diagnostic().Report(loc, diag_note_implicit_dtor_) << problem_record;
696 PrintInheritanceChain(*it);
697 } else if (issue == PublicDestructor) {
698 diagnostic().Report(record_location, diag_public_dtor_);
699 PrintInheritanceChain(refcounted_path.front());
700 diagnostic().Report(loc, diag_note_public_dtor_);
701 PrintInheritanceChain(*it);
706 // Check for any problems with WeakPtrFactory class members. This currently
707 // only checks that any WeakPtrFactory<T> member of T appears as the last
708 // data member in T. We could consider checking for bad uses of
709 // WeakPtrFactory to refer to other data members, but that would require
710 // looking at the initializer list in constructors to see what the factory
712 // Note, if we later add other unrelated checks of data members, we should
713 // consider collapsing them in to one loop to avoid iterating over the data
714 // members more than once.
715 void FindBadConstructsConsumer::CheckWeakPtrFactoryMembers(
716 SourceLocation record_location,
717 CXXRecordDecl* record) {
718 // Skip anonymous structs.
719 if (record->getIdentifier() == NULL)
722 // Iterate through members of the class.
723 RecordDecl::field_iterator iter(record->field_begin()),
724 the_end(record->field_end());
725 SourceLocation weak_ptr_factory_location; // Invalid initially.
726 for (; iter != the_end; ++iter) {
727 // If we enter the loop but have already seen a matching WeakPtrFactory,
728 // it means there is at least one member after the factory.
729 if (weak_ptr_factory_location.isValid()) {
730 diagnostic().Report(weak_ptr_factory_location,
731 diag_weak_ptr_factory_order_);
733 const TemplateSpecializationType* template_spec_type =
734 iter->getType().getTypePtr()->getAs<TemplateSpecializationType>();
735 if (template_spec_type) {
736 const TemplateDecl* template_decl =
737 template_spec_type->getTemplateName().getAsTemplateDecl();
738 if (template_decl && template_spec_type->getNumArgs() >= 1) {
739 if (template_decl->getNameAsString().compare("WeakPtrFactory") == 0 &&
740 GetNamespace(template_decl) == "base") {
741 const TemplateArgument& arg = template_spec_type->getArg(0);
742 if (arg.getAsType().getTypePtr()->getAsCXXRecordDecl() ==
743 record->getTypeForDecl()->getAsCXXRecordDecl()) {
744 weak_ptr_factory_location = iter->getLocation();
752 } // namespace chrome_checker