#include "FindBadConstructsConsumer.h"
#include "Util.h"
#include "clang/AST/Attr.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Lexer.h"
#include "clang/Sema/Sema.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace chrome_checker {
namespace {
const Type* UnwrapType(const Type* type) {
if (const ElaboratedType* elaborated = dyn_cast<ElaboratedType>(type))
return UnwrapType(elaborated->getNamedType().getTypePtr());
if (const TypedefType* typedefed = dyn_cast<TypedefType>(type))
return UnwrapType(typedefed->desugar().getTypePtr());
return type;
}
bool InTestingNamespace(const Decl* record) {
return GetNamespace(record).find("testing") != std::string::npos;
}
bool IsGtestTestFixture(const CXXRecordDecl* decl) {
return decl->getQualifiedNameAsString() == "testing::Test";
}
bool IsMethodInTestingNamespace(const CXXMethodDecl* method) {
for (auto* overridden : method->overridden_methods()) {
if (IsMethodInTestingNamespace(overridden) ||
(InTestingNamespace(overridden) &&
!IsGtestTestFixture(overridden->getParent()))) {
return true;
}
}
return false;
}
bool IsGmockObject(const CXXRecordDecl* decl) {
for (auto* field : decl->fields()) {
CXXRecordDecl* record_type = field->getTypeSourceInfo()
->getTypeLoc()
.getTypePtr()
->getAsCXXRecordDecl();
if (record_type) {
if (InTestingNamespace(record_type)) {
return true;
}
}
}
return false;
}
bool IsPodOrTemplateType(const CXXRecordDecl& record) {
return record.isPOD() ||
record.getDescribedClassTemplate() ||
record.getTemplateSpecializationKind() ||
record.isDependentType();
}
std::set<FunctionDecl*> GetLateParsedFunctionDecls(TranslationUnitDecl* decl) {
struct Visitor : public RecursiveASTVisitor<Visitor> {
bool VisitFunctionDecl(FunctionDecl* function_decl) {
if (function_decl->isLateTemplateParsed())
late_parsed_decls.insert(function_decl);
return true;
}
std::set<FunctionDecl*> late_parsed_decls;
} v;
v.TraverseDecl(decl);
return v.late_parsed_decls;
}
std::string GetAutoReplacementTypeAsString(QualType type,
StorageClass storage_class) {
QualType non_reference_type = type.getNonReferenceType();
if (!non_reference_type->isPointerType())
return storage_class == SC_Static ? "static auto" : "auto";
std::string result = GetAutoReplacementTypeAsString(
non_reference_type->getPointeeType(), storage_class);
result += "*";
if (non_reference_type.isConstQualified())
result += " const";
if (non_reference_type.isVolatileQualified())
result += " volatile";
if (type->isReferenceType() && !non_reference_type.isConstQualified()) {
if (type->isLValueReferenceType())
result += "&";
else if (type->isRValueReferenceType())
result += "&&";
}
return result;
}
}
FindBadConstructsConsumer::FindBadConstructsConsumer(CompilerInstance& instance,
const Options& options)
: ChromeClassTester(instance, options) {
if (options.check_ipc) {
ipc_visitor_.reset(new CheckIPCVisitor(instance));
}
diag_method_requires_override_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Overriding method must be marked with 'override' or "
"'final'.");
diag_redundant_virtual_specifier_ = diagnostic().getCustomDiagID(
getErrorLevel(), "[chromium-style] %0 is redundant; %1 implies %0.");
diag_will_be_redundant_virtual_specifier_ = diagnostic().getCustomDiagID(
getErrorLevel(), "[chromium-style] %0 will be redundant; %1 implies %0.");
diag_base_method_virtual_and_final_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] The virtual method does not override anything and is "
"final; consider making it non-virtual.");
diag_virtual_with_inline_body_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] virtual methods with non-empty bodies shouldn't be "
"declared inline.");
diag_no_explicit_ctor_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Complex class/struct needs an explicit out-of-line "
"constructor.");
diag_no_explicit_copy_ctor_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Complex class/struct needs an explicit out-of-line "
"copy constructor.");
diag_inline_complex_ctor_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Complex constructor has an inlined body.");
diag_no_explicit_dtor_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Complex class/struct needs an explicit out-of-line "
"destructor.");
diag_inline_complex_dtor_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Complex destructor has an inline body.");
diag_refcounted_needs_explicit_dtor_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Classes that are ref-counted should have explicit "
"destructors that are declared protected or private.");
diag_refcounted_with_public_dtor_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Classes that are ref-counted should have "
"destructors that are declared protected or private.");
diag_refcounted_with_protected_non_virtual_dtor_ =
diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] Classes that are ref-counted and have non-private "
"destructors should declare their destructor virtual.");
diag_weak_ptr_factory_order_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] WeakPtrFactory members which refer to their outer "
"class must be the last member in the outer class definition.");
diag_bad_enum_max_value_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] kMaxValue enumerator does not match max value %0 of "
"other enumerators");
diag_enum_max_value_unique_ = diagnostic().getCustomDiagID(
getErrorLevel(),
"[chromium-style] kMaxValue enumerator should not have a unique value: "
"it should share the value of the highest enumerator");
diag_auto_deduced_to_a_pointer_type_ =
diagnostic().getCustomDiagID(getErrorLevel(),
"[chromium-style] auto variable type "
"must not deduce to a raw pointer "
"type.");
diag_note_inheritance_ = diagnostic().getCustomDiagID(
DiagnosticsEngine::Note, "[chromium-style] %0 inherits from %1 here");
diag_note_implicit_dtor_ = diagnostic().getCustomDiagID(
DiagnosticsEngine::Note,
"[chromium-style] No explicit destructor for %0 defined");
diag_note_public_dtor_ = diagnostic().getCustomDiagID(
DiagnosticsEngine::Note,
"[chromium-style] Public destructor declared here");
diag_note_protected_non_virtual_dtor_ = diagnostic().getCustomDiagID(
DiagnosticsEngine::Note,
"[chromium-style] Protected non-virtual destructor declared here");
}
void FindBadConstructsConsumer::Traverse(ASTContext& context) {
if (ipc_visitor_) {
ipc_visitor_->set_context(&context);
ParseFunctionTemplates(context.getTranslationUnitDecl());
}
RecursiveASTVisitor::TraverseDecl(context.getTranslationUnitDecl());
if (ipc_visitor_) ipc_visitor_->set_context(nullptr);
}
bool FindBadConstructsConsumer::TraverseDecl(Decl* decl) {
if (ipc_visitor_) ipc_visitor_->BeginDecl(decl);
bool result = RecursiveASTVisitor::TraverseDecl(decl);
if (ipc_visitor_) ipc_visitor_->EndDecl();
return result;
}
bool FindBadConstructsConsumer::VisitEnumDecl(clang::EnumDecl* decl) {
CheckEnumMaxValue(decl);
return true;
}
bool FindBadConstructsConsumer::VisitTagDecl(clang::TagDecl* tag_decl) {
if (tag_decl->isCompleteDefinition())
CheckTag(tag_decl);
return true;
}
bool FindBadConstructsConsumer::VisitTemplateSpecializationType(
TemplateSpecializationType* spec) {
if (ipc_visitor_) ipc_visitor_->VisitTemplateSpecializationType(spec);
return true;
}
bool FindBadConstructsConsumer::VisitCallExpr(CallExpr* call_expr) {
if (ipc_visitor_) ipc_visitor_->VisitCallExpr(call_expr);
return true;
}
bool FindBadConstructsConsumer::VisitVarDecl(clang::VarDecl* var_decl) {
CheckVarDecl(var_decl);
return true;
}
void FindBadConstructsConsumer::CheckChromeClass(LocationType location_type,
SourceLocation record_location,
CXXRecordDecl* record) {
bool implementation_file = InImplementationFile(record_location);
if (!implementation_file) {
if (!IsPodOrTemplateType(*record))
CheckCtorDtorWeight(record_location, record);
}
bool warn_on_inline_bodies = !implementation_file;
if (!IsPodOrTemplateType(*record))
CheckVirtualMethods(record_location, record, warn_on_inline_bodies);
if (location_type != LocationType::kBlink)
CheckRefCountedDtors(record_location, record);
CheckWeakPtrFactoryMembers(record_location, record);
}
void FindBadConstructsConsumer::CheckEnumMaxValue(EnumDecl* decl) {
if (!decl->isScoped())
return;
clang::EnumConstantDecl* max_value = nullptr;
std::set<clang::EnumConstantDecl*> max_enumerators;
llvm::APSInt max_seen;
for (clang::EnumConstantDecl* enumerator : decl->enumerators()) {
if (enumerator->getName() == "kMaxValue")
max_value = enumerator;
llvm::APSInt current_value = enumerator->getInitVal();
if (max_enumerators.empty()) {
max_enumerators.emplace(enumerator);
max_seen = current_value;
continue;
}
assert(max_seen.isSigned() == current_value.isSigned());
if (current_value < max_seen)
continue;
if (current_value == max_seen) {
max_enumerators.emplace(enumerator);
continue;
}
assert(current_value > max_seen);
max_enumerators.clear();
max_enumerators.emplace(enumerator);
max_seen = current_value;
}
if (!max_value)
return;
if (max_enumerators.find(max_value) == max_enumerators.end()) {
ReportIfSpellingLocNotIgnored(max_value->getLocation(),
diag_bad_enum_max_value_)
<< max_seen.toString(10);
} else if (max_enumerators.size() < 2) {
ReportIfSpellingLocNotIgnored(decl->getLocation(),
diag_enum_max_value_unique_);
}
}
void FindBadConstructsConsumer::CheckCtorDtorWeight(
SourceLocation record_location,
CXXRecordDecl* record) {
if (record->getIdentifier() == NULL)
return;
if (record->isUnion())
return;
if (HasIgnoredBases(record))
return;
int templated_base_classes = 0;
for (CXXRecordDecl::base_class_const_iterator it = record->bases_begin();
it != record->bases_end();
++it) {
if (it->getTypeSourceInfo()->getTypeLoc().getTypeLocClass() ==
TypeLoc::TemplateSpecialization) {
++templated_base_classes;
}
}
int trivial_member = 0;
int non_trivial_member = 0;
int templated_non_trivial_member = 0;
for (RecordDecl::field_iterator it = record->field_begin();
it != record->field_end();
++it) {
CountType(it->getType().getTypePtr(),
&trivial_member,
&non_trivial_member,
&templated_non_trivial_member);
}
int dtor_score = 0;
dtor_score += templated_base_classes * 9;
dtor_score += templated_non_trivial_member * 10;
dtor_score += non_trivial_member * 3;
int ctor_score = dtor_score;
ctor_score += trivial_member;
if (ctor_score >= 10) {
if (!record->hasUserDeclaredConstructor()) {
ReportIfSpellingLocNotIgnored(record_location, diag_no_explicit_ctor_);
} else {
for (CXXRecordDecl::ctor_iterator it = record->ctor_begin();
it != record->ctor_end();
++it) {
if (it->hasInlineBody()) {
if (it->isCopyConstructor() &&
!record->hasUserDeclaredCopyConstructor()) {
if (!record->hasAttr<DLLExportAttr>())
ReportIfSpellingLocNotIgnored(record_location,
diag_no_explicit_copy_ctor_);
} else {
bool is_likely_compiler_generated_dllexport_move_ctor =
it->isMoveConstructor() &&
!record->hasUserDeclaredMoveConstructor() &&
record->hasAttr<DLLExportAttr>();
if (!is_likely_compiler_generated_dllexport_move_ctor)
ReportIfSpellingLocNotIgnored(it->getInnerLocStart(),
diag_inline_complex_ctor_);
}
} else if (it->isInlined() && !it->isInlineSpecified() &&
!it->isDeleted() && (!it->isCopyOrMoveConstructor() ||
it->isExplicitlyDefaulted())) {
ReportIfSpellingLocNotIgnored(it->getInnerLocStart(),
diag_inline_complex_ctor_);
}
}
}
}
if (dtor_score >= 10 && !record->hasTrivialDestructor()) {
if (!record->hasUserDeclaredDestructor()) {
ReportIfSpellingLocNotIgnored(record_location, diag_no_explicit_dtor_);
} else if (CXXDestructorDecl* dtor = record->getDestructor()) {
if (dtor->isInlined() && !dtor->isInlineSpecified() &&
!dtor->isDeleted()) {
ReportIfSpellingLocNotIgnored(dtor->getInnerLocStart(),
diag_inline_complex_dtor_);
}
}
}
}
SuppressibleDiagnosticBuilder
FindBadConstructsConsumer::ReportIfSpellingLocNotIgnored(
SourceLocation loc,
unsigned diagnostic_id) {
LocationType type =
ClassifyLocation(instance().getSourceManager().getSpellingLoc(loc));
bool ignored = type == LocationType::kThirdParty;
if (type == LocationType::kBlink) {
if (diagnostic_id == diag_no_explicit_ctor_ ||
diagnostic_id == diag_no_explicit_copy_ctor_ ||
diagnostic_id == diag_inline_complex_ctor_ ||
diagnostic_id == diag_no_explicit_dtor_ ||
diagnostic_id == diag_inline_complex_dtor_ ||
diagnostic_id == diag_refcounted_with_protected_non_virtual_dtor_ ||
diagnostic_id == diag_virtual_with_inline_body_) {
ignored = true;
}
}
return SuppressibleDiagnosticBuilder(&diagnostic(), loc, diagnostic_id,
ignored);
}
void FindBadConstructsConsumer::CheckVirtualMethods(
SourceLocation record_location,
CXXRecordDecl* record,
bool warn_on_inline_bodies) {
if (IsGmockObject(record)) {
if (!options_.check_gmock_objects)
return;
warn_on_inline_bodies = false;
}
for (CXXRecordDecl::method_iterator it = record->method_begin();
it != record->method_end();
++it) {
if (it->isCopyAssignmentOperator() || isa<CXXConstructorDecl>(*it)) {
} else if (isa<CXXDestructorDecl>(*it) &&
!record->hasUserDeclaredDestructor()) {
} else if (!it->isVirtual()) {
continue;
} else {
CheckVirtualSpecifiers(*it);
if (warn_on_inline_bodies)
CheckVirtualBodies(*it);
}
}
}
void FindBadConstructsConsumer::CheckVirtualSpecifiers(
const CXXMethodDecl* method) {
bool is_override = method->size_overridden_methods() > 0;
bool has_virtual = method->isVirtualAsWritten();
OverrideAttr* override_attr = method->getAttr<OverrideAttr>();
FinalAttr* final_attr = method->getAttr<FinalAttr>();
if (IsMethodInTestingNamespace(method))
return;
SourceManager& manager = instance().getSourceManager();
const LangOptions& lang_opts = instance().getLangOpts();
bool remove_virtual = false;
bool add_override = false;
if (has_virtual && (override_attr || final_attr))
remove_virtual = true;
if (is_override && !override_attr && !final_attr) {
add_override = true;
if (has_virtual)
remove_virtual = true;
}
if (final_attr && override_attr) {
ReportIfSpellingLocNotIgnored(override_attr->getLocation(),
diag_redundant_virtual_specifier_)
<< override_attr << final_attr
<< FixItHint::CreateRemoval(override_attr->getRange());
}
if (!remove_virtual && !add_override)
return;
SourceLocation virtual_loc;
SourceLocation override_insertion_loc;
std::pair<FileID, unsigned> decomposed_start =
manager.getDecomposedLoc(method->getBeginLoc());
bool invalid = false;
StringRef buffer = manager.getBufferData(decomposed_start.first, &invalid);
if (!invalid) {
int nested_parentheses = 0;
Lexer lexer(manager.getLocForStartOfFile(decomposed_start.first), lang_opts,
buffer.begin(), buffer.begin() + decomposed_start.second,
buffer.end());
Token token;
while (!lexer.LexFromRawLexer(token)) {
if ((token.is(tok::equal) || token.is(tok::semi) ||
token.is(tok::l_brace)) &&
nested_parentheses == 0) {
override_insertion_loc = token.getLocation();
break;
}
if (token.is(tok::l_paren)) {
++nested_parentheses;
} else if (token.is(tok::r_paren)) {
--nested_parentheses;
} else if (token.is(tok::raw_identifier)) {
if (token.getRawIdentifier() == "virtual")
virtual_loc = token.getLocation();
}
}
}
if (add_override && override_insertion_loc.isValid()) {
ReportIfSpellingLocNotIgnored(override_insertion_loc,
diag_method_requires_override_)
<< FixItHint::CreateInsertion(override_insertion_loc, " override");
}
if (remove_virtual && virtual_loc.isValid()) {
ReportIfSpellingLocNotIgnored(
virtual_loc, add_override ? diag_will_be_redundant_virtual_specifier_
: diag_redundant_virtual_specifier_)
<< "'virtual'"
<< (final_attr ? "'final'" : "'override'")
<< FixItHint::CreateRemoval(
CharSourceRange::getTokenRange(SourceRange(virtual_loc)));
}
}
void FindBadConstructsConsumer::CheckVirtualBodies(
const CXXMethodDecl* method) {
if (method->hasBody() && method->hasInlineBody()) {
if (CompoundStmt* cs = dyn_cast<CompoundStmt>(method->getBody())) {
if (cs->size()) {
SourceLocation loc = cs->getLBracLoc();
bool emit = true;
if (loc.isMacroID()) {
SourceManager& manager = instance().getSourceManager();
LocationType type = ClassifyLocation(manager.getSpellingLoc(loc));
if (type == LocationType::kThirdParty || type == LocationType::kBlink)
emit = false;
else {
StringRef name = Lexer::getImmediateMacroName(
loc, manager, instance().getLangOpts());
if (name == "CR_BEGIN_MSG_MAP_EX" ||
name == "BEGIN_SAFE_MSG_MAP_EX")
emit = false;
}
}
if (emit)
ReportIfSpellingLocNotIgnored(loc, diag_virtual_with_inline_body_);
}
}
}
}
void FindBadConstructsConsumer::CountType(const Type* type,
int* trivial_member,
int* non_trivial_member,
int* templated_non_trivial_member) {
switch (type->getTypeClass()) {
case Type::Record: {
auto* record_decl = type->getAsCXXRecordDecl();
if (!record_decl->hasDefinition() || record_decl->hasTrivialDestructor())
(*trivial_member)++;
else
(*non_trivial_member)++;
break;
}
case Type::TemplateSpecialization: {
TemplateName name =
dyn_cast<TemplateSpecializationType>(type)->getTemplateName();
bool whitelisted_template = false;
if (TemplateDecl* decl = name.getAsTemplateDecl()) {
std::string base_name = decl->getNameAsString();
if (base_name == "basic_string")
whitelisted_template = true;
}
if (whitelisted_template)
(*non_trivial_member)++;
else
(*templated_non_trivial_member)++;
break;
}
case Type::Elaborated: {
CountType(dyn_cast<ElaboratedType>(type)->getNamedType().getTypePtr(),
trivial_member,
non_trivial_member,
templated_non_trivial_member);
break;
}
case Type::Typedef: {
while (const TypedefType* TT = dyn_cast<TypedefType>(type)) {
if (auto* decl = TT->getDecl()) {
const std::string name = decl->getNameAsString();
auto* context = decl->getDeclContext();
if (name == "atomic_int" && context->isStdNamespace()) {
(*trivial_member)++;
return;
}
type = decl->getUnderlyingType().getTypePtr();
}
}
CountType(type,
trivial_member,
non_trivial_member,
templated_non_trivial_member);
break;
}
default: {
(*trivial_member)++;
break;
}
}
}
FindBadConstructsConsumer::RefcountIssue
FindBadConstructsConsumer::CheckRecordForRefcountIssue(
const CXXRecordDecl* record,
SourceLocation& loc) {
if (!record->hasUserDeclaredDestructor()) {
loc = record->getLocation();
return ImplicitDestructor;
}
if (CXXDestructorDecl* dtor = record->getDestructor()) {
if (dtor->getAccess() == AS_public) {
loc = dtor->getInnerLocStart();
return PublicDestructor;
}
}
return None;
}
bool FindBadConstructsConsumer::IsRefCounted(
const CXXBaseSpecifier* base,
CXXBasePath& path) {
const TemplateSpecializationType* base_type =
dyn_cast<TemplateSpecializationType>(
UnwrapType(base->getType().getTypePtr()));
if (!base_type) {
return false;
}
TemplateName name = base_type->getTemplateName();
if (TemplateDecl* decl = name.getAsTemplateDecl()) {
std::string base_name = decl->getNameAsString();
if (base_name.compare(0, 10, "RefCounted") == 0 &&
GetNamespace(decl) == "base") {
return true;
}
}
return false;
}
bool FindBadConstructsConsumer::HasPublicDtorCallback(
const CXXBaseSpecifier* base,
CXXBasePath& path,
void* user_data) {
if (path.Access != AS_public)
return false;
CXXRecordDecl* record =
dyn_cast<CXXRecordDecl>(base->getType()->getAs<RecordType>()->getDecl());
SourceLocation unused;
return None != CheckRecordForRefcountIssue(record, unused);
}
void FindBadConstructsConsumer::PrintInheritanceChain(const CXXBasePath& path) {
for (CXXBasePath::const_iterator it = path.begin(); it != path.end(); ++it) {
diagnostic().Report(it->Base->getBeginLoc(), diag_note_inheritance_)
<< it->Class << it->Base->getType();
}
}
unsigned FindBadConstructsConsumer::DiagnosticForIssue(RefcountIssue issue) {
switch (issue) {
case ImplicitDestructor:
return diag_refcounted_needs_explicit_dtor_;
case PublicDestructor:
return diag_refcounted_with_public_dtor_;
case None:
assert(false && "Do not call DiagnosticForIssue with issue None");
return 0;
}
assert(false);
return 0;
}
void FindBadConstructsConsumer::CheckRefCountedDtors(
SourceLocation record_location,
CXXRecordDecl* record) {
if (record->getIdentifier() == NULL)
return;
CXXBasePaths refcounted_path;
if (!record->lookupInBases(
[this](const CXXBaseSpecifier* base, CXXBasePath& path) {
return IsRefCounted(base, path);
},
refcounted_path)) {
return; }
SourceLocation loc;
RefcountIssue issue = CheckRecordForRefcountIssue(record, loc);
if (issue != None) {
diagnostic().Report(loc, DiagnosticForIssue(issue));
PrintInheritanceChain(refcounted_path.front());
return;
}
if (CXXDestructorDecl* dtor =
refcounted_path.begin()->back().Class->getDestructor()) {
if (dtor->getAccess() == AS_protected && !dtor->isVirtual()) {
loc = dtor->getInnerLocStart();
ReportIfSpellingLocNotIgnored(
loc, diag_refcounted_with_protected_non_virtual_dtor_);
return;
}
}
if (!options_.check_base_classes)
return;
CXXBasePaths dtor_paths;
if (!record->lookupInBases(
[](const CXXBaseSpecifier* base, CXXBasePath& path) {
return HasPublicDtorCallback(base, path, nullptr);
},
dtor_paths)) {
return;
}
for (CXXBasePaths::const_paths_iterator it = dtor_paths.begin();
it != dtor_paths.end();
++it) {
const CXXRecordDecl* problem_record = dyn_cast<CXXRecordDecl>(
it->back().Base->getType()->getAs<RecordType>()->getDecl());
issue = CheckRecordForRefcountIssue(problem_record, loc);
if (issue == ImplicitDestructor) {
diagnostic().Report(record_location,
diag_refcounted_needs_explicit_dtor_);
PrintInheritanceChain(refcounted_path.front());
diagnostic().Report(loc, diag_note_implicit_dtor_) << problem_record;
PrintInheritanceChain(*it);
} else if (issue == PublicDestructor) {
diagnostic().Report(record_location, diag_refcounted_with_public_dtor_);
PrintInheritanceChain(refcounted_path.front());
diagnostic().Report(loc, diag_note_public_dtor_);
PrintInheritanceChain(*it);
}
}
}
void FindBadConstructsConsumer::CheckWeakPtrFactoryMembers(
SourceLocation record_location,
CXXRecordDecl* record) {
if (record->getIdentifier() == NULL)
return;
RecordDecl::field_iterator iter(record->field_begin()),
the_end(record->field_end());
SourceLocation weak_ptr_factory_location; for (; iter != the_end; ++iter) {
const TemplateSpecializationType* template_spec_type =
iter->getType().getTypePtr()->getAs<TemplateSpecializationType>();
bool param_is_weak_ptr_factory_to_self = false;
if (template_spec_type) {
const TemplateDecl* template_decl =
template_spec_type->getTemplateName().getAsTemplateDecl();
if (template_decl && template_spec_type->getNumArgs() == 1) {
if (template_decl->getNameAsString().compare("WeakPtrFactory") == 0 &&
GetNamespace(template_decl) == "base") {
const TemplateArgument& arg = template_spec_type->getArg(0);
if (arg.getAsType().getTypePtr()->getAsCXXRecordDecl() ==
record->getTypeForDecl()->getAsCXXRecordDecl()) {
if (!weak_ptr_factory_location.isValid()) {
weak_ptr_factory_location = iter->getLocation();
}
param_is_weak_ptr_factory_to_self = true;
}
}
}
}
if (weak_ptr_factory_location.isValid() &&
!param_is_weak_ptr_factory_to_self) {
ReportIfSpellingLocNotIgnored(weak_ptr_factory_location,
diag_weak_ptr_factory_order_);
}
}
}
void FindBadConstructsConsumer::ParseFunctionTemplates(
TranslationUnitDecl* decl) {
if (!instance().getLangOpts().DelayedTemplateParsing)
return;
std::set<FunctionDecl*> late_parsed_decls = GetLateParsedFunctionDecls(decl);
clang::Sema& sema = instance().getSema();
for (const FunctionDecl* fd : late_parsed_decls) {
assert(fd->isLateTemplateParsed());
if (instance().getSourceManager().isInSystemHeader(
instance().getSourceManager().getSpellingLoc(fd->getLocation())))
continue;
clang::LateParsedTemplate* lpt = sema.LateParsedTemplateMap[fd].get();
sema.LateTemplateParser(sema.OpaqueParser, *lpt);
}
}
void FindBadConstructsConsumer::CheckVarDecl(clang::VarDecl* var_decl) {
if (var_decl->isInitCapture())
return;
QualType non_reference_type = var_decl->getType().getNonReferenceType();
for (;;) {
const clang::AutoType* auto_type =
non_reference_type->getAs<clang::AutoType>();
if (auto_type) {
if (auto_type->isDeduced()) {
QualType deduced_type = auto_type->getDeducedType();
if (!deduced_type.isNull() && deduced_type->isPointerType() &&
!deduced_type->isFunctionPointerType()) {
LocationType location_type =
ClassifyLocation(var_decl->getBeginLoc());
if (location_type != LocationType::kThirdParty) {
clang::SourceRange range(
var_decl->getBeginLoc(),
var_decl->getTypeSourceInfo()->getTypeLoc().getEndLoc());
ReportIfSpellingLocNotIgnored(range.getBegin(),
diag_auto_deduced_to_a_pointer_type_)
<< FixItHint::CreateReplacement(
range,
GetAutoReplacementTypeAsString(
var_decl->getType(), var_decl->getStorageClass()));
}
}
}
} else if (non_reference_type->isPointerType()) {
non_reference_type = non_reference_type->getPointeeType();
continue;
}
break;
}
}
}