Skip to content

[ClangImporter] Prefer available enum elements over unavailable ones. #6990

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 10 additions & 13 deletions lib/ClangImporter/ClangAdapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -671,15 +671,9 @@ bool importer::isUnavailableInSwift(
if (enableObjCInterop && isObjCId(decl))
return true;

// FIXME: Somewhat duplicated from importAttributes(), but this is a
// more direct path.
if (decl->getAvailability() == clang::AR_Unavailable)
if (decl->isUnavailable())
return true;

// Apply the deprecated-as-unavailable filter.
if (!platformAvailability.deprecatedAsUnavailableFilter)
return false;

for (auto *attr : decl->specific_attrs<clang::AvailabilityAttr>()) {
if (attr->getPlatform()->getName() == "swift")
return true;
Expand All @@ -689,12 +683,15 @@ bool importer::isUnavailableInSwift(
continue;
}

clang::VersionTuple version = attr->getDeprecated();
if (version.empty())
continue;
if (platformAvailability.deprecatedAsUnavailableFilter(version.getMajor(),
version.getMinor()))
return true;
if (platformAvailability.deprecatedAsUnavailableFilter) {
clang::VersionTuple version = attr->getDeprecated();
if (version.empty())
continue;
if (platformAvailability.deprecatedAsUnavailableFilter(
version.getMajor(), version.getMinor())) {
return true;
}
}
}

return false;
Expand Down
106 changes: 84 additions & 22 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1792,6 +1792,26 @@ applyPropertyOwnership(VarDecl *prop,
}

namespace {
/// Customized llvm::DenseMapInfo for storing borrowed APSInts.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very... clever...alright.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably not even necessary, but it's not worse than what was there before, and it's boxed up pretty neatly.

struct APSIntRefDenseMapInfo {
static inline const llvm::APSInt *getEmptyKey() {
return llvm::DenseMapInfo<const llvm::APSInt *>::getEmptyKey();
}
static inline const llvm::APSInt *getTombstoneKey() {
return llvm::DenseMapInfo<const llvm::APSInt *>::getTombstoneKey();
}
static unsigned getHashValue(const llvm::APSInt *ptrVal) {
assert(ptrVal != getEmptyKey() && ptrVal != getTombstoneKey());
return llvm::hash_value(*ptrVal);
}
static bool isEqual(const llvm::APSInt *lhs, const llvm::APSInt *rhs) {
if (lhs == rhs) return true;
if (lhs == getEmptyKey() || rhs == getEmptyKey()) return false;
if (lhs == getTombstoneKey() || rhs == getTombstoneKey()) return false;
return *lhs == *rhs;
}
};

/// \brief Convert Clang declarations into the corresponding Swift
/// declarations.
class SwiftDeclConverter
Expand Down Expand Up @@ -2473,36 +2493,87 @@ namespace {
addEnumeratorsAsMembers = true;
break;
}

for (auto ec = decl->enumerator_begin(), ecEnd = decl->enumerator_end();
ec != ecEnd; ++ec) {

llvm::SmallDenseMap<const llvm::APSInt *,
PointerUnion<const clang::EnumConstantDecl *,
EnumElementDecl *>, 8,
APSIntRefDenseMapInfo> canonicalEnumConstants;

if (enumKind == EnumKind::Enum) {
for (auto constant : decl->enumerators()) {
if (Impl.isUnavailableInSwift(constant))
continue;
canonicalEnumConstants.insert({&constant->getInitVal(), constant});
}
}

for (auto constant : decl->enumerators()) {
Decl *enumeratorDecl;
Decl *swift2EnumeratorDecl = nullptr;
switch (enumKind) {
case EnumKind::Constants:
case EnumKind::Unknown:
enumeratorDecl = Impl.importDecl(*ec, getActiveSwiftVersion());
enumeratorDecl = Impl.importDecl(constant, getActiveSwiftVersion());
swift2EnumeratorDecl =
Impl.importDecl(*ec, ImportNameVersion::Swift2);
Impl.importDecl(constant, ImportNameVersion::Swift2);
break;
case EnumKind::Options:
enumeratorDecl =
SwiftDeclConverter(Impl, getActiveSwiftVersion())
.importOptionConstant(*ec, decl, enumeratorContext);
.importOptionConstant(constant, decl, enumeratorContext);
swift2EnumeratorDecl =
SwiftDeclConverter(Impl, ImportNameVersion::Swift2)
.importOptionConstant(*ec, decl, enumeratorContext);
.importOptionConstant(constant, decl, enumeratorContext);
break;
case EnumKind::Enum:
enumeratorDecl =
SwiftDeclConverter(Impl, getActiveSwiftVersion())
.importEnumCase(*ec, decl, cast<EnumDecl>(enumeratorContext));
case EnumKind::Enum: {
auto canonicalCaseIter =
canonicalEnumConstants.find(&constant->getInitVal());

if (canonicalCaseIter == canonicalEnumConstants.end()) {
// Unavailable declarations get no special treatment.
enumeratorDecl =
SwiftDeclConverter(Impl, getActiveSwiftVersion())
.importEnumCase(constant, decl,
cast<EnumDecl>(enumeratorContext));
} else {
const clang::EnumConstantDecl *unimported =
canonicalCaseIter->
second.dyn_cast<const clang::EnumConstantDecl *>();

// Import the canonical enumerator for this case first.
if (unimported) {
enumeratorDecl = SwiftDeclConverter(Impl, getActiveSwiftVersion())
.importEnumCase(unimported, decl,
cast<EnumDecl>(enumeratorContext));
if (enumeratorDecl) {
canonicalCaseIter->getSecond() =
cast<EnumElementDecl>(enumeratorDecl);
}
} else {
enumeratorDecl =
canonicalCaseIter->second.get<EnumElementDecl *>();
}

if (unimported != constant && enumeratorDecl) {
ImportedName importedName =
Impl.importFullName(constant, getActiveSwiftVersion());
Identifier name = importedName.getDeclName().getBaseName();
if (!name.empty()) {
auto original = cast<ValueDecl>(enumeratorDecl);
enumeratorDecl = importEnumCaseAlias(name, constant, original,
decl, enumeratorContext);
}
}
}

swift2EnumeratorDecl =
SwiftDeclConverter(Impl, ImportNameVersion::Swift2)
.importEnumCase(*ec, decl, cast<EnumDecl>(enumeratorContext),
.importEnumCase(constant, decl,
cast<EnumDecl>(enumeratorContext),
enumeratorDecl);
break;
}
}
if (!enumeratorDecl)
continue;

Expand All @@ -2524,7 +2595,7 @@ namespace {
if (errorWrapper) {
auto enumeratorValue = cast<ValueDecl>(enumeratorDecl);
auto alias = importEnumCaseAlias(enumeratorValue->getName(),
*ec,
constant,
enumeratorValue,
decl,
enumeratorContext,
Expand Down Expand Up @@ -4743,14 +4814,6 @@ Decl *SwiftDeclConverter::importEnumCase(const clang::EnumConstantDecl *decl,
bool negative = false;
llvm::APSInt rawValue = decl->getInitVal();

// Did we already import an enum constant for this enum with the
// same value? If so, import it as a standalone constant.
auto insertResult =
Impl.EnumConstantValues.insert({{clangEnum, rawValue}, nullptr});
if (!insertResult.second)
return importEnumCaseAlias(name, decl, insertResult.first->second,
clangEnum, theEnum);

if (clangEnum->getIntegerType()->isSignedIntegerOrEnumerationType() &&
rawValue.slt(0)) {
rawValue = -rawValue;
Expand All @@ -4768,7 +4831,6 @@ Decl *SwiftDeclConverter::importEnumCase(const clang::EnumConstantDecl *decl,
auto element = Impl.createDeclWithClangNode<EnumElementDecl>(
decl, Accessibility::Public, SourceLoc(), name, TypeLoc(), SourceLoc(),
rawValueExpr, theEnum);
insertResult.first->second = element;

// Give the enum element the appropriate type.
element->computeType();
Expand Down
25 changes: 0 additions & 25 deletions lib/ClangImporter/ImporterImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -410,37 +410,12 @@ class LLVM_LIBRARY_VISIBILITY ClangImporter::Implementation
LookupTableMap &getLookupTables() { return LookupTables; }

private:
class EnumConstantDenseMapInfo {
public:
using PairTy = std::pair<const clang::EnumDecl *, llvm::APSInt>;
using PointerInfo = llvm::DenseMapInfo<const clang::EnumDecl *>;
static inline PairTy getEmptyKey() {
return {PointerInfo::getEmptyKey(), llvm::APSInt(/*bitwidth=*/1)};
}
static inline PairTy getTombstoneKey() {
return {PointerInfo::getTombstoneKey(), llvm::APSInt(/*bitwidth=*/1)};
}
static unsigned getHashValue(const PairTy &pair) {
return llvm::combineHashValue(PointerInfo::getHashValue(pair.first),
llvm::hash_value(pair.second));
}
static bool isEqual(const PairTy &lhs, const PairTy &rhs) {
return lhs == rhs;
}
};

/// A mapping from imported declarations to their "alternate" declarations,
/// for cases where a single Clang declaration is imported to two
/// different Swift declarations.
llvm::DenseMap<Decl *, TinyPtrVector<ValueDecl *>> AlternateDecls;

public:
/// \brief Keep track of enum constant values that have been imported.
llvm::DenseMap<std::pair<const clang::EnumDecl *, llvm::APSInt>,
EnumElementDecl *,
EnumConstantDenseMapInfo>
EnumConstantValues;

/// \brief Keep track of initializer declarations that correspond to
/// imported methods.
llvm::DenseMap<
Expand Down
11 changes: 6 additions & 5 deletions lib/Sema/TypeCheckAvailability.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1405,10 +1405,11 @@ const AvailableAttr *TypeChecker::getDeprecated(const Decl *D) {

/// Returns true if some declaration lexically enclosing the reference
/// matches the passed in predicate and false otherwise.
static bool someEnclosingDeclMatches(SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
TypeChecker &TC,
std::function<bool(const Decl *)> Pred) {
static bool
someEnclosingDeclMatches(SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
TypeChecker &TC,
llvm::function_ref<bool(const Decl *)> Pred) {
ASTContext &Ctx = TC.Context;

// Climb the DeclContext hierarchy to see if any of the containing
Expand Down Expand Up @@ -1500,7 +1501,7 @@ bool TypeChecker::isInsideUnavailableDeclaration(

bool TypeChecker::isInsideDeprecatedDeclaration(SourceRange ReferenceRange,
const DeclContext *ReferenceDC){
std::function<bool(const Decl *)> IsDeprecated = [](const Decl *D) {
auto IsDeprecated = [](const Decl *D) {
return D->getAttrs().getDeprecated(D->getASTContext());
};

Expand Down
14 changes: 14 additions & 0 deletions test/ClangImporter/enum.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil %s -verify
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck %s 2>&1 | %FileCheck %s
// -- Check that we can successfully round-trip.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -D IRGEN -emit-ir %s >/dev/null

// REQUIRES: objc_interop

// At one point we diagnosed enum case aliases that referred to unavailable
// cases in their (synthesized) implementation.
// CHECK-NOT: unknown

import Foundation
import user_objc

Expand Down Expand Up @@ -106,6 +111,15 @@ extension NSAliasesEnum {
}
}

#if !IRGEN
_ = NSUnavailableAliasesEnum.originalAU
_ = NSUnavailableAliasesEnum.aliasAU // expected-error {{'aliasAU' is unavailable}}
_ = NSUnavailableAliasesEnum.originalUA // expected-error {{'originalUA' is unavailable}}
_ = NSUnavailableAliasesEnum.aliasUA
_ = NSUnavailableAliasesEnum.originalUU // expected-error {{'originalUU' is unavailable}}
_ = NSUnavailableAliasesEnum.aliasUU // expected-error {{'aliasUU' is unavailable}}
#endif

// Test NS_SWIFT_NAME:
_ = XMLNode.Kind.DTDKind == .invalid

Expand Down
9 changes: 9 additions & 0 deletions test/Inputs/clang-importer-sdk/usr/include/Foundation.h
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,15 @@ typedef NS_ENUM(unsigned char, NSAliasesEnum) {
NSAliasesDifferentValue = 2
};

typedef NS_ENUM(unsigned char, NSUnavailableAliasesEnum) {
NSUnavailableAliasesOriginalAU = 0,
NSUnavailableAliasesAliasAU __attribute__((unavailable)) = 0,
NSUnavailableAliasesOriginalUA __attribute__((unavailable)) = 1,
NSUnavailableAliasesAliasUA = 1,
NSUnavailableAliasesOriginalUU __attribute__((unavailable)) = 2,
NSUnavailableAliasesAliasUU __attribute__((unavailable)) = 2,
};

NS_ENUM(NSInteger, NSMalformedEnumMissingTypedef) {
NSMalformedEnumMissingTypedefValue
};
Expand Down