Skip to content

[Import as member] Core Graphics #2071

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 6 commits into from
Apr 6, 2016
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
6 changes: 5 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,11 @@ endif()
#
# Set up global CMake variables for API notes.
#

# API notes version 1.0.0
#
# Change the above comment to 'touch' this file and keep incremental builds
# working when adding a new apinotes file.
#
set(SWIFT_API_NOTES_PATH "${SWIFT_SOURCE_DIR}/apinotes")
if(NOT EXISTS "${SWIFT_API_NOTES_PATH}/Foundation.apinotes")
message(FATAL_ERROR "API notes are not available in ${SWIFT_API_NOTES_PATH}")
Expand Down
65 changes: 65 additions & 0 deletions apinotes/CoreGraphics.apinotes
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
Name: CoreGraphics
SwiftInferImportAsMember: true
# The below are inline functions that are irrelevant due to memberwise inits
Functions:
- Name: CGPointMake
Availability: nonswift
- Name: CGSizeMake
Availability: nonswift
- Name: CGVectorMake
Availability: nonswift
- Name: CGRectMake
Availability: nonswift
- Name: CGAffineTransformMake
Availability: nonswift
# The below are fixups that inference didn't quite do what we wanted, and are
# pulled over from what used to be in the overlays
- Name: CGRectIsNull
SwiftName: "getter:CGRect.isNull(self:)"
- Name: CGRectIsEmpty
SwiftName: "getter:CGRect.isEmpty(self:)"
- Name: CGRectIsInfinite
SwiftName: "getter:CGRect.isInfinite(self:)"
- Name: CGRectStandardize
SwiftName: "getter:CGRect.standardized(self:)"
- Name: CGRectIntegral
SwiftName: "getter:CGRect.integral(self:)"
- Name: CGRectInset
SwiftName: "CGRect.insetBy(self:dx:dy:)"
- Name: CGRectOffset
SwiftName: "CGRect.offsetBy(self:dx:dy:)"
- Name: CGRectUnion
SwiftName: "CGRect.union(self:_:)"
- Name: CGRectIntersection
SwiftName: "CGRect.intersect(self:_:)"
- Name: CGRectContainsRect
SwiftName: "CGRect.contains(self:_:)"
- Name: CGRectContainsPoint
SwiftName: "CGRect.contains(self:_:)"
- Name: CGRectIntersectsRect
SwiftName: "CGRect.intersects(self:_:)"
# The below are left alone, due to an unknown bug
# FIXME: fix me
- Name: CGColorSpaceCreateDeviceRGB
SwiftName: "CGColorSpaceCreateDeviceRGB()"

# The below are globals that are defined as opaque C constants for no good
# reason.
Globals:
- Name: CGPointZero
Availability: nonswift
- Name: CGSizeZero
Availability: nonswift
- Name: CGVectorZero
Availability: nonswift
- Name: CGRectZero
Availability: nonswift
- Name: CGAffineTransformIdentity
Availability: nonswift
# The below are left alone, due to an unknown bug
# FIXME: fix me
- Name: kCGColorBlack
SwiftName: "kCGColorBlack"
- Name: kCGColorWhite
SwiftName: "kCGColorWhite"
33 changes: 32 additions & 1 deletion lib/ClangImporter/ClangImporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2004,6 +2004,36 @@ hasOrInheritsSwiftBridgeAttr(const clang::ObjCInterfaceDecl *objcClass) {
return false;
}

/// Whether the decl is from a module who requested import-as-member inference
static bool moduleIsInferImportAsMember(const clang::NamedDecl *decl,
clang::Sema &clangSema) {
clang::Module *submodule;
if (auto m = decl->getImportedOwningModule()) {
submodule = m;
} else if (auto m = decl->getLocalOwningModule()) {
submodule = m;
} else if (auto m = clangSema.getPreprocessor().getCurrentModule()) {
submodule = m;
} else if (auto m = clangSema.getPreprocessor().getCurrentSubmodule()) {
submodule = m;
} else {
return false;
}

while (submodule) {
if (submodule->IsSwiftInferImportAsMember) {
// HACK HACK HACK: This is a workaround for some module invalidation issue
// and inconsistency. This will go away soon.
if (submodule->Name != "CoreGraphics")
return false;
return true;
}
submodule = submodule->Parent;
}

return false;
}

auto ClangImporter::Implementation::importFullName(
const clang::NamedDecl *D,
ImportNameOptions options,
Expand Down Expand Up @@ -2186,7 +2216,8 @@ auto ClangImporter::Implementation::importFullName(

return result;
}
} else if (InferImportAsMember &&
} else if ((InferImportAsMember ||
moduleIsInferImportAsMember(D, clangSema)) &&
(isa<clang::VarDecl>(D) || isa<clang::FunctionDecl>(D)) &&
dc->isTranslationUnit()) {
auto inference = IAMResult::infer(SwiftContext, clangSema, D);
Expand Down
148 changes: 97 additions & 51 deletions lib/ClangImporter/IAMInference.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ STATISTIC(FailInferFunction, "# of functions unable to infer");
// Specifically skipped/avoided
STATISTIC(SkipLeadingUnderscore,
"# of globals skipped due to leading underscore");
STATISTIC(SkipCFMemoryManagement,
"# of CF memory management globals skipped");

// Success statistics
STATISTIC(SuccessImportAsTypeID, "# imported as 'typeID'");
Expand Down Expand Up @@ -176,6 +178,7 @@ class IAMInference {
}

IAMResult infer(const clang::NamedDecl *);
IAMResult inferVar(const clang::VarDecl *);

private:
// typeID
Expand Down Expand Up @@ -536,40 +539,42 @@ static bool roughlyEqual(clang::QualType left, clang::QualType right) {
right->getUnqualifiedDesugaredType();
}

bool IAMInference::validToImportAsProperty(
const clang::FunctionDecl *originalDecl, StringRef propSpec,
Optional<unsigned> selfIndex, const clang::FunctionDecl *&pairedAccessor) {
bool isGet = propSpec == "Get";
pairedAccessor = findPairedAccessor(originalDecl->getName(), propSpec);
if (!pairedAccessor)
return isGet;
static bool
isValidAsStaticProperty(const clang::FunctionDecl *getterDecl,
const clang::FunctionDecl *setterDecl = nullptr) {
// Getter has none, setter has one arg
if (getterDecl->getNumParams() != 0 ||
(setterDecl && setterDecl->getNumParams() != 1)) {
++InvalidPropertyStaticNumParams;
return false;
}

auto getterDecl = isGet ? originalDecl : pairedAccessor;
auto setterDecl = isGet ? pairedAccessor : originalDecl;
// Setter's arg type should be same as getter's return type
auto getterTy = getterDecl->getReturnType();

// See if this is a static property
if (!selfIndex) {
// Getter has none, setter has one arg
if (getterDecl->getNumParams() != 0 || setterDecl->getNumParams() != 1) {
++InvalidPropertyStaticNumParams;
return false;
}

// Setter's arg type should be same as getter's return type
if (!roughlyEqual(getterTy, setterDecl->getParamDecl(0)->getType())) {
++InvalidPropertyStaticGetterSetterType;
return false;
}

return true;
if (setterDecl &&
!roughlyEqual(getterTy, setterDecl->getParamDecl(0)->getType())) {
++InvalidPropertyStaticGetterSetterType;
return false;
}

return true;
}

static bool
isValidAsInstanceProperty(const clang::FunctionDecl *getterDecl,
const clang::FunctionDecl *setterDecl = nullptr) {
// Instance property, look beyond self
if (getterDecl->getNumParams() != 1 || setterDecl->getNumParams() != 2) {
if (getterDecl->getNumParams() != 1 ||
(setterDecl && setterDecl->getNumParams() != 2)) {
++InvalidPropertyInstanceNumParams;
return false;
}

if (!setterDecl)
return true;

// Make sure they pair up
auto getterTy = getterDecl->getReturnType();
auto selfTy = getterDecl->getParamDecl(0)->getType();

clang::QualType setterTy = {};
Expand All @@ -593,39 +598,65 @@ bool IAMInference::validToImportAsProperty(
return true;
}

IAMResult IAMInference::infer(const clang::NamedDecl *clangDecl) {
if (clangDecl->getName().startswith("_")) {
++SkipLeadingUnderscore;
return {};
bool IAMInference::validToImportAsProperty(
const clang::FunctionDecl *originalDecl, StringRef propSpec,
Optional<unsigned> selfIndex, const clang::FunctionDecl *&pairedAccessor) {
bool isGet = propSpec == "Get";
pairedAccessor = findPairedAccessor(originalDecl->getName(), propSpec);
if (!pairedAccessor) {
if (!isGet)
return false;
if (!selfIndex)
return isValidAsStaticProperty(originalDecl);
return isValidAsInstanceProperty(originalDecl);
}

if (auto varDecl = dyn_cast<clang::VarDecl>(clangDecl)) {
auto fail = [varDecl]() -> IAMResult {
DEBUG(llvm::dbgs() << "failed to infer variable: ");
DEBUG(varDecl->print(llvm::dbgs()));
DEBUG(llvm::dbgs() << "\n");
++FailInferVar;
return {};
};

// Try to find a type to add this as a static property to
StringRef workingName = varDecl->getName();
if (workingName.empty())
return fail();
auto getterDecl = isGet ? originalDecl : pairedAccessor;
auto setterDecl = isGet ? pairedAccessor : originalDecl;

// Special pattern: constants of the form "kFooBarBaz", extend "FooBar" with
// property "Baz"
if (*camel_case::getWords(workingName).begin() == "k")
workingName = workingName.drop_front(1);
if (!selfIndex)
return isValidAsStaticProperty(getterDecl, setterDecl);

NameBuffer remainingName;
if (auto effectiveDC = findTypeAndMatch(workingName, remainingName))
return isValidAsInstanceProperty(getterDecl, setterDecl);
}

return importAsStaticProperty(remainingName, effectiveDC);
IAMResult IAMInference::inferVar(const clang::VarDecl *varDecl) {
auto fail = [varDecl]() -> IAMResult {
DEBUG(llvm::dbgs() << "failed to infer variable: ");
DEBUG(varDecl->print(llvm::dbgs()));
DEBUG(llvm::dbgs() << "\n");
++FailInferVar;
return {};
};

// Try to find a type to add this as a static property to
StringRef workingName = varDecl->getName();
if (workingName.empty())
return fail();

// Special pattern: constants of the form "kFooBarBaz", extend "FooBar" with
// property "Baz"
if (*camel_case::getWords(workingName).begin() == "k")
workingName = workingName.drop_front(1);

NameBuffer remainingName;
if (auto effectiveDC = findTypeAndMatch(workingName, remainingName))

return importAsStaticProperty(remainingName, effectiveDC);

return fail();
}

IAMResult IAMInference::infer(const clang::NamedDecl *clangDecl) {
if (clangDecl->getName().startswith("_")) {
++SkipLeadingUnderscore;
return {};
}

// Try to infer a member variable
if (auto varDecl = dyn_cast<clang::VarDecl>(clangDecl))
return inferVar(varDecl);

// Try to infer a member function
auto funcDecl = dyn_cast<clang::FunctionDecl>(clangDecl);
if (!funcDecl) {
Expand All @@ -651,9 +682,11 @@ IAMResult IAMInference::infer(const clang::NamedDecl *clangDecl) {
auto retTy = funcDecl->getReturnType();
unsigned numParams = funcDecl->getNumParams();

// 0) Special cases are specially handled: *GetTypeID()
// 0) Special cases are specially handled
//
StringRef getTypeID = "GetTypeID";
StringRef cfSpecials[] = {"Release", "Retain", "Autorelease"};
// *GetTypeID
if (numParams == 0 && workingName.endswith(getTypeID)) {
NameBuffer remainingName;
if (auto effectiveDC = findTypeAndMatch(
Expand All @@ -664,6 +697,19 @@ IAMResult IAMInference::infer(const clang::NamedDecl *clangDecl) {
return importAsTypeID(retTy, effectiveDC);
}
}
// *Release/*Retain/*Autorelease
} else if (numParams == 1 &&
std::any_of(std::begin(cfSpecials), std::end(cfSpecials),
[workingName](StringRef suffix) {
return workingName.endswith(suffix);
})) {
if (auto type =
funcDecl->getParamDecl(0)->getType()->getAs<clang::TypedefType>()) {
if (CFPointeeInfo::classifyTypedef(type->getDecl())) {
++SkipCFMemoryManagement;
return {};
}
}
}

// 1) If we find an init specifier and our name matches the return type, we
Expand Down
2 changes: 1 addition & 1 deletion lib/ClangImporter/SwiftLookupTable.h
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ const uint16_t SWIFT_LOOKUP_TABLE_VERSION_MAJOR = 1;
/// Lookup table minor version number.
///
/// When the format changes IN ANY WAY, this number should be incremented.
const uint16_t SWIFT_LOOKUP_TABLE_VERSION_MINOR = 11; // globals-as-members
const uint16_t SWIFT_LOOKUP_TABLE_VERSION_MINOR = 12; // CG import-as-member

/// A lookup table that maps Swift names to the set of Clang
/// declarations with that particular name.
Expand Down
Loading