mirror of
https://github.com/apple/swift.git
synced 2025-12-14 20:36:38 +01:00
Update master to build with Xcode 9 beta 1, OS X 10.13, iOS 11, tvOS 11, and watchOS 4 SDKs.
This commit is contained in:
61
apinotes/Accelerate.apinotes
Normal file
61
apinotes/Accelerate.apinotes
Normal file
@@ -0,0 +1,61 @@
|
||||
Name: Accelerate
|
||||
Enumerators:
|
||||
- Name: BNNSDataTypeFloatBit
|
||||
Availability: nonswift
|
||||
- Name: BNNSDataTypeIntBit
|
||||
Availability: nonswift
|
||||
- Name: BNNSDataTypeUIntBit
|
||||
Availability: nonswift
|
||||
- Name: BNNSDataTypeIndexedBit
|
||||
Availability: nonswift
|
||||
- Name: BNNSDataTypeFloat16
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSDataTypeFloat32
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSDataTypeInt8
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSDataTypeInt16
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSDataTypeInt32
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSDataTypeUInt8
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSDataTypeUInt16
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSDataTypeUInt32
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSDataTypeIndexed8
|
||||
SwiftPrivate: true
|
||||
|
||||
- Name: BNNSPoolingFunctionMax
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSPoolingFunctionAverage
|
||||
SwiftPrivate: true
|
||||
|
||||
- Name: BNNSActivationFunctionIdentity
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionRectifiedLinear
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionLeakyRectifiedLinear
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionSigmoid
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionTanh
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionScaledTanh
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionAbs
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionLinear
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionClamp
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionIntegerLinearSaturate
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionIntegerLinearSaturatePerChannel
|
||||
SwiftPrivate: true
|
||||
- Name: BNNSActivationFunctionSoftmax
|
||||
SwiftPrivate: true
|
||||
|
||||
- Name: BNNSFlagsUseClientPtr
|
||||
SwiftPrivate: true
|
||||
@@ -1,4 +1,5 @@
|
||||
set(SWIFT_API_NOTES_INPUTS
|
||||
Accelerate
|
||||
AVFoundation
|
||||
AVKit
|
||||
AppKit
|
||||
|
||||
@@ -91,6 +91,8 @@ Protocols:
|
||||
SwiftName: DispatchSourceUserDataOr
|
||||
- Name: OS_dispatch_source_data_add
|
||||
SwiftName: DispatchSourceUserDataAdd
|
||||
- Name: OS_dispatch_source_data_replace
|
||||
SwiftName: DispatchSourceUserDataReplace
|
||||
- Name: OS_dispatch_source_vnode
|
||||
SwiftName: DispatchSourceFileSystemObject
|
||||
- Name: OS_dispatch_source_write
|
||||
|
||||
@@ -25,7 +25,7 @@ is_sdk_requested(IOS_SIMULATOR swift_build_ios_simulator)
|
||||
if(swift_build_ios_simulator)
|
||||
configure_sdk_darwin(
|
||||
IOS_SIMULATOR "iOS Simulator" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
iphonesimulator ios-simulator ios "i386;x86_64")
|
||||
iphonesimulator ios-simulator ios "x86_64")
|
||||
configure_target_variant(
|
||||
IOS_SIMULATOR-DA "iOS Debug+Asserts" IOS_SIMULATOR DA "Debug+Asserts")
|
||||
configure_target_variant(
|
||||
|
||||
@@ -101,6 +101,8 @@ ERROR(error_os_minimum_deployment,none,
|
||||
"Swift requires a minimum deployment target of %0", (StringRef))
|
||||
ERROR(error_sdk_too_old,none,
|
||||
"Swift does not support the SDK '%0'", (StringRef))
|
||||
ERROR(error_ios_maximum_deployment_32,none,
|
||||
"iOS %0 does not support 32-bit programs", (unsigned))
|
||||
|
||||
ERROR(error_two_files_same_name,none,
|
||||
"filename \"%0\" used twice: '%1' and '%2'",
|
||||
|
||||
@@ -142,6 +142,10 @@ static void validateArgs(DiagnosticEngine &diags, const ArgList &Args) {
|
||||
if (triple.isOSVersionLT(7))
|
||||
diags.diagnose(SourceLoc(), diag::error_os_minimum_deployment,
|
||||
"iOS 7");
|
||||
if (triple.isArch32Bit() && !triple.isOSVersionLT(11)) {
|
||||
diags.diagnose(SourceLoc(), diag::error_ios_maximum_deployment_32,
|
||||
triple.getOSMajorVersion());
|
||||
}
|
||||
} else if (triple.isWatchOS()) {
|
||||
if (triple.isOSVersionLT(2, 0)) {
|
||||
diags.diagnose(SourceLoc(), diag::error_os_minimum_deployment,
|
||||
@@ -1034,14 +1038,14 @@ static bool isSDKTooOld(StringRef sdkPath, clang::VersionTuple minVersion,
|
||||
/// the given target.
|
||||
static bool isSDKTooOld(StringRef sdkPath, const llvm::Triple &target) {
|
||||
if (target.isMacOSX()) {
|
||||
return isSDKTooOld(sdkPath, clang::VersionTuple(10, 12), "OSX");
|
||||
return isSDKTooOld(sdkPath, clang::VersionTuple(10, 13), "OSX");
|
||||
|
||||
} else if (target.isiOS()) {
|
||||
// Includes both iOS and TVOS.
|
||||
return isSDKTooOld(sdkPath, clang::VersionTuple(10, 0), "Simulator", "OS");
|
||||
return isSDKTooOld(sdkPath, clang::VersionTuple(11, 0), "Simulator", "OS");
|
||||
|
||||
} else if (target.isWatchOS()) {
|
||||
return isSDKTooOld(sdkPath, clang::VersionTuple(3, 0), "Simulator", "OS");
|
||||
return isSDKTooOld(sdkPath, clang::VersionTuple(4, 0), "Simulator", "OS");
|
||||
|
||||
} else {
|
||||
return false;
|
||||
|
||||
57
stdlib/public/SDK/ARKit/ARKit.swift
Normal file
57
stdlib/public/SDK/ARKit/ARKit.swift
Normal file
@@ -0,0 +1,57 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_exported import ARKit
|
||||
|
||||
@available(iOS, introduced: 11.0)
|
||||
extension ARCamera {
|
||||
/**
|
||||
A value describing the camera's tracking state.
|
||||
*/
|
||||
public enum TrackingState {
|
||||
public enum Reason {
|
||||
/** Tracking is limited due to a excessive motion of the camera. */
|
||||
case excessiveMotion
|
||||
|
||||
/** Tracking is limited due to a lack of features visible to the camera. */
|
||||
case insufficientFeatures
|
||||
}
|
||||
|
||||
/** Tracking is not available. */
|
||||
case notAvailable
|
||||
|
||||
/** Tracking is limited. See tracking reason for details. */
|
||||
case limited(Reason)
|
||||
|
||||
/** Tracking is normal. */
|
||||
case normal
|
||||
}
|
||||
|
||||
/**
|
||||
The tracking state of the camera.
|
||||
*/
|
||||
public var trackingState: TrackingState {
|
||||
switch __trackingState {
|
||||
case .notAvailable: return .notAvailable
|
||||
case .normal: return .normal
|
||||
case .limited:
|
||||
let reason: TrackingState.Reason
|
||||
|
||||
switch __trackingStateReason {
|
||||
case .excessiveMotion: reason = .excessiveMotion
|
||||
default: reason = .insufficientFeatures
|
||||
}
|
||||
|
||||
return .limited(reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
14
stdlib/public/SDK/ARKit/CMakeLists.txt
Normal file
14
stdlib/public/SDK/ARKit/CMakeLists.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 3.4.3)
|
||||
include("../../../../cmake/modules/StandaloneOverlay.cmake")
|
||||
|
||||
add_swift_library(swiftARKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY
|
||||
ARKit.swift
|
||||
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS IOS IOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin AVFoundation CoreAudio CoreFoundation CoreGraphics CoreImage CoreMedia Dispatch Foundation GLKit ObjectiveC QuartzCore SceneKit simd SpriteKit UIKit # auto-updated
|
||||
FRAMEWORK_DEPENDS_WEAK ARKit
|
||||
|
||||
DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_ARKIT_IOS}
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_exported import AVFoundation // Clang module
|
||||
import Foundation
|
||||
|
||||
|
||||
#if os(iOS)
|
||||
@available(iOS, introduced: 11.0)
|
||||
extension AVCaptureSynchronizedDataCollection : Sequence {
|
||||
public func makeIterator() -> Iterator {
|
||||
return Iterator(self)
|
||||
}
|
||||
|
||||
public struct Iterator : IteratorProtocol {
|
||||
internal var fastIterator: NSFastEnumerationIterator
|
||||
|
||||
internal init(_ collection: AVCaptureSynchronizedDataCollection) {
|
||||
self.fastIterator = NSFastEnumerationIterator(collection)
|
||||
}
|
||||
|
||||
public mutating func next() -> AVCaptureSynchronizedData? {
|
||||
guard let nextAny = fastIterator.next() else { return nil }
|
||||
return nextAny as! AVCaptureSynchronizedData
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.4.3)
|
||||
include("../../../../cmake/modules/StandaloneOverlay.cmake")
|
||||
|
||||
add_swift_library(swiftAVFoundation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY
|
||||
AVCaptureSynchronizedDataCollection.swift
|
||||
AVError.swift
|
||||
NSValue.swift.gyb
|
||||
|
||||
|
||||
291
stdlib/public/SDK/Accelerate/BNNS.swift.gyb
Normal file
291
stdlib/public/SDK/Accelerate/BNNS.swift.gyb
Normal file
@@ -0,0 +1,291 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Swift
|
||||
@_exported import Accelerate
|
||||
@_exported import Accelerate.vecLib.BNNS
|
||||
|
||||
%{
|
||||
bnns2016 = [
|
||||
('OSX','10.12'), ('iOS','10.0'), ('tvOS','10.0'), ('watchOS','3.0')
|
||||
]
|
||||
|
||||
bnns2017 = [
|
||||
('OSX','10.13'), ('iOS','11.0'), ('tvOS','11.0'), ('watchOS','4.0')
|
||||
]
|
||||
|
||||
def available(releases):
|
||||
return '@available(' + ', '.join([
|
||||
r[0] + ' ' + r[1] for r in releases
|
||||
]) + ', *)'
|
||||
|
||||
def renamed(name):
|
||||
return '\n'.join([
|
||||
'@available(*, deprecated, renamed: "' + name + '")'
|
||||
])
|
||||
|
||||
def newEnumValue(base, new, old, rel):
|
||||
decl = ' public static var ' + new + ': ' + base + ' {\n'
|
||||
impl = ' return __' + base + old + '\n }'
|
||||
return ' ' + available(rel) + '\n' + decl + impl
|
||||
|
||||
def oldEnumValue(base, new, old):
|
||||
return renamed(base + '.' + new) + '\n' + \
|
||||
'public var ' + base + old + ' = __' + base + old
|
||||
|
||||
def renameEnumMembers(base, names):
|
||||
return 'extension ' + base + ' {\n' + \
|
||||
'\n'.join([newEnumValue(base, new, old, rel) for new, old, rel in names]) + '\n}\n' + \
|
||||
'\n'.join([oldEnumValue(base, new, old) for new, old, rel in names if rel != bnns2017])
|
||||
}%
|
||||
|
||||
${renameEnumMembers('BNNSDataType', [
|
||||
('float16', 'Float16', bnns2016),
|
||||
('float', 'Float32', bnns2016),
|
||||
('int8', 'Int8', bnns2016),
|
||||
('int16', 'Int16', bnns2016),
|
||||
('int32', 'Int32', bnns2016),
|
||||
('uint8', 'UInt8', bnns2017),
|
||||
('uint16', 'UInt16', bnns2017),
|
||||
('uint32', 'UInt32', bnns2017),
|
||||
('indexed8','Indexed8',bnns2016),
|
||||
])}
|
||||
|
||||
${renameEnumMembers('BNNSPoolingFunction', [
|
||||
('max', 'Max', bnns2016),
|
||||
('average', 'Average', bnns2016),
|
||||
])}
|
||||
|
||||
${renameEnumMembers('BNNSActivationFunction', [
|
||||
('identity', 'Identity', bnns2016),
|
||||
('rectifiedLinear', 'RectifiedLinear', bnns2016),
|
||||
('leakyRectifiedLinear', 'LeakyRectifiedLinear', bnns2016),
|
||||
('sigmoid', 'Sigmoid', bnns2016),
|
||||
('tanh', 'Tanh', bnns2016),
|
||||
('scaledTanh', 'ScaledTanh', bnns2016),
|
||||
('abs', 'Abs', bnns2016),
|
||||
('linear', 'Linear', bnns2017),
|
||||
('clamp', 'Clamp', bnns2017),
|
||||
('integerLinearSaturate', 'IntegerLinearSaturate', bnns2017),
|
||||
('integerLinearSaturatePerChannel', 'IntegerLinearSaturatePerChannel', bnns2017),
|
||||
('softmax', 'Softmax', bnns2017),
|
||||
])}
|
||||
|
||||
${renameEnumMembers('BNNSFlags', [('useClientPointer', 'UseClientPtr', bnns2016)])}
|
||||
|
||||
extension BNNSImageStackDescriptor {
|
||||
${available(bnns2016)}
|
||||
public init(width: Int,
|
||||
height: Int,
|
||||
channels: Int,
|
||||
row_stride: Int,
|
||||
image_stride: Int,
|
||||
data_type: BNNSDataType,
|
||||
data_scale: Float = 1,
|
||||
data_bias: Float = 0) {
|
||||
|
||||
_precondition(data_type != .indexed8,
|
||||
"Image stacks cannot use the indexed8 data type.")
|
||||
|
||||
self.width = width
|
||||
self.height = height
|
||||
self.channels = channels
|
||||
self.row_stride = row_stride
|
||||
self.image_stride = image_stride
|
||||
self.data_type = data_type
|
||||
self.data_scale = data_scale
|
||||
self.data_bias = data_bias
|
||||
}
|
||||
}
|
||||
|
||||
extension BNNSVectorDescriptor {
|
||||
${available(bnns2016)}
|
||||
public init(size: Int,
|
||||
data_type: BNNSDataType,
|
||||
data_scale: Float = 1,
|
||||
data_bias: Float = 0) {
|
||||
|
||||
_precondition(data_type != .indexed8,
|
||||
"Vectors cannot use the indexed8 data type.")
|
||||
|
||||
self.size = size
|
||||
self.data_type = data_type
|
||||
self.data_scale = data_scale
|
||||
self.data_bias = data_bias
|
||||
}
|
||||
}
|
||||
|
||||
extension BNNSLayerData {
|
||||
${available(bnns2016)}
|
||||
public init(data: UnsafeRawPointer?,
|
||||
data_type: BNNSDataType,
|
||||
data_scale: Float = 1,
|
||||
data_bias: Float = 0,
|
||||
data_table: UnsafePointer<Float>? = nil) {
|
||||
|
||||
if data_type == .indexed8 {
|
||||
_precondition(data_table != nil,
|
||||
"data_table cannot be nil if data_type is .indexed8.")
|
||||
}
|
||||
|
||||
self.data = data
|
||||
self.data_type = data_type
|
||||
self.data_scale = data_scale
|
||||
self.data_bias = data_bias
|
||||
self.data_table = data_table
|
||||
}
|
||||
|
||||
${available(bnns2016)}
|
||||
public static var zero: BNNSLayerData {
|
||||
return BNNSLayerData()
|
||||
}
|
||||
}
|
||||
|
||||
extension BNNSActivation {
|
||||
|
||||
${available(bnns2016)}
|
||||
public init(function: BNNSActivationFunction,
|
||||
alpha: Float = .nan,
|
||||
beta: Float = .nan) {
|
||||
if #available(OSX 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) {
|
||||
_precondition(function != .integerLinearSaturate,
|
||||
"This initializer cannot be used with the integerLinearSaturate activation function; use BNNSActivation.integerLinearSaturate(scale:Int32, offset:Int32, shift:Int32) instead.")
|
||||
_precondition(function != .integerLinearSaturatePerChannel,
|
||||
"This initializer cannot be used with the integerLinearSaturatePerChannel activation function; use BNNSActivation.integerLinearSaturatePerChannel(scale:UnsafePointer<Int32>, offset:UnsafePointer<Int32>, shift:UnsafePointer<Int32>) instead.")
|
||||
}
|
||||
self.function = function
|
||||
self.alpha = alpha
|
||||
self.beta = beta
|
||||
iscale = 1 // unused
|
||||
ioffset = 0 // unused
|
||||
ishift = 0 // unused
|
||||
iscale_per_channel = nil // unused
|
||||
ioffset_per_channel = nil // unused
|
||||
ishift_per_channel = nil // unused
|
||||
}
|
||||
|
||||
/// A BNNSActivation object that uses the identity activation function.
|
||||
${available(bnns2016)}
|
||||
public static var identity: BNNSActivation {
|
||||
return BNNSActivation(function: .identity)
|
||||
}
|
||||
|
||||
/// A BNNSActivation object that uses the integerLinearSaturate
|
||||
/// activation function.
|
||||
${available(bnns2017)}
|
||||
public static func integerLinearSaturate(
|
||||
scale: Int32 = 1,
|
||||
offset: Int32 = 0,
|
||||
shift: Int32 = 0)
|
||||
-> BNNSActivation {
|
||||
return BNNSActivation(function: .integerLinearSaturate,
|
||||
alpha: .nan, // unused
|
||||
beta: .nan, // unused
|
||||
iscale: scale,
|
||||
ioffset: offset,
|
||||
ishift: shift,
|
||||
iscale_per_channel: nil, // unused
|
||||
ioffset_per_channel: nil,// unused
|
||||
ishift_per_channel: nil) // unused
|
||||
}
|
||||
|
||||
/// A BNNSActivation object that uses the integerLinearSaturatePerChannel
|
||||
/// activation function.
|
||||
///
|
||||
/// `scale`, `offset`, and `shift` must each point to a buffer with count
|
||||
/// equal to the number of channels on which this activation object operates.
|
||||
${available(bnns2017)}
|
||||
public static func integerLinearSaturatePerChannel(
|
||||
scale: UnsafePointer<Int32>,
|
||||
offset: UnsafePointer<Int32>,
|
||||
shift: UnsafePointer<Int32>)
|
||||
-> BNNSActivation {
|
||||
return BNNSActivation(function: .integerLinearSaturatePerChannel,
|
||||
alpha: .nan, // unused
|
||||
beta: .nan, // unused
|
||||
iscale: 1, // unused
|
||||
ioffset: 0, // unused
|
||||
ishift: 0, // unused
|
||||
iscale_per_channel: scale,
|
||||
ioffset_per_channel: offset,
|
||||
ishift_per_channel: shift)
|
||||
}
|
||||
}
|
||||
|
||||
extension BNNSConvolutionLayerParameters {
|
||||
${available(bnns2016)}
|
||||
public init(x_stride: Int,
|
||||
y_stride: Int,
|
||||
x_padding: Int,
|
||||
y_padding: Int,
|
||||
k_width: Int,
|
||||
k_height: Int,
|
||||
in_channels: Int,
|
||||
out_channels: Int,
|
||||
weights: BNNSLayerData,
|
||||
bias: BNNSLayerData = .zero,
|
||||
activation: BNNSActivation = .identity) {
|
||||
self.x_stride = x_stride
|
||||
self.y_stride = y_stride
|
||||
self.x_padding = x_padding
|
||||
self.y_padding = y_padding
|
||||
self.k_width = k_width
|
||||
self.k_height = k_height
|
||||
self.in_channels = in_channels
|
||||
self.out_channels = out_channels
|
||||
self.weights = weights
|
||||
self.bias = bias
|
||||
self.activation = activation
|
||||
}
|
||||
}
|
||||
|
||||
extension BNNSPoolingLayerParameters {
|
||||
${available(bnns2016)}
|
||||
public init(x_stride: Int,
|
||||
y_stride: Int,
|
||||
x_padding: Int,
|
||||
y_padding: Int,
|
||||
k_width: Int,
|
||||
k_height: Int,
|
||||
in_channels: Int,
|
||||
out_channels: Int,
|
||||
pooling_function: BNNSPoolingFunction,
|
||||
bias: BNNSLayerData = .zero,
|
||||
activation: BNNSActivation = .identity) {
|
||||
self.x_stride = x_stride
|
||||
self.y_stride = y_stride
|
||||
self.x_padding = x_padding
|
||||
self.y_padding = y_padding
|
||||
self.k_width = k_width
|
||||
self.k_height = k_height
|
||||
self.in_channels = in_channels
|
||||
self.out_channels = out_channels
|
||||
self.pooling_function = pooling_function
|
||||
self.bias = bias
|
||||
self.activation = activation
|
||||
}
|
||||
}
|
||||
|
||||
extension BNNSFullyConnectedLayerParameters {
|
||||
${available(bnns2016)}
|
||||
public init(in_size: Int,
|
||||
out_size: Int,
|
||||
weights: BNNSLayerData,
|
||||
bias: BNNSLayerData = .zero,
|
||||
activation: BNNSActivation = .identity) {
|
||||
self.in_size = in_size
|
||||
self.out_size = out_size
|
||||
self.weights = weights
|
||||
self.bias = bias
|
||||
self.activation = activation
|
||||
}
|
||||
}
|
||||
17
stdlib/public/SDK/Accelerate/CMakeLists.txt
Normal file
17
stdlib/public/SDK/Accelerate/CMakeLists.txt
Normal file
@@ -0,0 +1,17 @@
|
||||
add_swift_library(swiftAccelerate ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY
|
||||
BNNS.swift.gyb
|
||||
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
|
||||
SWIFT_COMPILE_FLAGS ${STDLIB_SIL_SERIALIZE_ALL} -parse-stdlib
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC os XPC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC os # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC os # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreFoundation CoreGraphics Dispatch ObjectiveC os # auto-updated
|
||||
|
||||
DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_OSX}
|
||||
DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_IOS}
|
||||
DEPLOYMENT_VERSION_TVOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_TVOS}
|
||||
DEPLOYMENT_VERSION_WATCHOS ${SWIFTLIB_DEPLOYMENT_VERSION_SIMD_WATCHOS}
|
||||
)
|
||||
@@ -70,6 +70,13 @@ public func NSApplicationMain(
|
||||
}
|
||||
}
|
||||
|
||||
extension NSApplication {
|
||||
@available(swift 4)
|
||||
public static func loadApplication() {
|
||||
NSApplicationLoad()
|
||||
}
|
||||
}
|
||||
|
||||
extension NSColor : _ExpressibleByColorLiteral {
|
||||
@nonobjc
|
||||
public required convenience init(colorLiteralRed red: Float, green: Float,
|
||||
|
||||
@@ -5,6 +5,8 @@ add_swift_library(swiftAppKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OV
|
||||
AppKit.swift
|
||||
AppKit_FoundationExtensions.swift
|
||||
NSError.swift
|
||||
NSGraphics.swift
|
||||
NSOpenGL.swift
|
||||
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
|
||||
@@ -39,6 +39,10 @@ extension CocoaError.Code {
|
||||
public static var sharingServiceNotConfigured: CocoaError.Code {
|
||||
return CocoaError.Code(rawValue: 67072)
|
||||
}
|
||||
@available(macOS 10.13, *)
|
||||
public static var fontAssetDownloadError: CocoaError.Code {
|
||||
return CocoaError.Code(rawValue: 66304)
|
||||
}
|
||||
}
|
||||
|
||||
// Names deprecated late in Swift 3
|
||||
@@ -109,6 +113,10 @@ extension CocoaError {
|
||||
public static var sharingServiceNotConfigured: CocoaError.Code {
|
||||
return CocoaError.Code(rawValue: 67072)
|
||||
}
|
||||
@available(macOS 10.13, *)
|
||||
public static var fontAssetDownloadError: CocoaError.Code {
|
||||
return CocoaError.Code(rawValue: 66304)
|
||||
}
|
||||
}
|
||||
|
||||
// Names deprecated late in Swift 3
|
||||
@@ -163,6 +171,11 @@ extension CocoaError {
|
||||
public var isTextReadWriteError: Bool {
|
||||
return code.rawValue >= 65792 && code.rawValue <= 66303
|
||||
}
|
||||
|
||||
@available(macOS 10.13, *)
|
||||
public var isFontError: Bool {
|
||||
return code.rawValue >= 66304 && code.rawValue <= 66335
|
||||
}
|
||||
}
|
||||
|
||||
extension CocoaError {
|
||||
|
||||
212
stdlib/public/SDK/AppKit/NSGraphics.swift
Normal file
212
stdlib/public/SDK/AppKit/NSGraphics.swift
Normal file
@@ -0,0 +1,212 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
@_exported import AppKit
|
||||
|
||||
extension NSRect {
|
||||
/// Fills this rect in the current NSGraphicsContext in the context's fill
|
||||
/// color.
|
||||
/// The compositing operation of the fill defaults to the context's
|
||||
/// compositing operation, not necessarily using `.copy` like `NSRectFill()`.
|
||||
/// - precondition: There must be a set current NSGraphicsContext.
|
||||
@available(swift 4)
|
||||
public func fill(using operation: NSCompositingOperation =
|
||||
NSGraphicsContext.current()?.compositingOperation ?? .sourceOver) {
|
||||
precondition(NSGraphicsContext.current() != nil,
|
||||
"There must be a set current NSGraphicsContext")
|
||||
NSRectFillUsingOperation(self, operation)
|
||||
}
|
||||
|
||||
/// Draws a frame around the inside of this rect in the current
|
||||
/// NSGraphicsContext in the context's fill color
|
||||
/// The compositing operation of the fill defaults to the context's
|
||||
/// compositing operation, not necessarily using `.copy` like `NSFrameRect()`.
|
||||
/// - precondition: There must be a set current NSGraphicsContext.
|
||||
@available(swift 4)
|
||||
public func frame(withWidth width: CGFloat = 1.0,
|
||||
using operation: NSCompositingOperation =
|
||||
NSGraphicsContext.current()?.compositingOperation ?? .sourceOver) {
|
||||
precondition(NSGraphicsContext.current() != nil,
|
||||
"There must be a set current NSGraphicsContext")
|
||||
NSFrameRectWithWidthUsingOperation(self, width, operation)
|
||||
}
|
||||
|
||||
/// Modifies the current graphics context clipping path by intersecting it
|
||||
/// with this rect.
|
||||
/// This permanently modifies the graphics state, so the current state should
|
||||
/// be saved beforehand and restored afterwards.
|
||||
/// - precondition: There must be a set current NSGraphicsContext.
|
||||
@available(swift 4)
|
||||
public func clip() {
|
||||
precondition(NSGraphicsContext.current() != nil,
|
||||
"There must be a set current NSGraphicsContext")
|
||||
NSRectClip(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Iterator.Element == NSRect {
|
||||
/// Fills this list of rects in the current NSGraphicsContext in the context's
|
||||
/// fill color.
|
||||
/// The compositing operation of the fill defaults to the context's
|
||||
/// compositing operation, not necessarily using `.copy` like `NSRectFill()`.
|
||||
/// - precondition: There must be a set current NSGraphicsContext.
|
||||
@available(swift 4)
|
||||
public func fill(using operation: NSCompositingOperation =
|
||||
NSGraphicsContext.current()?.compositingOperation ?? .sourceOver) {
|
||||
precondition(NSGraphicsContext.current() != nil,
|
||||
"There must be a set current NSGraphicsContext")
|
||||
let rects = Array(self)
|
||||
let count = rects.count
|
||||
guard count > 0 else { return }
|
||||
rects.withUnsafeBufferPointer { rectBufferPointer in
|
||||
guard let rectArray = rectBufferPointer.baseAddress else { return }
|
||||
NSRectFillListUsingOperation(rectArray, count, operation)
|
||||
}
|
||||
}
|
||||
|
||||
/// Modifies the current graphics context clipping path by intersecting it
|
||||
/// with the graphical union of this list of rects
|
||||
/// This permanently modifies the graphics state, so the current state should
|
||||
/// be saved beforehand and restored afterwards.
|
||||
/// - precondition: There must be a set current NSGraphicsContext.
|
||||
@available(swift 4)
|
||||
public func clip() {
|
||||
precondition(NSGraphicsContext.current() != nil,
|
||||
"There must be a set current NSGraphicsContext")
|
||||
let rects = Array(self)
|
||||
let count = rects.count
|
||||
guard count > 0 else { return }
|
||||
rects.withUnsafeBufferPointer { rectBufferPointer in
|
||||
guard let rectArray = rectBufferPointer.baseAddress else { return }
|
||||
NSRectClipList(rectArray, count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Iterator.Element == (CGRect, NSColor) {
|
||||
/// Fills this list of rects in the current NSGraphicsContext with that rect's
|
||||
/// associated color
|
||||
/// The compositing operation of the fill defaults to the context's
|
||||
/// compositing operation, not necessarily using `.copy` like `NSRectFill()`.
|
||||
/// - precondition: There must be a set current NSGraphicsContext.
|
||||
@available(swift 4)
|
||||
public func fill(using operation: NSCompositingOperation =
|
||||
NSGraphicsContext.current()?.compositingOperation ?? .sourceOver) {
|
||||
precondition(NSGraphicsContext.current() != nil,
|
||||
"There must be a set current NSGraphicsContext")
|
||||
let rects = map { $0.0 }
|
||||
let colors = map { $0.1 }
|
||||
let count = rects.count
|
||||
guard count > 0 else { return }
|
||||
rects.withUnsafeBufferPointer { rectBufferPointer in
|
||||
colors.withUnsafeBufferPointer { colorBufferPointer in
|
||||
guard let rectArray = rectBufferPointer.baseAddress else { return }
|
||||
guard let colorArray = colorBufferPointer.baseAddress else { return }
|
||||
NSRectFillListWithColorsUsingOperation(
|
||||
rectArray, colorArray, count, operation)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Iterator.Element == (CGRect, gray: CGFloat) {
|
||||
/// Fills this list of rects in the current NSGraphicsContext with that rect's
|
||||
/// associated gray component value in the DeviceGray color space.
|
||||
/// The compositing operation of the fill defaults to the context's
|
||||
/// compositing operation, not necessarily using `.copy` like
|
||||
/// `NSRectFillListWithGrays()`.
|
||||
/// - precondition: There must be a set current NSGraphicsContext.
|
||||
@available(swift 4)
|
||||
public func fill(using operation: NSCompositingOperation =
|
||||
NSGraphicsContext.current()?.compositingOperation ?? .sourceOver) {
|
||||
// NSRectFillListWithGrays does not have a variant taking an operation, but
|
||||
// is added here for consistency with the other drawing operations.
|
||||
guard let graphicsContext = NSGraphicsContext.current() else {
|
||||
fatalError("There must be a set current NSGraphicsContext")
|
||||
}
|
||||
let cgContext: CGContext
|
||||
if #available(macOS 10.10, *) {
|
||||
cgContext = graphicsContext.cgContext
|
||||
} else {
|
||||
cgContext = Unmanaged<CGContext>.fromOpaque(
|
||||
graphicsContext.graphicsPort).takeUnretainedValue()
|
||||
}
|
||||
cgContext.saveGState()
|
||||
forEach {
|
||||
cgContext.setFillColor(gray: $0.gray, alpha: 1.0)
|
||||
NSRectFillUsingOperation($0.0, operation)
|
||||
}
|
||||
cgContext.restoreGState()
|
||||
}
|
||||
}
|
||||
|
||||
extension NSWindowDepth {
|
||||
@available(swift 4)
|
||||
public static func bestDepth(
|
||||
colorSpaceName: NSColorSpaceName,
|
||||
bitsPerSample: Int,
|
||||
bitsPerPixel: Int,
|
||||
isPlanar: Bool
|
||||
) -> (NSWindowDepth, isExactMatch: Bool) {
|
||||
var isExactMatch: ObjCBool = false
|
||||
let depth = NSBestDepth(
|
||||
colorSpaceName as String,
|
||||
bitsPerSample, bitsPerPixel, isPlanar, &isExactMatch)
|
||||
return (depth, isExactMatch: isExactMatch.boolValue)
|
||||
}
|
||||
@available(swift 4)
|
||||
public static var availableDepths: [NSWindowDepth] {
|
||||
// __NSAvailableWindowDepths is NULL terminated, the length is not known up front
|
||||
let depthsCArray = NSAvailableWindowDepths()
|
||||
var depths: [NSWindowDepth] = []
|
||||
var length = 0
|
||||
var depth = depthsCArray[length]
|
||||
while depth.rawValue != 0 {
|
||||
depths.append(depth)
|
||||
length += 1
|
||||
depth = depthsCArray[length]
|
||||
}
|
||||
return depths
|
||||
}
|
||||
}
|
||||
|
||||
extension NSAnimationEffect {
|
||||
private class _CompletionHandlerDelegate : NSObject {
|
||||
var completionHandler: () -> Void = { }
|
||||
@objc func animationEffectDidEnd(_ contextInfo: UnsafeMutableRawPointer?) {
|
||||
completionHandler()
|
||||
}
|
||||
}
|
||||
@available(swift 4)
|
||||
public func show(centeredAt centerLocation: NSPoint, size: NSSize,
|
||||
completionHandler: @escaping () -> Void = { }) {
|
||||
let delegate = _CompletionHandlerDelegate()
|
||||
delegate.completionHandler = completionHandler
|
||||
// Note that the delegate of `__NSShowAnimationEffect` is retained for the
|
||||
// duration of the animation.
|
||||
NSShowAnimationEffect(
|
||||
self,
|
||||
centerLocation,
|
||||
size,
|
||||
delegate,
|
||||
#selector(_CompletionHandlerDelegate.animationEffectDidEnd(_:)),
|
||||
nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSSound {
|
||||
@available(swift 4)
|
||||
public static func beep() {
|
||||
NSBeep()
|
||||
}
|
||||
}
|
||||
38
stdlib/public/SDK/AppKit/NSOpenGL.swift
Normal file
38
stdlib/public/SDK/AppKit/NSOpenGL.swift
Normal file
@@ -0,0 +1,38 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
@_exported import AppKit
|
||||
|
||||
extension NSOpenGLGlobalOption {
|
||||
@available(swift 4)
|
||||
public var globalValue: GLint {
|
||||
get {
|
||||
var value: GLint = 0
|
||||
NSOpenGLGetOption(self, &value)
|
||||
return value
|
||||
}
|
||||
set {
|
||||
NSOpenGLSetOption(self, newValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension NSOpenGLContext {
|
||||
@available(swift 4)
|
||||
public static var openGLVersion: (major: GLint, minor: GLint) {
|
||||
var major: GLint = 0
|
||||
var minor: GLint = 0
|
||||
NSOpenGLGetVersion(&major, &minor)
|
||||
return (major: major, minor: minor)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ add_swift_library(swiftAssetsLibrary ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS IOS IOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS AssetsLibrary
|
||||
|
||||
DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_ASSETSLIBRARY_IOS}
|
||||
|
||||
@@ -8,7 +8,7 @@ if(SWIFT_BUILD_STATIC_SDK_OVERLAY)
|
||||
list(APPEND SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES STATIC)
|
||||
endif()
|
||||
|
||||
set(all_overlays "AppKit;AssetsLibrary;AVFoundation;CallKit;CloudKit;Contacts;CoreAudio;CoreData;CoreFoundation;CoreGraphics;CoreImage;CoreLocation;CoreMedia;CryptoTokenKit;Dispatch;Foundation;GameplayKit;GLKit;HomeKit;IOKit;Intents;MapKit;ObjectiveC;OpenCL;os;Photos;QuartzCore;SafariServices;SceneKit;simd;SpriteKit;UIKit;WatchKit;XCTest;XPC")
|
||||
set(all_overlays "Accelerate;AppKit;ARKit;AssetsLibrary;AVFoundation;CallKit;CloudKit;Contacts;CoreAudio;CoreData;CoreFoundation;CoreGraphics;CoreImage;CoreLocation;CoreMedia;CryptoTokenKit;Dispatch;Foundation;GameplayKit;GLKit;HomeKit;IOKit;Intents;MapKit;ObjectiveC;OpenCL;os;Photos;QuartzCore;SafariServices;SceneKit;simd;SpriteKit;UIKit;WatchKit;XCTest;XPC")
|
||||
|
||||
if(DEFINED SWIFT_OVERLAY_TARGETS)
|
||||
set(overlays_to_build ${SWIFT_OVERLAY_TARGETS})
|
||||
|
||||
@@ -7,9 +7,9 @@ add_swift_library(swiftContacts ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS OSX IOS IOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS_WEAK Contacts
|
||||
|
||||
DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_CONTACTS_OSX}
|
||||
|
||||
@@ -8,10 +8,10 @@ add_swift_library(swiftCoreData ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_
|
||||
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS CoreData
|
||||
|
||||
DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_COREDATA_OSX}
|
||||
|
||||
@@ -3,8 +3,8 @@ add_swift_library(swiftCoreFoundation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} I
|
||||
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch ObjectiveC
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch ObjectiveC
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch ObjectiveC
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch ObjectiveC
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin Dispatch ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin Dispatch ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin Dispatch ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin Dispatch ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS CoreFoundation)
|
||||
|
||||
@@ -7,9 +7,9 @@ add_swift_library(swiftCoreImage ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch Foundation IOKit ObjectiveC XPC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC XPC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS_OSX QuartzCore
|
||||
FRAMEWORK_DEPENDS_IOS_TVOS CoreImage
|
||||
|
||||
|
||||
@@ -7,10 +7,10 @@ add_swift_library(swiftCoreLocation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_
|
||||
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS CoreLocation
|
||||
|
||||
DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_CORELOCATION_OSX}
|
||||
|
||||
@@ -7,7 +7,7 @@ add_swift_library(swiftCryptoTokenKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} I
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS OSX
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS CryptoTokenKit
|
||||
|
||||
DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_CRYPTOTOKENKIT_OSX}
|
||||
|
||||
@@ -193,6 +193,10 @@ public extension DispatchSource {
|
||||
return __dispatch_source_create(_swift_dispatch_source_type_DATA_OR(), 0, 0, queue) as DispatchSourceUserDataOr
|
||||
}
|
||||
|
||||
public class func makeUserDataReplaceSource(queue: DispatchQueue? = nil) -> DispatchSourceUserDataReplace {
|
||||
return __dispatch_source_create(_swift_dispatch_source_type_DATA_REPLACE(), 0, 0, queue) as DispatchSourceUserDataReplace
|
||||
}
|
||||
|
||||
public class func makeFileSystemObjectSource(
|
||||
fileDescriptor: Int32, eventMask: FileSystemEvent, queue: DispatchQueue? = nil) -> DispatchSourceFileSystemObject
|
||||
{
|
||||
@@ -299,16 +303,14 @@ public extension DispatchSourceFileSystemObject {
|
||||
}
|
||||
|
||||
public extension DispatchSourceUserDataAdd {
|
||||
/// @function mergeData
|
||||
/// @function add
|
||||
///
|
||||
/// @abstract
|
||||
/// Merges data into a dispatch source of type DISPATCH_SOURCE_TYPE_DATA_ADD or
|
||||
/// DISPATCH_SOURCE_TYPE_DATA_OR and submits its event handler block to its
|
||||
/// target queue.
|
||||
/// Merges data into a dispatch source of type DISPATCH_SOURCE_TYPE_DATA_ADD
|
||||
/// and submits its event handler block to its target queue.
|
||||
///
|
||||
/// @param value
|
||||
/// The value to coalesce with the pending data using a logical OR or an ADD
|
||||
/// as specified by the dispatch source type. A value of zero has no effect
|
||||
/// @param data
|
||||
/// The value to add to the current pending data. A value of zero has no effect
|
||||
/// and will not result in the submission of the event handler block.
|
||||
public func add(data: UInt) {
|
||||
__dispatch_source_merge_data(self as! DispatchSource, data)
|
||||
@@ -316,18 +318,31 @@ public extension DispatchSourceUserDataAdd {
|
||||
}
|
||||
|
||||
public extension DispatchSourceUserDataOr {
|
||||
/// @function mergeData
|
||||
/// @function or
|
||||
///
|
||||
/// @abstract
|
||||
/// Merges data into a dispatch source of type DISPATCH_SOURCE_TYPE_DATA_ADD or
|
||||
/// DISPATCH_SOURCE_TYPE_DATA_OR and submits its event handler block to its
|
||||
/// target queue.
|
||||
/// Merges data into a dispatch source of type DISPATCH_SOURCE_TYPE_DATA_OR and
|
||||
/// submits its event handler block to its target queue.
|
||||
///
|
||||
/// @param value
|
||||
/// The value to coalesce with the pending data using a logical OR or an ADD
|
||||
/// as specified by the dispatch source type. A value of zero has no effect
|
||||
/// @param data
|
||||
/// The value to OR into the current pending data. A value of zero has no effect
|
||||
/// and will not result in the submission of the event handler block.
|
||||
public func or(data: UInt) {
|
||||
__dispatch_source_merge_data(self as! DispatchSource, data)
|
||||
}
|
||||
}
|
||||
|
||||
public extension DispatchSourceUserDataReplace {
|
||||
/// @function replace
|
||||
///
|
||||
/// @abstract
|
||||
/// Merges data into a dispatch source of type DISPATCH_SOURCE_TYPE_DATA_REPLACE
|
||||
/// and submits its event handler block to its target queue.
|
||||
///
|
||||
/// @param data
|
||||
/// The value that will replace the current pending data. A value of zero will be stored
|
||||
/// but will not result in the submission of the event handler block.
|
||||
public func replace(data: UInt) {
|
||||
__dispatch_source_merge_data(self as! DispatchSource, data)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,9 +32,11 @@ add_swift_library(swiftFoundation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SD
|
||||
NSGeometry.swift
|
||||
NSIndexSet.swift
|
||||
NSNumber.swift
|
||||
NSObject.swift
|
||||
NSPredicate.swift
|
||||
NSRange.swift
|
||||
NSSet.swift
|
||||
NSSortDescriptor.swift
|
||||
NSString.swift
|
||||
NSStringAPI.swift
|
||||
NSStringEncodings.swift
|
||||
@@ -44,6 +46,7 @@ add_swift_library(swiftFoundation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SD
|
||||
NSValue.swift.gyb
|
||||
PersonNameComponents.swift
|
||||
PlistEncoder.swift
|
||||
Progress.swift
|
||||
ReferenceConvertible.swift
|
||||
String.swift
|
||||
TimeZone.swift
|
||||
|
||||
@@ -19,12 +19,21 @@ open class JSONEncoder {
|
||||
// MARK: Options
|
||||
|
||||
/// The formatting of the output JSON data.
|
||||
public enum OutputFormatting {
|
||||
/// Produce JSON compacted by removing whitespace. This is the default formatting.
|
||||
case compact
|
||||
public struct OutputFormatting : OptionSet {
|
||||
/// The format's default value.
|
||||
public let rawValue: UInt
|
||||
|
||||
/// Creates an OutputFormatting value with the given raw value.
|
||||
public init(rawValue: UInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// Produce human-readable JSON with indented output.
|
||||
case prettyPrinted
|
||||
public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0)
|
||||
|
||||
/// Produce JSON with dictionary keys sorted in lexicographic order.
|
||||
@available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
|
||||
public static let sortedKeys = OutputFormatting(rawValue: 1 << 1)
|
||||
}
|
||||
|
||||
/// The strategy to use for encoding `Date` values.
|
||||
@@ -71,8 +80,8 @@ open class JSONEncoder {
|
||||
case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String)
|
||||
}
|
||||
|
||||
/// The output format to produce. Defaults to `.compact`.
|
||||
open var outputFormatting: OutputFormatting = .compact
|
||||
/// The output format to produce. Defaults to `[]`.
|
||||
open var outputFormatting: OutputFormatting = []
|
||||
|
||||
/// The strategy to use in encoding dates. Defaults to `.deferredToDate`.
|
||||
open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate
|
||||
@@ -132,7 +141,8 @@ open class JSONEncoder {
|
||||
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment."))
|
||||
}
|
||||
|
||||
return try JSONSerialization.data(withJSONObject: topLevel, options: outputFormatting == .prettyPrinted ? .prettyPrinted : [])
|
||||
var writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue)
|
||||
return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -640,6 +640,16 @@ public extension CocoaError {
|
||||
}
|
||||
}
|
||||
|
||||
public extension CocoaError {
|
||||
public static func error(_ code: CocoaError.Code, userInfo: [AnyHashable : Any]? = nil, url: URL? = nil) -> Error {
|
||||
var info: [AnyHashable : Any] = userInfo ?? [:]
|
||||
if let url = url {
|
||||
info[NSURLErrorKey] = url
|
||||
}
|
||||
return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info)
|
||||
}
|
||||
}
|
||||
|
||||
extension CocoaError.Code {
|
||||
public static var fileNoSuchFile: CocoaError.Code {
|
||||
return CocoaError.Code(rawValue: 4)
|
||||
|
||||
@@ -20,3 +20,9 @@ extension NSExpression {
|
||||
self.init(format: expressionFormat, arguments: va_args)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSExpression {
|
||||
public convenience init<Root, Value>(forKeyPath keyPath: KeyPath<Root, Value>) {
|
||||
self.init(forKeyPath: _bridgeKeyPathToString(keyPath))
|
||||
}
|
||||
}
|
||||
|
||||
227
stdlib/public/SDK/Foundation/NSObject.swift
Normal file
227
stdlib/public/SDK/Foundation/NSObject.swift
Normal file
@@ -0,0 +1,227 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2017 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_exported import Foundation // Clang module
|
||||
import ObjectiveC
|
||||
|
||||
public protocol _KeyValueCodingAndObserving {}
|
||||
|
||||
public struct NSKeyValueObservedChange<Value> {
|
||||
public typealias Kind = NSKeyValueChange
|
||||
public let kind: Kind
|
||||
///newValue and oldValue will only be non-nil if .new/.old is passed to `observe()`. In general, get the most up to date value by accessing it directly on the observed object instead.
|
||||
public let newValue: Value?
|
||||
public let oldValue: Value?
|
||||
///indexes will be nil unless the observed KeyPath refers to an ordered to-many property
|
||||
public let indexes: IndexSet?
|
||||
///'isPrior' will be true if this change observation is being sent before the change happens, due to .prior being passed to `observe()`
|
||||
public let isPrior:Bool
|
||||
}
|
||||
|
||||
///Conforming to NSKeyValueObservingCustomization is not required to use Key-Value Observing. Provide an implementation of these functions if you need to disable auto-notifying for a key, or add dependent keys
|
||||
public protocol NSKeyValueObservingCustomization : NSObjectProtocol {
|
||||
static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath>
|
||||
static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool
|
||||
}
|
||||
|
||||
fileprivate extension NSObject {
|
||||
|
||||
@objc class func _old_unswizzled_automaticallyNotifiesObservers(forKey key: String?) -> Bool {
|
||||
fatalError("Should never be reached")
|
||||
}
|
||||
|
||||
@objc class func _old_unswizzled_keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> {
|
||||
fatalError("Should never be reached")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@objc private class _KVOKeyPathBridgeMachinery : NSObject {
|
||||
@nonobjc static var keyPathTable: [String : AnyKeyPath] = {
|
||||
/*
|
||||
Move all our methods into place. We want the following:
|
||||
_KVOKeyPathBridgeMachinery's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replaces NSObject's versions of them
|
||||
NSObject's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replace NSObject's _old_unswizzled_* methods
|
||||
NSObject's _old_unswizzled_* methods replace _KVOKeyPathBridgeMachinery's methods, and are never invoked
|
||||
*/
|
||||
let rootClass: AnyClass = NSObject.self
|
||||
let bridgeClass: AnyClass = _KVOKeyPathBridgeMachinery.self
|
||||
|
||||
let dependentSel = #selector(NSObject.keyPathsForValuesAffectingValue(forKey:))
|
||||
let rootDependentImpl = class_getClassMethod(rootClass, dependentSel)!
|
||||
let bridgeDependentImpl = class_getClassMethod(bridgeClass, dependentSel)!
|
||||
method_exchangeImplementations(rootDependentImpl, bridgeDependentImpl) // NSObject <-> Us
|
||||
|
||||
let originalDependentImpl = class_getClassMethod(bridgeClass, dependentSel)! //we swizzled it onto this class, so this is actually NSObject's old implementation
|
||||
let originalDependentSel = #selector(NSObject._old_unswizzled_keyPathsForValuesAffectingValue(forKey:))
|
||||
let dummyDependentImpl = class_getClassMethod(rootClass, originalDependentSel)!
|
||||
method_exchangeImplementations(originalDependentImpl, dummyDependentImpl) // NSObject's original version <-> NSObject's _old_unswizzled_ version
|
||||
|
||||
let autoSel = #selector(NSObject.automaticallyNotifiesObservers(forKey:))
|
||||
let rootAutoImpl = class_getClassMethod(rootClass, autoSel)!
|
||||
let bridgeAutoImpl = class_getClassMethod(bridgeClass, autoSel)!
|
||||
method_exchangeImplementations(rootAutoImpl, bridgeAutoImpl) // NSObject <-> Us
|
||||
|
||||
let originalAutoImpl = class_getClassMethod(bridgeClass, autoSel)! //we swizzled it onto this class, so this is actually NSObject's old implementation
|
||||
let originalAutoSel = #selector(NSObject._old_unswizzled_automaticallyNotifiesObservers(forKey:))
|
||||
let dummyAutoImpl = class_getClassMethod(rootClass, originalAutoSel)!
|
||||
method_exchangeImplementations(originalAutoImpl, dummyAutoImpl) // NSObject's original version <-> NSObject's _old_unswizzled_ version
|
||||
|
||||
return [:]
|
||||
}()
|
||||
|
||||
@nonobjc static var keyPathTableLock = NSLock()
|
||||
|
||||
@nonobjc fileprivate static func _bridgeKeyPath(_ keyPath:AnyKeyPath) -> String {
|
||||
guard let keyPathString = keyPath._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \(keyPath)") }
|
||||
_KVOKeyPathBridgeMachinery.keyPathTableLock.lock()
|
||||
defer { _KVOKeyPathBridgeMachinery.keyPathTableLock.unlock() }
|
||||
_KVOKeyPathBridgeMachinery.keyPathTable[keyPathString] = keyPath
|
||||
return keyPathString
|
||||
}
|
||||
|
||||
@nonobjc fileprivate static func _bridgeKeyPath(_ keyPath:String?) -> AnyKeyPath? {
|
||||
guard let keyPath = keyPath else { return nil }
|
||||
_KVOKeyPathBridgeMachinery.keyPathTableLock.lock()
|
||||
defer { _KVOKeyPathBridgeMachinery.keyPathTableLock.unlock() }
|
||||
let path = _KVOKeyPathBridgeMachinery.keyPathTable[keyPath]
|
||||
return path
|
||||
}
|
||||
|
||||
@objc override class func automaticallyNotifiesObservers(forKey key: String) -> Bool {
|
||||
//This is swizzled so that it's -[NSObject automaticallyNotifiesObserversForKey:]
|
||||
if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = _KVOKeyPathBridgeMachinery._bridgeKeyPath(key) {
|
||||
return customizingSelf.automaticallyNotifiesObservers(for: path)
|
||||
} else {
|
||||
return self._old_unswizzled_automaticallyNotifiesObservers(forKey: key) //swizzled to be NSObject's original implementation
|
||||
}
|
||||
}
|
||||
|
||||
@objc override class func keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> {
|
||||
//This is swizzled so that it's -[NSObject keyPathsForValuesAffectingValueForKey:]
|
||||
if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = _KVOKeyPathBridgeMachinery._bridgeKeyPath(key!) {
|
||||
let resultSet = customizingSelf.keyPathsAffectingValue(for: path)
|
||||
return Set(resultSet.lazy.map {
|
||||
guard let str = $0._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \($0)") }
|
||||
return str
|
||||
})
|
||||
} else {
|
||||
return self._old_unswizzled_keyPathsForValuesAffectingValue(forKey: key) //swizzled to be NSObject's original implementation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func _bridgeKeyPathToString(_ keyPath:AnyKeyPath) -> String {
|
||||
return _KVOKeyPathBridgeMachinery._bridgeKeyPath(keyPath)
|
||||
}
|
||||
|
||||
func _bridgeStringToKeyPath(_ keyPath:String) -> AnyKeyPath? {
|
||||
return _KVOKeyPathBridgeMachinery._bridgeKeyPath(keyPath)
|
||||
}
|
||||
|
||||
public class NSKeyValueObservation : NSObject {
|
||||
|
||||
weak var object : NSObject?
|
||||
let callback : (NSObject, NSKeyValueObservedChange<Any>) -> Void
|
||||
let path : String
|
||||
|
||||
//workaround for <rdar://problem/31640524> Erroneous (?) error when using bridging in the Foundation overlay
|
||||
static var swizzler : NSKeyValueObservation? = {
|
||||
let bridgeClass: AnyClass = NSKeyValueObservation.self
|
||||
let observeSel = #selector(NSObject.observeValue(forKeyPath:of:change:context:))
|
||||
let swapSel = #selector(NSKeyValueObservation._swizzle_me_observeValue(forKeyPath:of:change:context:))
|
||||
let rootObserveImpl = class_getInstanceMethod(bridgeClass, observeSel)
|
||||
let swapObserveImpl = class_getInstanceMethod(bridgeClass, swapSel)
|
||||
method_exchangeImplementations(rootObserveImpl, swapObserveImpl)
|
||||
return nil
|
||||
}()
|
||||
|
||||
fileprivate init(object: NSObject, keyPath: AnyKeyPath, callback: @escaping (NSObject, NSKeyValueObservedChange<Any>) -> Void) {
|
||||
path = _bridgeKeyPathToString(keyPath)
|
||||
let _ = NSKeyValueObservation.swizzler
|
||||
self.object = object
|
||||
self.callback = callback
|
||||
}
|
||||
|
||||
fileprivate func start(_ options: NSKeyValueObservingOptions) {
|
||||
object?.addObserver(self, forKeyPath: path, options: options, context: nil)
|
||||
}
|
||||
|
||||
///invalidate() will be called automatically when an NSKeyValueObservation is deinited
|
||||
public func invalidate() {
|
||||
object?.removeObserver(self, forKeyPath: path, context: nil)
|
||||
object = nil
|
||||
}
|
||||
|
||||
@objc func _swizzle_me_observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSString : Any]?, context: UnsafeMutableRawPointer?) {
|
||||
guard let ourObject = self.object, object as? NSObject == ourObject, let change = change else { return }
|
||||
let rawKind:UInt = change[NSKeyValueChangeKey.kindKey.rawValue as NSString] as! UInt
|
||||
let kind = NSKeyValueChange(rawValue: rawKind)!
|
||||
let notification = NSKeyValueObservedChange(kind: kind,
|
||||
newValue: change[NSKeyValueChangeKey.newKey.rawValue as NSString],
|
||||
oldValue: change[NSKeyValueChangeKey.oldKey.rawValue as NSString],
|
||||
indexes: change[NSKeyValueChangeKey.indexesKey.rawValue as NSString] as! IndexSet?,
|
||||
isPrior: change[NSKeyValueChangeKey.notificationIsPriorKey.rawValue as NSString] as? Bool ?? false)
|
||||
callback(ourObject, notification)
|
||||
}
|
||||
|
||||
deinit {
|
||||
object?.removeObserver(self, forKeyPath: path, context: nil)
|
||||
}
|
||||
}
|
||||
|
||||
public extension _KeyValueCodingAndObserving {
|
||||
|
||||
///when the returned NSKeyValueObservation is deinited or invalidated, it will stop observing
|
||||
public func observe<Value>(
|
||||
_ keyPath: KeyPath<Self, Value>,
|
||||
options: NSKeyValueObservingOptions = [],
|
||||
changeHandler: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void)
|
||||
-> NSKeyValueObservation {
|
||||
let result = NSKeyValueObservation(object: self as! NSObject, keyPath: keyPath) { (obj, change) in
|
||||
let notification = NSKeyValueObservedChange(kind: change.kind,
|
||||
newValue: change.newValue as? Value,
|
||||
oldValue: change.oldValue as? Value,
|
||||
indexes: change.indexes,
|
||||
isPrior: change.isPrior)
|
||||
changeHandler(obj as! Self, notification)
|
||||
}
|
||||
result.start(options)
|
||||
return result
|
||||
}
|
||||
|
||||
public func willChangeValue<Value>(for keyPath: KeyPath<Self, Value>) {
|
||||
(self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath))
|
||||
}
|
||||
|
||||
public func willChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: KeyPath<Self, Value>) {
|
||||
(self as! NSObject).willChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath))
|
||||
}
|
||||
|
||||
public func willChangeValue<Value>(for keyPath: KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void {
|
||||
(self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set)
|
||||
}
|
||||
|
||||
public func didChangeValue<Value>(for keyPath: KeyPath<Self, Value>) {
|
||||
(self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath))
|
||||
}
|
||||
|
||||
public func didChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: KeyPath<Self, Value>) {
|
||||
(self as! NSObject).didChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath))
|
||||
}
|
||||
|
||||
public func didChangeValue<Value>(for keyPath: KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void {
|
||||
(self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSObject : _KeyValueCodingAndObserving {}
|
||||
28
stdlib/public/SDK/Foundation/NSSortDescriptor.swift
Normal file
28
stdlib/public/SDK/Foundation/NSSortDescriptor.swift
Normal file
@@ -0,0 +1,28 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2017 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_exported import Foundation // Clang module
|
||||
|
||||
extension NSSortDescriptor {
|
||||
public convenience init<Root, Value>(keyPath: KeyPath<Root, Value>, ascending: Bool) {
|
||||
self.init(key: _bridgeKeyPathToString(keyPath), ascending: ascending)
|
||||
}
|
||||
|
||||
public convenience init<Root, Value>(keyPath: KeyPath<Root, Value>, ascending: Bool, comparator cmptr: @escaping Foundation.Comparator) {
|
||||
self.init(key: _bridgeKeyPathToString(keyPath), ascending: ascending, comparator: cmptr)
|
||||
}
|
||||
|
||||
public var keyPath: AnyKeyPath? {
|
||||
guard let key = self.key else { return nil }
|
||||
return _bridgeStringToKeyPath(key)
|
||||
}
|
||||
}
|
||||
85
stdlib/public/SDK/Foundation/Progress.swift
Normal file
85
stdlib/public/SDK/Foundation/Progress.swift
Normal file
@@ -0,0 +1,85 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_exported import Foundation // Clang module
|
||||
|
||||
public extension Progress {
|
||||
@available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
|
||||
public var estimatedTimeRemaining: TimeInterval? {
|
||||
get {
|
||||
guard let v = self.__estimatedTimeRemaining else { return nil }
|
||||
return v.doubleValue as TimeInterval
|
||||
}
|
||||
set {
|
||||
guard let nv = newValue else {
|
||||
self.__estimatedTimeRemaining = nil
|
||||
return
|
||||
}
|
||||
let v = NSNumber(value: nv)
|
||||
self.__estimatedTimeRemaining = v
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
|
||||
public var throughput: Int? {
|
||||
get {
|
||||
guard let v = self.__throughput else { return nil }
|
||||
return v.intValue
|
||||
}
|
||||
set {
|
||||
guard let nv = newValue else {
|
||||
self.__throughput = nil
|
||||
return
|
||||
}
|
||||
let v = NSNumber(value: nv)
|
||||
self.__throughput = v
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
|
||||
public var fileTotalCount: Int? {
|
||||
get {
|
||||
guard let v = self.__fileTotalCount else { return nil }
|
||||
return v.intValue
|
||||
}
|
||||
set {
|
||||
guard let nv = newValue else {
|
||||
self.__fileTotalCount = nil
|
||||
return
|
||||
}
|
||||
let v = NSNumber(value: nv)
|
||||
self.__fileTotalCount = v
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
|
||||
public var fileCompletedCount: Int? {
|
||||
get {
|
||||
guard let v = self.__fileCompletedCount else { return nil }
|
||||
return v.intValue
|
||||
}
|
||||
set {
|
||||
guard let nv = newValue else {
|
||||
self.__fileCompletedCount = nil
|
||||
return
|
||||
}
|
||||
let v = NSNumber(value: nv)
|
||||
self.__fileCompletedCount = v
|
||||
}
|
||||
}
|
||||
|
||||
public func performAsCurrent<ReturnType>(withPendingUnitCount unitCount: Int64, using work: () throws -> ReturnType) rethrows -> ReturnType {
|
||||
becomeCurrent(withPendingUnitCount: unitCount)
|
||||
defer { resignCurrent() }
|
||||
return try work()
|
||||
}
|
||||
}
|
||||
@@ -300,6 +300,19 @@ public struct URLResourceValues {
|
||||
/// Total free space in bytes.
|
||||
public var volumeAvailableCapacity : Int? { return _get(.volumeAvailableCapacityKey) }
|
||||
|
||||
#if os(OSX) || os(iOS)
|
||||
/// Total available capacity in bytes for "Important" resources, including space expected to be cleared by purging non-essential and cached resources. "Important" means something that the user or application clearly expects to be present on the local system, but is ultimately replaceable. This would include items that the user has explicitly requested via the UI, and resources that an application requires in order to provide functionality.
|
||||
/// Examples: A video that the user has explicitly requested to watch but has not yet finished watching or an audio file that the user has requested to download.
|
||||
/// This value should not be used in determining if there is room for an irreplaceable resource. In the case of irreplaceable resources, always attempt to save the resource regardless of available capacity and handle failure as gracefully as possible.
|
||||
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
|
||||
public var volumeAvailableCapacityForImportantUsage: Int64? { return _get(.volumeAvailableCapacityForImportantUsageKey) }
|
||||
|
||||
/// Total available capacity in bytes for "Opportunistic" resources, including space expected to be cleared by purging non-essential and cached resources. "Opportunistic" means something that the user is likely to want but does not expect to be present on the local system, but is ultimately non-essential and replaceable. This would include items that will be created or downloaded without an explicit request from the user on the current device.
|
||||
/// Examples: A background download of a newly available episode of a TV series that a user has been recently watching, a piece of content explicitly requested on another device, and a new document saved to a network server by the current user from another device.
|
||||
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
|
||||
public var volumeAvailableCapacityForOpportunisticUsage: Int64? { return _get(.volumeAvailableCapacityForOpportunisticUsageKey) }
|
||||
#endif
|
||||
|
||||
/// Total number of resources on the volume.
|
||||
public var volumeResourceCount : Int? { return _get(.volumeResourceCountKey) }
|
||||
|
||||
@@ -431,6 +444,28 @@ public struct URLResourceValues {
|
||||
@available(OSX 10.10, iOS 8.0, *)
|
||||
public var ubiquitousItemContainerDisplayName : String? { return _get(.ubiquitousItemContainerDisplayNameKey) }
|
||||
|
||||
#if os(OSX) || os(iOS)
|
||||
// true if ubiquitous item is shared.
|
||||
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
|
||||
public var ubiquitousItemIsShared: Bool? { return _get(.ubiquitousItemIsSharedKey) }
|
||||
|
||||
// The current user's role for this shared item, or nil if not shared
|
||||
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
|
||||
public var ubiquitousSharedItemCurrentUserRole: URLUbiquitousSharedItemRole? { return _get(.ubiquitousSharedItemCurrentUserRoleKey) }
|
||||
|
||||
// The permissions for the current user, or nil if not shared.
|
||||
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
|
||||
public var ubiquitousSharedItemCurrentUserPermissions: URLUbiquitousSharedItemPermissions? { return _get(.ubiquitousSharedItemCurrentUserPermissionsKey) }
|
||||
|
||||
// The name components for the owner, or nil if not shared.
|
||||
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
|
||||
public var ubiquitousSharedItemOwnerNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemOwnerNameComponentsKey) }
|
||||
|
||||
// The name components for the most recent editor, or nil if not shared.
|
||||
@available(OSX 10.13, iOS 11.0, *) @available(tvOS, unavailable) @available(watchOS, unavailable)
|
||||
public var ubiquitousSharedItemMostRecentEditorNameComponents: PersonNameComponents? { return _get(.ubiquitousSharedItemMostRecentEditorNameComponentsKey) }
|
||||
#endif
|
||||
|
||||
#if !os(OSX)
|
||||
/// The protection level for this file
|
||||
@available(iOS 9.0, *)
|
||||
|
||||
@@ -7,9 +7,9 @@ add_swift_library(swiftHomeKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_O
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics CoreImage Dispatch Foundation ObjectiveC os QuartzCore UIKit # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics CoreImage Dispatch Foundation ObjectiveC QuartzCore UIKit # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation ObjectiveC QuartzCore UIKit os # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation ObjectiveC QuartzCore UIKit # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
UIKit # required in some configurations but not found by tool
|
||||
FRAMEWORK_DEPENDS_WEAK HomeKit
|
||||
|
||||
|
||||
@@ -3,12 +3,14 @@ include("../../../../cmake/modules/StandaloneOverlay.cmake")
|
||||
|
||||
add_swift_library(swiftIntents ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY
|
||||
INBooleanResolutionResult.swift
|
||||
INCallRecord.swift
|
||||
INDoubleResolutionResult.swift
|
||||
INGetCarLockStatusIntentResponse.swift
|
||||
INGetCarPowerLevelStatusIntentResponse.swift
|
||||
INIntegerResolutionResult.swift
|
||||
INRequestRideIntent.swift
|
||||
INSaveProfileInCarIntent.swift
|
||||
INSearchCallHistoryIntent.swift
|
||||
INSearchForPhotosIntentResponse.swift
|
||||
INSetCarLockStatusIntent.swift
|
||||
INSetClimateSettingsInCarIntent.swift
|
||||
@@ -22,9 +24,9 @@ add_swift_library(swiftIntents ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_O
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS OSX IOS IOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics CoreLocation Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics CoreLocation Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics CoreLocation Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin Contacts CoreFoundation CoreGraphics CoreLocation Dispatch Foundation IOKit ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin Contacts CoreFoundation CoreGraphics CoreLocation Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin Contacts CoreFoundation CoreGraphics CoreLocation Dispatch Foundation ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS_WEAK Intents
|
||||
|
||||
DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_INTENTS_OSX}
|
||||
|
||||
48
stdlib/public/SDK/Intents/INCallRecord.swift
Normal file
48
stdlib/public/SDK/Intents/INCallRecord.swift
Normal file
@@ -0,0 +1,48 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_exported import Intents
|
||||
import Foundation
|
||||
|
||||
#if os(iOS) || os(watchOS)
|
||||
@available(iOS 11.0, watchOS 4.0, *)
|
||||
extension INCallRecord {
|
||||
@nonobjc
|
||||
public convenience init(
|
||||
identifier: String,
|
||||
dateCreated: Date? = nil,
|
||||
caller: INPerson? = nil,
|
||||
callRecordType: INCallRecordType,
|
||||
callCapability: INCallCapability,
|
||||
callDuration: Double? = nil,
|
||||
unseen: Bool? = nil
|
||||
) {
|
||||
self.init(__identifier: identifier,
|
||||
dateCreated: dateCreated,
|
||||
caller: caller,
|
||||
callRecordType: callRecordType,
|
||||
callCapability: callCapability,
|
||||
callDuration: callDuration.map { NSNumber(value: $0) },
|
||||
unseen: unseen.map { NSNumber(value: $0) })
|
||||
}
|
||||
|
||||
@nonobjc
|
||||
public final var callDuration: Double? {
|
||||
return __callDuration?.doubleValue
|
||||
}
|
||||
|
||||
@nonobjc
|
||||
public final var unseen: Bool? {
|
||||
return __unseen?.boolValue
|
||||
}
|
||||
}
|
||||
#endif
|
||||
40
stdlib/public/SDK/Intents/INSearchCallHistoryIntent.swift
Normal file
40
stdlib/public/SDK/Intents/INSearchCallHistoryIntent.swift
Normal file
@@ -0,0 +1,40 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@_exported import Intents
|
||||
import Foundation
|
||||
|
||||
#if os(iOS) || os(watchOS)
|
||||
@available(iOS 11.0, watchOS 4.0, *)
|
||||
extension INSearchCallHistoryIntent {
|
||||
@nonobjc
|
||||
public convenience init(
|
||||
dateCreated: INDateComponentsRange? = nil,
|
||||
recipient: INPerson? = nil,
|
||||
callCapabilities: INCallCapabilityOptions,
|
||||
callTypes: INCallRecordTypeOptions,
|
||||
unseen: Bool? = nil
|
||||
) {
|
||||
|
||||
self.init(__dateCreated: dateCreated,
|
||||
recipient: recipient,
|
||||
callCapabilities: callCapabilities,
|
||||
callTypes: callTypes,
|
||||
unseen: unseen.map { NSNumber(value: $0) })
|
||||
}
|
||||
|
||||
@nonobjc
|
||||
public final var unseen: Bool? {
|
||||
return __unseen?.boolValue
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -7,8 +7,8 @@ add_swift_library(swiftPhotos ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OV
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin AVFoundation CoreAudio CoreData CoreGraphics CoreImage CoreLocation CoreMedia Dispatch Foundation ObjectiveC os QuartzCore simd UIKit # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin AVFoundation CoreAudio CoreData CoreGraphics CoreImage CoreLocation CoreMedia Dispatch Foundation ObjectiveC QuartzCore simd UIKit # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin AVFoundation CoreAudio CoreFoundation CoreGraphics CoreData CoreImage CoreLocation CoreMedia Dispatch Foundation ObjectiveC QuartzCore simd UIKit os # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin AVFoundation CoreAudio CoreFoundation CoreGraphics CoreData CoreImage CoreLocation CoreMedia Dispatch Foundation ObjectiveC QuartzCore simd UIKit # auto-updated
|
||||
FRAMEWORK_DEPENDS Photos
|
||||
|
||||
DEPLOYMENT_VERSION_IOS ${SWIFTLIB_DEPLOYMENT_VERSION_PHOTOS_IOS}
|
||||
|
||||
@@ -7,9 +7,9 @@ add_swift_library(swiftQuartzCore ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SD
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS OSX IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreGraphics CoreImage Dispatch Foundation IOKit ObjectiveC XPC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_OSX Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation IOKit ObjectiveC XPC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
FRAMEWORK_DEPENDS QuartzCore
|
||||
|
||||
DEPLOYMENT_VERSION_OSX ${SWIFTLIB_DEPLOYMENT_VERSION_QUARTZCORE_OSX}
|
||||
|
||||
@@ -9,9 +9,9 @@ add_swift_library(swiftUIKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVE
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS IOS IOS_SIMULATOR TVOS TVOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics CoreImage Dispatch Foundation ObjectiveC os QuartzCore # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreGraphics CoreImage Dispatch Foundation ObjectiveC QuartzCore # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation ObjectiveC QuartzCore os # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_TVOS Darwin CoreFoundation CoreGraphics CoreImage Dispatch Foundation ObjectiveC QuartzCore # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreFoundation CoreGraphics Dispatch Foundation ObjectiveC # auto-updated
|
||||
SWIFT_COMPILE_FLAGS_WATCHOS -Xfrontend -disable-autolink-framework -Xfrontend CoreText
|
||||
FRAMEWORK_DEPENDS UIKit
|
||||
|
||||
|
||||
@@ -233,3 +233,59 @@ extension UIImage : _ExpressibleByImageLiteral {
|
||||
}
|
||||
|
||||
public typealias _ImageLiteralType = UIImage
|
||||
|
||||
extension UIFontTextStyle {
|
||||
@available(iOS 11.0, watchOS 4.0, tvOS 11.0, *)
|
||||
public var metrics: UIFontMetrics {
|
||||
return UIFontMetrics(forTextStyle: self)
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(watchOS) // UIContentSizeCategory not available on watchOS
|
||||
extension UIContentSizeCategory {
|
||||
@available(iOS 11.0, tvOS 11.0, *)
|
||||
public var isAccessibilityCategory: Bool {
|
||||
return __UIContentSizeCategoryIsAccessibilityCategory(self)
|
||||
}
|
||||
|
||||
@available(iOS 11.0, tvOS 11.0, *)
|
||||
public static func < (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool {
|
||||
return __UIContentSizeCategoryCompareToCategory(left, right) == .orderedAscending
|
||||
}
|
||||
|
||||
@available(iOS 11.0, tvOS 11.0, *)
|
||||
public static func <= (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool {
|
||||
return __UIContentSizeCategoryCompareToCategory(left, right) != .orderedDescending
|
||||
}
|
||||
|
||||
@available(iOS 11.0, tvOS 11.0, *)
|
||||
public static func > (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool {
|
||||
return __UIContentSizeCategoryCompareToCategory(left, right) == .orderedDescending
|
||||
}
|
||||
|
||||
@available(iOS 11.0, tvOS 11.0, *)
|
||||
public static func >= (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool {
|
||||
return __UIContentSizeCategoryCompareToCategory(left, right) != .orderedAscending
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Focus
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if os(iOS) || os(tvOS)
|
||||
@available(iOS 11.0, tvOS 11.0, *)
|
||||
extension UIFocusEnvironment {
|
||||
public func contains(_ environment: UIFocusEnvironment) -> Bool {
|
||||
return UIFocusSystem.environment(self, contains: environment)
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 11.0, tvOS 11.0, *)
|
||||
extension UIFocusItem {
|
||||
public var isFocused: Bool {
|
||||
return self === UIScreen.main.focusedItem
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -7,8 +7,8 @@ add_swift_library(swiftWatchKit ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
TARGET_SDKS IOS IOS_SIMULATOR WATCHOS WATCHOS_SIMULATOR
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreGraphics CoreImage CoreLocation Dispatch Foundation MapKit ObjectiveC os QuartzCore UIKit # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreGraphics CoreLocation Dispatch Foundation ObjectiveC SceneKit simd UIKit # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_IOS Darwin CoreFoundation CoreGraphics CoreImage CoreLocation Dispatch Foundation MapKit ObjectiveC QuartzCore UIKit os # auto-updated
|
||||
SWIFT_MODULE_DEPENDS_WATCHOS Darwin CoreFoundation CoreGraphics CoreLocation Dispatch Foundation HomeKit MapKit ObjectiveC SceneKit simd UIKit # auto-updated
|
||||
FRAMEWORK_DEPENDS_WEAK WatchKit
|
||||
SWIFT_COMPILE_FLAGS_WATCHOS -Xfrontend -disable-autolink-framework -Xfrontend CoreText
|
||||
|
||||
|
||||
@@ -15,6 +15,31 @@
|
||||
import CoreGraphics
|
||||
import _SwiftXCTestOverlayShims
|
||||
|
||||
// --- XCTest API Swiftification ---
|
||||
|
||||
public extension XCTContext {
|
||||
|
||||
/// Create and run a new activity with provided name and block.
|
||||
public class func runActivity(named name: String, block: (XCTActivity) throws -> ()) rethrows {
|
||||
let context = _XCTContextCurrent()
|
||||
|
||||
if _XCTContextShouldStartActivity(context, XCTActivityTypeUserCreated) {
|
||||
try autoreleasepool {
|
||||
let activity = _XCTContextWillStartActivity(context, name, XCTActivityTypeUserCreated)
|
||||
do {
|
||||
try block(activity)
|
||||
_XCTContextDidFinishActivity(context, activity)
|
||||
} catch {
|
||||
_XCTContextDidFinishActivity(context, activity)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
} else {
|
||||
XCTFail("XCTContext.runActivity(named:block:) failed because activities are disallowed in the current configuration.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Failure Formatting ---
|
||||
|
||||
/// Register the failure, expected or unexpected, of the current test case.
|
||||
@@ -717,7 +742,7 @@ func _XCTCheckEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _
|
||||
&& (abs(value1 - value2) <= accuracy)
|
||||
}
|
||||
|
||||
public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
|
||||
public func XCTAssertEqual<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
|
||||
let assertionType = _XCTAssertionType.equalWithAccuracy
|
||||
|
||||
// evaluate each expression exactly once
|
||||
@@ -748,7 +773,7 @@ public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autocl
|
||||
|
||||
default:
|
||||
// unknown type, fail with prejudice
|
||||
_preconditionFailure("unsupported floating-point type passed to XCTAssertEqualWithAccuracy")
|
||||
_preconditionFailure("unsupported floating-point type passed to XCTAssertEqual")
|
||||
}
|
||||
|
||||
if !equalWithAccuracy {
|
||||
@@ -763,7 +788,7 @@ public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autocl
|
||||
}
|
||||
|
||||
case .failedWithError(let error):
|
||||
_XCTRegisterFailure(false, "XCTAssertEqualWithAccuracy failed: threw error \"\(error)\"", message, file, line)
|
||||
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
|
||||
|
||||
case .failedWithException(_, _, let reason):
|
||||
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
|
||||
@@ -773,6 +798,11 @@ public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autocl
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "XCTAssertEqual(_:_:accuracy:file:line:)")
|
||||
public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
|
||||
XCTAssertEqual(expression1, expression2, accuracy: accuracy, message, file: file, line: line)
|
||||
}
|
||||
|
||||
func _XCTCheckNotEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
|
||||
return (value1.isNaN || value2.isNaN)
|
||||
|| (abs(value1 - value2) > accuracy)
|
||||
@@ -788,7 +818,7 @@ func _XCTCheckNotEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat,
|
||||
|| (abs(value1 - value2) > accuracy)
|
||||
}
|
||||
|
||||
public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
|
||||
public func XCTAssertNotEqual<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
|
||||
let assertionType = _XCTAssertionType.notEqualWithAccuracy
|
||||
|
||||
// evaluate each expression exactly once
|
||||
@@ -819,7 +849,7 @@ public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @aut
|
||||
|
||||
default:
|
||||
// unknown type, fail with prejudice
|
||||
_preconditionFailure("unsupported floating-point type passed to XCTAssertNotEqualWithAccuracy")
|
||||
_preconditionFailure("unsupported floating-point type passed to XCTAssertNotEqual")
|
||||
}
|
||||
|
||||
if !notEqualWithAccuracy {
|
||||
@@ -834,7 +864,7 @@ public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @aut
|
||||
}
|
||||
|
||||
case .failedWithError(let error):
|
||||
_XCTRegisterFailure(false, "XCTAssertNotEqualWithAccuracy failed: threw error \"\(error)\"", message, file, line)
|
||||
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
|
||||
|
||||
case .failedWithException(_, _, let reason):
|
||||
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
|
||||
@@ -844,6 +874,11 @@ public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @aut
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "XCTAssertNotEqual(_:_:accuracy:file:line:)")
|
||||
public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
|
||||
XCTAssertNotEqual(expression1, expression2, accuracy: accuracy, message, file: file, line: line)
|
||||
}
|
||||
|
||||
public func XCTAssertGreaterThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
|
||||
let assertionType = _XCTAssertionType.greaterThan
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ include("../../../../cmake/modules/StandaloneOverlay.cmake")
|
||||
|
||||
add_swift_library(swiftsimd ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY
|
||||
simd.swift.gyb
|
||||
Quaternion.swift.gyb
|
||||
|
||||
SWIFT_COMPILE_FLAGS "${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS}"
|
||||
LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}"
|
||||
|
||||
277
stdlib/public/SDK/simd/Quaternion.swift.gyb
Normal file
277
stdlib/public/SDK/simd/Quaternion.swift.gyb
Normal file
@@ -0,0 +1,277 @@
|
||||
//===----------------------------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
// simd module overlays for Swift
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Swift
|
||||
import Darwin
|
||||
@_exported import simd
|
||||
|
||||
%for scalar in ['Float','Double']:
|
||||
% quat = 'simd_quat' + ('f' if scalar == 'Float' else 'd')
|
||||
% vec3 = str.lower(scalar) + '3'
|
||||
% vec4 = str.lower(scalar) + '4'
|
||||
% mat3 = 'simd_' + str.lower(scalar) + '3x3'
|
||||
% mat4 = 'simd_' + str.lower(scalar) + '4x4'
|
||||
|
||||
extension ${quat} {
|
||||
|
||||
/// Construct a quaternion from components.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - ix: The x-component of the imaginary (vector) part.
|
||||
/// - iy: The y-component of the imaginary (vector) part.
|
||||
/// - iz: The z-component of the imaginary (vector) part.
|
||||
/// - r: The real (scalar) part.
|
||||
@_transparent
|
||||
public init(ix: ${scalar}, iy: ${scalar}, iz: ${scalar}, r: ${scalar}) {
|
||||
vector = ${vec4}(ix, iy, iz, r)
|
||||
}
|
||||
|
||||
/// Construct a quaternion from real and imaginary parts.
|
||||
@_transparent
|
||||
public init(real: ${scalar}, imag: ${vec3}) {
|
||||
vector = simd_make_${vec4}(imag, real)
|
||||
}
|
||||
|
||||
/// Construct a quaternion from a vector; the imaginary parts are the first
|
||||
/// three components of the vector, and the real part is the last component.
|
||||
@_transparent
|
||||
public init(vector: ${vec4}) {
|
||||
self.vector = vector
|
||||
}
|
||||
|
||||
/// A quaternion whose action is a rotation by `angle` radians about `axis`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - angle: The angle to rotate by measured in radians.
|
||||
/// - axis: The axis to rotate around.
|
||||
@_transparent
|
||||
public init(angle: ${scalar}, axis: ${vec3}) {
|
||||
self = simd_quaternion(angle, axis)
|
||||
}
|
||||
|
||||
/// A quaternion whose action rotates the vector `from` onto the vector `to`.
|
||||
@_transparent
|
||||
public init(from: ${vec3}, to: ${vec3}) {
|
||||
self = simd_quaternion(from, to)
|
||||
}
|
||||
|
||||
/// Construct a quaternion from `rotationMatrix`.
|
||||
@_transparent
|
||||
public init(_ rotationMatrix: ${mat3}) {
|
||||
self = simd_quaternion(rotationMatrix)
|
||||
}
|
||||
|
||||
/// Construct a quaternion from `rotationMatrix`.
|
||||
@_transparent
|
||||
public init(_ rotationMatrix: ${mat4}) {
|
||||
self = simd_quaternion(rotationMatrix)
|
||||
}
|
||||
|
||||
/// The real (scalar) part of `self`.
|
||||
public var real: ${scalar} {
|
||||
@_transparent
|
||||
get { return vector.w }
|
||||
@_transparent
|
||||
set { vector.w = newValue }
|
||||
}
|
||||
|
||||
/// The imaginary (vector) part of `self`.
|
||||
public var imag: ${vec3} {
|
||||
@_transparent
|
||||
get { return simd_make_${vec3}(vector) }
|
||||
@_transparent
|
||||
set { vector = simd_make_${vec4}(newValue, vector.w) }
|
||||
}
|
||||
|
||||
/// The angle (in radians) by which `self`'s action rotates.
|
||||
@_transparent
|
||||
public var angle: ${scalar} {
|
||||
return simd_angle(self)
|
||||
}
|
||||
|
||||
/// The normalized axis about which `self`'s action rotates.
|
||||
@_transparent
|
||||
public var axis: ${vec3} {
|
||||
return simd_axis(self)
|
||||
}
|
||||
|
||||
/// The conjugate of `self`.
|
||||
@_transparent
|
||||
public var conjugate: ${quat} {
|
||||
return simd_conjugate(self)
|
||||
}
|
||||
|
||||
/// The inverse of `self`.
|
||||
@_transparent
|
||||
public var inverse: ${quat} {
|
||||
return simd_inverse(self)
|
||||
}
|
||||
|
||||
/// The unit quaternion obtained by normalizing `self`.
|
||||
@_transparent
|
||||
public var normalized: ${quat} {
|
||||
return simd_normalize(self)
|
||||
}
|
||||
|
||||
/// The length of the quaternion interpreted as a 4d vector.
|
||||
@_transparent
|
||||
public var length: ${scalar} {
|
||||
return simd_length(self)
|
||||
}
|
||||
|
||||
/// Applies the rotation represented by a unit quaternion to the vector and
|
||||
/// returns the result.
|
||||
@_transparent
|
||||
public func act(_ vector: ${vec3}) -> ${vec3} {
|
||||
return simd_act(self, vector)
|
||||
}
|
||||
}
|
||||
|
||||
extension ${mat3} {
|
||||
/// Construct a 3x3 matrix from `quaternion`.
|
||||
public init(_ quaternion: ${quat}) {
|
||||
self = simd_matrix3x3(quaternion)
|
||||
}
|
||||
}
|
||||
|
||||
extension ${mat4} {
|
||||
/// Construct a 4x4 matrix from `quaternion`.
|
||||
public init(_ quaternion: ${quat}) {
|
||||
self = simd_matrix4x4(quaternion)
|
||||
}
|
||||
}
|
||||
|
||||
extension ${quat} : CustomDebugStringConvertible {
|
||||
public var debugDescription: String {
|
||||
return "${quat}(real: \(real), imag: \(imag))"
|
||||
}
|
||||
}
|
||||
|
||||
extension ${quat} : Equatable {
|
||||
@_transparent
|
||||
public static func ==(lhs: ${quat}, rhs: ${quat}) -> Bool {
|
||||
return lhs.vector == rhs.vector
|
||||
}
|
||||
}
|
||||
|
||||
extension ${quat} {
|
||||
/// The sum of `lhs` and `rhs`.
|
||||
@_transparent
|
||||
public static func +(lhs: ${quat}, rhs: ${quat}) -> ${quat} {
|
||||
return simd_add(lhs, rhs)
|
||||
}
|
||||
|
||||
/// Add `rhs` to `lhs`.
|
||||
@_transparent
|
||||
public static func +=(lhs: inout ${quat}, rhs: ${quat}) {
|
||||
lhs = lhs + rhs
|
||||
}
|
||||
|
||||
/// The difference of `lhs` and `rhs`.
|
||||
@_transparent
|
||||
public static func -(lhs: ${quat}, rhs: ${quat}) -> ${quat} {
|
||||
return simd_sub(lhs, rhs)
|
||||
}
|
||||
|
||||
/// Subtract `rhs` from `lhs`.
|
||||
@_transparent
|
||||
public static func -=(lhs: inout ${quat}, rhs: ${quat}) {
|
||||
lhs = lhs - rhs
|
||||
}
|
||||
|
||||
/// The negation of `rhs`.
|
||||
@_transparent
|
||||
public static prefix func -(rhs: ${quat}) -> ${quat} {
|
||||
return simd_sub(${quat}(), rhs)
|
||||
}
|
||||
|
||||
/// The product of `lhs` and `rhs`.
|
||||
@_transparent
|
||||
public static func *(lhs: ${quat}, rhs: ${quat}) -> ${quat} {
|
||||
return simd_mul(lhs, rhs)
|
||||
}
|
||||
|
||||
/// The product of `lhs` and `rhs`.
|
||||
@_transparent
|
||||
public static func *(lhs: ${scalar}, rhs: ${quat}) -> ${quat} {
|
||||
return simd_mul(lhs, rhs)
|
||||
}
|
||||
|
||||
/// The product of `lhs` and `rhs`.
|
||||
@_transparent
|
||||
public static func *(lhs: ${quat}, rhs: ${scalar}) -> ${quat} {
|
||||
return simd_mul(lhs, rhs)
|
||||
}
|
||||
|
||||
/// Multiply `lhs` by `rhs`.
|
||||
@_transparent
|
||||
public static func *=(lhs: inout ${quat}, rhs: ${quat}) {
|
||||
lhs = lhs * rhs
|
||||
}
|
||||
|
||||
/// Multiply `lhs` by `rhs`.
|
||||
@_transparent
|
||||
public static func *=(lhs: inout ${quat}, rhs: ${scalar}) {
|
||||
lhs = lhs * rhs
|
||||
}
|
||||
|
||||
/// The quotient of `lhs` and `rhs`.
|
||||
@_transparent
|
||||
public static func /(lhs: ${quat}, rhs: ${quat}) -> ${quat} {
|
||||
return simd_mul(lhs, rhs.inverse)
|
||||
}
|
||||
|
||||
/// The quotient of `lhs` and `rhs`.
|
||||
@_transparent
|
||||
public static func /(lhs: ${quat}, rhs: ${scalar}) -> ${quat} {
|
||||
return ${quat}(vector: lhs.vector/rhs)
|
||||
}
|
||||
|
||||
/// Divide `lhs` by `rhs`.
|
||||
@_transparent
|
||||
public static func /=(lhs: inout ${quat}, rhs: ${quat}) {
|
||||
lhs = lhs / rhs
|
||||
}
|
||||
|
||||
/// Divide `lhs` by `rhs`.
|
||||
@_transparent
|
||||
public static func /=(lhs: inout ${quat}, rhs: ${scalar}) {
|
||||
lhs = lhs / rhs
|
||||
}
|
||||
}
|
||||
|
||||
/// The dot product of the quaternions `p` and `q` interpreted as
|
||||
/// four-dimensional vectors.
|
||||
@_transparent
|
||||
public func dot(_ lhs: ${quat}, _ rhs: ${quat}) -> ${scalar} {
|
||||
return simd_dot(lhs, rhs)
|
||||
}
|
||||
|
||||
/// Logarithm of the quaternion `q`.
|
||||
///
|
||||
/// We can write a quaternion `q` in the form: `r(cos(t) + sin(t)v)` where
|
||||
/// `r` is the length of `q`, `t` is an angle, and `v` is a unit 3-vector.
|
||||
/// The logarithm of `q` is `log(r) + tv`, just like the logarithm of the
|
||||
/// complex number `r*(cos(t) + i sin(t))` is `log(r) + it`.
|
||||
public func log(_ q: ${quat}) -> ${quat} {
|
||||
return __tg_log(q)
|
||||
}
|
||||
|
||||
/// Inverse function of `log`; the exponential map on quaternions.
|
||||
@_transparent
|
||||
public func exp(_ q: ${quat}) -> ${quat} {
|
||||
return __tg_exp(q)
|
||||
}
|
||||
|
||||
%end # for scalar
|
||||
File diff suppressed because it is too large
Load Diff
@@ -65,6 +65,7 @@ _swift_dispatch_data_destructor_munmap(void) {
|
||||
|
||||
SWIFT_DISPATCH_SOURCE_TYPE(DATA_ADD)
|
||||
SWIFT_DISPATCH_SOURCE_TYPE(DATA_OR)
|
||||
SWIFT_DISPATCH_SOURCE_TYPE(DATA_REPLACE)
|
||||
SWIFT_DISPATCH_SOURCE_TYPE(MACH_SEND)
|
||||
SWIFT_DISPATCH_SOURCE_TYPE(MACH_RECV)
|
||||
SWIFT_DISPATCH_SOURCE_TYPE(MEMORYPRESSURE)
|
||||
|
||||
@@ -17,10 +17,22 @@
|
||||
|
||||
@class XCTestCase;
|
||||
|
||||
XCTestCase * _Nonnull _XCTCurrentTestCase(void);
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
XCTestCase *_XCTCurrentTestCase(void);
|
||||
|
||||
NSDictionary<NSString *, NSString *> * _Nullable
|
||||
_XCTRunThrowableBlockBridge(void (^ _Nonnull NS_NOESCAPE block)());
|
||||
|
||||
extern NSString * XCTActivityTypeUserCreated;
|
||||
@protocol XCTActivity;
|
||||
@class XCTContext;
|
||||
XCTContext *_XCTContextCurrent(void);
|
||||
BOOL _XCTContextShouldStartActivity(XCTContext *context, NSString *activityType);
|
||||
id<XCTActivity> _XCTContextWillStartActivity(XCTContext *context, NSString *name, NSString *activityType);
|
||||
void _XCTContextDidFinishActivity(XCTContext *context, id<XCTActivity> activity);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif // SWIFT_STDLIB_SHIMS_XCTEST_OVERLAY_H
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
import os
|
||||
|
||||
let p: Protocol = objc_getProtocol("NSObject")
|
||||
let p: Protocol? = objc_getProtocol("NSObject")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import ObjectiveC
|
||||
import os
|
||||
|
||||
let p: Protocol = objc_getProtocol("NSObject")
|
||||
let p: Protocol? = objc_getProtocol("NSObject")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import os
|
||||
import ObjectiveC
|
||||
|
||||
let p: Protocol = objc_getProtocol("NSObject")
|
||||
let p: Protocol? = objc_getProtocol("NSObject")
|
||||
|
||||
@@ -9,4 +9,4 @@
|
||||
|
||||
import ObjectiveC
|
||||
|
||||
let p: Protocol = objc_getProtocol("NSObject")
|
||||
let p: Protocol? = objc_getProtocol("NSObject")
|
||||
|
||||
@@ -3,9 +3,20 @@
|
||||
// RUN: not %swiftc_driver -target x86_64-apple-tvos8.0 %s 2>&1 | %FileCheck --check-prefix=CHECK-tvOS %s
|
||||
// RUN: not %swiftc_driver -target x86_64-apple-watchos1.0 %s 2>&1 | %FileCheck --check-prefix=CHECK-watchOS %s
|
||||
|
||||
// RUN: not %swiftc_driver -target i386-apple-ios11.0 %s -### 2>&1 | %FileCheck --check-prefix=CHECK-IOS-11 %s
|
||||
// RUN: not %swiftc_driver -target armv7-apple-ios11.0 %s -### 2>&1 | %FileCheck --check-prefix=CHECK-IOS-11 %s
|
||||
// RUN: not %swiftc_driver -target i386-apple-ios12.0 %s -### 2>&1 | %FileCheck --check-prefix=CHECK-IOS-12 %s
|
||||
// RUN: not %swiftc_driver -target armv7-apple-ios12.0 %s -### 2>&1 | %FileCheck --check-prefix=CHECK-IOS-12 %s
|
||||
// RUN: %swiftc_driver -target i386-apple-ios10.3 %s -### >/dev/null
|
||||
// RUN: %swiftc_driver -target armv7-apple-ios10.3 %s -### >/dev/null
|
||||
// RUN: %swiftc_driver -target x86_64-apple-ios11.0 %s -### >/dev/null
|
||||
// RUN: %swiftc_driver -target arm64-apple-ios11.0 %s -### >/dev/null
|
||||
|
||||
|
||||
// CHECK-OSX: Swift requires a minimum deployment target of OS X 10.9
|
||||
// CHECK-IOS: Swift requires a minimum deployment target of iOS 7
|
||||
// CHECK-tvOS: Swift requires a minimum deployment target of tvOS 9.0
|
||||
// CHECK-watchOS: Swift requires a minimum deployment target of watchOS 2.0
|
||||
|
||||
// CHECK-IOS-11: iOS 11 does not support 32-bit programs
|
||||
// CHECK-IOS-12: iOS 12 does not support 32-bit programs
|
||||
|
||||
@@ -30,8 +30,11 @@
|
||||
// RUN: %empty-directory(%t/MacOSX10.10.Internal.sdk) && not %swift_driver -sdk %t/MacOSX10.10.Internal.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/MacOSX10.11.sdk) && not %swift_driver -sdk %t/MacOSX10.11.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/MacOSX10.11.Internal.sdk) && not %swift_driver -sdk %t/MacOSX10.11.Internal.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/MacOSX10.12.sdk) && %swift_driver -sdk %t/MacOSX10.12.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %empty-directory(%t/OSX12.sdk) && %swift_driver -sdk %t/OSX12.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %empty-directory(%t/MacOSX10.12.sdk) && not %swift_driver -sdk %t/MacOSX10.12.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/MacOSX10.12.Internal.sdk) && not %swift_driver -sdk %t/MacOSX10.12.Internal.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/MacOSX10.13.sdk) && %swift_driver -sdk %t/MacOSX10.13.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %empty-directory(%t/MacOSX10.13.Internal.sdk) && %swift_driver -sdk %t/MacOSX10.13.Internal.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %empty-directory(%t/OSX50.sdk) && %swift_driver -sdk %t/OSX50.sdk -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
|
||||
// RUN: not %swift_driver -sdk %t/MacOSX10.9.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: not %swift_driver -sdk %t/MacOSX10.9.Internal.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
@@ -39,25 +42,30 @@
|
||||
// RUN: not %swift_driver -sdk %t/MacOSX10.10.Internal.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: not %swift_driver -sdk %t/MacOSX10.11.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: not %swift_driver -sdk %t/MacOSX10.11.Internal.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %swift_driver -sdk %t/MacOSX10.12.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %swift_driver -sdk %t/MacOSX10.12.Internal.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: not %swift_driver -sdk %t/MacOSX10.12.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: not %swift_driver -sdk %t/MacOSX10.12.Internal.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %swift_driver -sdk %t/MacOSX10.13.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %swift_driver -sdk %t/MacOSX10.13.Internal.sdk/ -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
|
||||
// RUN: %empty-directory(%t/iPhoneOS7.0.sdk) && not %swift_driver -sdk %t/iPhoneOS7.0.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/iPhoneOS7.0.Internal.sdk) && not %swift_driver -sdk %t/iPhoneOS7.0.Internal.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/iPhoneOS8.0.sdk) && not %swift_driver -sdk %t/iPhoneOS8.0.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/iPhoneOS8.0.Internal.sdk) && not %swift_driver -sdk %t/iPhoneOS8.0.Internal.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/iPhoneOS9.0.sdk) && not %swift_driver -sdk %t/iPhoneOS9.0.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/iPhoneOS10.0.sdk) && %swift_driver -sdk %t/iPhoneOS10.0.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %empty-directory(%t/iPhoneOS10.0.sdk) && not %swift_driver -sdk %t/iPhoneOS10.0.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/iPhoneOS11.0.sdk) && %swift_driver -sdk %t/iPhoneOS11.0.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
|
||||
// RUN: %empty-directory(%t/tvOS8.0.sdk) && not %swift_driver -sdk %t/tvOS8.0.sdk -target x86_64-apple-tvos9 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/tvOS8.0.Internal.sdk) && not %swift_driver -sdk %t/tvOS8.0.Internal.sdk -target x86_64-apple-tvos9 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/tvOS9.0.sdk) && not %swift_driver -sdk %t/tvOS9.0.sdk -target x86_64-apple-tvos9 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/tvOS10.0.sdk) && %swift_driver -sdk %t/tvOS10.0.sdk -target x86_64-apple-tvos9 -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %empty-directory(%t/tvOS10.0.sdk) && not %swift_driver -sdk %t/tvOS10.0.sdk -target x86_64-apple-tvos9 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/tvOS11.0.sdk) && %swift_driver -sdk %t/tvOS11.0.sdk -target x86_64-apple-tvos9 -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
|
||||
// RUN: %empty-directory(%t/watchOS1.0.sdk) && not %swift_driver -sdk %t/watchOS1.0.sdk -target x86_64-apple-watchos2 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/watchOS1.0.Internal.sdk) && not %swift_driver -sdk %t/watchOS1.0.Internal.sdk -target x86_64-apple-watchos2 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/watchOS2.0.sdk) && not %swift_driver -sdk %t/watchOS2.0.sdk -target x86_64-apple-watchos2 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/watchOS3.0.sdk) && %swift_driver -sdk %t/watchOS3.0.sdk -target x86_64-apple-watchos2 -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
// RUN: %empty-directory(%t/watchOS3.0.sdk) && not %swift_driver -sdk %t/watchOS3.0.sdk -target x86_64-apple-watchos2 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/watchOS4.0.sdk) && %swift_driver -sdk %t/watchOS4.0.sdk -target x86_64-apple-watchos2 -### 2>&1 | %FileCheck -check-prefix=SDK-OKAY %s
|
||||
|
||||
// RUN: %empty-directory(%t/iPhoneSimulator7.0.sdk) && not %swift_driver -sdk %t/iPhoneSimulator7.0.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
// RUN: %empty-directory(%t/iPhoneSimulator8.0.sdk) && not %swift_driver -sdk %t/iPhoneSimulator8.0.sdk -target x86_64-apple-ios7 -### 2>&1 | %FileCheck -check-prefix=SDK-TOO-OLD %s
|
||||
|
||||
@@ -18,6 +18,9 @@ class SuperString : NSString {
|
||||
required init?(coder aDecoder: NSCoder) {
|
||||
super.init(coder: aDecoder)
|
||||
}
|
||||
required init(itemProviderData data: Data, typeIdentifier: String) throws {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
|
||||
override var length: Int {
|
||||
return len
|
||||
|
||||
@@ -39,4 +39,22 @@ coreMedia.test("NSValue bridging") {
|
||||
equal: equalCMTimeMappings)
|
||||
}
|
||||
|
||||
|
||||
var AVFoundationTests = TestSuite("AVFoundation")
|
||||
|
||||
#if os(iOS)
|
||||
|
||||
if #available(iOS 11, *) {
|
||||
AVFoundationTests.test("AVCaptureSynchronizedDataCollection/iteration") {
|
||||
func f(c: AVCaptureSynchronizedDataCollection) {
|
||||
for element in c {
|
||||
var element = element
|
||||
expectType(AVCaptureSynchronizedData.self, &element)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
runAllTests()
|
||||
|
||||
58
test/stdlib/Accelerate.swift
Normal file
58
test/stdlib/Accelerate.swift
Normal file
@@ -0,0 +1,58 @@
|
||||
// RUN: %target-run-simple-swift
|
||||
// REQUIRES: executable_test
|
||||
|
||||
// UNSUPPORTED: OS=watchos
|
||||
// XFAIL: linux
|
||||
|
||||
import StdlibUnittest
|
||||
import Accelerate
|
||||
|
||||
var AccelerateTests = TestSuite("Accelerate")
|
||||
|
||||
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, *) {
|
||||
|
||||
AccelerateTests.test("BNNS/ImageStackDescriptor") {
|
||||
let succeed = BNNSImageStackDescriptor(width: 0, height: 0, channels: 0,
|
||||
row_stride: 0, image_stride: 0,
|
||||
data_type: .int8)
|
||||
expectEqual(succeed.data_scale, 1)
|
||||
expectEqual(succeed.data_bias, 0)
|
||||
expectCrashLater()
|
||||
// indexed8 is not allowed as an imageStack data type.
|
||||
let _ = BNNSImageStackDescriptor(width: 0, height: 0, channels: 0,
|
||||
row_stride: 0, image_stride: 0,
|
||||
data_type: .indexed8)
|
||||
}
|
||||
|
||||
AccelerateTests.test("BNNS/VectorDescriptor") {
|
||||
let succeed = BNNSVectorDescriptor(size: 0, data_type: .int8)
|
||||
expectEqual(succeed.data_scale, 1)
|
||||
expectEqual(succeed.data_bias, 0)
|
||||
expectCrashLater()
|
||||
// indexed8 is not allowed as a vector data type.
|
||||
let _ = BNNSVectorDescriptor(size: 0, data_type: .indexed8)
|
||||
}
|
||||
|
||||
AccelerateTests.test("BNNS/LayerData") {
|
||||
// The zero layer should have data == nil.
|
||||
expectEqual(BNNSLayerData.zero.data, nil)
|
||||
var succeed = BNNSLayerData(data: nil, data_type: .int8)
|
||||
expectEqual(succeed.data_scale, 1)
|
||||
expectEqual(succeed.data_bias, 0)
|
||||
var table: [Float] = [1.0]
|
||||
succeed = BNNSLayerData(data: nil, data_type: .indexed8, data_table: &table)
|
||||
expectCrashLater()
|
||||
// indexed8 requires a non-nil data table.
|
||||
let _ = BNNSLayerData(data: nil, data_type: .indexed8)
|
||||
}
|
||||
|
||||
AccelerateTests.test("BNNS/Activation") {
|
||||
expectEqual(BNNSActivation.identity.function, .identity)
|
||||
let id = BNNSActivation(function: .identity)
|
||||
expectTrue(id.alpha.isNaN)
|
||||
expectTrue(id.beta.isNaN)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
runAllTests()
|
||||
20
test/stdlib/AppKit_Swift3.swift
Normal file
20
test/stdlib/AppKit_Swift3.swift
Normal file
@@ -0,0 +1,20 @@
|
||||
// RUN: rm -rf %t && mkdir %t
|
||||
// RUN: %target-build-swift -swift-version 3 %s -o %t/a.out
|
||||
// RUN: %target-run %t/a.out
|
||||
// REQUIRES: executable_test
|
||||
// REQUIRES: OS=macosx
|
||||
// REQUIRES: objc_interop
|
||||
|
||||
import AppKit
|
||||
import StdlibUnittest
|
||||
import StdlibUnittestFoundationExtras
|
||||
|
||||
let AppKitTests = TestSuite("AppKit_Swift3")
|
||||
|
||||
AppKitTests.test("NSEventMaskFromType") {
|
||||
let eventType: NSEventType = .keyDown
|
||||
let eventMask = NSEventMaskFromType(eventType)
|
||||
expectEqual(eventMask, .keyDown)
|
||||
}
|
||||
|
||||
runAllTests()
|
||||
97
test/stdlib/AppKit_Swift4.swift
Normal file
97
test/stdlib/AppKit_Swift4.swift
Normal file
@@ -0,0 +1,97 @@
|
||||
// RUN: rm -rf %t && mkdir %t
|
||||
// RUN: %target-build-swift -swift-version 4 %s -o %t/a.out
|
||||
// RUN: %target-run %t/a.out
|
||||
// REQUIRES: executable_test
|
||||
// REQUIRES: OS=macosx
|
||||
// REQUIRES: objc_interop
|
||||
|
||||
import AppKit
|
||||
import StdlibUnittest
|
||||
import StdlibUnittestFoundationExtras
|
||||
|
||||
let AppKitTests = TestSuite("AppKit_Swift4")
|
||||
|
||||
AppKitTests.test("NSEventMaskFromType") {
|
||||
let eventType: NSEvent.EventType = .keyDown
|
||||
let eventMask = NSEvent.EventTypeMask(type: eventType)
|
||||
expectEqual(eventMask, .keyDown)
|
||||
}
|
||||
|
||||
AppKitTests.test("NSWindowDepth.availableDepths") {
|
||||
let depths = NSWindow.Depth.availableDepths
|
||||
expectGT(depths.count, 0)
|
||||
for depth in depths {
|
||||
expectNotEqual(depth.rawValue, 0)
|
||||
}
|
||||
}
|
||||
|
||||
AppKitTests.test("NSRectFills") {
|
||||
let bitmapImage = NSBitmapImageRep(
|
||||
bitmapDataPlanes: nil, pixelsWide: 3, pixelsHigh: 3,
|
||||
bitsPerSample: 8, samplesPerPixel: 4,
|
||||
hasAlpha: true, isPlanar: false,
|
||||
colorSpaceName: .deviceRGB,
|
||||
bytesPerRow: 0, bitsPerPixel: 0)!
|
||||
let graphicsContext = NSGraphicsContext(bitmapImageRep: bitmapImage)!
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
NSGraphicsContext.current = graphicsContext
|
||||
|
||||
let canvas = NSRect(x: 0, y: 0, width: 3, height: 3)
|
||||
let bottomLeft = NSRect(x: 0, y: 0, width: 1, height: 1)
|
||||
let bottomCenter = NSRect(x: 1, y: 0, width: 1, height: 1)
|
||||
let bottomRight = NSRect(x: 2, y: 0, width: 1, height: 1)
|
||||
let middleCenter = NSRect(x: 1, y: 1, width: 1, height: 1)
|
||||
let middleRight = NSRect(x: 2, y: 1, width: 1, height: 1)
|
||||
let topLeft = NSRect(x: 0, y: 2, width: 1, height: 1)
|
||||
let topCenter = NSRect(x: 1, y: 2, width: 1, height: 1)
|
||||
let topRight = NSRect(x: 2, y: 2, width: 1, height: 1)
|
||||
let red = NSColor(deviceRed: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
|
||||
let green = NSColor(deviceRed: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)
|
||||
let blue = NSColor(deviceRed: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
|
||||
let black = NSColor(deviceRed: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
|
||||
let white = NSColor(deviceRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
|
||||
|
||||
// Blank out the canvas with white
|
||||
white.set()
|
||||
canvas.fill()
|
||||
|
||||
// Fill the bottomLeft and middleRight with red using the Sequence<Rect> convenience
|
||||
red.set()
|
||||
[bottomLeft, middleRight].fill()
|
||||
|
||||
// Fill the bottom right corner by clipping to it, and then filling the canvas
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
topRight.clip()
|
||||
black.set()
|
||||
canvas.fill()
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
|
||||
// Fill bottomRight and topLeft by clipping to them and filling a superset
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
[bottomRight, topLeft].clip()
|
||||
green.set()
|
||||
canvas.fill()
|
||||
blue.set()
|
||||
// effectively fill bottomRight only
|
||||
NSRect(x: 0, y: 0, width: 3, height: 1).fill()
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
|
||||
// Fill the center regions using the Sequence<(Rect, Color)> convenience
|
||||
[(topCenter, blue),
|
||||
(middleCenter, green),
|
||||
(bottomCenter, red)].fill()
|
||||
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
|
||||
expectEqual(bitmapImage.colorAt(x: 0, y: 0), green)
|
||||
expectEqual(bitmapImage.colorAt(x: 1, y: 0), blue)
|
||||
expectEqual(bitmapImage.colorAt(x: 2, y: 0), black)
|
||||
expectEqual(bitmapImage.colorAt(x: 0, y: 1), white)
|
||||
expectEqual(bitmapImage.colorAt(x: 1, y: 1), green)
|
||||
expectEqual(bitmapImage.colorAt(x: 2, y: 1), red)
|
||||
expectEqual(bitmapImage.colorAt(x: 0, y: 2), red)
|
||||
expectEqual(bitmapImage.colorAt(x: 1, y: 2), red)
|
||||
expectEqual(bitmapImage.colorAt(x: 2, y: 2), blue)
|
||||
}
|
||||
|
||||
runAllTests()
|
||||
@@ -70,7 +70,7 @@ if #available(OSX 10.10, iOS 8.0, *) {
|
||||
|
||||
DispatchAPI.test("dispatch_data_t enumeration") {
|
||||
// Ensure we can iterate the empty iterator
|
||||
for x in DispatchData.empty {
|
||||
for _ in DispatchData.empty {
|
||||
_ = 1
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,7 @@ DispatchAPI.test("dispatch_data_t deallocator") {
|
||||
autoreleasepool {
|
||||
let size = 1024
|
||||
let p = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
|
||||
let d = DispatchData(bytesNoCopy: UnsafeRawBufferPointer(start: p, count: size), deallocator: .custom(q, {
|
||||
let _ = DispatchData(bytesNoCopy: UnsafeBufferPointer(start: p, count: size), deallocator: .custom(q, {
|
||||
t = 1
|
||||
}))
|
||||
}
|
||||
@@ -151,7 +151,7 @@ DispatchAPI.test("DispatchData.copyBytes") {
|
||||
let srcPtr1 = UnsafeBufferPointer(start: source1, count: source1.count)
|
||||
|
||||
var dest: [UInt8] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
|
||||
var destPtr = UnsafeMutableBufferPointer(start: UnsafeMutablePointer(&dest),
|
||||
let destPtr = UnsafeMutableBufferPointer(start: UnsafeMutablePointer(&dest),
|
||||
count: dest.count)
|
||||
|
||||
var dispatchData = DispatchData(bytes: srcPtr1)
|
||||
@@ -468,3 +468,43 @@ DispatchAPI.test("DispatchIO.initRelativePath") {
|
||||
chan.setInterval(interval: .seconds(1)) // Dereference of unexpected nil should crash
|
||||
#endif
|
||||
}
|
||||
|
||||
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
|
||||
var block = DispatchWorkItem(qos: .unspecified, flags: .assignCurrentContext) {}
|
||||
DispatchAPI.test("DispatchSource.replace") {
|
||||
let g = DispatchGroup()
|
||||
let q = DispatchQueue(label: "q")
|
||||
let ds = DispatchSource.makeUserDataReplaceSource(queue: q)
|
||||
var lastValue = UInt(0)
|
||||
var nextValue = UInt(1)
|
||||
let maxValue = UInt(1 << 24)
|
||||
|
||||
ds.setEventHandler() {
|
||||
let value = ds.data;
|
||||
expectTrue(value > lastValue) // Values must increase
|
||||
expectTrue((value & (value - 1)) == 0) // Must be power of two
|
||||
lastValue = value
|
||||
if value == maxValue {
|
||||
g.leave()
|
||||
}
|
||||
}
|
||||
ds.activate()
|
||||
|
||||
g.enter()
|
||||
block = DispatchWorkItem(qos: .unspecified, flags: .assignCurrentContext) {
|
||||
ds.replace(data: nextValue)
|
||||
nextValue <<= 1
|
||||
if nextValue <= maxValue {
|
||||
q.asyncAfter(
|
||||
deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1),
|
||||
execute: block)
|
||||
}
|
||||
}
|
||||
q.asyncAfter(
|
||||
deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1),
|
||||
execute: block)
|
||||
|
||||
let result = g.wait(timeout: DispatchTime.now() + .seconds(30))
|
||||
expectTrue(result == .success)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,17 +290,6 @@ FloatingPoint.test("${Self}.round") {
|
||||
for value in [${Self}(), 1, 1/${Self}.ulpOfOne,
|
||||
.greatestFiniteMagnitude, .infinity] {
|
||||
expectBitwiseEqual(value, value.rounded(rule))
|
||||
|
||||
// FIXME: rdar://27347596
|
||||
// Double -0 rounded toNearestOrEven is wrong on watchos armv7k
|
||||
% if Self == 'Double':
|
||||
#if os(watchOS) && arch(arm)
|
||||
if (value == 0 && rule == .toNearestOrEven) {
|
||||
continue
|
||||
}
|
||||
#endif
|
||||
% end
|
||||
|
||||
expectBitwiseEqual(-value, (-value).rounded(rule))
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ class Target : NSString {
|
||||
self.objcValue = ""
|
||||
super.init(coder: aDecoder)
|
||||
}
|
||||
required init(itemProviderData data: Data, typeIdentifier: String) throws {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
|
||||
func print() {
|
||||
Swift.print("swiftValue \(self.swiftValue.value), objcValue \(objcValue)")
|
||||
|
||||
111
test/stdlib/KVOKeyPaths.swift
Normal file
111
test/stdlib/KVOKeyPaths.swift
Normal file
@@ -0,0 +1,111 @@
|
||||
// RUN: %target-run-simple-swift | %FileCheck %s
|
||||
// REQUIRES: executable_test
|
||||
|
||||
// REQUIRES: objc_interop
|
||||
|
||||
import Foundation
|
||||
|
||||
struct Guts {
|
||||
var internalValue = 42
|
||||
var value: Int {
|
||||
get {
|
||||
return internalValue
|
||||
}
|
||||
}
|
||||
init(value: Int) {
|
||||
internalValue = value
|
||||
}
|
||||
init() {
|
||||
}
|
||||
}
|
||||
|
||||
class Target : NSObject, NSKeyValueObservingCustomization {
|
||||
// This dynamic property is observed by KVO
|
||||
dynamic var objcValue: String
|
||||
dynamic var objcValue2: String {
|
||||
willSet {
|
||||
willChangeValue(for: \.objcValue2)
|
||||
}
|
||||
didSet {
|
||||
didChangeValue(for: \.objcValue2)
|
||||
}
|
||||
}
|
||||
dynamic var objcValue3: String
|
||||
|
||||
// This Swift-typed property causes vtable usage on this class.
|
||||
var swiftValue: Guts
|
||||
|
||||
override init() {
|
||||
self.swiftValue = Guts()
|
||||
self.objcValue = ""
|
||||
self.objcValue2 = ""
|
||||
self.objcValue3 = ""
|
||||
super.init()
|
||||
}
|
||||
|
||||
static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath> {
|
||||
if (key == \Target.objcValue) {
|
||||
return [\Target.objcValue2, \Target.objcValue3]
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool {
|
||||
if key == \Target.objcValue2 || key == \Target.objcValue3 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func print() {
|
||||
Swift.print("swiftValue \(self.swiftValue.value), objcValue \(objcValue)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class ObserverKVO : NSObject {
|
||||
var target: Target?
|
||||
var observation: NSKeyValueObservation? = nil
|
||||
|
||||
override init() { target = nil; super.init() }
|
||||
|
||||
func observeTarget(_ target: Target) {
|
||||
self.target = target
|
||||
observation = target.observe(\.objcValue) { (object, change) in
|
||||
Swift.print("swiftValue \(object.swiftValue.value), objcValue \(object.objcValue)")
|
||||
}
|
||||
}
|
||||
|
||||
func removeTarget() {
|
||||
observation!.invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var t2 = Target()
|
||||
var o2 = ObserverKVO()
|
||||
print("unobserved 2")
|
||||
t2.objcValue = "one"
|
||||
t2.objcValue = "two"
|
||||
print("registering observer 2")
|
||||
o2.observeTarget(t2)
|
||||
print("Now witness the firepower of this fully armed and operational panopticon!")
|
||||
t2.objcValue = "three"
|
||||
t2.objcValue = "four"
|
||||
t2.swiftValue = Guts(value: 13)
|
||||
t2.objcValue2 = "six" //should fire
|
||||
t2.objcValue3 = "nothing" //should not fire
|
||||
o2.removeTarget()
|
||||
t2.objcValue = "five" //make sure that we don't crash or keep posting changes if you deallocate an observation after invalidating it
|
||||
print("target removed")
|
||||
|
||||
// CHECK: registering observer 2
|
||||
// CHECK-NEXT: Now witness the firepower of this fully armed and operational panopticon!
|
||||
// CHECK-NEXT: swiftValue 42, objcValue three
|
||||
// CHECK-NEXT: swiftValue 42, objcValue four
|
||||
// CHECK-NEXT: swiftValue 13, objcValue four
|
||||
// CHECK-NEXT: swiftValue 13, objcValue four
|
||||
// CHECK-NEXT: swiftValue 13, objcValue four
|
||||
// CHECK-NEXT: target removed
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// RUN: %target-run-simple-swift
|
||||
// REQUIRES: executable_test
|
||||
|
||||
// REQUIRES: objc_interop
|
||||
|
||||
// RUN: %target-build-swift %s 2> %t.warnings.txt
|
||||
@@ -28,4 +35,22 @@ tests.test("user info") {
|
||||
expectEqual("reason", error.userInfo[ErrorUserInfoKey.localizedFailureReasonErrorKey as NSObject]! as! String)
|
||||
}
|
||||
|
||||
tests.test("convenience") {
|
||||
let error1 = CocoaError.error(.fileNoSuchFile)
|
||||
expectNotNil((error1 as NSError).localizedDescription)
|
||||
expectEqual(CocoaError.Code.fileNoSuchFile.rawValue, (error1 as NSError).code)
|
||||
|
||||
let url = URL(string: "file:///tmp/bar/foo")
|
||||
let error2 = CocoaError.error(.fileNoSuchFile, url: url)
|
||||
expectEqual(url, (error2 as! CocoaError).url)
|
||||
expectNotNil((error2 as NSError).localizedDescription)
|
||||
expectEqual(url, (error2 as NSError).userInfo[NSURLErrorKey] as? URL)
|
||||
|
||||
let error3 = CocoaError.error(.fileNoSuchFile, userInfo: ["foo" : "bar"], url: url)
|
||||
expectEqual(url, (error3 as! CocoaError).url)
|
||||
expectNotNil((error3 as NSError).localizedDescription)
|
||||
expectEqual(url, (error3 as NSError).userInfo[NSURLErrorKey] as? URL)
|
||||
expectEqual("bar", (error3 as NSError).userInfo["foo"] as? String)
|
||||
}
|
||||
|
||||
runAllTests()
|
||||
|
||||
@@ -3,6 +3,11 @@
|
||||
|
||||
// REQUIRES: objc_interop
|
||||
|
||||
// FIXME: rdar://problem/31311598
|
||||
// UNSUPPORTED: OS=ios
|
||||
// UNSUPPORTED: OS=tvos
|
||||
// UNSUPPORTED: OS=watchos
|
||||
|
||||
//
|
||||
// Tests for the NSString APIs as exposed by String
|
||||
//
|
||||
@@ -19,6 +24,9 @@ class NonContiguousNSString : NSString {
|
||||
required init(coder aDecoder: NSCoder) {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
required init(itemProviderData data: Data, typeIdentifier: String) throws {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
|
||||
override init() {
|
||||
_value = []
|
||||
|
||||
@@ -452,6 +452,9 @@ var nsStringCanaryCount = 0
|
||||
required init(coder: NSCoder) {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
required init(itemProviderData data: Data, typeIdentifier: String) throws {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
deinit {
|
||||
nsStringCanaryCount -= 1
|
||||
}
|
||||
|
||||
@@ -69,19 +69,6 @@ struct MyError : Error {
|
||||
#if !arch(arm64)
|
||||
% end
|
||||
|
||||
extension ${TestType} : Equatable {}
|
||||
public func ==(_ x: ${TestType}, _ y: ${TestType}) -> Bool {
|
||||
for i in 0..<${cols} {
|
||||
// Workaround <rdar://problem/18900352>
|
||||
% if type in float_types:
|
||||
if x[i] != y[i] && !(x[i].isNaN && y[i].isNaN) { return false }
|
||||
% else:
|
||||
if x[i] != y[i] { return false }
|
||||
% end
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
enum Enum${TestType} : Equatable {
|
||||
case Empty
|
||||
case Value(${TestType})
|
||||
|
||||
@@ -15,6 +15,11 @@
|
||||
// REQUIRES: executable_test
|
||||
// REQUIRES: objc_interop
|
||||
|
||||
// FIXME: rdar://problem/31207060
|
||||
// UNSUPPORTED: OS=ios
|
||||
// UNSUPPORTED: OS=tvos
|
||||
// UNSUPPORTED: OS=watchos
|
||||
|
||||
import Foundation
|
||||
import FoundationBridgeObjC
|
||||
|
||||
|
||||
@@ -86,6 +86,35 @@ class TestJSONEncoder : TestJSONEncoderSuper {
|
||||
_testRoundTrip(of: company)
|
||||
}
|
||||
|
||||
// MARK: - Output Formatting Tests
|
||||
func testEncodingOutputFormattingDefault() {
|
||||
let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"appleseed@apple.com\"}".data(using: .utf8)!
|
||||
let person = Person.testValue
|
||||
_testRoundTrip(of: person, expectedJSON: expectedJSON)
|
||||
}
|
||||
|
||||
func testEncodingOutputFormattingPrettyPrinted() {
|
||||
let expectedJSON = "{\n \"name\" : \"Johnny Appleseed\",\n \"email\" : \"appleseed@apple.com\"\n}".data(using: .utf8)!
|
||||
let person = Person.testValue
|
||||
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted])
|
||||
}
|
||||
|
||||
func testEncodingOutputFormattingSortedKeys() {
|
||||
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
|
||||
let expectedJSON = "{\"email\":\"appleseed@apple.com\",\"name\":\"Johnny Appleseed\"}".data(using: .utf8)!
|
||||
let person = Person.testValue
|
||||
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
|
||||
}
|
||||
}
|
||||
|
||||
func testEncodingOutputFormattingPrettyPrintedSortedKeys() {
|
||||
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
|
||||
let expectedJSON = "{\n \"email\" : \"appleseed@apple.com\",\n \"name\" : \"Johnny Appleseed\"\n}".data(using: .utf8)!
|
||||
let person = Person.testValue
|
||||
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted, .sortedKeys])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Date Strategy Tests
|
||||
func testEncodingDate() {
|
||||
// We can't encode a top-level Date, so it'll be wrapped in an array.
|
||||
@@ -298,6 +327,7 @@ class TestJSONEncoder : TestJSONEncoderSuper {
|
||||
|
||||
private func _testRoundTrip<T>(of value: T,
|
||||
expectedJSON json: Data? = nil,
|
||||
outputFormatting: JSONEncoder.OutputFormatting = [],
|
||||
dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate,
|
||||
dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
|
||||
dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64Encode,
|
||||
@@ -307,6 +337,7 @@ class TestJSONEncoder : TestJSONEncoderSuper {
|
||||
var payload: Data! = nil
|
||||
do {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = outputFormatting
|
||||
encoder.dateEncodingStrategy = dateEncodingStrategy
|
||||
encoder.dataEncodingStrategy = dataEncodingStrategy
|
||||
encoder.nonConformingFloatEncodingStrategy = nonConformingFloatEncodingStrategy
|
||||
@@ -766,6 +797,10 @@ JSONEncoderTests.test("testEncodingTopLevelStructuredClass") { TestJSONEncoder()
|
||||
JSONEncoderTests.test("testEncodingTopLevelStructuredSingleStruct") { TestJSONEncoder().testEncodingTopLevelStructuredSingleStruct() }
|
||||
JSONEncoderTests.test("testEncodingTopLevelStructuredSingleClass") { TestJSONEncoder().testEncodingTopLevelStructuredSingleClass() }
|
||||
JSONEncoderTests.test("testEncodingTopLevelDeepStructuredType") { TestJSONEncoder().testEncodingTopLevelDeepStructuredType()}
|
||||
JSONEncoderTests.test("testEncodingOutputFormattingDefault") { TestJSONEncoder().testEncodingOutputFormattingDefault() }
|
||||
JSONEncoderTests.test("testEncodingOutputFormattingPrettyPrinted") { TestJSONEncoder().testEncodingOutputFormattingPrettyPrinted() }
|
||||
JSONEncoderTests.test("testEncodingOutputFormattingSortedKeys") { TestJSONEncoder().testEncodingOutputFormattingSortedKeys() }
|
||||
JSONEncoderTests.test("testEncodingOutputFormattingPrettyPrintedSortedKeys") { TestJSONEncoder().testEncodingOutputFormattingPrettyPrintedSortedKeys() }
|
||||
JSONEncoderTests.test("testEncodingDate") { TestJSONEncoder().testEncodingDate() }
|
||||
JSONEncoderTests.test("testEncodingDateSecondsSince1970") { TestJSONEncoder().testEncodingDateSecondsSince1970() }
|
||||
JSONEncoderTests.test("testEncodingDateMillisecondsSince1970") { TestJSONEncoder().testEncodingDateMillisecondsSince1970() }
|
||||
|
||||
76
test/stdlib/TestProgress.swift
Normal file
76
test/stdlib/TestProgress.swift
Normal file
@@ -0,0 +1,76 @@
|
||||
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// RUN: %target-run-simple-swift
|
||||
// REQUIRES: executable_test
|
||||
// REQUIRES: objc_interop
|
||||
|
||||
import Foundation
|
||||
|
||||
#if FOUNDATION_XCTEST
|
||||
import XCTest
|
||||
class TestProgressSuper : XCTestCase { }
|
||||
#else
|
||||
import StdlibUnittest
|
||||
class TestProgressSuper { }
|
||||
#endif
|
||||
|
||||
class TestProgress : TestProgressSuper {
|
||||
func testUserInfoConveniences() {
|
||||
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
|
||||
let p = Progress(parent:nil, userInfo: nil)
|
||||
|
||||
expectNil(p.userInfo[.throughputKey])
|
||||
expectNil(p.throughput)
|
||||
p.throughput = 50
|
||||
expectEqual(p.throughput, 50)
|
||||
expectNotNil(p.userInfo[.throughputKey])
|
||||
|
||||
expectNil(p.userInfo[.estimatedTimeRemainingKey])
|
||||
expectNil(p.estimatedTimeRemaining)
|
||||
p.estimatedTimeRemaining = 100
|
||||
expectEqual(p.estimatedTimeRemaining, 100)
|
||||
expectNotNil(p.userInfo[.estimatedTimeRemainingKey])
|
||||
|
||||
expectNil(p.userInfo[.fileTotalCountKey])
|
||||
expectNil(p.fileTotalCount)
|
||||
p.fileTotalCount = 42
|
||||
expectEqual(p.fileTotalCount, 42)
|
||||
expectNotNil(p.userInfo[.fileTotalCountKey])
|
||||
|
||||
expectNil(p.userInfo[.fileCompletedCountKey])
|
||||
expectNil(p.fileCompletedCount)
|
||||
p.fileCompletedCount = 24
|
||||
expectEqual(p.fileCompletedCount, 24)
|
||||
expectNotNil(p.userInfo[.fileCompletedCountKey])
|
||||
}
|
||||
}
|
||||
|
||||
func testPerformAsCurrent() {
|
||||
if #available(OSX 10.11, iOS 8.0, *) {
|
||||
// This test can be enabled once <rdar://problem/31867347> is in the SDK
|
||||
/*
|
||||
let p = Progress.discreteProgress(totalUnitCount: 10)
|
||||
let r = p.performAsCurrent(withPendingUnitCount: 10) {
|
||||
expectNotNil(Progress.current())
|
||||
return 42
|
||||
}
|
||||
expectEqual(r, 42)
|
||||
expectEqual(p.completedUnitCount, 10)
|
||||
expectNil(Progress.current())
|
||||
*/
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !FOUNDATION_XCTEST
|
||||
let ProgressTests = TestSuite("TestProgress")
|
||||
ProgressTests.test("testUserInfoConveniences") { TestProgress().testUserInfoConveniences() }
|
||||
ProgressTests.test("testPerformAsCurrent") { TestProgress().testPerformAsCurrent() }
|
||||
runAllTests()
|
||||
#endif
|
||||
@@ -107,4 +107,51 @@ UIKitTests.test("NSValue bridging") {
|
||||
equal: (==))
|
||||
}
|
||||
|
||||
#if os(iOS) || os(tvOS)
|
||||
UIKitTests.test("UIContentSizeCategory comparison") {
|
||||
if #available(iOS 11.0, tvOS 11.0, *) {
|
||||
expectTrue(UIContentSizeCategory.large < UIContentSizeCategory.extraLarge)
|
||||
expectTrue(UIContentSizeCategory.large <= UIContentSizeCategory.extraLarge)
|
||||
expectFalse(UIContentSizeCategory.large >= UIContentSizeCategory.extraLarge)
|
||||
expectFalse(UIContentSizeCategory.large > UIContentSizeCategory.extraLarge)
|
||||
expectFalse(UIContentSizeCategory.large == UIContentSizeCategory.extraLarge)
|
||||
|
||||
expectTrue(UIContentSizeCategory.extraLarge > UIContentSizeCategory.large)
|
||||
expectTrue(UIContentSizeCategory.extraLarge >= UIContentSizeCategory.large)
|
||||
expectFalse(UIContentSizeCategory.extraLarge < UIContentSizeCategory.large)
|
||||
expectFalse(UIContentSizeCategory.extraLarge <= UIContentSizeCategory.large)
|
||||
expectFalse(UIContentSizeCategory.extraLarge == UIContentSizeCategory.large)
|
||||
|
||||
expectTrue(UIContentSizeCategory.large == UIContentSizeCategory.large)
|
||||
expectTrue(UIContentSizeCategory.large >= UIContentSizeCategory.large)
|
||||
expectTrue(UIContentSizeCategory.large <= UIContentSizeCategory.large)
|
||||
expectFalse(UIContentSizeCategory.large > UIContentSizeCategory.large)
|
||||
expectFalse(UIContentSizeCategory.large < UIContentSizeCategory.large)
|
||||
|
||||
expectTrue(UIContentSizeCategory.accessibilityExtraExtraExtraLarge.isAccessibilityCategory)
|
||||
expectFalse(UIContentSizeCategory.extraSmall.isAccessibilityCategory)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(iOS) || os(watchOS) || os(tvOS)
|
||||
UIKitTests.test("UIFontMetrics scaling") {
|
||||
if #available(iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
|
||||
let metrics = UIFontTextStyle.headline.metrics
|
||||
expectTrue(metrics != nil)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(iOS) || os(tvOS)
|
||||
UIKitTests.test("UIFocusEnvironment") {
|
||||
if #available(iOS 11.0, tvOS 11.0, *) {
|
||||
let item1 = UIView()
|
||||
let item2 = UIView()
|
||||
_ = item1.contains(item2)
|
||||
_ = item1.isFocused
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
runAllTests()
|
||||
|
||||
@@ -279,9 +279,6 @@ simdTestSuite.test("matrix init") {
|
||||
}
|
||||
}
|
||||
|
||||
// Round-trip through C matrix type.
|
||||
expectEqualTest(${mat}, ${mattype}(${mat}.cmatrix), sameValue: same)
|
||||
|
||||
% end # for rows
|
||||
% end # for cols
|
||||
% end # for type
|
||||
|
||||
@@ -1486,7 +1486,7 @@ function calculate_targets_for_host() {
|
||||
}
|
||||
|
||||
|
||||
COMMON_C_FLAGS=""
|
||||
COMMON_C_FLAGS=" -Wno-unknown-warning-option -Werror=unguarded-availability-new"
|
||||
|
||||
# Convert to an array.
|
||||
eval COMMON_CMAKE_OPTIONS=(${COMMON_CMAKE_OPTIONS})
|
||||
@@ -1589,34 +1589,34 @@ function common_cross_c_flags() {
|
||||
|
||||
case $1 in
|
||||
iphonesimulator-i386)
|
||||
echo "-arch i386 -mios-simulator-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
echo -n " -arch i386 -mios-simulator-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
;;
|
||||
iphonesimulator-x86_64)
|
||||
echo "-arch x86_64 -mios-simulator-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
echo -n " -arch x86_64 -mios-simulator-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
;;
|
||||
iphoneos-armv7)
|
||||
echo "-arch armv7 -miphoneos-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
echo -n " -arch armv7 -miphoneos-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
;;
|
||||
iphoneos-armv7s)
|
||||
echo "-arch armv7s -miphoneos-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
echo -n " -arch armv7s -miphoneos-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
;;
|
||||
iphoneos-arm64)
|
||||
echo "-arch arm64 -miphoneos-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
echo -n " -arch arm64 -miphoneos-version-min=${DARWIN_DEPLOYMENT_VERSION_IOS}"
|
||||
;;
|
||||
appletvsimulator-x86_64)
|
||||
echo "-arch x86_64 -mtvos-simulator-version-min=${DARWIN_DEPLOYMENT_VERSION_TVOS}"
|
||||
echo -n " -arch x86_64 -mtvos-simulator-version-min=${DARWIN_DEPLOYMENT_VERSION_TVOS}"
|
||||
;;
|
||||
appletvos-arm64)
|
||||
echo "-arch arm64 -mtvos-version-min=${DARWIN_DEPLOYMENT_VERSION_TVOS}"
|
||||
echo -n " -arch arm64 -mtvos-version-min=${DARWIN_DEPLOYMENT_VERSION_TVOS}"
|
||||
;;
|
||||
watchsimulator-i386)
|
||||
echo "-arch i386 -mwatchos-simulator-version-min=${DARWIN_DEPLOYMENT_VERSION_WATCHOS}"
|
||||
echo -n " -arch i386 -mwatchos-simulator-version-min=${DARWIN_DEPLOYMENT_VERSION_WATCHOS}"
|
||||
;;
|
||||
watchos-armv7k)
|
||||
echo "-arch armv7k -mwatchos-version-min=${DARWIN_DEPLOYMENT_VERSION_WATCHOS}"
|
||||
echo -n " -arch armv7k -mwatchos-version-min=${DARWIN_DEPLOYMENT_VERSION_WATCHOS}"
|
||||
;;
|
||||
android-armv7)
|
||||
echo "-arch armv7"
|
||||
echo -n " -arch armv7"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ class StdlibDeploymentTarget(object):
|
||||
|
||||
iOS = DarwinPlatform("iphoneos", archs=["armv7", "armv7s", "arm64"],
|
||||
sdk_name="IOS")
|
||||
iOSSimulator = DarwinPlatform("iphonesimulator", archs=["i386", "x86_64"],
|
||||
iOSSimulator = DarwinPlatform("iphonesimulator", archs=["x86_64"],
|
||||
sdk_name="IOS_SIMULATOR",
|
||||
is_simulator=True)
|
||||
|
||||
|
||||
@@ -1545,6 +1545,9 @@ class NonContiguousNSString : NSString {
|
||||
required init(coder aDecoder: NSCoder) {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
required init(itemProviderData data: Data, typeIdentifier: String) throws {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
|
||||
@nonobjc
|
||||
convenience init(_ utf8: [UInt8]) {
|
||||
|
||||
@@ -88,6 +88,10 @@ class NonContiguousNSString : NSString {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
|
||||
required init(itemProviderData data: Data, typeIdentifier: String) throws {
|
||||
fatalError("don't call this initializer")
|
||||
}
|
||||
|
||||
@nonobjc
|
||||
init(_ value: [UInt16]) {
|
||||
_value = value
|
||||
|
||||
@@ -184,6 +184,30 @@ XCTestTestSuite.test("XCTAssertEqual/Dictionary<T, U>") {
|
||||
expectFalse(failingTestRun.hasSucceeded)
|
||||
}
|
||||
|
||||
XCTestTestSuite.test("XCTAssertEqual/XCTAssertNotEqual + accuracy") {
|
||||
class AssertEqualTestCase: XCTestCase {
|
||||
dynamic func test_whenEqual_passes() {
|
||||
XCTAssertEqual(1, 1.09, accuracy: 0.1)
|
||||
XCTAssertNotEqual(1, 1.11, accuracy: 0.1)
|
||||
}
|
||||
|
||||
dynamic func test_whenNotEqual_fails() {
|
||||
XCTAssertEqual(1, 1.11, accuracy: 0.1)
|
||||
XCTAssertNotEqual(1, 1.09, accuracy: 0.1)
|
||||
}
|
||||
}
|
||||
|
||||
let passingTestCase = AssertEqualTestCase(selector: #selector(AssertEqualTestCase.test_whenEqual_passes))
|
||||
execute(passingTestCase.run)
|
||||
expectTrue(passingTestCase.testRun!.hasSucceeded)
|
||||
|
||||
let failingTestCase = AssertEqualTestCase(selector: #selector(AssertEqualTestCase.test_whenNotEqual_fails))
|
||||
execute(failingTestCase.run)
|
||||
let failingTestRun = failingTestCase.testRun!
|
||||
expectEqual(2, failingTestRun.failureCount)
|
||||
expectEqual(0, failingTestRun.unexpectedExceptionCount)
|
||||
}
|
||||
|
||||
XCTestTestSuite.test("XCTAssertThrowsError") {
|
||||
class ErrorTestCase: XCTestCase {
|
||||
var doThrow = true
|
||||
@@ -407,5 +431,34 @@ XCTestTestSuite.test("Test methods that wind up throwing") {
|
||||
|
||||
}
|
||||
|
||||
XCTestTestSuite.test("XCTContext/runActivity(named:block:)") {
|
||||
class RunActivityTestCase: XCTestCase {
|
||||
|
||||
dynamic func test_noThrow() {
|
||||
var blockCalled = false
|
||||
XCTContext.runActivity(named: "noThrow") { activity in
|
||||
blockCalled = true
|
||||
}
|
||||
expectTrue(blockCalled)
|
||||
}
|
||||
|
||||
dynamic func test_throwing() {
|
||||
var blockCalled = false
|
||||
var catchCalled = false
|
||||
do {
|
||||
try XCTContext.runActivity(named: "throwing") { activity in
|
||||
blockCalled = true
|
||||
throw NSError(domain: "MyDomain", code: -1, userInfo: nil)
|
||||
}
|
||||
} catch {
|
||||
catchCalled = true
|
||||
}
|
||||
expectTrue(blockCalled)
|
||||
expectTrue(catchCalled)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
runAllTests()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user