Resolve conflicts with upstream

This commit is contained in:
Patrick Pijnappel
2016-05-05 08:55:34 +02:00
2843 changed files with 124882 additions and 59649 deletions

3
.gitignore vendored
View File

@@ -16,7 +16,7 @@
# Byte compiled python modules.
*.pyc
# vim swap files
.*.swp
.*.sw[a-z]
.sw?
#==============================================================================#
@@ -39,3 +39,4 @@ docs/_build
#==============================================================================#
CMakeCache.txt
CMakeFiles
.atom-build.json

2
.pep8
View File

@@ -1,2 +1,2 @@
[flake8]
filename = *.py,Benchmark_Driver,Benchmark_DTrace.in,Benchmark_GuardMalloc.in,Benchmark_RuntimeLeaksRunner.in,build-script,gyb,line-directive,ns-html2rst,recursive-lipo,rth,submit-benchmark-results,update-checkout,viewcfg
filename = *.py,80+-check,Benchmark_Driver,Benchmark_DTrace.in,Benchmark_GuardMalloc.in,Benchmark_RuntimeLeaksRunner.in,build-script,gyb,line-directive,mock-distcc,ns-html2rst,recursive-lipo,rth,split-generated-tests,submit-benchmark-results,update-checkout,viewcfg

View File

@@ -1,6 +1,149 @@
Note: This is in reverse chronological order, so newer entries are added to the top.
Swift 3.0
-------
---------
* [SE-0071](https://github.com/apple/swift-evolution/blob/master/proposals/0071-member-keywords.md):
"Allow (most) keywords in member references" is implemented. This allows the
use of members after a dot without backticks, e.g. "foo.default".
* [SE-0057](https://github.com/apple/swift-evolution/blob/master/proposals/0057-importing-objc-generics.md):
Objective-C lightweight generic classes are now imported as generic types
in Swift. Because Objective-C generics are not represented at runtime,
there are some limitations on what can be done with them in Swift:
- If an ObjC generic class is used in a checked `as?`, `as!`, or `is` cast,
the generic parameters are not checked at runtime. The cast succeeds if the
operand is an instance of the ObjC class, regardless of parameters.
```swift
let x = NSFoo<NSNumber>(value: NSNumber(integer: 0))
let y: AnyObject = x
let z = y as! NSFoo<NSString> // Succeeds
```
- Swift subclasses can only inherit an ObjC generic class if its generic
parameters are fully specified.
```swift
// Error: Can't inherit ObjC generic class with unbound parameter T
class SwiftFoo1<T>: NSFoo<T> { }
// OK: Can inherit ObjC generic class with specific parameters
class SwiftFoo2<T>: NSFoo<NSString> { }
```
- Swift can extend ObjC generic classes, but the extensions cannot be
constrained, and definitions inside the extension do not have access to
the class's generic parameters.
```swift
extension NSFoo {
// Error: Can't access generic param T
func foo() -> T {
return T()
}
}
// Error: extension can't be constrained
extension NSFoo where T: NSString {
}
```
- Foundation container classes `NS[Mutable]Array`, `NS[Mutable]Set`, and
`NS[Mutable]Dictionary` are still imported as nongeneric classes for
the time being.
* As part of the changes for SE-0055 (see below), the *pointee* types of
imported pointers (e.g. the `id` in `id *`) are no longer assumed to always
be `_Nullable` even if annotated otherwise. However, an implicit or explicit
annotation of `_Null_unspecified` on a pointee type is still imported as
`Optional`.
* [SE-0055](https://github.com/apple/swift-evolution/blob/master/proposals/0055-optional-unsafe-pointers.md):
The types `UnsafePointer`, `UnsafeMutablePointer`,
`AutoreleasingUnsafeMutablePointer`, `OpaquePointer`, `Selector`, and `Zone`
(formerly `NSZone`) now represent non-nullable pointers, i.e. pointers that
are never `nil`. A nullable pointer is now represented using `Optional`, e.g.
`UnsafePointer<Int>?` For types imported from C, non-object pointers (such as
`int *`) now have their nullability taken into account.
One possible area of difficulty is passing a nullable pointer to a function
that uses C variadics. Swift will not permit this directly, so as a
workaround please use the following idiom to pass it as a pointer-sized
integer value instead:
```swift
unsafeBitCast(nullablePointer, to: Int.self)
```
* [SE-0046] (https://github.com/apple/swift-evolution/blob/master/proposals/0046-first-label.md) Function parameters now have consistent labelling across all function parameters. With this update the first parameter declarations will now match the existing behavior of the second and later parameters. This change makes the language simpler.
Functions that were written and called as follows
```swift
func foo(x: Int, y: Int) {
}
foo(1, y: 2)
func bar(a a: Int, b: Int) {
}
bar(a: 3, b: 4)
```
will now be written as (to achieve the same behavior):
```swift
func foo(_ x: Int, y: Int) {}
foo(1, y: 2)
func bar(a: Int, b: Int) {}
bar(a: 3, b: 4)
```
* [SE-0037](https://github.com/apple/swift-evolution/blob/master/proposals/0037-clarify-comments-and-operators.md)
Comments are now treated as whitespace when determining whether an operator is
prefix, postfix, or binary. For example, these now work:
```swift
if /*comment*/!foo { ... }
1 +/*comment*/2
```
This also means that comments can no longer appear between a unary operator
and its argument.
```swift
foo/* comment */! // no longer works
```
Any parse errors resulting from this change can be resolved by moving the
comment outside of the expression.
* [SE-0031](https://github.com/apple/swift-evolution/blob/master/proposals/0031-adjusting-inout-declarations.md) The location of the inout attribute has been moved to after the `:` and before the parameter type.
```swift
func foo(inout x: Int) {
}
```
will now be written as:
```swift
func foo(x: inout Int) {
}
```
* [SE-0053](https://github.com/apple/swift-evolution/blob/master/proposals/0053-remove-let-from-function-parameters.md) `let` is no longer accepted as a parameter attribute for functions. The compiler provides a fixit to remove it from the function declaration.
* [SE-0003](https://github.com/apple/swift-evolution/blob/master/proposals/0003-remove-var-parameters.md) `var` is no longer accepted as a parameter attribute for functions. The compiler provides a fixit to create a shadow copy in the function body.
```swift
func foo(var x: Int) {
}
```
will now be written as:
```swift
func foo(x: Int) {
var x = x
}
```
* The "none" members of imported NS_OPTIONS option sets are marked as unavailable
when they are imported. Use [] to make an empty option set, instead of a None member.
* [SE-0043](https://github.com/apple/swift-evolution/blob/master/proposals/0043-declare-variables-in-case-labels-with-multiple-patterns.md)
landed, adding the ability to declare variables in multiple patterns in cases.
* Renamification landed, so the Clang importer imports ObjC symbols
substantially differently. *Someone should expand on this point.*
@@ -14,7 +157,7 @@ Swift 3.0
typealias StringDictionary<T> = Dictionary<String, T>
typealias IntFunction<T> = (T) -> Int
typealias MatchingTriple<T> = (T, T, T)
typealias BackwardTriple<T1,T2,T3> = (T3, T2, T1)
typealias BackwardTriple<T1, T2, T3> = (T3, T2, T1)
```
etc.
@@ -61,6 +204,13 @@ Swift 3.0
}
}
```
* Throwing closure arguments of a rethrowing function may now be optional. For example:
```swift
func executeClosureIfNotNil(closure: (() throws -> Void)?) rethrows {
try closure?()
}
```
Swift 2.2
---------
@@ -791,7 +941,7 @@ Swift 2.2
structures to be defined. For example:
```swift
enum List<T> {
enum List<T> {
case Nil
indirect case Cons(head: T, tail: List<T>)
}
@@ -1039,7 +1189,7 @@ Swift 2.2
needs to be written as:
```swift
var (a,b) : (Int, Float) = foo()
var (a, b) : (Int, Float) = foo()
```
if an explicit type annotation is needed. The former syntax was ambiguous
@@ -1835,10 +1985,10 @@ Swift 2.2
2014-10-09 [Roughly Xcode 6.1, and Swift 1.1]
----------
* `HeapBuffer<Value,Element>`, `HeapBufferStorage<Value,Element>`, and
* `HeapBuffer<Value, Element>`, `HeapBufferStorage<Value, Element>`, and
`OnHeap<Value>` were never really useful, because their APIs were
insufficiently public. They have been replaced with a single class,
`ManagedBuffer<Value,Element>`. See also the new function
`ManagedBuffer<Value, Element>`. See also the new function
`isUniquelyReferenced(x)` which is often useful in conjunction with
`ManagedBuffer`.
@@ -1941,7 +2091,7 @@ Swift 2.2
```swift
enum Foo: Int { case A = 0, B = 1, C = 2 }
let foo = Foo(rawValue: 2)! // formerly 'Foo.fromRaw(2)!'
println(foo.rawValue) // formerly 'foo.toRaw()'
println(foo.rawValue) // formerly 'foo.toRaw()'
```
2014-09-02
@@ -2646,7 +2796,7 @@ Swift 2.2
In many common cases, this will just work. Unfortunately, values
are returned from `CF`-style APIs in a wide variety of ways, and
unlike Objective C methods, there simply isn't enough consistency
unlike Objective-C methods, there simply isn't enough consistency
for Swift to be able to safely apply the documented conventions
universally. The framework teams have already audited many of the
most important `CF`-style APIs, and those APIs should be imported
@@ -3875,7 +4025,7 @@ Swift 2.2
```swift
func swap<T>(a : @inout T, b : @inout T) {
(a,b) = (b,a)
(a, b) = (b, a)
}
```
@@ -3883,7 +4033,7 @@ Swift 2.2
```swift
func swap<T>(inout a : T, inout b : T) {
(a,b) = (b,a)
(a, b) = (b, a)
}
```
@@ -4744,8 +4894,8 @@ Swift 2.2
* Array and dictionary literals allow an optional trailing comma:
```swift
var a = [ 1, 2, ]
var d = [ "a": 1, "b": 2, ]
var a = [1, 2,]
var d = ["a": 1, "b": 2,]
```
2013-10-16

View File

@@ -32,6 +32,10 @@ option(SWIFT_SERIALIZE_STDLIB_UNITTEST
"Compile the StdlibUnittest module with -sil-serialize-all to increase the test coverage for the optimizer"
FALSE)
option(SWIFT_STDLIB_SIL_DEBUGGING
"Compile the Swift standard library with -gsil to enable debugging and profiling on SIL level"
FALSE)
option(SWIFT_BUILD_TOOLS
"Build the Swift compiler and other tools"
TRUE)
@@ -58,6 +62,10 @@ option(SWIFT_INCLUDE_DOCS
"Create targets for building docs."
TRUE)
option(SWIFT_BUILD_RUNTIME_WITH_HOST_COMPILER
"Use the host compiler and not the internal clang to build the swift runtime"
FALSE)
set(SWIFT_ANALYZE_CODE_COVERAGE FALSE CACHE STRING
"Build Swift with code coverage instrumenting enabled [FALSE, NOT-MERGED, MERGED]")
set_property(CACHE SWIFT_ANALYZE_CODE_COVERAGE PROPERTY
@@ -78,7 +86,7 @@ set(SWIFT_ENABLE_GOLD_LINKER FALSE CACHE BOOL
"Enable using the gold linker when available")
set(_SWIFT_KNOWN_INSTALL_COMPONENTS
"compiler;clang-builtin-headers;clang-resource-dir-symlink;clang-builtin-headers-in-clang-resource-dir;stdlib;stdlib-experimental;sdk-overlay;editor-integration;tools;testsuite-tools;dev;license;sourcekit-xpc-service;sourcekit-inproc")
"autolink-driver;compiler;clang-builtin-headers;clang-resource-dir-symlink;clang-builtin-headers-in-clang-resource-dir;stdlib;stdlib-experimental;sdk-overlay;editor-integration;tools;testsuite-tools;toolchain-dev-tools;dev;license;sourcekit-xpc-service;sourcekit-inproc;swift-remote-mirror-headers")
# Set the SWIFT_INSTALL_COMPONENTS variable to the default value if it is not passed in via -D
set(SWIFT_INSTALL_COMPONENTS "${_SWIFT_KNOWN_INSTALL_COMPONENTS}" CACHE STRING
@@ -87,6 +95,7 @@ set(SWIFT_INSTALL_COMPONENTS "${_SWIFT_KNOWN_INSTALL_COMPONENTS}" CACHE STRING
# components would approximately correspond to packages in a Debian-style Linux
# packaging. The following components are defined:
#
# * autolink-driver -- the Swift driver support tools
# * compiler -- the Swift compiler and (on supported platforms) the REPL.
# * clang-builtin-headers -- install a copy of Clang builtin headers under
# 'lib/swift/clang'. This is useful when Swift compiler is installed in
@@ -103,6 +112,7 @@ set(SWIFT_INSTALL_COMPONENTS "${_SWIFT_KNOWN_INSTALL_COMPONENTS}" CACHE STRING
# * tools -- tools (other than the compiler) useful for developers writing
# Swift code.
# * testsuite-tools -- extra tools required to run the Swift testsuite.
# * toolchain-dev-tools -- install development tools useful in a shared toolchain
# * dev -- headers and libraries required to use Swift compiler as a library.
set(SWIFT_SDKS "" CACHE STRING
@@ -128,6 +138,20 @@ option(SWIFT_ENABLE_LTO
# The following only works with the Ninja generator in CMake >= 3.0.
set(SWIFT_PARALLEL_LINK_JOBS "" CACHE STRING
"Define the maximum number of linker jobs for swift.")
set(SWIFT_ANDROID_NDK_PATH "" CACHE STRING
"Path to the directory that contains the Android NDK tools that are executable on the build machine")
set(SWIFT_ANDROID_NDK_GCC_VERSION "" CACHE STRING
"The GCC version to use when building for Android. Currently only 4.9 is supported.")
set(SWIFT_ANDROID_SDK_PATH "" CACHE STRING
"Path to the directory that contains the Android SDK tools that will be passed to the swiftc frontend")
set(SWIFT_ANDROID_ICU_UC "" CACHE STRING
"Path to a directory containing libicuuc.so")
set(SWIFT_ANDROID_ICU_UC_INCLUDE "" CACHE STRING
"Path to a directory containing headers for libicuuc")
set(SWIFT_ANDROID_ICU_I18N "" CACHE STRING
"Path to a directory containing libicui18n.so")
set(SWIFT_ANDROID_ICU_I18N_INCLUDE "" CACHE STRING
"Path to a directory containing headers libicui18n")
#
# User-configurable Darwin-specific options.
@@ -206,14 +230,27 @@ option(SWIFT_STDLIB_ENABLE_RESILIENCE
"Build the standard libraries and overlays with resilience enabled; see docs/LibraryEvolution.rst"
FALSE)
option(SWIFT_STDLIB_ENABLE_REFLECTION_METADATA
"Build the standard libraries and overlays with remote reflection metadata; see docs/proposals/RemoteMirrors.rst"
TRUE)
option(SWIFT_STDLIB_ENABLE_REFLECTION_NAMES
"Build the standard libraries and overlays with remote reflection names; see docs/proposals/RemoteMirrors.rst"
FALSE)
option(SWIFT_STDLIB_SIL_SERIALIZE_ALL
"Build the standard libraries and overlays serializing all method bodies"
TRUE)
if(SWIFT_SERIALIZE_STDLIB_UNITTEST AND SWIFT_STDLIB_ENABLE_RESILIENCE)
message(WARNING "Ignoring SWIFT_SERIALIZE_STDLIB_UNITTEST because SWIFT_STDLIB_ENABLE_RESILIENCE is set")
set(SWIFT_SERIALIZE_STDLIB_UNITTEST FALSE)
endif()
option(SWIFT_XCODE_GENERATE_FOR_IDE_ONLY
"Generate an Xcode project suitable for IDE use, but which cannot build"
FALSE)
if(SWIFT_STDLIB_SIL_SERIALIZE_ALL AND SWIFT_STDLIB_ENABLE_RESILIENCE)
message(WARNING "Ignoring SWIFT_STDLIB_SIL_SERIALIZE_ALL because SWIFT_STDLIB_ENABLE_RESILIENCE is set")
set(SWIFT_STDLIB_SIL_SERIALIZE_ALL FALSE)
endif()
#
# End of user-configurable options.
@@ -265,7 +302,10 @@ else()
endif()
# lipo is used to create universal binaries.
find_program(LIPO "lipo")
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
include(SwiftDarwin)
find_toolchain_tool(LIPO "${SWIFT_DARWIN_XCRUN_TOOLCHAIN}" lipo)
endif()
if("${SWIFT_NATIVE_LLVM_TOOLS_PATH}" STREQUAL "")
set(SWIFT_CROSS_COMPILING FALSE)
@@ -333,7 +373,7 @@ set(SWIFT_GYB_FLAGS
# Directory to use as the Clang module cache when building Swift source files.
set(SWIFT_MODULE_CACHE_PATH
"${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/clang-module-cache")
"${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/module-cache")
# Xcode: use libc++ and c++11 using proper build settings.
if(XCODE)
@@ -407,9 +447,33 @@ if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
# FIXME: This will not work while trying to cross-compile.
if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
configure_sdk_unix(LINUX "Linux" "linux" "linux" "x86_64" "x86_64-unknown-linux-gnu")
set(SWIFT_HOST_VARIANT_ARCH "x86_64")
set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64")
if("${SWIFT_ANDROID_NDK_PATH}" STREQUAL "")
set(swift_can_crosscompile_stdlib FALSE)
else()
set(swift_can_crosscompile_stdlib TRUE)
endif()
is_sdk_requested(LINUX swift_build_linux)
if(swift_build_linux)
configure_sdk_unix(LINUX "Linux" "linux" "linux" "x86_64" "x86_64-unknown-linux-gnu")
set(SWIFT_PRIMARY_VARIANT_SDK_default "LINUX")
set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64")
endif()
is_sdk_requested(ANDROID swift_build_android)
if(swift_build_android AND ${swift_can_crosscompile_stdlib})
configure_sdk_unix(ANDROID "Android" "android" "android" "armv7" "armv7-none-linux-androideabi")
# This must be set, as variables such as "${SWIFT_SDK_${sdk}_PATH}" are
# referenced in several other locations.
set(SWIFT_SDK_ANDROID_PATH "${SWIFT_ANDROID_SDK_PATH}")
set(SWIFT_PRIMARY_VARIANT_SDK_default "ANDROID")
set(SWIFT_PRIMARY_VARIANT_ARCH_default "armv7")
endif()
# FIXME: This only matches ARMv6l (by far the most common variant).
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv6l")
configure_sdk_unix(LINUX "Linux" "linux" "linux" "armv6" "armv6-unknown-linux-gnueabihf")
@@ -636,6 +700,13 @@ if(SWIFT_PARALLEL_LINK_JOBS)
endif()
endif()
# Set the CMAKE_OSX_* variables in a way that minimizes conflicts.
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
set(CMAKE_OSX_SYSROOT "${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_PATH}")
set(CMAKE_OSX_ARCHITECTURES "")
set(CMAKE_OSX_DEPLOYMENT_TARGET "")
endif()
message(STATUS "Building host Swift tools for ${SWIFT_HOST_VARIANT_SDK} ${SWIFT_HOST_VARIANT_ARCH}")
message(STATUS " Build type: ${CMAKE_BUILD_TYPE}")
message(STATUS " Assertions: ${LLVM_ENABLE_ASSERTIONS}")
@@ -669,7 +740,11 @@ endif()
#
# Set up global CMake variables for API notes.
#
# API notes version 1.0.0
#
# Change the above comment to 'touch' this file and keep incremental builds
# working when adding a new apinotes file.
#
set(SWIFT_API_NOTES_PATH "${SWIFT_SOURCE_DIR}/apinotes")
if(NOT EXISTS "${SWIFT_API_NOTES_PATH}/Foundation.apinotes")
message(FATAL_ERROR "API notes are not available in ${SWIFT_API_NOTES_PATH}")
@@ -687,8 +762,19 @@ if(SWIFT_BUILD_TOOLS)
add_subdirectory(lib)
add_subdirectory(tools)
endif()
is_sdk_requested("${SWIFT_HOST_VARIANT_SDK}" SWIFT_HOST_SDK_REQUESTED)
if(SWIFT_BUILD_TOOLS AND SWIFT_BUILD_STDLIB AND SWIFT_HOST_SDK_REQUESTED)
add_subdirectory(tools/swift-reflection-dump)
endif()
add_subdirectory(utils)
add_subdirectory(stdlib)
if(SWIFT_BUILD_STDLIB AND SWIFT_INCLUDE_TESTS)
add_subdirectory(tools/swift-reflection-test)
endif()
if(SWIFT_BUILD_PERF_TESTSUITE AND "${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
add_subdirectory(benchmark)
endif()

View File

@@ -5,8 +5,7 @@ what goes in or not.
The list is sorted by surname and formatted to allow easy grepping and
beautification by scripts. The fields are: name (N), email (E), web-address
(W), PGP key ID and fingerprint (P), description (D), and snail-mail address
(S).
(W), description (D).
N: David Abrahams
E: dabrahams@apple.com

View File

@@ -30,7 +30,7 @@ To read the documentation, start by installing the
More recent versions are currently **not supported.**
Once complete, you can build the Swift documentation by changing directory into
`docs` and typing `make`. This compiles the `.rst` files in the `docs` directory
[docs](https://github.com/apple/swift/tree/master/docs) and typing `make`. This compiles the `.rst` files in the [docs](https://github.com/apple/swift/tree/master/docs) directory
into HTML in the `docs/_build/html` directory.
Many of the docs are out of date, but you can see some historical design
@@ -90,7 +90,7 @@ uploading SSH keys to GitHub):
[CMake](http://cmake.org) is the core infrastructure used to configure builds of
Swift and its companion projects; at least version 2.8.12.2 is required. Your
favorite Linux distribution likely already has a CMake package you can install.
On OS X, you can download the [CMake Binary Distribution](https://cmake.org/install),
On OS X, you can download the [CMake Binary Distribution](https://cmake.org/download),
bundled as an application, copy it to `/Applications`, and add the embedded
command line tools to your `PATH`:
@@ -115,7 +115,7 @@ it next to the other projects and it will be bootstrapped automatically:
git checkout release
cat README
#### Install via third-party packaging tool (OSX only)
#### Install via third-party packaging tool (OS X only)
**[Homebrew](http://brew.sh/)**
@@ -139,28 +139,20 @@ To find out more:
Note: Arguments after "--" above are forwarded to `build-script-impl`, which is
the ultimate shell script that invokes the actual build and test commands.
A basic command to build Swift and run basic tests with Ninja:
A basic command to build Swift with optimizations and run basic tests with
Ninja:
utils/build-script -t
utils/build-script -r -t
## Developing Swift in Xcode
`build-script` can also generate Xcode projects:
utils/build-script -x
The Xcode IDE can be used to edit the Swift source code, but it is not currently
fully supported as a build environment for SDKs other than OS X. If you'd like
to build for other SDKs but still use Xcode, once you've built Swift using Ninja
or one of the other supported CMake generators, you can set up an IDE-only Xcode
environment using the build-script's `-X` flag:
utils/build-script -X --skip-build -- --reconfigure
The `--skip-build` flag tells `build-script` to only generate the project,
not build it in its entirety. A bare minimum of LLVM tools will build in order
to configure the Xcode projects.
The `--reconfigure` flag tells `build-script-impl` to run the CMake configuration
step even if there is a cached configuration. As you develop in Xcode, you may
need to rerun this from time to time to refresh your generated Xcode project,
picking up new targets, file removals, or file additions.
fully supported as a build environment for SDKs other than OS X. If you need to
work with other SDKs, you'll need to create a second build using Ninja.
## Testing Swift
@@ -170,7 +162,7 @@ See [docs/Testing.rst](docs/Testing.rst).
Contributions to Swift are welcomed and encouraged! Please see the [Contributing to Swift guide](https://swift.org/contributing/).
To be a truly great community, Swift.org needs to welcome developers from all
To be a truly great community, [Swift.org](https://swift.org/) needs to welcome developers from all
walks of life, with different backgrounds, and with a wide range of experience.
A diverse and friendly community will have more great ideas, more unique
perspectives, and produce more great code. We will work diligently to make the
@@ -179,4 +171,4 @@ Swift community welcoming to everyone.
To give clarity of what is expected of our members, Swift has adopted the
code of conduct defined by the Contributor Covenant. This document is used
across many open source communities, and we think it articulates our values
well. For more, see [the website](https://swift.org/community/#code-of-conduct).
well. For more, see the [Code of Conduct](https://swift.org/community/#code-of-conduct).

View File

@@ -0,0 +1,66 @@
---
Name: AVFoundation
Classes:
- Name: AVAssetWriterInput
Methods:
- Selector: 'appendSampleBuffer:'
SwiftName: 'appendSampleBuffer(_:)'
MethodKind: Instance
- Name: AVAssetWriterInputPixelBufferAdaptor
Methods:
- Selector: 'appendPixelBuffer:withPresentationTime:'
SwiftName: 'appendPixelBuffer(_:withPresentationTime:)'
MethodKind: Instance
- Name: AVAssetWriterInputMetadataAdaptor
Methods:
- Selector: 'appendTimedMetadataGroup:'
SwiftName: 'appendTimedMetadataGroup(_:)'
MethodKind: Instance
- Name: AVMutableComposition
Methods:
- Selector: 'insertTimeRange:ofAsset:atTime:error:'
SwiftName: 'insertTimeRange(_:of:at:)'
MethodKind: Instance
- Selector: 'insertEmptyTimeRange:'
SwiftName: 'insertEmptyTimeRange(_:)'
MethodKind: Instance
- Selector: 'removeTimeRange:'
SwiftName: 'removeTimeRange(_:)'
MethodKind: Instance
- Name: AVPlayerItem
Methods:
- Selector: 'selectMediaOption:inMediaSelectionGroup:'
SwiftName: 'select(_:in:)'
MethodKind: Instance
- Name: AVSampleCursor
Methods:
- Selector: 'stepByDecodeTime:wasPinned:'
SwiftName: 'step(byDecodeTime:wasPinned:)'
MethodKind: Instance
- Selector: 'samplesWithEarlierDecodeTimeStampsMayHaveLaterPresentationTimeStampsThanCursor:'
SwiftName: 'maySamplesWithEarlierDecodeTimeStampsHavePresentationTimeStamps(laterThan:)'
MethodKind: Instance
- Selector: 'samplesWithLaterDecodeTimeStampsMayHaveEarlierPresentationTimeStampsThanCursor:'
SwiftName: 'maySamplesWithLaterDecodeTimeStampsHavePresentationTimeStamps(earlierThan:)'
MethodKind: Instance
- Name: AVVideoComposition
Methods:
- Selector: 'videoCompositionWithPropertiesOfAsset:'
SwiftName: 'init(withPropertiesOf:)'
MethodKind: Instance
- Name: AVMutableVideoCompositionLayerInstruction
Methods:
- Selector: 'setTransformRampFromStartTransform:toEndTransform:timeRange:'
SwiftName: 'setTransformRamp(fromStart:toEnd:timeRange:)'
MethodKind: Instance
Protocols:
- Name: AVVideoCompositing
Methods:
- Selector: 'startVideoCompositionRequest:'
SwiftName: 'startRequest(_:)'
MethodKind: Instance
- Name: AVVideoCompositionValidationHandling
Methods:
- Selector: 'videoComposition:shouldContinueValidatingAfterFindingEmptyTimeRange:'
SwiftName: 'videoComposition(_:shouldContinueValidatingAfterFindingEmptyTimeRange:)'
MethodKind: Instance

133
apinotes/CoreData.apinotes Normal file
View File

@@ -0,0 +1,133 @@
---
Name: CoreData
Classes:
- Name: NSAtomicStore
Methods:
- Selector: 'objectIDForEntity:referenceObject:'
SwiftName: 'objectID(for:withReferenceObject:)'
MethodKind: Instance
- Name: NSEntityDescription
Methods:
- Selector: 'entityForName:inManagedObjectContext:'
SwiftName: 'entity(forEntityName:in:)'
MethodKind: Class
- Selector: 'insertNewObjectForEntityForName:inManagedObjectContext:'
SwiftName: 'insertNewObject(forEntityName:into:)'
MethodKind: Class
- Selector: 'relationshipsWithDestinationEntity:'
SwiftName: 'relationships(forDestination:)'
MethodKind: Instance
- Selector: 'isKindOfEntity:'
SwiftName: 'isKindOf(entity:)'
MethodKind: Instance
- Name: NSEntityMigrationPolicy
Methods:
- Selector: 'beginEntityMapping:manager:error:'
SwiftName: 'begin(_:with:)'
MethodKind: Instance
- Selector: 'createDestinationInstancesForSourceInstance:entityMapping:manager:error:'
SwiftName: 'createDestinationInstances(forSource:in:manager:)'
MethodKind: Instance
- Selector: 'endInstanceCreationForEntityMapping:manager:error:'
SwiftName: 'endInstanceCreation(forMapping:manager:)'
MethodKind: Instance
- Selector: 'createRelationshipsForDestinationInstance:entityMapping:manager:error:'
SwiftName: 'createRelationships(forDestination:in:manager:)'
MethodKind: Instance
- Selector: 'endRelationshipCreationForEntityMapping:manager:error:'
SwiftName: 'endRelationshipCreation(forMapping:manager:)'
MethodKind: Instance
- Selector: 'performCustomValidationForEntityMapping:manager:error:'
SwiftName: 'performCustomValidation(forMapping:manager:)'
MethodKind: Instance
- Name: NSIncrementalStore
Methods:
- Selector: 'newObjectIDForEntity:referenceObject:'
SwiftName: 'newObjectID(for:referenceObject:)'
MethodKind: Instance
- Name: NSManagedObjectContext
Methods:
- Selector: 'performBlockAndWait:'
SwiftName: 'performAndWait(_:)'
MethodKind: Instance
- Selector: 'objectRegisteredForID:'
SwiftName: 'registeredObject(for:)'
MethodKind: Instance
- Selector: 'executeFetchRequest:error:'
SwiftName: 'fetch(_:)'
MethodKind: Instance
- Selector: 'refreshObject:mergeChanges:'
SwiftName: 'refresh(_:mergeChanges:)'
MethodKind: Instance
- Name: NSManagedObjectModel
Methods:
- Selector: 'entitiesForConfiguration:'
SwiftName: 'entities(forConfigurationName:)'
MethodKind: Instance
- Selector: 'setEntities:forConfiguration:'
SwiftName: 'setEntities(_:forConfigurationName:)'
MethodKind: Instance
- Selector: 'isConfiguration:compatibleWithStoreMetadata:'
SwiftName: 'isConfiguration(withName:compatibleWithStoreMetadata:)'
MethodKind: Instance
- Name: NSMergePolicy
Methods:
- Selector: 'resolveConflicts:error:'
SwiftName: 'resolve(mergeConflicts:)'
MethodKind: Instance
- Selector: 'resolveConstraintConflicts:error:'
SwiftName: 'resolve(constraintConflicts:)'
MethodKind: Instance
- Name: NSMigrationManager
Methods:
- Selector: 'migrateStoreFromURL:type:options:withMappingModel:toDestinationURL:destinationType:destinationOptions:error:'
SwiftName: 'migrateStore(from:sourceType:options:with:toDestinationURL:destinationType:destinationOptions:)'
MethodKind: Instance
- Selector: 'associateSourceInstance:withDestinationInstance:forEntityMapping:'
SwiftName: 'associate(sourceInstance:withDestinationInstance:for:)'
MethodKind: Instance
- Selector: 'destinationInstancesForEntityMappingNamed:sourceInstances:'
SwiftName: 'destinationInstances(forEntityMappingName:sourceInstances:)'
MethodKind: Instance
- Selector: 'sourceInstancesForEntityMappingNamed:destinationInstances:'
SwiftName: 'sourceInstances(forEntityMappingName:destinationInstances:)'
MethodKind: Instance
- Name: NSPersistentStore
Methods:
- Selector: 'setMetadata:forPersistentStoreWithURL:error:'
SwiftName: 'setMetadata(_:forPersistentStoreAt:)'
MethodKind: Class
- Selector: 'initWithPersistentStoreCoordinator:configurationName:URL:options:'
SwiftName: 'init(persistentStoreCoordinator:configurationName:at:options:)'
MethodKind: Instance
- Name: NSPersistentStoreCoordinator
Methods:
- Selector: 'addPersistentStoreWithType:configuration:URL:options:error:'
SwiftName: 'addPersistentStore(ofType:configurationName:at:options:)'
MethodKind: Instance
- Selector: 'removePersistentStore:error:'
SwiftName: 'remove(_:)'
MethodKind: Instance
- Selector: 'metadataForPersistentStoreOfType:URL:options:error:'
SwiftName: 'metadataForPersistentStore(ofType:at:options:)'
MethodKind: Class
- Selector: 'setMetadata:forPersistentStoreOfType:URL:options:error:'
SwiftName: 'setMetadata(_:forPersistentStoreOfType:at:options:)'
MethodKind: Class
- Selector: 'elementsDerivedFromExternalRecordURL:'
SwiftName: 'elementsDerived(fromExternalRecordAt:)'
MethodKind: Class
- Selector: 'importStoreWithIdentifier:fromExternalRecordsDirectory:toURL:options:withType:error:'
SwiftName: 'importStore(withIdentifier:fromExternalRecordsDirectoryAt:to:options:ofType:)'
MethodKind: Instance
- Name: NSSaveChangesRequest
Methods:
- Selector: 'initWithInsertedObjects:updatedObjects:deletedObjects:lockedObjects:'
SwiftName: 'init(inserted:updated:deleted:locked:)'
MethodKind: Instance
Protocols:
- Name: NSFetchedResultsControllerDelegate
Methods:
- Selector: 'controller:didChangeSection:atIndex:forChangeType:'
SwiftName: 'controller(_:didChange:atSectionIndex:for:)'
MethodKind: Instance

View File

@@ -0,0 +1,411 @@
---
Name: CoreGraphics
SwiftInferImportAsMember: true
#
# Global functions
#
Functions:
# The below are inline functions that are irrelevant due to memberwise inits
- Name: CGPointMake
Availability: nonswift
- Name: CGSizeMake
Availability: nonswift
- Name: CGVectorMake
Availability: nonswift
- Name: CGRectMake
Availability: nonswift
- Name: CGAffineTransformMake
Availability: nonswift
# The below are fixups that inference didn't quite do what we wanted, and are
# pulled over from what used to be in the overlays
- Name: CGRectIsNull
SwiftName: "getter:CGRect.isNull(self:)"
- Name: CGRectIsEmpty
SwiftName: "getter:CGRect.isEmpty(self:)"
- Name: CGRectIsInfinite
SwiftName: "getter:CGRect.isInfinite(self:)"
- Name: CGRectStandardize
SwiftName: "getter:CGRect.standardized(self:)"
- Name: CGRectIntegral
SwiftName: "getter:CGRect.integral(self:)"
- Name: CGRectInset
SwiftName: "CGRect.insetBy(self:dx:dy:)"
- Name: CGRectOffset
SwiftName: "CGRect.offsetBy(self:dx:dy:)"
- Name: CGRectUnion
SwiftName: "CGRect.union(self:_:)"
- Name: CGRectIntersection
SwiftName: "CGRect.intersection(self:_:)"
- Name: CGRectContainsRect
SwiftName: "CGRect.contains(self:_:)"
- Name: CGRectContainsPoint
SwiftName: "CGRect.contains(self:_:)"
- Name: CGRectIntersectsRect
SwiftName: "CGRect.intersects(self:_:)"
# The below are not available in Swift
# FIXME: empty-argument-label pattern is currently failing SILGen
- Name: CGColorSpaceCreateDeviceGray
SwiftName: CGColorSpaceCreateDeviceGray()
- Name: CGColorSpaceCreateDeviceRGB
SwiftName: CGColorSpaceCreateDeviceRGB()
- Name: CGColorSpaceCreateDeviceCMYK
SwiftName: CGColorSpaceCreateDeviceCMYK()
# TODO: make these unavailable, but they're needed for pre-iOS 9
# - Name: CGColorSpaceCreateDeviceGray
# Availability: nonswift
# - Name: CGColorSpaceCreateDeviceRGB
# Availability: nonswift
# - Name: CGColorSpaceCreateDeviceCMYK
# Availability: nonswift
# The below are attempts at providing better names than inference
# CGAffineTransform
- Name: CGAffineTransformMakeTranslation
SwiftName: CGAffineTransform.init(withTranslationX:y:)
- Name: CGAffineTransformMakeScale
SwiftName: CGAffineTransform.init(withScaleX:y:)
- Name: CGAffineTransformMakeRotation
SwiftName: CGAffineTransform.init(withRotationAngle:)
- Name: CGAffineTransformTranslate
SwiftName: CGAffineTransform.translateBy(self:x:y:)
- Name: CGAffineTransformScale
SwiftName: CGAffineTransform.scaleBy(self:x:y:)
- Name: CGAffineTransformRotate
SwiftName: CGAffineTransform.rotate(self:byAngle:)
- Name: CGAffineTransformConcat
SwiftName: CGAffineTransform.concat(self:_:)
- Name: CGAffineTransformEqualToTransform
SwiftName: CGAffineTransform.equalTo(self:_:)
- Name: CGPointApplyAffineTransform
SwiftName: CGPoint.applyAffineTransform(self:_:)
- Name: CGSizeApplyAffineTransform
SwiftName: CGSize.applyAffineTransform(self:_:)
- Name: CGRectApplyAffineTransform
SwiftName: CGRect.applyAffineTransform(self:_:)
# CGBitmapContext
- Name: CGBitmapContextCreateImage
SwiftName: CGContextRef.makeImageFromBitmap(self:)
# CGColor
- Name: CGColorCreate
SwiftName: CGColorRef.init(withColorSpace:components:)
- Name: CGColorGetConstantColor
SwiftName: CGColorRef.constantColorForName(_:)
- Name: CGColorEqualToColor
SwiftName: CGColorRef.equalTo(self:_:)
# CGColorSpace
- Name: CGColorSpaceCopyICCProfile
SwiftName: CGColorSpaceRef.copyICCData(self:)
# CGContext
- Name: CGContextScaleCTM
SwiftName: CGContextRef.scaleBy(self:x:y:)
- Name: CGContextTranslateCTM
SwiftName: CGContextRef.translateBy(self:x:y:)
- Name: CGContextRotateCTM
SwiftName: CGContextRef.rotate(self:byAngle:)
- Name: CGContextSetLineWidth
SwiftName: CGContextRef.setLineWidth(self:_:)
- Name: CGContextSetMiterLimit
SwiftName: CGContextRef.setMiterLimit(self:_:)
- Name: CGContextSetLineDash
SwiftName: CGContextRef.setLineDash(self:withPhase:lengths:count:)
- Name: CGContextSetFlatness
SwiftName: CGContextRef.setFlatness(self:_:)
- Name: CGContextSetAlpha
SwiftName: CGContextRef.setAlpha(self:_:)
- Name: CGContextMoveToPoint
SwiftName: CGContextRef.moveTo(self:x:y:)
- Name: CGContextAddLineToPoint
SwiftName: CGContextRef.addLineTo(self:x:y:)
- Name: CGContextAddCurveToPoint
SwiftName: CGContextRef.addCurve(self:cp1x:cp1y:cp2x:cp2y:endingAtX:y:)
- Name: CGContextAddQuadCurveToPoint
SwiftName: CGContextRef.addQuadCurve(self:cpx:cpy:endingAtX:y:)
- Name: CGContextAddRects
SwiftName: CGContextRef.addRects(self:_:count:)
- Name: CGContextAddLines
SwiftName: CGContextRef.addLines(self:between:count:)
- Name: CGContextAddEllipseInRect
SwiftName: CGContextRef.addEllipseIn(self:_:)
- Name: CGContextAddArc
SwiftName: CGContextRef.addArc(self:centeredAtX:y:radius:startAngle:endAngle:clockwise:)
- Name: CGContextAddArcToPoint
SwiftName: CGContextRef.addArc(self:x1:y1:x2:y2:radius:)
- Name: CGContextIsPathEmpty
SwiftName: getter:CGContextRef.isPathEmpty(self:)
- Name: CGContextGetPathCurrentPoint
SwiftName: getter:CGContextRef.currentPointOfPath(self:)
- Name: CGContextGetPathBoundingBox
SwiftName: getter:CGContextRef.boundingBoxOfPath(self:)
- Name: CGContextPathContainsPoint
SwiftName: CGContextRef.pathContains(self:_:mode:)
- Name: CGContextDrawPath
SwiftName: CGContextRef.drawPath(self:using:)
- Name: CGContextFillRect
SwiftName: CGContextRef.fill(self:_:)
- Name: CGContextFillRects
SwiftName: CGContextRef.fill(self:_:count:)
- Name: CGContextStrokeRect
SwiftName: CGContextRef.stroke(self:_:)
- Name: CGContextStrokeRectWithWidth
SwiftName: CGContextRef.stroke(self:_:width:)
- Name: CGContextClearRect
SwiftName: CGContextRef.clear(self:_:)
- Name: CGContextFillEllipseInRect
SwiftName: CGContextRef.fillEllipse(self:in:)
- Name: CGContextStrokeEllipseInRect
SwiftName: CGContextRef.strokeEllipse(self:in:)
- Name: CGContextStrokeLineSegments
SwiftName: CGContextRef.strokeLineSegments(self:between:count:)
- Name: CGContextGetClipBoundingBox
SwiftName: getter:CGContextRef.boundingBoxOfClipPath(self:)
- Name: CGContextClipToRect
SwiftName: CGContextRef.clip(self:to:)
- Name: CGContextClipToRects
SwiftName: CGContextRef.clip(self:to:count:)
- Name: CGContextSetFillColor
SwiftName: CGContextRef.setFillColor(self:withComponents:)
- Name: CGContextSetFillColorWithColor
SwiftName: CGContextRef.setFillColor(self:_:)
- Name: CGContextSetFillPattern
SwiftName: CGContextRef.setFillPattern(self:_:colorComponents:)
- Name: CGContextSetStrokePattern
SwiftName: CGContextRef.setStrokePattern(self:_:colorComponents:)
- Name: CGContextSetPatternPhase
SwiftName: CGContextRef.setPatternPhase(self:_:)
- Name: CGContextSetGrayFillColor
SwiftName: CGContextRef.setFillColor(self:withGray:alpha:)
- Name: CGContextSetGrayStrokeColor
SwiftName: CGContextRef.setStrokeColor(self:withGray:alpha:)
- Name: CGContextSetRGBFillColor
SwiftName: CGContextRef.setFillColor(self:withRed:green:blue:alpha:)
- Name: CGContextSetRGBStrokeColor
SwiftName: CGContextRef.setStrokeColor(self:withRed:green:blue:alpha:)
- Name: CGContextSetStrokeColor
SwiftName: CGContextRef.setStrokeColor(self:withComponents:)
- Name: CGContextSetStrokeColorWithColor
SwiftName: CGContextRef.setStrokeColor(self:_:)
- Name: CGContextSetCMYKFillColor
SwiftName: CGContextRef.setFillColor(self:withCyan:magenta:yellow:black:alpha:)
- Name: CGContextSetCMYKStrokeColor
SwiftName: CGContextRef.setStrokeColor(self:withCyan:magenta:yellow:black:alpha:)
- Name: CGContextDrawImage
SwiftName: CGContextRef.draw(self:in:image:)
- Name: CGContextDrawTiledImage
SwiftName: CGContextRef.draw(self:in:byTiling:)
- Name: CGContextSetShadowWithColor
SwiftName: CGContextRef.setShadow(self:withOffset:blur:color:)
- Name: CGContextSetShadow
SwiftName: CGContextRef.setShadow(self:withOffset:blur:)
- Name: CGContextSetCharacterSpacing
SwiftName: CGContextRef.setCharacterSpacing(self:_:)
- Name: CGContextGetTextPosition
SwiftName: getter:CGContextRef.textPosition(self:)
- Name: CGContextSetFontSize
SwiftName: CGContextRef.setFontSize(self:_:)
- Name: CGContextShowGlyphsAtPositions
SwiftName: CGContextRef.showGlyphs(self:_:atPositions:count:)
- Name: CGContextBeginPage
SwiftName: CGContextRef.beginPage(self:withMediaBox:)
- Name: CGContextSetShouldAntialias
SwiftName: CGContextRef.setShouldAntialias(self:_:)
- Name: CGContextSetAllowsAntialiasing
SwiftName: CGContextRef.setAllowsAntialiasing(self:_:)
- Name: CGContextSetShouldSmoothFonts
SwiftName: CGContextRef.setShouldSmoothFonts(self:_:)
- Name: CGContextSetAllowsFontSmoothing
SwiftName: CGContextRef.setAllowsFontSmoothing(self:_:)
- Name: CGContextSetShouldSubpixelPositionFonts
SwiftName: CGContextRef.setShouldSubpixelPositionFonts(self:_:)
- Name: CGContextSetAllowsFontSubpixelPositioning
SwiftName: CGContextRef.setAllowsFontSubpixelPositioning(self:_:)
- Name: CGContextSetShouldSubpixelQuantizeFonts
SwiftName: CGContextRef.setShouldSubpixelQuantizeFonts(self:_:)
- Name: CGContextSetAllowsFontSubpixelQuantization
SwiftName: CGContextRef.setAllowsFontSubpixelQuantization(self:_:)
- Name: CGContextBeginTransparencyLayer
SwiftName: CGContextRef.beginTransparencyLayer(self:withAuxiliaryInfo:)
- Name: CGContextBeginTransparencyLayerWithRect
SwiftName: CGContextRef.beginTransparencyLayer(self:in:auxiliaryInfo:)
# CGEvent
- Name: CGEventCreateFromData
SwiftName: CGEventRef.init(withDataAllocator:data:)
- Name: CGEventPostToPid
SwiftName: CGEventRef.postToPid(_:self:)
- Name: CGEventCreateSourceFromEvent
SwiftName: CGEventSourceRef.init(_:)
# CGFont
- Name: CGFontCopyTableForTag
SwiftName: CGFontRef.copyTableForTag(self:_:)
# CGGeometry
- Name: CGPointEqualToPoint
SwiftName: CGPoint.equalTo(self:_:)
- Name: CGPointMakeWithDictionaryRepresentation
SwiftName: CGPoint.makeWithDictionaryRepresentation(_:self:)
- Name: CGSizeMakeWithDictionaryRepresentation
SwiftName: CGSize.makeWithDictionaryRepresentation(_:self:)
- Name: CGRectMakeWithDictionaryRepresentation
SwiftName: CGRect.makeWithDictionaryRepresentation(_:self:)
- Name: CGSizeEqualToSize
SwiftName: CGSize.equalTo(self:_:)
- Name: CGRectEqualToRect
SwiftName: CGRect.equalTo(self:_:)
# CGPDFDocument
- Name: CGPDFDocumentGetID
SwiftName: getter:CGPDFDocumentRef.fileIdentifier(self:)
- Name: CGPDFDocumentIsEncrypted
SwiftName: getter:CGPDFDocumentRef.isEncrypted(self:)
- Name: CGPDFDocumentIsUnlocked
SwiftName: getter:CGPDFDocumentRef.isUnlocked(self:)
- Name: CGPDFDocumentAllowsPrinting
SwiftName: getter:CGPDFDocumentRef.allowsPrinting(self:)
- Name: CGPDFDocumentAllowsCopying
SwiftName: getter:CGPDFDocumentRef.allowsCopying(self:)
- Name: CGPDFDocumentCreateWithProvider
SwiftName: CGPDFDocumentRef.init(_:)
- Name: CGPDFDocumentCreateWithURL
SwiftName: CGPDFDocumentRef.init(with:)
- Name: CGPDFDocumentUnlockWithPassword
SwiftName: CGPDFDocumentRef.unlockWithPassword(self:_:)
- Name: CGPDFDocumentGetPage
SwiftName: CGPDFDocumentRef.page(self:AtIndex:)
# CGPDFPage
- Name: CGPDFPageGetBoxRect
SwiftName: getter:CGPDFPageRef.boxRect(self:)
# CGPSConverter
- Name: CGPSConverterIsConverting
SwiftName: getter:CGPSConverterRef.isConverting(self:)
# CGPath
- Name: CGPathEqualToPath
SwiftName: CGPathRef.equalTo(self:_:)
- Name: CGPathGetPathBoundingBox
SwiftName: getter:CGPathRef.boundingBoxOfPath(self:)
- Name: CGPathContainsPoint
SwiftName: CGPathRef.containsPoint(self:_:point:eoFill:)
- Name: CGPathMoveToPoint
SwiftName: CGMutablePathRef.moveTo(self:_:x:y:)
- Name: CGPathAddLineToPoint
SwiftName: CGMutablePathRef.addLineTo(self:_:x:y:)
- Name: CGPathAddCurveToPoint
SwiftName: CGMutablePathRef.addCurve(self:_:cp1x:cp1y:cp2x:cp2y:endingAtX:y:)
- Name: CGPathAddQuadCurveToPoint
SwiftName: CGMutablePathRef.addQuadCurve(self:_:cpx:cpy:endingAtX:y:)
- Name: CGPathAddRect
SwiftName: CGMutablePathRef.addRect(self:_:rect:)
- Name: CGPathAddRects
SwiftName: CGMutablePathRef.addRects(self:_:rects:count:)
- Name: CGPathAddLines
SwiftName: CGMutablePathRef.addLines(self:_:between:count:)
- Name: CGPathAddEllipseInRect
SwiftName: CGMutablePathRef.addEllipseIn(self:_:rect:)
- Name: CGPathAddArc
SwiftName: CGMutablePathRef.addArc(self:_:x:y:radius:startAngle:endAngle:clockwise:)
- Name: CGPathAddArcToPoint
SwiftName: CGMutablePathRef.addArc(self:_:x1:y1:x2:y2:radius:)
- Name: CGPathAddPath
SwiftName: CGMutablePathRef.addPath(self:_:path:)
#
# Global variables
#
Globals:
# The below are globals that are defined as opaque C constants for no good
# reason.
- Name: CGPointZero
Availability: nonswift
- Name: CGSizeZero
Availability: nonswift
- Name: CGVectorZero
Availability: nonswift
- Name: CGRectZero
Availability: nonswift
- Name: CGAffineTransformIdentity
Availability: nonswift
# The below are not available in Swift
- Name: kCGColorSpaceGenericGray
Availability: nonswift
- Name: kCGColorSpaceGenericRGB
Availability: nonswift
#
# Enums
#
Enumerators:
# The below are attempts at providing better names than inference
# CGColorSpace
- Name: kCGRenderingIntentDefault
SwiftName: CGColorRenderingIntent.defaultIntent
- Name: kCGRenderingIntentAbsoluteColorimetric
SwiftName: CGColorRenderingIntent.absoluteColorimetric
- Name: kCGRenderingIntentRelativeColorimetric
SwiftName: CGColorRenderingIntent.relativeColorimetric
- Name: kCGRenderingIntentPerceptual
SwiftName: CGColorRenderingIntent.perceptual
- Name: kCGRenderingIntentSaturation
SwiftName: CGColorRenderingIntent.saturation
- Name: kCGMomentumScrollPhaseContinue
SwiftName: CGMomentumScrollPhase.continuous
# CGContext
- Name: kCGBlendModeXOR
SwiftName: CGBlendMode.xor
# CGEventTypes
- Name: kCGEventMouseSubtypeDefault
SwiftName: CGEventMouseSubtype.defaultType
- Name: kCGEventTapOptionDefault
SwiftName: CGEventTapOptions.defaultTap
- Name: kCGEventSourceStatePrivate
SwiftName: CGEventSourceStateID.privateState
# CGImage
- Name: kCGImageAlphaOnly
SwiftName: alphaOnly
# CGWindowLevel
- Name: kCGBaseWindowLevelKey
SwiftName: CGWindowLevelKey.baseWindow
- Name: kCGMinimumWindowLevelKey
SwiftName: CGWindowLevelKey.minimumWindow
- Name: kCGDesktopWindowLevelKey
SwiftName: CGWindowLevelKey.desktopWindow
- Name: kCGDesktopIconWindowLevelKey
SwiftName: CGWindowLevelKey.desktopIconWindow
- Name: kCGBackstopMenuLevelKey
SwiftName: CGWindowLevelKey.backstopMenu
- Name: kCGNormalWindowLevelKey
SwiftName: CGWindowLevelKey.normalWindow
- Name: kCGFloatingWindowLevelKey
SwiftName: CGWindowLevelKey.floatingWindow
- Name: kCGTornOffMenuWindowLevelKey
SwiftName: CGWindowLevelKey.tornOffMenuWindow
- Name: kCGDockWindowLevelKey
SwiftName: CGWindowLevelKey.dockWindow
- Name: kCGMainMenuWindowLevelKey
SwiftName: CGWindowLevelKey.mainMenuWindow
- Name: kCGStatusWindowLevelKey
SwiftName: CGWindowLevelKey.statusWindow
- Name: kCGModalPanelWindowLevelKey
SwiftName: CGWindowLevelKey.modalPanelWindow
- Name: kCGPopUpMenuWindowLevelKey
SwiftName: CGWindowLevelKey.popUpMenuWindow
- Name: kCGDraggingWindowLevelKey
SwiftName: CGWindowLevelKey.draggingWindow
- Name: kCGScreenSaverWindowLevelKey
SwiftName: CGWindowLevelKey.screenSaverWindow
- Name: kCGMaximumWindowLevelKey
SwiftName: CGWindowLevelKey.maximumWindow
- Name: kCGOverlayWindowLevelKey
SwiftName: CGWindowLevelKey.overlayWindow
- Name: kCGHelpWindowLevelKey
SwiftName: CGWindowLevelKey.helpWindow
- Name: kCGUtilityWindowLevelKey
SwiftName: CGWindowLevelKey.utilityWindow
- Name: kCGCursorWindowLevelKey
SwiftName: CGWindowLevelKey.cursorWindow
- Name: kCGAssistiveTechHighWindowLevelKey
SwiftName: CGWindowLevelKey.assistiveTechHighWindow
#
# Tags
#
Tags:
# The below are not available in Swift
- Name: CGGlypDeprecatedEnum
Availability: nonswift

View File

@@ -2,13 +2,75 @@
Name: Foundation
Classes:
- Name: NSArray
SwiftBridge: 'Swift.Array'
SwiftBridge: Swift.Array
Methods:
- Selector: 'pathsMatchingExtensions:'
SwiftName: pathsMatchingExtensions(_:)
MethodKind: Instance
- Selector: 'filteredArrayUsingPredicate:'
SwiftName: filtered(using:)
MethodKind: Instance
- Name: NSDictionary
SwiftBridge: 'Swift.Dictionary'
SwiftBridge: Swift.Dictionary
- Name: NSSet
SwiftBridge: 'Swift.Set'
SwiftBridge: Swift.Set
Methods:
- Selector: 'filteredSetUsingPredicate:'
SwiftName: filtered(using:)
MethodKind: Instance
- Name: NSString
SwiftBridge: 'Swift.String'
SwiftBridge: Swift.String
Methods:
- Selector: 'uppercaseStringWithLocale:'
SwiftName: uppercased(with:)
MethodKind: Instance
- Selector: 'lowercaseStringWithLocale:'
SwiftName: lowercased(with:)
MethodKind: Instance
- Selector: 'capitalizedStringWithLocale:'
SwiftName: capitalized(with:)
MethodKind: Instance
- Selector: 'dataUsingEncoding:allowLossyConversion:'
SwiftName: data(using:allowLossyConversion:)
MethodKind: Instance
- Selector: 'dataUsingEncoding:'
SwiftName: data(using:)
MethodKind: Instance
- Selector: 'canBeConvertedToEncoding:'
SwiftName: canBeConverted(to:)
MethodKind: Instance
- Selector: 'cStringUsingEncoding:'
SwiftName: cString(using:)
MethodKind: Instance
- Selector: 'maximumLengthOfBytesUsingEncoding:'
SwiftName: maximumLengthOfBytes(using:)
MethodKind: Instance
- Selector: 'lengthOfBytesUsingEncoding:'
SwiftName: lengthOfBytes(using:)
MethodKind: Instance
- Selector: 'localizedNameOfStringEncoding:'
SwiftName: localizedName(of:)
MethodKind: Class
- Selector: 'componentsSeparatedByString:'
SwiftName: components(separatedBy:)
MethodKind: Instance
- Selector: 'componentsSeparatedByCharactersInSet:'
SwiftName: components(separatedBy:)
MethodKind: Instance
- Selector: 'stringByPaddingToLength:withString:startingAtIndex:'
SwiftName: padding(toLength:withPad:startingAt:)
MethodKind: Instance
- Selector: 'stringByAddingPercentEscapesUsingEncoding:'
SwiftName: addingPercentEscapes(using:)
MethodKind: Instance
- Selector: 'stringByReplacingPercentEscapesUsingEncoding:'
SwiftName: replacingPercentEscapes(using:)
MethodKind: Instance
Properties:
- Name: uppercaseString
SwiftName: uppercased
- Name: lowercaseString
SwiftName: lowercased
- Name: NSDistributedNotificationCenter
Methods:
- Selector: 'notificationCenterForType:'
@@ -20,9 +82,656 @@ Classes:
MethodKind: Instance
Availability: nonswift
AvailabilityMsg: use generic 'decodeObjectOfClass(_:forKey:)'
- Selector: 'encodeInt:forKey:'
Availability: nonswift
MethodKind: Instance
- Selector: 'decodeIntForKey:'
Availability: nonswift
MethodKind: Instance
- Name: NSProcessInfo
Methods:
- Selector: processInfo
MethodKind: Class
NullabilityOfRet: N
FactoryAsInit: C
- Selector: 'isOperatingSystemAtLeastVersion:'
SwiftName: isOperatingSystemAtLeast(_:)
MethodKind: Instance
- Name: NSMutableArray
Methods:
- Selector: 'removeObjectIdenticalTo:inRange:'
SwiftName: removeObject(identicalTo:in:)
MethodKind: Instance
- Selector: 'removeObjectIdenticalTo:'
SwiftName: removeObject(identicalTo:)
MethodKind: Instance
- Name: NSBundle
Methods:
- Selector: 'URLForAuxiliaryExecutable:'
SwiftName: urlForAuxiliaryExecutable(_:)
MethodKind: Instance
- Selector: 'pathForAuxiliaryExecutable:'
SwiftName: pathForAuxiliaryExecutable(_:)
MethodKind: Instance
- Selector: 'URLForResource:withExtension:subdirectory:inBundleWithURL:'
SwiftName: urlForResource(_:withExtension:subdirectory:inBundleWith:)
MethodKind: Class
- Selector: 'URLForResource:withExtension:'
SwiftName: urlForResource(_:withExtension:)
MethodKind: Instance
- Selector: 'URLForResource:withExtension:subdirectory:'
SwiftName: urlForResource(_:withExtension:subdirectory:)
MethodKind: Instance
- Selector: 'URLForResource:withExtension:subdirectory:localization:'
SwiftName: urlForResource(_:withExtension:subdirectory:localization:)
MethodKind: Instance
- Selector: 'pathForResource:ofType:inDirectory:'
SwiftName: pathForResource(_:ofType:inDirectory:)
MethodKind: Class
- Selector: 'pathForResource:ofType:'
SwiftName: pathForResource(_:ofType:)
MethodKind: Instance
- Selector: 'pathForResource:ofType:inDirectory:'
SwiftName: pathForResource(_:ofType:inDirectory:)
MethodKind: Instance
- Selector: 'pathForResource:ofType:inDirectory:forLocalization:'
SwiftName: pathForResource(_:ofType:inDirectory:forLocalization:)
MethodKind: Instance
- Selector: 'objectForInfoDictionaryKey:'
SwiftName: objectForInfoDictionaryKey(_:)
MethodKind: Instance
- Name: NSByteCountFormatter
Methods:
- Selector: 'stringFromByteCount:'
SwiftName: stringFromByteCount(_:)
MethodKind: Instance
- Name: NSCalendar
Methods:
- Selector: 'dateWithEra:year:month:day:hour:minute:second:nanosecond:'
SwiftName: date(era:year:month:day:hour:minute:second:nanosecond:)
MethodKind: Instance
- Selector: 'dateWithEra:yearForWeekOfYear:weekOfYear:weekday:hour:minute:second:nanosecond:'
SwiftName: date(era:yearForWeekOfYear:weekOfYear:weekday:hour:minute:second:nanosecond:)
MethodKind: Instance
- Selector: 'enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock:'
SwiftName: enumerateDates(startingAfter:matching:options:using:)
MethodKind: Instance
- Selector: 'isDateInToday:'
SwiftName: isDateInToday(_:)
MethodKind: Instance
- Selector: 'isDateInYesterday:'
SwiftName: isDateInYesterday(_:)
MethodKind: Instance
- Selector: 'isDateInTomorrow:'
SwiftName: isDateInTomorrow(_:)
MethodKind: Instance
- Selector: 'isDateInWeekend:'
SwiftName: isDateInWeekend(_:)
MethodKind: Instance
- Name: NSCharacterSet
Methods:
- Selector: controlCharacterSet
SwiftName: controlCharacters()
MethodKind: Class
- Selector: whitespaceCharacterSet
SwiftName: whitespaces()
MethodKind: Class
- Selector: whitespaceAndNewlineCharacterSet
SwiftName: whitespacesAndNewlines()
MethodKind: Class
- Selector: decimalDigitCharacterSet
SwiftName: decimalDigits()
MethodKind: Class
- Selector: letterCharacterSet
SwiftName: letters()
MethodKind: Class
- Selector: lowercaseLetterCharacterSet
SwiftName: lowercaseLetters()
MethodKind: Class
- Selector: uppercaseLetterCharacterSet
SwiftName: uppercaseLetters()
MethodKind: Class
- Selector: nonBaseCharacterSet
SwiftName: nonBaseCharacters()
MethodKind: Class
- Selector: alphanumericCharacterSet
SwiftName: alphanumerics()
MethodKind: Class
- Selector: decomposableCharacterSet
SwiftName: decomposables()
MethodKind: Class
- Selector: illegalCharacterSet
SwiftName: illegalCharacters()
MethodKind: Class
- Selector: capitalizedLetterCharacterSet
SwiftName: capitalizedLetters()
MethodKind: Class
- Selector: symbolCharacterSet
SwiftName: symbols()
MethodKind: Class
- Selector: newlineCharacterSet
SwiftName: newlines()
MethodKind: Class
- Selector: 'hasMemberInPlane:'
SwiftName: hasMemberInPlane(_:)
MethodKind: Instance
- Name: NSData
Methods:
- Selector: 'enumerateByteRangesUsingBlock:'
SwiftName: enumerateBytes(_:)
MethodKind: Instance
- Selector: 'rangeOfData:options:range:'
SwiftName: range(of:options:in:)
MethodKind: Instance
- Selector: 'initWithBase64EncodedString:options:'
SwiftName: init(base64Encoded:options:)
MethodKind: Instance
- Selector: 'initWithBase64EncodedData:options:'
SwiftName: init(base64Encoded:options:)
MethodKind: Instance
- Selector: 'dataWithContentsOfMappedFile:'
SwiftName: dataWithContentsOfMappedFile(_:)
MethodKind: Class
- Name: NSMutableData
Methods:
- Selector: 'appendBytes:length:'
SwiftName: append(_:length:)
MethodKind: Instance
- Name: NSDate
Methods:
- Selector: 'timeIntervalSinceDate:'
SwiftName: timeIntervalSince(_:)
MethodKind: Instance
- Selector: 'descriptionWithLocale:'
SwiftName: description(with:)
MethodKind: Instance
- Name: NSDateComponentsFormatter
Methods:
- Selector: 'stringFromTimeInterval:'
SwiftName: string(from:)
MethodKind: Instance
- Name: NSDateFormatter
Methods:
- Selector: 'localizedStringFromDate:dateStyle:timeStyle:'
SwiftName: localizedString(from:dateStyle:timeStyle:)
MethodKind: Class
- Name: NSDecimalNumber
Methods:
- Selector: notANumber
SwiftName: notANumber()
MethodKind: Class
- Name: NSObject
Methods:
- Selector: 'attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:'
SwiftName: attemptRecovery(fromError:optionIndex:delegate:didRecoverSelector:contextInfo:)
MethodKind: Class
- Selector: 'attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:'
SwiftName: attemptRecovery(fromError:optionIndex:delegate:didRecoverSelector:contextInfo:)
MethodKind: Instance
- Selector: 'setValuesForKeysWithDictionary:'
SwiftName: setValuesForKeys(_:)
MethodKind: Class
- Selector: 'setValuesForKeysWithDictionary:'
SwiftName: setValuesForKeys(_:)
MethodKind: Instance
- Name: NSExpression
Methods:
- Selector: expressionForEvaluatedObject
SwiftName: expressionForEvaluatedObject()
MethodKind: Class
- Selector: expressionForAnyKey
SwiftName: expressionForAnyKey()
MethodKind: Class
- Selector: 'expressionForBlock:arguments:'
SwiftName: init(block:arguments:)
MethodKind: Class
- Name: NSExtensionContext
Methods:
- Selector: 'completeRequestReturningItems:completionHandler:'
SwiftName: completeRequest(returningItems:completionHandler:)
MethodKind: Instance
- Selector: 'cancelRequestWithError:'
SwiftName: cancelRequest(withError:)
MethodKind: Instance
- Name: NSFileCoordinator
Methods:
- Selector: 'coordinateAccessWithIntents:queue:byAccessor:'
SwiftName: coordinate(with:queue:byAccessor:)
MethodKind: Instance
- Selector: 'coordinateReadingItemAtURL:options:error:byAccessor:'
SwiftName: coordinate(readingItemAt:options:error:byAccessor:)
MethodKind: Instance
- Selector: 'coordinateWritingItemAtURL:options:error:byAccessor:'
SwiftName: coordinate(writingItemAt:options:error:byAccessor:)
MethodKind: Instance
- Selector: 'coordinateReadingItemAtURL:options:writingItemAtURL:options:error:byAccessor:'
SwiftName: coordinate(readingItemAt:options:writingItemAt:options:error:byAccessor:)
MethodKind: Instance
- Selector: 'coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor:'
SwiftName: coordinate(writingItemAt:options:writingItemAt:options:error:byAccessor:)
MethodKind: Instance
- Selector: 'prepareForReadingItemsAtURLs:options:writingItemsAtURLs:options:error:byAccessor:'
SwiftName: prepare(forReadingItemsAt:options:writingItemsAt:options:error:byAccessor:)
MethodKind: Instance
- Name: NSFileHandle
Methods:
- Selector: fileHandleWithStandardInput
SwiftName: standardInput()
MethodKind: Class
- Selector: fileHandleWithStandardOutput
SwiftName: standardOutput()
MethodKind: Class
- Selector: fileHandleWithStandardError
SwiftName: standardError()
MethodKind: Class
- Selector: fileHandleWithNullDevice
SwiftName: nullDevice()
MethodKind: Class
- Name: NSFileManager
Methods:
- Selector: 'mountedVolumeURLsIncludingResourceValuesForKeys:options:'
SwiftName: mountedVolumeURLs(includingResourceValuesForKeys:options:)
MethodKind: Instance
- Selector: 'URLsForDirectory:inDomains:'
SwiftName: urlsForDirectory(_:inDomains:)
MethodKind: Instance
- Selector: 'URLForDirectory:inDomain:appropriateForURL:create:error:'
SwiftName: urlForDirectory(_:in:appropriateFor:create:)
MethodKind: Instance
- Selector: 'URLForUbiquityContainerIdentifier:'
SwiftName: urlForUbiquityContainerIdentifier(_:)
MethodKind: Instance
- Selector: 'containerURLForSecurityApplicationGroupIdentifier:'
SwiftName: containerURLForSecurityApplicationGroupIdentifier(_:)
MethodKind: Instance
- Name: NSFileVersion
Methods:
- Selector: 'versionOfItemAtURL:forPersistentIdentifier:'
SwiftName: init(itemAt:forPersistentIdentifier:)
MethodKind: Class
- Name: NSFileWrapper
Methods:
- Selector: 'keyForFileWrapper:'
SwiftName: keyForChildFileWrapper(_:)
MethodKind: Instance
- Name: NSFormatter
Methods:
- Selector: 'isPartialStringValid:newEditingString:errorDescription:'
SwiftName: isPartialStringValid(_:newEditingString:errorDescription:)
MethodKind: Instance
- Name: NSItemProvider
Methods:
- Selector: 'hasItemConformingToTypeIdentifier:'
SwiftName: hasItemConformingToTypeIdentifier(_:)
MethodKind: Instance
- Name: NSConditionLock
Methods:
- Selector: 'tryLockWhenCondition:'
SwiftName: tryLock(whenCondition:)
MethodKind: Instance
- Name: NSNotificationCenter
Methods:
- Selector: 'postNotificationName:object:'
SwiftName: post(name:object:)
MethodKind: Instance
- Selector: 'postNotificationName:object:userInfo:'
SwiftName: post(name:object:userInfo:)
MethodKind: Instance
- Name: NSOrderedSet
Methods:
- Selector: 'enumerateObjectsWithOptions:usingBlock:'
SwiftName: enumerateObjects(options:using:)
MethodKind: Instance
- Selector: 'filteredOrderedSetUsingPredicate:'
SwiftName: filtered(using:)
MethodKind: Instance
- Selector: 'indexesOfObjectsAtIndexes:options:passingTest:'
SwiftName: indexes(ofObjectsAt:options:passingTest:)
MethodKind: Instance
- Selector: 'indexesOfObjectsPassingTest:'
SwiftName: indexes(ofObjectsPassingTest:)
MethodKind: Instance
- Selector: 'indexesOfObjectsWithOptions:passingTest:'
SwiftName: indexes(options:ofObjectsPassingTest:)
MethodKind: Instance
- Selector: 'indexOfObjectAtIndexes:options:passingTest:'
SwiftName: index(ofObjectAt:options:passingTest:)
MethodKind: Instance
- Selector: 'indexOfObjectPassingTest:'
SwiftName: index(ofObjectPassingTest:)
MethodKind: Instance
- Selector: 'indexOfObjectWithOptions:passingTest:'
SwiftName: index(_:ofObjectPassingTest:)
MethodKind: Instance
- Name: NSProgress
Methods:
- Selector: 'discreteProgressWithTotalUnitCount:'
SwiftName: discreteProgress(totalUnitCount:)
MethodKind: Class
- Name: NSPropertyListSerialization
Methods:
- Selector: 'dataWithPropertyList:format:options:error:'
SwiftName: data(fromPropertyList:format:options:)
MethodKind: Class
- Selector: 'propertyListWithData:options:format:error:'
SwiftName: propertyList(from:options:format:)
MethodKind: Class
- Selector: 'dataFromPropertyList:format:errorDescription:'
SwiftName: dataFromPropertyList(_:format:errorDescription:)
MethodKind: Class
- Selector: 'propertyListFromData:mutabilityOption:format:errorDescription:'
SwiftName: propertyListFromData(_:mutabilityOption:format:errorDescription:)
MethodKind: Class
- Name: NSRunLoop
Methods:
- Selector: 'runMode:beforeDate:'
SwiftName: run(mode:before:)
MethodKind: Instance
- Name: NSScanner
Methods:
- Selector: 'scanInt:'
SwiftName: scanInt32(_:)
MethodKind: Instance
- Selector: 'scanInteger:'
SwiftName: scanInt(_:)
MethodKind: Instance
- Selector: 'scanLongLong:'
SwiftName: scanInt64(_:)
MethodKind: Instance
- Selector: 'scanHexInt:'
SwiftName: scanHexInt32(_:)
MethodKind: Instance
- Selector: 'scanHexLongLong:'
SwiftName: scanHexInt64(_:)
MethodKind: Instance
- Selector: 'scanUpToString:intoString:'
SwiftName: scanUpTo(_:into:)
MethodKind: Instance
- Name: NSTextCheckingResult
Methods:
- Selector: 'resultByAdjustingRangesWithOffset:'
SwiftName: resultByAdjustingRangesWithOffset(_:)
MethodKind: Instance
- Selector: 'orthographyCheckingResultWithRange:orthography:'
SwiftName: orthographyCheckingResult(range:orthography:)
MethodKind: Class
- Selector: 'spellCheckingResultWithRange:'
SwiftName: spellCheckingResult(range:)
MethodKind: Class
- Selector: 'grammarCheckingResultWithRange:details:'
SwiftName: grammarCheckingResult(range:details:)
MethodKind: Class
- Selector: 'dateCheckingResultWithRange:date:'
SwiftName: dateCheckingResult(range:date:)
MethodKind: Class
- Selector: 'dateCheckingResultWithRange:date:timeZone:duration:'
SwiftName: dateCheckingResult(range:date:timeZone:duration:)
MethodKind: Class
- Selector: 'addressCheckingResultWithRange:components:'
SwiftName: addressCheckingResult(range:components:)
MethodKind: Class
- Selector: 'linkCheckingResultWithRange:URL:'
SwiftName: linkCheckingResult(range:url:)
MethodKind: Class
- Selector: 'quoteCheckingResultWithRange:replacementString:'
SwiftName: quoteCheckingResult(range:replacementString:)
MethodKind: Class
- Selector: 'dashCheckingResultWithRange:replacementString:'
SwiftName: dashCheckingResult(range:replacementString:)
MethodKind: Class
- Selector: 'replacementCheckingResultWithRange:replacementString:'
SwiftName: replacementCheckingResult(range:replacementString:)
MethodKind: Class
- Selector: 'correctionCheckingResultWithRange:replacementString:'
SwiftName: correctionCheckingResult(range:replacementString:)
MethodKind: Class
- Selector: 'regularExpressionCheckingResultWithRanges:count:regularExpression:'
SwiftName: regularExpressionCheckingResult(ranges:count:regularExpression:)
MethodKind: Class
- Selector: 'phoneNumberCheckingResultWithRange:phoneNumber:'
SwiftName: phoneNumberCheckingResult(range:phoneNumber:)
MethodKind: Class
- Selector: 'transitInformationCheckingResultWithRange:components:'
SwiftName: transitInformationCheckingResult(range:components:)
MethodKind: Class
- Name: NSTimer
Methods:
- Selector: 'scheduledTimerWithTimeInterval:invocation:repeats:'
SwiftName: scheduledTimer(timeInterval:invocation:repeats:)
MethodKind: Class
- Selector: 'scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:'
SwiftName: scheduledTimer(timeInterval:target:selector:userInfo:repeats:)
MethodKind: Class
- Selector: 'initWithFireDate:interval:target:selector:userInfo:repeats:'
SwiftName: init(fireAt:interval:target:selector:userInfo:repeats:)
MethodKind: Instance
- Name: NSURL
Properties:
- Name: baseURL
SwiftName: baseURL
- Name: absoluteURL
SwiftName: absoluteURL
- Name: filePathURL
SwiftName: filePathURL
Methods:
- Selector: fileReferenceURL
SwiftName: fileReferenceURL()
MethodKind: Instance
- Selector: 'initByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:'
SwiftName: init(resolvingBookmarkData:options:relativeTo:bookmarkDataIsStale:)
MethodKind: Instance
- Selector: 'URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:'
Availability: nonswift
MethodKind: Class
- Selector: 'URLByResolvingAliasFileAtURL:options:error:'
SwiftName: init(resolvingAliasFileAt:options:)
MethodKind: Class
- Name: NSURLComponents
Methods:
- Selector: 'URLRelativeToURL:'
SwiftName: url(relativeTo:)
MethodKind: Instance
- Name: NSURLCredential
Methods:
- Selector: 'credentialForTrust:'
SwiftName: init(trust:)
MethodKind: Class
- Name: NSURLCredentialStorage
Methods:
- Selector: 'setCredential:forProtectionSpace:'
SwiftName: set(_:for:)
MethodKind: Instance
- Name: NSUbiquitousKeyValueStore
Methods:
- Selector: 'setObject:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setString:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setData:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setArray:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setDictionary:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setLongLong:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setDouble:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setBool:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Name: NSUndoManager
Methods:
- Selector: 'registerUndoWithTarget:handler:'
SwiftName: __registerUndoWithTarget(_:handler:)
MethodKind: Instance
- Name: NSUserDefaults
Methods:
- Selector: 'setObject:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setInteger:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setFloat:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setDouble:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'setBool:forKey:'
SwiftName: set(_:forKey:)
MethodKind: Instance
- Selector: 'addSuiteNamed:'
SwiftName: addSuite(named:)
MethodKind: Instance
- Selector: 'removeSuiteNamed:'
SwiftName: removeSuite(named:)
MethodKind: Instance
- Name: NSNumber
Methods:
- Selector: 'initWithChar:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithUnsignedChar:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithShort:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithUnsignedShort:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithInt:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithUnsignedInt:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithLong:'
Availability: nonswift
MethodKind: Instance
- Selector: 'initWithUnsignedLong:'
Availability: nonswift
MethodKind: Instance
- Selector: 'initWithLongLong:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithUnsignedLongLong:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithFloat:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithDouble:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithBool:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithInteger:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'initWithUnsignedInteger:'
SwiftName: init(value:)
MethodKind: Instance
- Selector: 'numberWithChar:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithUnsignedChar:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithShort:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithUnsignedShort:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithInt:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithUnsignedInt:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithLong:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithUnsignedLong:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithLongLong:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithUnsignedLongLong:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithFloat:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithDouble:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithBool:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithInteger:'
Availability: nonswift
MethodKind: Class
- Selector: 'numberWithUnsignedInteger:'
Availability: nonswift
MethodKind: Class
Properties:
- Name: charValue
SwiftName: int8Value
- Name: unsignedCharValue
SwiftName: uint8Value
- Name: shortValue
SwiftName: int16Value
- Name: unsignedShortValue
SwiftName: uint16Value
- Name: intValue
SwiftName: int32Value
- Name: unsignedIntValue
SwiftName: uint32Value
- Name: longValue
Availability: nonswift
- Name: unsignedLongValue
Availability: nonswift
- Name: longLongValue
SwiftName: int64Value
- Name: unsignedLongLongValue
SwiftName: uint64Value
- Name: integerValue
SwiftName: intValue
- Name: unsignedIntegerValue
SwiftName: uintValue
Protocols:
- Name: NSFilePresenter
Methods:
- Selector: 'presentedItemDidGainVersion:'
SwiftName: presentedItemDidGain(_:)
MethodKind: Instance
- Selector: 'presentedItemDidResolveConflictVersion:'
SwiftName: presentedItemDidResolveConflict(_:)
MethodKind: Instance
- Selector: 'presentedSubitemAtURL:didGainVersion:'
SwiftName: presentedSubitem(at:didGain:)
MethodKind: Instance
- Selector: 'presentedSubitemAtURL:didResolveConflictVersion:'
SwiftName: presentedSubitem(at:didResolve:)
MethodKind: Instance
- Name: NSDiscardableContent
Methods:
- Selector: beginContentAccess
SwiftName: beginContentAccess()
MethodKind: Instance
- Selector: endContentAccess
SwiftName: endContentAccess()
MethodKind: Instance

33
apinotes/HomeKit.apinotes Normal file
View File

@@ -0,0 +1,33 @@
---
Name: HomeKit
Classes:
- Name: HMHome
Methods:
- Selector: 'servicesWithTypes:'
SwiftName: 'servicesWithTypes(_:)'
MethodKind: Instance
- Selector: 'addRoomWithName:completionHandler:'
SwiftName: 'addRoom(name:completionHandler:NSError?):)'
MethodKind: Instance
- Selector: 'addZoneWithName:completionHandler:'
SwiftName: 'addZone(name:completionHandler:NSError?):)'
MethodKind: Instance
- Selector: 'addServiceGroupWithName:completionHandler:'
SwiftName: 'addServiceGroup(name:completionHandler:NSError?):)'
MethodKind: Instance
- Selector: 'addActionSetWithName:completionHandler:'
SwiftName: 'addActionSet(name:completionHandler:NSError?):)'
MethodKind: Instance
- Name: HMHomeManager
Methods:
- Selector: 'addHomeWithName:completionHandler:'
SwiftName: 'addHome(name:completionHandler:NSError?):)'
MethodKind: Instance
- Name: HMTimerTrigger
Methods:
- Selector: 'initWithName:fireDate:timeZone:recurrence:recurrenceCalendar:'
SwiftName: 'init(name:fireDate:timeZone:recurrence:recurrenceCalendar:)'
MethodKind: Instance
- Selector: 'updateFireDate:completionHandler:'
SwiftName: 'updateFireDate(_:completionHandler:)'
MethodKind: Instance

View File

@@ -44,7 +44,7 @@ Swift compiler itself need not be recompiled except in rare cases
where the changes affect how the SDK overlays are built. To recompile
API notes for a given module `$MODULE` and place them into their
### OSX
### OS X
```
xcrun swift -apinotes -yaml-to-binary -target x86_64-apple-macosx10.10 -o $SWIFT_EXEC/lib/swift/macosx/$MODULE.apinotesc $MODULE.apinotes
```

70
apinotes/TVMLKit.apinotes Normal file
View File

@@ -0,0 +1,70 @@
---
Name: TVMLKit
Classes:
- Name: TVElementFactory
Methods:
- Selector: 'registerViewElementClass:forElementName:'
SwiftName: 'registerViewElementClass(_:elementName:)'
MethodKind: Class
- Name: TVStyleFactory
Methods:
- Selector: 'registerStyle:withType:inherited:'
SwiftName: 'registerStyleName(_:type:inherited:)'
MethodKind: Class
- Name: TVTextElement
Properties:
- Name: attributedText
SwiftName: attributedString
Methods:
- Selector: 'attributedStringWithFont:'
SwiftName: 'makeAttributedString(font:)'
MethodKind: Instance
- Selector: 'attributedStringWithFont:foregroundColor:textAlignment:'
SwiftName: 'makeAttributedString(font:foregroundColor:textAlignment:)'
MethodKind: Instance
- Name: TVViewElement
Properties:
- Name: elementIdentifier
SwiftName: identifier
- Name: elementName
SwiftName: name
- Name: childViewElements
SwiftName: children
Methods:
- Selector: 'dispatchEventOfType:canBubble:cancellable:extraInfo:completion:'
SwiftName: 'dispatchEvent(type:canBubble:cancellable:extraInfo:completion:Bool):)'
MethodKind: Instance
- Selector: 'dispatchEventWithName:canBubble:cancellable:extraInfo:completion:'
SwiftName: 'dispatchEvent(name:canBubble:cancellable:extraInfo:completion:Bool):)'
MethodKind: Instance
- Name: TVViewElementStyle
Methods:
- Selector: 'valueForStyleProperty:'
SwiftName: 'value(propertyName:)'
MethodKind: Instance
Protocols:
- Name: TVApplicationControllerDelegate
Methods:
- Selector: 'appController:didFinishLaunchingWithOptions:'
SwiftName: 'appController(_:didFinishLaunching:)'
MethodKind: Instance
- Selector: 'appController:didFailWithError:'
SwiftName: 'appController(_:didFail:)'
MethodKind: Instance
- Selector: 'appController:didStopWithOptions:'
SwiftName: 'appController(_:didStop:)'
MethodKind: Instance
- Name: TVInterfaceCreating
Methods:
- Selector: 'viewForElement:existingView:'
SwiftName: 'makeView(element:existingView:)'
MethodKind: Instance
- Selector: 'viewControllerForElement:existingViewController:'
SwiftName: 'makeViewController(element:existingViewController:)'
MethodKind: Instance
- Selector: 'URLForResource:'
SwiftName: 'resourceURL(name:)'
MethodKind: Instance
Enumerators:
- Name: TVElementUpdateTypeSelf
SwiftName: node

View File

@@ -0,0 +1,5 @@
---
Name: TVServices
Functions:
- Name: TVTopShelfImageSizeForShape
SwiftName: 'TVTopShelfImageSize(shape:style:)'

View File

@@ -0,0 +1,27 @@
---
Name: WatchKit
Classes:
- Name: WKInterfaceController
Methods:
- Selector: 'pushControllerWithName:context:'
SwiftName: 'pushController(withName:context:)'
MethodKind: Instance
- Selector: 'presentControllerWithName:context:'
SwiftName: 'presentController(withName:context:)'
MethodKind: Instance
- Selector: 'presentControllerWithNames:contexts:'
SwiftName: 'presentController(withNames:contexts:)'
MethodKind: Instance
Enumerators:
- Name: WatchKitUnknownError
SwiftName: unknown
- Name: WatchKitApplicationDelegateWatchKitRequestReplyNotCalledError
SwiftName: applicationDelegateWatchKitRequestReplyNotCalled
- Name: WatchKitInvalidArgumentError
SwiftName: invalidArgument
- Name: WatchKitMediaPlayerError
SwiftName: mediaPlayerFailed
- Name: WatchKitDownloadError
SwiftName: downloadFailed
- Name: WatchKitRecordingFailedError
SwiftName: recordingFailed

View File

@@ -15,6 +15,9 @@ list(APPEND CMAKE_MODULE_PATH
include(AddSwiftBenchmarkSuite)
set(SWIFT_BENCH_MODULES
single-source/unit-tests/ObjectiveCBridging
single-source/unit-tests/ObjectiveCBridgingStubs
single-source/unit-tests/ObjectiveCNoBridgingStubs
single-source/unit-tests/StackPromo
single-source/Ackermann
single-source/AngryPhonebook
@@ -127,7 +130,7 @@ if(NOT SWIFT_LIBRARY_PATH)
set(SWIFT_LIBRARY_PATH "${tmp_dir}/lib/swift")
endif()
runcmd(COMMAND "xcrun" "-f" "clang"
runcmd(COMMAND "xcrun" "-toolchain" "${SWIFT_DARWIN_XCRUN_TOOLCHAIN}" "-f" "clang"
VARIABLE CLANG_EXEC
ERROR "Unable to find Clang driver")

View File

@@ -49,7 +49,8 @@ function (swift_benchmark_compile_archopts)
"-${BENCH_COMPILE_ARCHOPTS_OPT}"
"-D" "INTERNAL_CHECKS_ENABLED"
"-D" "SWIFT_ENABLE_OBJECT_LITERALS"
"-no-link-objc-runtime")
"-no-link-objc-runtime"
"-I" "${srcdir}/utils/ObjectiveCTests")
# Always optimize the driver modules.
# Note that we compile the driver for Ounchecked also with -Ounchecked
@@ -156,6 +157,12 @@ function (swift_benchmark_compile_archopts)
get_filename_component(module_name "${module_name_path}" NAME)
if(module_name)
set(extra_options "")
# For this file we disable automatic bridging between Foundation and swift.
if("${module_name}" STREQUAL "ObjectiveCNoBridgingStubs")
set(extra_options "-Xfrontend"
"-disable-swift-bridge-attr")
endif()
set(objfile "${objdir}/${module_name}.o")
set(swiftmodule "${objdir}/${module_name}.swiftmodule")
set(source "${srcdir}/${module_name_path}.swift")
@@ -167,6 +174,7 @@ function (swift_benchmark_compile_archopts)
"${srcdir}/${module_name_path}.swift"
COMMAND "${SWIFT_EXEC}"
${common_options}
${extra_options}
"-parse-as-library"
${bench_flags}
"-module-name" "${module_name}"
@@ -281,10 +289,34 @@ function (swift_benchmark_compile_archopts)
set(OUTPUT_EXEC "${benchmark-bin-dir}/Benchmark_${BENCH_COMPILE_ARCHOPTS_OPT}-${target}")
endif()
set(objcfile "${objdir}/ObjectiveCTests.o")
add_custom_command(
OUTPUT "${objcfile}"
DEPENDS "${srcdir}/utils/ObjectiveCTests/ObjectiveCTests.m"
"${srcdir}/utils/ObjectiveCTests/ObjectiveCTests.h"
COMMAND
"${CLANG_EXEC}"
"-fno-stack-protector"
"-fPIC"
"-Werror=date-time"
"-fcolor-diagnostics"
"-O3"
"-target" "${target}"
"-isysroot" "${sdk}"
"-fobjc-arc"
"-arch" "${BENCH_COMPILE_ARCHOPTS_ARCH}"
"-F" "${sdk}/../../../Developer/Library/Frameworks"
"-m${triple_platform}-version-min=${ver}"
"-I" "${srcdir}/utils/ObjectiveCTests"
"${srcdir}/utils/ObjectiveCTests/ObjectiveCTests.m"
"-c"
"-o" "${objcfile}")
add_custom_command(
OUTPUT "${OUTPUT_EXEC}"
DEPENDS
${bench_library_objects} ${SWIFT_BENCH_OBJFILES}
"${objcfile}"
"adhoc-sign-swift-stdlib-${BENCH_COMPILE_ARCHOPTS_PLATFORM}"
COMMAND
"${CLANG_EXEC}"
@@ -306,6 +338,7 @@ function (swift_benchmark_compile_archopts)
"-Xlinker" "@executable_path/../lib/swift/${BENCH_COMPILE_ARCHOPTS_PLATFORM}"
${bench_library_objects}
${SWIFT_BENCH_OBJFILES}
${objcfile}
"-o" "${OUTPUT_EXEC}"
COMMAND
"codesign" "-f" "-s" "-" "${OUTPUT_EXEC}")

View File

@@ -255,10 +255,13 @@ def format_name(log_path):
return '/'.join(log_path.split('/')[-2:])
def compare_logs(compare_script, new_log, old_log):
def compare_logs(compare_script, new_log, old_log, log_dir, opt):
"""Return diff of log files at paths `new_log` and `old_log`"""
print('Comparing %s %s ...' % (format_name(old_log), format_name(new_log)))
subprocess.call([compare_script, old_log, new_log])
subprocess.call([compare_script, '--old-file', old_log,
'--new-file', new_log, '--format', 'markdown',
'--output', os.path.join(log_dir, 'latest_compare_{0}.md'
.format(opt))])
def compare(args):
@@ -288,10 +291,12 @@ def compare(args):
len(recent_logs['master_Onone']) > 1:
compare_logs(compare_script,
recent_logs['master_O'][0],
recent_logs['master_O'][1])
recent_logs['master_O'][1],
log_dir, 'O')
compare_logs(compare_script,
recent_logs['master_Onone'][0],
recent_logs['master_Onone'][1])
recent_logs['master_Onone'][1],
log_dir, 'Onone')
else:
print('master/master comparison skipped: no previous master logs')
else:
@@ -307,10 +312,12 @@ def compare(args):
else:
compare_logs(compare_script,
recent_logs[current_branch + '_O'][0],
recent_logs[current_branch + '_O'][1])
recent_logs[current_branch + '_O'][1],
log_dir, 'O')
compare_logs(compare_script,
recent_logs[current_branch + '_Onone'][0],
recent_logs[current_branch + '_Onone'][1])
recent_logs[current_branch + '_Onone'][1],
log_dir, 'Onone')
if len(recent_logs['master_O']) == 0 or \
len(recent_logs['master_Onone']) == 0:
@@ -319,10 +326,12 @@ def compare(args):
else:
compare_logs(compare_script,
recent_logs[current_branch + '_O'][0],
recent_logs['master_O'][0])
recent_logs['master_O'][0],
log_dir, 'O')
compare_logs(compare_script,
recent_logs[current_branch + '_Onone'][0],
recent_logs['master_Onone'][0])
recent_logs['master_Onone'][0],
log_dir, 'Onone')
# TODO: Fail on large regressions

View File

@@ -13,221 +13,354 @@
#
# ===---------------------------------------------------------------------===//
# e.g.
# repeat.sh 3 tot/bin/Benchmark_Driver run -o -O > tot.O.times
# repeat.sh 3 mypatch/bin/Benchmark_Driver run -o -O > mypatch.O.times
# compare_perf_tests.py tot.O.times mypatch.O.times | sort -t, -n -k 6 | \
# column -s, -t
from __future__ import print_function
import re
import argparse
import csv
import sys
TESTNAME = 1
SAMPLES = 2
MIN = 3
MAX = 4
MEAN = 5
SD = 6
MEDIAN = 7
VERBOSE = 0
HTML = """
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
{0}
</body>
</html>"""
# #,TEST,SAMPLES,MIN(ms),MAX(ms),MEAN(ms),SD(ms),MEDIAN(ms)
SCORERE = re.compile(
r"(\d+),[ \t]*(\w+),[ \t]*([\d.]+),[ \t]*([\d.]+),[ \t]*([\d.]+)")
TOTALRE = re.compile(
r"()(Totals),[ \t]*([\d.]+),[ \t]*([\d.]+),[ \t]*([\d.]+)")
NUMGROUP = 1
KEYGROUP = 2
BESTGROUP = 4
WORSTGROUP = 5
HTML_TABLE = """
<table>
<tr>
<th align='left'>{0}</th>
<th align='left'>{1}</th>
<th align='left'>{2}</th>
<th align='left'>{3}</th>
<th align='left'>{4}</th>
</tr>
{5}
</table>
"""
IsTime = 1
ShowSpeedup = 1
PrintAllScores = 0
HTML_ROW = """
<tr>
<td align='left'>{0}</td>
<td align='left'>{1}</td>
<td align='left'>{2}</td>
<td align='left'>{3}</td>
<td align='left'><font color='{4}'>{5}</font></td>
</tr>
"""
MARKDOWN_ROW = "{0} | {1} | {2} | {3} | {4} \n"
HEADER_SPLIT = "---"
MARKDOWN_DETAIL = """
<details {3}>
<summary>{0} ({1})</summary>
{2}
</details>
"""
PAIN_DETAIL = """
{0}: {1}"""
def parse_int(word):
try:
return int(word)
except ValueError:
raise Exception("Expected integer value, not " + word)
def main():
global RATIO_MIN
global RATIO_MAX
old_results = {}
new_results = {}
old_max_results = {}
new_max_results = {}
ratio_list = {}
delta_list = {}
unknown_list = {}
complete_perf_list = []
increased_perf_list = []
decreased_perf_list = []
normal_perf_list = []
def get_scores(fname):
scores = {}
worstscores = {}
nums = {}
runs = 0
f = open(fname)
try:
for line in f:
if VERBOSE:
print("Parsing", line, end="")
m = SCORERE.match(line)
is_total = False
if not m:
is_total = True
m = TOTALRE.match(line)
if not m:
continue
parser = argparse.ArgumentParser(description="Compare Performance tests.")
parser.add_argument('--old-file',
help='Baseline performance test suite (csv file)',
required=True)
parser.add_argument('--new-file',
help='New performance test suite (csv file)',
required=True)
parser.add_argument('--format',
help='Supported format git, html and markdown',
default="markdown")
parser.add_argument('--output', help='Output file name')
parser.add_argument('--changes-only',
help='Output only affected tests', action='store_true')
parser.add_argument('--new-branch',
help='Name of the new branch', default="NEW_MIN")
parser.add_argument('--old-branch',
help='Name of the old branch', default="OLD_MIN")
parser.add_argument('--delta-threshold',
help='delta threshold', default="0.05")
if VERBOSE:
print(" match", m.group(KEYGROUP), m.group(BESTGROUP))
args = parser.parse_args()
if not m.group(KEYGROUP) in scores:
scores[m.group(KEYGROUP)] = []
worstscores[m.group(KEYGROUP)] = []
scores[m.group(KEYGROUP)].append(parse_int(m.group(BESTGROUP)))
worstscores[m.group(KEYGROUP)].append(
parse_int(m.group(WORSTGROUP)))
if is_total:
nums[m.group(KEYGROUP)] = ""
old_file = args.old_file
new_file = args.new_file
new_branch = args.new_branch
old_branch = args.old_branch
old_data = csv.reader(open(old_file))
new_data = csv.reader(open(new_file))
RATIO_MIN = 1 - float(args.delta_threshold)
RATIO_MAX = 1 + float(args.delta_threshold)
for row in old_data:
if (len(row) > 7 and row[MIN].isdigit()):
if row[TESTNAME] in old_results:
if old_results[row[TESTNAME]] > int(row[MIN]):
old_results[row[TESTNAME]] = int(row[MIN])
if old_max_results[row[TESTNAME]] < int(row[MAX]):
old_max_results[row[TESTNAME]] = int(row[MAX])
else:
nums[m.group(KEYGROUP)] = m.group(NUMGROUP)
if len(scores[m.group(KEYGROUP)]) > runs:
runs = len(scores[m.group(KEYGROUP)])
finally:
f.close()
return scores, worstscores, runs, nums
old_results[row[TESTNAME]] = int(row[MIN])
old_max_results[row[TESTNAME]] = int(row[MAX])
for row in new_data:
if (len(row) > 7 and row[MIN].isdigit()):
if row[TESTNAME] in new_results:
if int(new_results[row[TESTNAME]]) > int(row[MIN]):
new_results[row[TESTNAME]] = int(row[MIN])
if new_max_results[row[TESTNAME]] < int(row[MAX]):
new_max_results[row[TESTNAME]] = int(row[MAX])
else:
new_results[row[TESTNAME]] = int(row[MIN])
new_max_results[row[TESTNAME]] = int(row[MAX])
def is_max_score(newscore, maxscore, invert):
return not maxscore or \
(newscore > maxscore if not invert else newscore < maxscore)
ratio_total = 0
for key in new_results.keys():
ratio = (old_results[key]+0.001)/(new_results[key]+0.001)
ratio_list[key] = round(ratio, 2)
ratio_total *= ratio
delta = (((float(new_results[key]+0.001) /
(old_results[key]+0.001)) - 1) * 100)
delta_list[key] = round(delta, 2)
if ((old_results[key] < new_results[key] and
new_results[key] < old_max_results[key]) or
(new_results[key] < old_results[key] and
old_results[key] < new_max_results[key])):
unknown_list[key] = "(?)"
else:
unknown_list[key] = ""
(complete_perf_list,
increased_perf_list,
decreased_perf_list,
normal_perf_list) = sort_ratio_list(ratio_list, args.changes_only)
def compare_scores(key, score1, worstsample1, score2, worstsample2, runs, num):
print(num.rjust(3), end=" ")
print(key.ljust(25), end="")
bestscore1 = None
bestscore2 = None
worstscore1 = None
worstscore2 = None
minbest = IsTime
minworst = not minbest
r = 0
for score in score1:
if is_max_score(newscore=score, maxscore=bestscore1, invert=minbest):
bestscore1 = score
if is_max_score(newscore=score, maxscore=worstscore1, invert=minworst):
worstscore1 = score
if PrintAllScores:
print (("%d" % score).rjust(16), end="")
for score in worstsample1:
if is_max_score(newscore=score, maxscore=worstscore1, invert=minworst):
worstscore1 = score
for score in score2:
if is_max_score(newscore=score, maxscore=bestscore2, invert=minbest):
bestscore2 = score
if is_max_score(newscore=score, maxscore=worstscore2, invert=minworst):
worstscore2 = score
if PrintAllScores:
print (("%d" % score).rjust(16), end="")
r += 1
for score in worstsample2:
if is_max_score(newscore=score, maxscore=worstscore2, invert=minworst):
worstscore2 = score
while r < runs:
if PrintAllScores:
print ("0".rjust(9), end="")
r += 1
"""
Create markdown formatted table
"""
test_name_width = max_width(ratio_list, title='TEST', key_len=True)
new_time_width = max_width(new_results, title=new_branch)
old_time_width = max_width(old_results, title=old_branch)
delta_width = max_width(delta_list, title='DELTA (%)')
if not PrintAllScores:
print (("%d" % bestscore1).rjust(16), end="")
print (("%d" % bestscore2).rjust(16), end="")
markdown_table_header = "\n" + MARKDOWN_ROW.format(
"TEST".ljust(test_name_width),
old_branch.ljust(old_time_width),
new_branch.ljust(new_time_width),
"DELTA (%)".ljust(delta_width),
"SPEEDUP".ljust(2))
markdown_table_header += MARKDOWN_ROW.format(
HEADER_SPLIT.ljust(test_name_width),
HEADER_SPLIT.ljust(old_time_width),
HEADER_SPLIT.ljust(new_time_width),
HEADER_SPLIT.ljust(delta_width),
HEADER_SPLIT.ljust(2))
markdown_regression = ""
for i, key in enumerate(decreased_perf_list):
ratio = "{0:.2f}x".format(ratio_list[key])
if i == 0:
markdown_regression = markdown_table_header
markdown_regression += MARKDOWN_ROW.format(
key.ljust(test_name_width),
str(old_results[key]).ljust(old_time_width),
str(new_results[key]).ljust(new_time_width),
("{0:+.1f}%".format(delta_list[key])).ljust(delta_width),
"**{0}{1}**".format(str(ratio).ljust(2), unknown_list[key]))
print (("%+d" % (bestscore2 - bestscore1)).rjust(9), end="")
markdown_improvement = ""
for i, key in enumerate(increased_perf_list):
ratio = "{0:.2f}x".format(ratio_list[key])
if i == 0:
markdown_improvement = markdown_table_header
markdown_improvement += MARKDOWN_ROW.format(
key.ljust(test_name_width),
str(old_results[key]).ljust(old_time_width),
str(new_results[key]).ljust(new_time_width),
("{0:+.1f}%".format(delta_list[key])).ljust(delta_width),
"**{0}{1}**".format(str(ratio).ljust(2), unknown_list[key]))
if bestscore1 != 0 and bestscore2 != 0:
print(("%+.1f%%" %
(((float(bestscore2) / bestscore1) - 1) * 100)).rjust(9),
end="")
if ShowSpeedup:
Num, Den = float(bestscore2), float(bestscore1)
if IsTime:
Num, Den = Den, Num
print (("%.2fx" % (Num / Den)).rjust(9), end="")
else:
print("*".rjust(9), end="")
if ShowSpeedup:
print("*".rjust(9), end="")
# check if the worst->best interval for each configuration overlap.
if minbest:
if (bestscore1 < bestscore2 and bestscore2 < worstscore1) \
or (bestscore2 < bestscore1 and bestscore1 < worstscore2):
print("(?)", end="")
else:
if (worstscore1 < worstscore2 and worstscore2 < bestscore1) \
or (worstscore2 < worstscore1 and worstscore1 < bestscore2):
print("(?)", end="")
print()
markdown_normal = ""
for i, key in enumerate(normal_perf_list):
ratio = "{0:.2f}x".format(ratio_list[key])
if i == 0:
markdown_normal = markdown_table_header
markdown_normal += MARKDOWN_ROW.format(
key.ljust(test_name_width),
str(old_results[key]).ljust(old_time_width),
str(new_results[key]).ljust(new_time_width),
("{0:+.1f}%".format(delta_list[key])).ljust(delta_width),
"{0}{1}".format(str(ratio).ljust(2), unknown_list[key]))
markdown_data = MARKDOWN_DETAIL.format("Regression",
len(decreased_perf_list),
markdown_regression, "open")
markdown_data += MARKDOWN_DETAIL.format("Improvement",
len(increased_perf_list),
markdown_improvement, "")
if not args.changes_only:
markdown_data += MARKDOWN_DETAIL.format("No Changes",
len(normal_perf_list),
markdown_normal, "")
def print_best_scores(key, scores):
print(key, end="")
bestscore = None
minbest = IsTime
for score in scores:
if is_max_score(newscore=score, maxscore=bestscore, invert=minbest):
bestscore = score
print(", %d" % bestscore)
if args.format:
if args.format.lower() != "markdown":
pain_data = PAIN_DETAIL.format("Regression", markdown_regression)
pain_data += PAIN_DETAIL.format("Improvement",
markdown_improvement)
if not args.changes_only:
pain_data += PAIN_DETAIL.format("No Changes", markdown_normal)
def usage():
print("repeat.sh <n> Benchmark_O[none|unchecked] > file.times")
print("compare_perf_tests.py <file.times> [<file2.times>]")
if __name__ == '__main__':
if len(sys.argv) < 2:
usage()
sys.exit(1)
file1 = sys.argv[1]
if len(sys.argv) < 3:
scores, worstscores, runs, nums = get_scores(file1)
keys = list(set(scores.keys()))
keys.sort()
for key in keys:
print_best_scores(key, scores[key])
sys.exit(0)
file2 = sys.argv[2]
if len(sys.argv) > 3:
SCORERE = re.compile(sys.argv[3])
scores1, worstscores1, runs1, nums = get_scores(file1)
scores2, worstscores2, runs2, nums = get_scores(file2)
runs = runs1
if runs2 > runs:
runs = runs2
if VERBOSE:
print(scores1)
print(scores2)
keys = list(set(scores1.keys() + scores2.keys()))
keys.sort()
if VERBOSE:
print("comparing ", file1, "vs", file2, "=", end="")
if IsTime:
print(file1, "/", file2)
print(pain_data.replace("|", " ").replace("-", " "))
else:
print(file2, "/", file1)
print(markdown_data)
print("#".rjust(3), end=" ")
print("TEST".ljust(25), end="")
if PrintAllScores:
for i in range(0, runs):
print(("OLD_RUN%d" % i).rjust(9), end="")
for i in range(0, runs):
print(("NEW_RUN%d" % i).rjust(9), end="")
if args.format:
if args.format.lower() == "html":
"""
Create HTML formatted table
"""
html_data = convert_to_html(ratio_list, old_results, new_results,
delta_list, unknown_list, old_branch,
new_branch, args.changes_only)
if args.output:
write_to_file(args.output, html_data)
else:
print("Error: missing --output flag.")
sys.exit(1)
elif args.format.lower() == "markdown":
if args.output:
write_to_file(args.output, markdown_data)
elif args.format.lower() != "git":
print("{0} is unknown format.".format(args.format))
sys.exit(1)
def convert_to_html(ratio_list, old_results, new_results, delta_list,
unknown_list, old_branch, new_branch, changes_only):
(complete_perf_list,
increased_perf_list,
decreased_perf_list,
normal_perf_list) = sort_ratio_list(ratio_list, changes_only)
html_rows = ""
for key in complete_perf_list:
if ratio_list[key] < RATIO_MIN:
color = "red"
elif ratio_list[key] > RATIO_MAX:
color = "green"
else:
color = "black"
if len(decreased_perf_list) > 0 and key == decreased_perf_list[0]:
html_rows += HTML_ROW.format(
"<strong>Regression:</strong>",
"", "", "", "black", "", "")
if len(increased_perf_list) > 0 and key == increased_perf_list[0]:
html_rows += HTML_ROW.format(
"<strong>Improvement:</strong>",
"", "", "", "black", "", "")
if len(normal_perf_list) > 0 and key == normal_perf_list[0]:
html_rows += HTML_ROW.format(
"<strong>No Changes:</strong>",
"", "", "", "black", "", "")
html_rows += HTML_ROW.format(key, old_results[key],
new_results[key],
"{0:+.1f}%".format(delta_list[key]),
color,
"{0:.2f}x {1}".format(ratio_list[key],
unknown_list[key]))
html_table = HTML_TABLE.format("TEST", old_branch, new_branch,
"DELTA (%)", "SPEEDUP", html_rows)
html_data = HTML.format(html_table)
return html_data
def write_to_file(file_name, data):
"""
Write data to given file
"""
file = open(file_name, "w")
file.write(data)
file.close
def sort_ratio_list(ratio_list, changes_only=False):
"""
Return 3 sorted list improvement, regression and normal.
"""
decreased_perf_list = []
increased_perf_list = []
sorted_normal_perf_list = []
normal_perf_list = {}
for key, v in sorted(ratio_list.items(), key=lambda x: x[1]):
if ratio_list[key] < RATIO_MIN:
decreased_perf_list.append(key)
elif ratio_list[key] > RATIO_MAX:
increased_perf_list.append(key)
else:
normal_perf_list[key] = v
for key, v in sorted(normal_perf_list.items(), key=lambda x: x[1],
reverse=True):
sorted_normal_perf_list.append(key)
if changes_only:
complete_perf_list = decreased_perf_list + increased_perf_list
else:
print("BEST_OLD_MIN(μs)".rjust(17), end=" ")
print("BEST_NEW_MIN(μs)".rjust(17), end=" ")
print('DELTA'.rjust(9), '%DELTA'.rjust(9), 'SPEEDUP'.rjust(9))
complete_perf_list = (decreased_perf_list + increased_perf_list +
sorted_normal_perf_list)
for key in keys:
if key not in scores1:
print(key, "not in", file1)
continue
if key not in scores2:
print(key, "not in", file2)
continue
compare_scores(key, scores1[key], worstscores1[key], scores2[key],
worstscores2[key], runs, nums[key])
return (complete_perf_list, increased_perf_list,
decreased_perf_list, sorted_normal_perf_list)
def max_width(items, title, key_len=False):
"""
Returns the max length of string in the list
"""
width = len(str(title))
for key in items.keys():
if key_len:
if width < len(str(key)):
width = len(str(key))
else:
if width < len(str(items[key])):
width = len(str(items[key]))
return width
if __name__ == "__main__":
sys.exit(main())

View File

@@ -14,14 +14,14 @@
// for performance measuring.
import TestsUtils
func ackermann(M : Int, _ N : Int) -> Int {
func ackermann(_ M: Int, _ N : Int) -> Int {
if (M == 0) { return N + 1 }
if (N == 0) { return ackermann(M - 1, 1) }
return ackermann(M - 1, ackermann(M, N - 1))
}
@inline(never)
func Ackermann(M : Int, _ N : Int) -> Int {
func Ackermann(_ M: Int, _ N : Int) -> Int {
// This if prevents optimizer from computing return value of Ackermann(3,9)
// at compile time.
if False() { return 0 }
@@ -33,7 +33,7 @@ func Ackermann(M : Int, _ N : Int) -> Int {
let ref_result = [5, 13, 29, 61, 125, 253, 509, 1021, 2045, 4093, 8189, 16381, 32765, 65533, 131069];
@inline(never)
public func run_Ackermann(N: Int) {
public func run_Ackermann(_ N: Int) {
let (m, n) = (3, 9)
var result = 0
for _ in 1...N {

View File

@@ -31,12 +31,12 @@ var words = [
"Bobby", "Dylan", "Johnny", "Phillip", "Craig"]
@inline(never)
public func run_AngryPhonebook(N: Int) {
public func run_AngryPhonebook(_ N: Int) {
// Permute the names.
for _ in 1...N {
for firstname in words {
for lastname in words {
(firstname.uppercased, lastname.lowercased)
(firstname.uppercased(), lastname.lowercased())
}
}
}

View File

@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===//
@inline(never)
public func run_Array2D(N: Int) {
public func run_Array2D(_ N: Int) {
var A: [[Int]] = []
for _ in 0 ..< 1024 {
var B: [Int] = []

View File

@@ -15,7 +15,7 @@
import TestsUtils
@inline(never)
public func run_ArrayAppend(N: Int) {
public func run_ArrayAppend(_ N: Int) {
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
@@ -27,7 +27,7 @@ public func run_ArrayAppend(N: Int) {
}
@inline(never)
public func run_ArrayAppendReserved(N: Int) {
public func run_ArrayAppendReserved(_ N: Int) {
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()

View File

@@ -17,7 +17,7 @@ class ArrayContainer {
arr = [Int] (repeating: 0, count: 100_000)
}
func runLoop(N: Int) {
func runLoop(_ N: Int) {
for _ in 0 ..< N {
for i in 0 ..< arr.count {
arr[i] = arr[i] + 1
@@ -32,7 +32,7 @@ func getArrayContainer() -> ArrayContainer {
}
@inline(never)
public func run_ArrayInClass(N: Int) {
public func run_ArrayInClass(_ N: Int) {
let a = getArrayContainer()
a.runLoop(N)
}

View File

@@ -21,7 +21,7 @@ func makeArray() -> [Int] {
}
@inline(never)
public func run_ArrayLiteral(N: Int) {
public func run_ArrayLiteral(_ N: Int) {
for _ in 1...10000*N {
makeArray()
}
@@ -34,7 +34,7 @@ func addLiteralArray() -> Int {
}
@inline(never)
public func run_ArrayValueProp(N: Int) {
public func run_ArrayValueProp(_ N: Int) {
var res = 123
for _ in 1...10000*N {
res += addLiteralArray()
@@ -75,7 +75,7 @@ func addLiteralArray4() -> Int {
}
@inline(never)
public func run_ArrayValueProp2(N: Int) {
public func run_ArrayValueProp2(_ N: Int) {
var res = 123
for _ in 1...10000*N {
res += addLiteralArray2()
@@ -85,7 +85,7 @@ public func run_ArrayValueProp2(N: Int) {
}
@inline(never)
public func run_ArrayValueProp3(N: Int) {
public func run_ArrayValueProp3(_ N: Int) {
var res = 123
for _ in 1...10000*N {
res += addLiteralArray3()
@@ -95,7 +95,7 @@ public func run_ArrayValueProp3(N: Int) {
}
@inline(never)
public func run_ArrayValueProp4(N: Int) {
public func run_ArrayValueProp4(_ N: Int) {
var res = 123
for _ in 1...10000*N {
res += addLiteralArray4()

View File

@@ -53,12 +53,12 @@ struct S<T> {
}
@inline(never)
func genStructArray() {
_ = RefArray<S<Int>>(S(x:3,y:4))
_ = RefArray<S<Int>>(S(x:3, y:4))
// should be a nop
}
@inline(never)
public func run_ArrayOfGenericPOD(N: Int) {
public func run_ArrayOfGenericPOD(_ N: Int) {
for _ in 0...N {
genEnumArray()
genIOUArray()

View File

@@ -86,7 +86,7 @@ func genRefStructArray() {
}
@inline(never)
public func run_ArrayOfGenericRef(N: Int) {
public func run_ArrayOfGenericRef(_ N: Int) {
for _ in 0...N {
genPODRefArray()
genCommonRefArray()

View File

@@ -53,7 +53,7 @@ func genStructArray() {
}
@inline(never)
public func run_ArrayOfPOD(N: Int) {
public func run_ArrayOfPOD(_ N: Int) {
for _ in 0...N {
genIntArray()
genEnumArray()

View File

@@ -97,7 +97,7 @@ func genRefStructArray() {
}
@inline(never)
public func run_ArrayOfRef(N: Int) {
public func run_ArrayOfRef(_ N: Int) {
for _ in 0...N {
genPODRefArray()
genCommonRefArray()

View File

@@ -14,13 +14,13 @@
import TestsUtils
@inline(never)
public func run_ArraySubscript(N: Int) {
public func run_ArraySubscript(_ N: Int) {
SRand()
let numArrays = 200*N
let numArrayElements = 100
func bound(x: Int) -> Int { return min(x, numArrayElements-1) }
func bound(_ x: Int) -> Int { return min(x, numArrayElements-1) }
var arrays = [[Int]](repeating: [], count: numArrays)
for i in 0..<numArrays {

View File

@@ -16,7 +16,7 @@
import Foundation
import TestsUtils
func countBitSet(num: Int) -> Int {
func countBitSet(_ num: Int) -> Int {
let bits = sizeof(Int) * 8
var cnt : Int = 0
var mask: Int = 1
@@ -30,7 +30,7 @@ func countBitSet(num: Int) -> Int {
}
@inline(never)
public func run_BitCount(N: Int) {
public func run_BitCount(_ N: Int) {
for _ in 1...100*N {
// Check some results.
CheckResults(countBitSet(1) == 1, "Incorrect results in BitCount.")

View File

@@ -17,7 +17,7 @@ import Foundation
import TestsUtils
// a naive O(n) implementation of byteswap.
func byteswap_n(a: UInt64) -> UInt64 {
func byteswap_n(_ a: UInt64) -> UInt64 {
return ((a & 0x00000000000000FF) << 56) |
((a & 0x000000000000FF00) << 40) |
((a & 0x0000000000FF0000) << 24) |
@@ -29,7 +29,7 @@ func byteswap_n(a: UInt64) -> UInt64 {
}
// a O(logn) implementation of byteswap.
func byteswap_logn(a: UInt64) -> UInt64 {
func byteswap_logn(_ a: UInt64) -> UInt64 {
var a = a
a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32
a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16
@@ -38,7 +38,7 @@ func byteswap_logn(a: UInt64) -> UInt64 {
}
@inline(never)
public func run_ByteSwap(N: Int) {
public func run_ByteSwap(_ N: Int) {
for _ in 1...100*N {
// Check some results.
CheckResults(byteswap_logn(byteswap_n(2457)) == 2457, "Incorrect results in ByteSwap.")

View File

@@ -14,7 +14,7 @@ import TestsUtils
import Foundation
@inline(never)
func my_atoi_impl(input : String) -> Int {
func my_atoi_impl(_ input : String) -> Int {
switch input {
case "0": return 0
case "1": return 1
@@ -31,7 +31,7 @@ func my_atoi_impl(input : String) -> Int {
}
@inline(never)
public func run_Calculator(N: Int) {
public func run_Calculator(_ N: Int) {
var c = 0
for _ in 1...N*5000 {
c += my_atoi_impl("10")

View File

@@ -10,21 +10,21 @@
//
//===----------------------------------------------------------------------===//
func sum(x:Int, y:Int) -> Int {
func sum(_ x:Int, y:Int) -> Int {
return x + y
}
@inline(never)
func benchCaptureProp<S : Sequence
>(
s:S, _ f:(S.Iterator.Element, S.Iterator.Element)->S.Iterator.Element) -> S.Iterator.Element {
_ s: S, _ f: (S.Iterator.Element, S.Iterator.Element) -> S.Iterator.Element) -> S.Iterator.Element {
var it = s.makeIterator()
let initial = it.next()!
return IteratorSequence(it).reduce(initial, combine: f)
}
public func run_CaptureProp(N: Int) {
public func run_CaptureProp(_ N: Int) {
let a = 1...10_000
for _ in 1...100*N {
benchCaptureProp(a, sum)

View File

@@ -14,7 +14,7 @@
import TestsUtils
@inline(never)
public func run_Chars(N: Int) {
public func run_Chars(_ N: Int) {
// Permute some characters.
let alphabet: [Character] = [
"A", "B", "C", "D", "E", "F", "G",

View File

@@ -16,7 +16,7 @@ class Box {
}
@inline(never)
func sumArray(a: [Box]) -> Int {
func sumArray(_ a: [Box]) -> Int {
var s = 0
for i in 0..<a.count {
s += a[i].v
@@ -24,7 +24,7 @@ func sumArray(a: [Box]) -> Int {
return s
}
public func run_ClassArrayGetter(N: Int) {
public func run_ClassArrayGetter(_ N: Int) {
let aSize = 10_000
var a: [Box] = []
a.reserveCapacity(aSize)

View File

@@ -14,7 +14,7 @@
import TestsUtils
@inline(__always)
func debug(m:String) {}
func debug(_ m:String) {}
private var Count = 0
@@ -22,7 +22,7 @@ private var Count = 0
func bar() { Count += 1 }
@inline(never)
func runLoop(var1: Int, var2: Int) {
func runLoop(_ var1: Int, var2: Int) {
for _ in 0..<100_000 {
debug("Var1: \(var1) Var2: \(var2)")
bar()
@@ -30,7 +30,7 @@ func runLoop(var1: Int, var2: Int) {
}
@inline(never)
public func run_DeadArray(N: Int) {
public func run_DeadArray(_ N: Int) {
for _ in 1...N {
Count = 0
runLoop(0, var2: 0)

View File

@@ -161,7 +161,7 @@ class Box<T : Hashable where T : Equatable> : Hashable {
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_Dictionary2(N: Int) {
public func run_Dictionary2(_ N: Int) {
let size = 500
let ref_result = 199
var res = 0
@@ -52,12 +52,12 @@ class Box<T : Hashable where T : Equatable> : Hashable {
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
@inline(never)
public func run_Dictionary2OfObjects(N: Int) {
public func run_Dictionary2OfObjects(_ N: Int) {
let size = 500
let ref_result = 199
var res = 0

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_Dictionary3(N: Int) {
public func run_Dictionary3(_ N: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"
@@ -59,12 +59,12 @@ class Box<T : Hashable where T : Equatable> : Hashable {
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
@inline(never)
public func run_Dictionary3OfObjects(N: Int) {
public func run_Dictionary3OfObjects(_ N: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"

View File

@@ -52,7 +52,7 @@ class Stuff {
}
@inline(never)
public func run_DictionaryBridge(N: Int) {
public func run_DictionaryBridge(_ N: Int) {
for _ in 1...100*N {
_ = Stuff()
}

View File

@@ -20,7 +20,7 @@ func makeDictionary() -> [Int: Int] {
}
@inline(never)
public func run_DictionaryLiteral(N: Int) {
public func run_DictionaryLiteral(_ N: Int) {
for _ in 1...10000*N {
makeDictionary()
}

View File

@@ -15,7 +15,7 @@
import TestsUtils
@inline(never)
public func run_DictionaryRemove(N: Int) {
public func run_DictionaryRemove(_ N: Int) {
let size = 100
var dict = [Int: Int](minimumCapacity: size)
@@ -57,12 +57,12 @@ class Box<T : Hashable where T : Equatable> : Hashable {
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
@inline(never)
public func run_DictionaryRemoveOfObjects(N: Int) {
public func run_DictionaryRemoveOfObjects(_ N: Int) {
let size = 100
var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size)

View File

@@ -15,7 +15,7 @@
import TestsUtils
@inline(never)
public func run_DictionarySwap(N: Int) {
public func run_DictionarySwap(_ N: Int) {
let size = 100
var dict = [Int: Int](minimumCapacity: size)
@@ -40,7 +40,7 @@ public func run_DictionarySwap(N: Int) {
}
// Return true if correctly swapped, false otherwise
func swappedCorrectly(swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {
func swappedCorrectly(_ swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {
return swapped && (p25 == 75 && p75 == 25) ||
!swapped && (p25 == 25 && p75 == 75)
}
@@ -60,12 +60,12 @@ class Box<T : Hashable where T : Equatable> : Hashable {
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
@inline(never)
public func run_DictionarySwapOfObjects(N: Int) {
public func run_DictionarySwapOfObjects(_ N: Int) {
let size = 100
var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size)

View File

@@ -29,7 +29,7 @@ func doSomething() throws -> String {
}
@inline(never)
public func run_ErrorHandling(N: Int) {
public func run_ErrorHandling(_ N: Int) {
for _ in 1...5000*N {
do {
try doSomething()

View File

@@ -12,13 +12,13 @@
import TestsUtils
func fibonacci(n: Int) -> Int {
func fibonacci(_ n: Int) -> Int {
if (n < 2) { return 1 }
return fibonacci(n - 2) + fibonacci(n - 1)
}
@inline(never)
func Fibonacci(n: Int) -> Int {
func Fibonacci(_ n: Int) -> Int {
// This if prevents optimizer from computing return value of Fibonacci(32)
// at compile time.
if False() { return 0 }
@@ -28,7 +28,7 @@ func Fibonacci(n: Int) -> Int {
}
@inline(never)
public func run_Fibonacci(N: Int) {
public func run_Fibonacci(_ N: Int) {
let n = 32
let ref_result = 3524578
var result = 0

View File

@@ -16,7 +16,7 @@ import TestsUtils
class A
{
func f(a : Int) -> Int
func f(_ a: Int) -> Int
{
return a + 1
}
@@ -25,7 +25,7 @@ class A
var x = 0
var a = A()
@inline(never)
public func run_GlobalClass(N: Int) {
public func run_GlobalClass(_ N: Int) {
for _ in 0..<N
{
x = a.f(x)

View File

@@ -28,7 +28,7 @@ class TowersOfHanoi {
// Record all moves made.
var moves : [Move] = [Move]()
func solve(n: Int, start: String, auxiliary: String, end: String) {
func solve(_ n: Int, start: String, auxiliary: String, end: String) {
if (n == 1) {
moves.append(Move(from:start, to:end))
} else {
@@ -40,7 +40,7 @@ class TowersOfHanoi {
}
@inline(never)
public func run_Hanoi(N: Int) {
public func run_Hanoi(_ N: Int) {
for _ in 1...100*N {
let hanoi: TowersOfHanoi = TowersOfHanoi()
hanoi.solve(10, start: "A", auxiliary: "B", end: "C")

View File

@@ -25,7 +25,7 @@ class Hash {
}
/// \brief Add the bytes in \p Msg to the hash.
func update(Msg: String) {
func update(_ Msg: String) {
for c in Msg.unicodeScalars {
data[dataLength] = UInt8(ascii: c)
dataLength += 1
@@ -35,7 +35,7 @@ class Hash {
}
/// \brief Add the bytes in \p Msg to the hash.
func update(Msg: [UInt8]) {
func update(_ Msg: [UInt8]) {
for c in Msg {
data[dataLength] = c
dataLength += 1
@@ -52,7 +52,7 @@ class Hash {
return x
}
func digestFast(Res: inout [UInt8]) {
func digestFast(_ Res: inout [UInt8]) {
fillBlock()
hash()
// We use [UInt8] to avoid using String::append.
@@ -76,7 +76,7 @@ class Hash {
func hashState() -> String {
fatalError("Pure virtual")
}
func hashStateFast(Res: inout [UInt8]) {
func hashStateFast(_ Res: inout [UInt8]) {
fatalError("Pure virtual")
}
@@ -91,7 +91,7 @@ class Hash {
/// \brief Convert a 4-byte integer to a hex string.
final
func toHex(In: UInt32) -> String {
func toHex(_ In: UInt32) -> String {
var In = In
var Res = ""
for _ in 0..<8 {
@@ -102,7 +102,7 @@ class Hash {
}
final
func toHexFast(In: UInt32, _ Res: inout Array<UInt8>, _ Index : Int) {
func toHexFast(_ In: UInt32, _ Res: inout Array<UInt8>, _ Index : Int) {
var In = In
for i in 0..<4 {
// Convert one byte each iteration.
@@ -114,7 +114,7 @@ class Hash {
/// \brief Left-rotate \p x by \p c.
final
func rol(x: UInt32, _ c: UInt32) -> UInt32 {
func rol(_ x: UInt32, _ c: UInt32) -> UInt32 {
// TODO: use the &>> operator.
let a = UInt32(truncatingBitPattern: Int64(x) << Int64(c))
let b = UInt32(truncatingBitPattern: Int64(x) >> (32 - Int64(c)))
@@ -123,7 +123,7 @@ class Hash {
/// \brief Right-rotate \p x by \p c.
final
func ror(x: UInt32, _ c: UInt32) -> UInt32 {
func ror(_ x: UInt32, _ c: UInt32) -> UInt32 {
// TODO: use the &>> operator.
let a = UInt32(truncatingBitPattern: Int64(x) >> Int64(c))
let b = UInt32(truncatingBitPattern: Int64(x) << (32 - Int64(c)))
@@ -178,7 +178,7 @@ class MD5 : Hash {
dataLength = 0
}
func appendBytes(Val: Int, _ Message: inout Array<UInt8>, _ Offset : Int) {
func appendBytes(_ Val: Int, _ Message: inout Array<UInt8>, _ Offset : Int) {
Message[Offset] = UInt8(truncatingBitPattern: Val)
Message[Offset + 1] = UInt8(truncatingBitPattern: Val >> 8)
Message[Offset + 2] = UInt8(truncatingBitPattern: Val >> 16)
@@ -215,7 +215,7 @@ class MD5 : Hash {
dataLength += 8
}
func toUInt32(Message: Array<UInt8>, _ Offset: Int) -> UInt32 {
func toUInt32(_ Message: Array<UInt8>, _ Offset: Int) -> UInt32 {
let first = UInt32(Message[Offset + 0])
let second = UInt32(Message[Offset + 1]) << 8
let third = UInt32(Message[Offset + 2]) << 16
@@ -272,7 +272,7 @@ class MD5 : Hash {
h3 = d &+ h3
}
func reverseBytes(In: UInt32) -> UInt32 {
func reverseBytes(_ In: UInt32) -> UInt32 {
let B0 = (In >> 0 ) & 0xFF
let B1 = (In >> 8 ) & 0xFF
let B2 = (In >> 16) & 0xFF
@@ -290,7 +290,7 @@ class MD5 : Hash {
}
override
func hashStateFast(Res: inout [UInt8]) {
func hashStateFast(_ Res: inout [UInt8]) {
#if !NO_RANGE
var Idx : Int = 0
for h in [h0, h1, h2, h3] {
@@ -374,7 +374,10 @@ class SHA1 : Hash {
// Init the rest of the "W" buffer.
for t in 16..<80 {
w[t] = rol((w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]) ,1)
// splitting into 2 subexpressions to help typechecker
let lhs = w[t-3] ^ w[t-8]
let rhs = w[t-14] ^ w[t-16]
w[t] = rol(lhs ^ rhs, 1)
}
dataLength = 0
@@ -572,7 +575,7 @@ func == (lhs: [UInt8], rhs: [UInt8]) -> Bool {
}
@inline(never)
public func run_HashTest(N: Int) {
public func run_HashTest(_ N: Int) {
let TestMD5 = ["" : "d41d8cd98f00b204e9800998ecf8427e",
"The quick brown fox jumps over the lazy dog." : "e4d909c290d0fb1ca068ffaddf22cbd0",
"The quick brown fox jumps over the lazy cog." : "68aa5deab43e4df2b5e1f80190477fb0"]

View File

@@ -16,7 +16,7 @@ import TestsUtils
typealias rrggbb_t = UInt32
func output_sorted_sparse_rgb_histogram<S: Sequence where S.Iterator.Element == rrggbb_t>(samples: S, _ N: Int) {
func output_sorted_sparse_rgb_histogram<S: Sequence where S.Iterator.Element == rrggbb_t>(_ samples: S, _ N: Int) {
var histogram = Dictionary<rrggbb_t, Int>()
for _ in 1...50*N {
for sample in samples { // This part is really awful, I agree
@@ -109,6 +109,6 @@ let samples: [rrggbb_t] = [
]
@inline(never)
public func run_Histogram(N: Int) {
public func run_Histogram(_ N: Int) {
output_sorted_sparse_rgb_histogram(samples, N);
}

View File

@@ -18,13 +18,13 @@ import TestsUtils
class Integrate {
static let epsilon = 1.0e-9;
let fun:(Double)->Double;
let fun: (Double) -> Double;
init (f:(Double)->Double) {
init (f: (Double) -> Double) {
fun = f;
}
private func recEval(l:Double, fl:Double, r:Double, fr:Double, a:Double)->Double {
private func recEval(_ l: Double, fl: Double, r: Double, fr: Double, a: Double) -> Double {
let h = (r - l) / 2
let hh = h / 2
let c = l + h
@@ -43,13 +43,13 @@ class Integrate {
}
@inline(never)
func computeArea(left:Double, right:Double)->Double {
func computeArea(_ left: Double, right: Double) -> Double {
return recEval(left, fl:fun(left), r:right, fr:fun(right), a:0)
}
}
@inline(never)
public func run_Integrate(N: Int) {
public func run_Integrate(_ N: Int) {
let obj = Integrate(f: { x in (x*x + 1.0) * x});
let left = 0.0
let right = 10.0

View File

@@ -14,7 +14,7 @@
import TestsUtils
@inline(never)
public func run_Join(N: Int) {
public func run_Join(_ N: Int) {
var array: [String] = []
for x in 0..<1000 * N {
array.append(String(x))

View File

@@ -25,7 +25,7 @@ final class Node {
}
@inline(never)
public func run_LinkedList(N: Int) {
public func run_LinkedList(_ N: Int) {
let size = 100
var head = Node(n:nil, d:0)
for i in 0..<size {

View File

@@ -14,7 +14,7 @@ import TestsUtils
import Foundation
@inline(never)
public func run_MapReduce(N: Int) {
public func run_MapReduce(_ N: Int) {
var numbers = [Int](0..<1000)
var c = 0

View File

@@ -13,14 +13,14 @@
import TestsUtils
@inline(never)
func memset(a: inout [Int], _ c: Int) {
func memset(_ a: inout [Int], _ c: Int) {
for i in 0..<a.count {
a[i] = c
}
}
@inline(never)
public func run_Memset(N: Int) {
public func run_Memset(_ N: Int) {
var a = [Int](repeating: 0, count: 10_000)
for _ in 1...50*N {
memset(&a, 1)

View File

@@ -19,7 +19,7 @@ import Foundation
import TestsUtils
@inline(never)
public func run_NSDictionaryCastToSwift(N: Int) {
public func run_NSDictionaryCastToSwift(_ N: Int) {
let NSDict = NSDictionary()
var swiftDict = [String: NSObject]()
for _ in 1...10000*N {

View File

@@ -29,12 +29,12 @@ class G : K {
override func buzz() throws -> Int { return 0 }
}
func caller(x : P) throws {
func caller(_ x: P) throws {
try x.buzz()
}
@inline(never)
public func run_NSError(N: Int) {
public func run_NSError(_ N: Int) {
for _ in 1...N*1000 {
let k = K()
let g = G()

View File

@@ -14,7 +14,7 @@
import TestsUtils
import Foundation
public func run_NSStringConversion(N: Int) {
public func run_NSStringConversion(_ N: Int) {
let test:NSString = NSString(cString: "test", encoding: NSASCIIStringEncoding)!
for _ in 1...N * 10000 {
test as String

View File

@@ -24,7 +24,7 @@ class X<T : Comparable> {
}
}
public func run_NopDeinit(N: Int) {
public func run_NopDeinit(_ N: Int) {
for _ in 1...N {
var arr :[X<Int>] = []
let size = 500

View File

@@ -42,7 +42,7 @@ final class LinkedNode {
}
@inline(never)
func getInt(x: XX) -> Int {
func getInt(_ x: XX) -> Int {
return x.xx
}
@@ -57,7 +57,7 @@ func testSingleObject() -> Int {
}
@inline(never)
func addInts(t: TreeNode) -> Int {
func addInts(_ t: TreeNode) -> Int {
return t.left.xx + t.right.xx
}
@@ -72,7 +72,7 @@ func testTree() -> Int {
}
@inline(never)
func addAllInts(n: LinkedNode) -> Int {
func addAllInts(_ n: LinkedNode) -> Int {
var s = 0
var iter: LinkedNode? = n
while let iter2 = iter {
@@ -93,7 +93,7 @@ func testList() -> Int {
}
@inline(never)
func identity(x: Int) -> Int {
func identity(_ x: Int) -> Int {
return x
}
@@ -109,7 +109,7 @@ func testArray() -> Int {
}
@inline(never)
public func run_ObjectAllocation(N: Int) {
public func run_ObjectAllocation(_ N: Int) {
var SingleObjectResult = 0
var TreeResult = 0

View File

@@ -22,12 +22,12 @@ enum MyState : String {
}
@inline(never)
func check_state(state : MyState) -> Int {
func check_state(_ state : MyState) -> Int {
return state == .Opened ? 1 : 0
}
@inline(never)
public func run_OpenClose(N: Int) {
public func run_OpenClose(_ N: Int) {
var c = 0
for _ in 1...N*10000 {
c += check_state(MyState.Closed)

View File

@@ -59,7 +59,7 @@ func <(lhs: Record, rhs: Record) -> Bool {
}
@inline(never)
public func run_Phonebook(N: Int) {
public func run_Phonebook(_ N: Int) {
// The list of names in the phonebook.
var Names : [Record] = []
for first in words {

View File

@@ -244,7 +244,7 @@ public class F3 : B3 {
// Test the cost of polymorphic method invocation
// on a class without any subclasses
@inline(never)
func test(a:A, _ UPTO: Int) -> Int64 {
func test(_ a:A, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO {
cnt += a.run2()
@@ -255,7 +255,7 @@ func test(a:A, _ UPTO: Int) -> Int64 {
// Test the cost of polymorphic method invocation
// on a class with 1 subclass
@inline(never)
func test(a:A1, _ UPTO: Int) -> Int64 {
func test(_ a:A1, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO {
cnt += a.run2()
@@ -266,7 +266,7 @@ func test(a:A1, _ UPTO: Int) -> Int64 {
// Test the cost of polymorphic method invocation
// on a class with 2 subclasses
@inline(never)
func test(a:A2, _ UPTO: Int) -> Int64 {
func test(_ a:A2, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO {
cnt += a.run2()
@@ -278,7 +278,7 @@ func test(a:A2, _ UPTO: Int) -> Int64 {
// on a class with 2 subclasses on objects
// of different subclasses
@inline(never)
func test(a2_c2:A2, _ a2_d2:A2, _ UPTO: Int) -> Int64 {
func test(_ a2_c2:A2, _ a2_d2:A2, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO/2 {
cnt += a2_c2.run2()
@@ -291,7 +291,7 @@ func test(a2_c2:A2, _ a2_d2:A2, _ UPTO: Int) -> Int64 {
// on a class with 4 subclasses on objects
// of different subclasses
@inline(never)
func test(a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ UPTO: Int) -> Int64 {
func test(_ a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO/4 {
cnt += a3_c3.run2()
@@ -305,7 +305,7 @@ func test(a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ UPTO: Int) -> Int6
@inline(never)
public func run_PolymorphicCalls(N:Int) {
public func run_PolymorphicCalls(_ N:Int) {
let UPTO = 10000 * N
let a = A(b:B(x:1))

View File

@@ -16,7 +16,7 @@ let reps = 1
let arrayCount = 1024
@inline(never)
public func run_PopFrontArray(N: Int) {
public func run_PopFrontArray(_ N: Int) {
let orig = Array(repeating: 1, count: arrayCount)
var a = [Int]()
for _ in 1...20*N {
@@ -33,7 +33,7 @@ public func run_PopFrontArray(N: Int) {
}
@inline(never)
public func run_PopFrontUnsafePointer(N: Int) {
public func run_PopFrontUnsafePointer(_ N: Int) {
var orig = Array(repeating: 1, count: arrayCount)
let a = UnsafeMutablePointer<Int>(allocatingCapacity: arrayCount)
for _ in 1...100*N {

View File

@@ -21,14 +21,14 @@ let arrayCount = 1024
func _arrayReplace<B: _ArrayBufferProtocol, C: Collection
where C.Iterator.Element == B.Element, B.Index == Int
>(
target: inout B, _ subRange: Range<Int>, _ newValues: C
_ target: inout B, _ subRange: Range<Int>, _ newValues: C
) {
_precondition(
subRange.startIndex >= 0,
subRange.lowerBound >= 0,
"Array replace: subRange start is negative")
_precondition(
subRange.endIndex <= target.endIndex,
subRange.upperBound <= target.endIndex,
"Array replace: subRange extends past the end")
let oldCount = target.count
@@ -46,7 +46,7 @@ func _arrayReplace<B: _ArrayBufferProtocol, C: Collection
@inline(never)
public func run_PopFrontArrayGeneric(N: Int) {
public func run_PopFrontArrayGeneric(_ N: Int) {
let orig = Array(repeating: 1, count: arrayCount)
var a = [Int]()
for _ in 1...20*N {

View File

@@ -37,7 +37,7 @@ class PriorityQueue {
}
// Insert element N to heap, maintaining the heap property.
func insert(n : EdgeCost) {
func insert(_ n: EdgeCost) {
let ind: Int = heap.count
heap.append(n)
graphIndexToHeapIndexMap[n.to] = heap.count - 1
@@ -46,7 +46,7 @@ class PriorityQueue {
// Insert element N if in's not in the heap, or update its cost if the new
// value is less than the existing one.
func insertOrUpdate(n : EdgeCost) {
func insertOrUpdate(_ n: EdgeCost) {
let id = n.to
let c = n.cost
if let ind = graphIndexToHeapIndexMap[id] {
@@ -64,7 +64,7 @@ class PriorityQueue {
// Restore heap property by moving element at index IND up.
// This is needed after insertion, and after decreasing an element's cost.
func bubbleUp(ind: Int) {
func bubbleUp(_ ind: Int) {
var ind = ind
let c = heap[ind].cost
while (ind != 0) {
@@ -93,7 +93,7 @@ class PriorityQueue {
// Restore heap property by moving element at index IND down.
// This is needed after removing an element, and after increasing an
// element's cost.
func bubbleDown(ind: Int) {
func bubbleDown(_ ind: Int) {
var ind = ind
let n = heap.count
while (ind < n) {
@@ -118,7 +118,7 @@ class PriorityQueue {
// Swaps elements I and J in the heap and correspondingly updates
// graphIndexToHeapIndexMap.
func Swap(i: Int, with j : Int) {
func Swap(_ i: Int, with j : Int) {
if (i == j) {
return
}
@@ -139,13 +139,13 @@ class PriorityQueue {
}
}
func getLeftChildIndex(index : Int) -> Int {
func getLeftChildIndex(_ index : Int) -> Int {
return index*2 + 1
}
func getRightChildIndex(index : Int) -> Int {
func getRightChildIndex(_ index : Int) -> Int {
return (index + 1)*2
}
func getParentIndex(childIndex : Int) -> Int {
func getParentIndex(_ childIndex : Int) -> Int {
return (childIndex - 1)/2
}
}
@@ -183,7 +183,7 @@ extension Edge : Hashable {
}
}
func Prims(graph : Array<GraphNode>, _ fun : (Int,Int)->Double) -> Array<Int?> {
func Prims(_ graph : Array<GraphNode>, _ fun : (Int, Int) -> Double) -> Array<Int?> {
var treeEdges = Array<Int?>(repeating:nil, count:graph.count)
let queue = PriorityQueue(Num:graph.count)
@@ -214,7 +214,7 @@ func Prims(graph : Array<GraphNode>, _ fun : (Int,Int)->Double) -> Array<Int?> {
}
@inline(never)
public func run_Prims(N: Int) {
public func run_Prims(_ N: Int) {
for _ in 1...5*N {
let nodes : [Int] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
@@ -226,7 +226,7 @@ public func run_Prims(N: Int) {
// Prim's algorithm is designed for undirected graphs.
// Due to that, in our set all the edges are paired, i.e. for any
// edge (start,end,C) there is also an edge (end,start,C).
// edge (start, end, C) there is also an edge (end, start, C).
let edges : [(Int, Int, Double)] = [
(26, 47, 921),
(20, 25, 971),

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_ProtocolDispatch(N: Int) {
public func run_ProtocolDispatch(_ N: Int) {
let x = someProtocolFactory()

View File

@@ -27,7 +27,7 @@ struct Game : Pingable {
}
@inline(never)
func use_protocol(val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
func use_protocol(_ val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
var t = game1.ping() + game1.pong()
if (val % 2 == 0) {
t += game1.pong() + game1.ping()
@@ -44,12 +44,12 @@ func use_protocol(val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
}
@inline(never)
func wrapper(val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
func wrapper(_ val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
return use_protocol(val, game1, game2)
}
@inline(never)
public func run_ProtocolDispatch2(N: Int) {
public func run_ProtocolDispatch2(_ N: Int) {
var c = 0
let g1 = Game()
let g2 = Game()

View File

@@ -24,7 +24,7 @@ struct RC4 {
}
mutating
func initialize(Key: [UInt8]) {
func initialize(_ Key: [UInt8]) {
for i in 0..<256 {
State[i] = UInt8(i)
}
@@ -39,7 +39,7 @@ struct RC4 {
}
mutating
func swapByIndex(x: Int, y: Int) {
func swapByIndex(_ x: Int, y: Int) {
let T1 : UInt8 = State[x]
let T2 : UInt8 = State[y]
State[x] = T2
@@ -55,7 +55,7 @@ struct RC4 {
}
mutating
func encrypt(Data: inout [UInt8]) {
func encrypt(_ Data: inout [UInt8]) {
let cnt = Data.count
for i in 0..<cnt {
Data[i] = Data[i] ^ next()
@@ -76,7 +76,7 @@ let RefResults : [UInt8] = [245, 62, 245, 202, 138, 120, 186, 107, 255, 189,
@inline(never)
public func run_RC4(N: Int) {
public func run_RC4(_ N: Int) {
let messageLen = 100
let iterations = 500
let Secret = "This is my secret message"

View File

@@ -19,7 +19,7 @@ import Foundation
import TestsUtils
@inline(never)
public func run_RGBHistogram(N: Int) {
public func run_RGBHistogram(_ N: Int) {
var histogram = [(key: rrggbb_t, value: Int)]()
for _ in 1...100*N {
histogram = createSortedSparseRGBHistogram(samples)
@@ -86,7 +86,7 @@ let samples: [rrggbb_t] = [
0x607F4D9F, 0x9733E55E, 0xA360439D, 0x1DB568FD, 0xB7A5C3A1, 0xBE84492D
]
func isCorrectHistogram(histogram: [(key: rrggbb_t, value: Int)]) -> Bool {
func isCorrectHistogram(_ histogram: [(key: rrggbb_t, value: Int)]) -> Bool {
return histogram.count == 157 &&
histogram[0].0 == 0x00808080 && histogram[0].1 == 54 &&
histogram[156].0 == 0x003B8D96 && histogram[156].1 == 1
@@ -94,7 +94,7 @@ func isCorrectHistogram(histogram: [(key: rrggbb_t, value: Int)]) -> Bool {
func createSortedSparseRGBHistogram
<S: Sequence where S.Iterator.Element == rrggbb_t>
(samples: S) -> [(key: rrggbb_t, value: Int)] {
(_ samples: S) -> [(key: rrggbb_t, value: Int)] {
var histogram = Dictionary<rrggbb_t, Int>()
for sample in samples {
@@ -126,11 +126,11 @@ class Box<T : Hashable where T : Equatable> : Hashable {
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
func isCorrectHistogramOfObjects(histogram: [(key: Box<rrggbb_t>, value: Box<Int>)]) -> Bool {
func isCorrectHistogramOfObjects(_ histogram: [(key: Box<rrggbb_t>, value: Box<Int>)]) -> Bool {
return histogram.count == 157 &&
histogram[0].0.value == 0x00808080 && histogram[0].1.value == 54 &&
histogram[156].0.value == 0x003B8D96 && histogram[156].1.value == 1
@@ -138,7 +138,7 @@ func isCorrectHistogramOfObjects(histogram: [(key: Box<rrggbb_t>, value: Box<Int
func createSortedSparseRGBHistogramOfObjects
<S: Sequence where S.Iterator.Element == rrggbb_t>
(samples: S) -> [(key: Box<rrggbb_t>, value: Box<Int>)] {
(_ samples: S) -> [(key: Box<rrggbb_t>, value: Box<Int>)] {
var histogram = Dictionary<Box<rrggbb_t>, Box<Int>>()
for sample in samples {
@@ -157,7 +157,7 @@ func createSortedSparseRGBHistogramOfObjects
}
@inline(never)
public func run_RGBHistogramOfObjects(N: Int) {
public func run_RGBHistogramOfObjects(_ N: Int) {
var histogram = [(key: Box<rrggbb_t>, value: Box<Int>)]()
for _ in 1...100*N {
histogram = createSortedSparseRGBHistogramOfObjects(samples)

View File

@@ -13,8 +13,8 @@
import TestsUtils
@inline(never)
public func run_RangeAssignment(scale: Int) {
let range = 100..<200
public func run_RangeAssignment(_ scale: Int) {
let range: Range = 100..<200
var vector = [Double](repeating: 0.0 , count: 5000)
let alfa = 1.0
let N = 500*scale

View File

@@ -27,7 +27,7 @@ class ArrayWrapper {
data = [Int](repeating: initialValue, count: count)
}
func compare(b: ArrayWrapper, _ iteration: Int, _ stopIteration: Int) -> Bool {
func compare(_ b: ArrayWrapper, _ iteration: Int, _ stopIteration: Int) -> Bool {
// We will never return true here by design. We want to test the full effect
// every time of retaining, releasing.
if iteration == stopIteration || data[iteration] == b.data[iteration] {
@@ -39,7 +39,7 @@ class ArrayWrapper {
}
@inline(never)
public func run_RecursiveOwnedParameter(N: Int) {
public func run_RecursiveOwnedParameter(_ N: Int) {
let numElts = 1_000
let a = ArrayWrapper(numElts, 0)

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_SetIsSubsetOf(N: Int) {
public func run_SetIsSubsetOf(_ N: Int) {
let size = 200
SRand()
@@ -28,7 +28,7 @@ public func run_SetIsSubsetOf(N: Int) {
var isSubset = false;
for _ in 0 ..< N * 5000 {
isSubset = set.isSubsetOf(otherSet)
isSubset = set.isSubset(of: otherSet)
if isSubset {
break
}
@@ -38,11 +38,11 @@ public func run_SetIsSubsetOf(N: Int) {
}
@inline(never)
func sink(s: inout Set<Int>) {
func sink(_ s: inout Set<Int>) {
}
@inline(never)
public func run_SetExclusiveOr(N: Int) {
public func run_SetExclusiveOr(_ N: Int) {
let size = 400
SRand()
@@ -57,13 +57,13 @@ public func run_SetExclusiveOr(N: Int) {
var xor = Set<Int>()
for _ in 0 ..< N * 100 {
xor = set.exclusiveOr(otherSet)
xor = set.symmetricDifference(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion(N: Int) {
public func run_SetUnion(_ N: Int) {
let size = 400
SRand()
@@ -84,7 +84,7 @@ public func run_SetUnion(N: Int) {
}
@inline(never)
public func run_SetIntersect(N: Int) {
public func run_SetIntersect(_ N: Int) {
let size = 400
SRand()
@@ -99,7 +99,7 @@ public func run_SetIntersect(N: Int) {
var and = Set<Int>()
for _ in 0 ..< N * 100 {
and = set.intersect(otherSet)
and = set.intersection(otherSet)
}
sink(&and)
}
@@ -119,12 +119,12 @@ class Box<T : Hashable where T : Equatable> : Hashable {
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
@inline(never)
public func run_SetIsSubsetOf_OfObjects(N: Int) {
public func run_SetIsSubsetOf_OfObjects(_ N: Int) {
let size = 200
SRand()
@@ -139,7 +139,7 @@ public func run_SetIsSubsetOf_OfObjects(N: Int) {
var isSubset = false;
for _ in 0 ..< N * 5000 {
isSubset = set.isSubsetOf(otherSet)
isSubset = set.isSubset(of: otherSet)
if isSubset {
break
}
@@ -149,11 +149,11 @@ public func run_SetIsSubsetOf_OfObjects(N: Int) {
}
@inline(never)
func sink(s: inout Set<Box<Int>>) {
func sink(_ s: inout Set<Box<Int>>) {
}
@inline(never)
public func run_SetExclusiveOr_OfObjects(N: Int) {
public func run_SetExclusiveOr_OfObjects(_ N: Int) {
let size = 400
SRand()
@@ -168,13 +168,13 @@ public func run_SetExclusiveOr_OfObjects(N: Int) {
var xor = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
xor = set.exclusiveOr(otherSet)
xor = set.symmetricDifference(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion_OfObjects(N: Int) {
public func run_SetUnion_OfObjects(_ N: Int) {
let size = 400
SRand()
@@ -195,7 +195,7 @@ public func run_SetUnion_OfObjects(N: Int) {
}
@inline(never)
public func run_SetIntersect_OfObjects(N: Int) {
public func run_SetIntersect_OfObjects(_ N: Int) {
let size = 400
SRand()
@@ -210,7 +210,7 @@ public func run_SetIntersect_OfObjects(N: Int) {
var and = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
and = set.intersect(otherSet)
and = set.intersection(otherSet)
}
sink(&and)
}

View File

@@ -14,14 +14,14 @@ import TestsUtils
import Foundation
@inline(never)
func filter_seven(input : Int) throws {
func filter_seven(_ input : Int) throws {
guard case 7 = input else {
throw NSError(domain: "AnDomain", code: 42, userInfo: nil)
}
}
@inline(never)
public func run_SevenBoom(N: Int) {
public func run_SevenBoom(_ N: Int) {
var c = 0
for i in 1...N*5000 {
do {

View File

@@ -23,7 +23,7 @@ struct Array2D {
}
@inline(never)
func workload_2DArrayTest(A: inout Array2D) {
func workload_2DArrayTest(_ A: inout Array2D) {
for _ in 0 ..< 10 {
for r in 0 ..< A.rows {
for c in 0 ..< A.cols {
@@ -34,7 +34,7 @@ func workload_2DArrayTest(A: inout Array2D) {
}
@inline(never)
public func run_Sim2DArray(N : Int) {
public func run_Sim2DArray(_ N: Int) {
for _ in 0 ..< N {
var A = Array2D(numRows:2048, numCols:32)
workload_2DArrayTest(&A)

View File

@@ -23,7 +23,7 @@ class Letter {
}
@inline(never)
public func run_SortLettersInPlace(N: Int) {
public func run_SortLettersInPlace(_ N: Int) {
for _ in 1...100*N {
var letters = [
Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"),

File diff suppressed because it is too large Load Diff

View File

@@ -19,16 +19,16 @@ import TestsUtils
protocol StaticArrayProtocol {
associatedtype ElemTy
init(_ defaultValue : ElemTy)
func get(idx : Int) -> ElemTy
mutating func set(idx : Int,_ val : ElemTy)
func get(_ idx : Int) -> ElemTy
mutating func set(_ idx : Int,_ val : ElemTy)
func count() -> Int
}
struct A0<ElemTy> : StaticArrayProtocol {
init(_ defaultValue : ElemTy) { x = defaultValue }
var x : ElemTy
func get(idx : Int) -> ElemTy { if idx == 0 { return x } else { fatalError("oob"); } }
mutating func set(idx : Int,_ val : ElemTy) { if idx == 0 { x = val }}
func get(_ idx : Int) -> ElemTy { if idx == 0 { return x } else { fatalError("oob"); } }
mutating func set(_ idx : Int,_ val : ElemTy) { if idx == 0 { x = val }}
func count() -> Int { return 1}
}
@@ -36,19 +36,24 @@ struct A2X<T : StaticArrayProtocol> : StaticArrayProtocol {
init(_ defaultValue : T.ElemTy) { lower = T(defaultValue); upper = T(defaultValue) }
var lower : T
var upper : T
func get(idx : Int) -> T.ElemTy { let size = lower.count(); if idx < size { return lower.get(idx) } else { return upper.get(idx - size) }}
mutating func set(idx : Int,_ val : T.ElemTy) {let size = lower.count(); if idx < size { return lower.set(idx, val) } else { return upper.set(idx - size, val) }}
func get(_ idx: Int) -> T.ElemTy { let size = lower.count(); if idx < size { return lower.get(idx) } else { return upper.get(idx - size) }}
mutating func set(_ idx: Int,_ val : T.ElemTy) {let size = lower.count(); if idx < size { return lower.set(idx, val) } else { return upper.set(idx - size, val) }}
func count() -> Int { return upper.count() + lower.count() }
}
struct StaticArray<T : StaticArrayProtocol> : StaticArrayProtocol, MutableCollection {
struct StaticArray<
T : StaticArrayProtocol
> : StaticArrayProtocol, RandomAccessCollection, MutableCollection {
typealias Indices = CountableRange<Int>
init(_ defaultValue : T.ElemTy) { values = T(defaultValue) }
var values : T
func get(idx : Int) -> T.ElemTy { return values.get(idx) }
mutating func set(idx : Int,_ val : T.ElemTy) { return values.set(idx, val) }
func get(_ idx: Int) -> T.ElemTy { return values.get(idx) }
mutating func set(_ idx: Int,_ val : T.ElemTy) { return values.set(idx, val) }
func count() -> Int { return values.count() }
typealias Index = Int
typealias IndexDistance = Int
let startIndex: Int = 0
var endIndex: Int { return count()}
@@ -62,6 +67,11 @@ struct StaticArray<T : StaticArrayProtocol> : StaticArrayProtocol, MutableCollec
}
typealias Iterator = IndexingIterator<StaticArray>
subscript(bounds: Range<Index>) -> StaticArray<T> {
get { fatalError() }
set { fatalError() }
}
}
typealias SA2Int = StaticArray<A0<Int>>
@@ -74,11 +84,11 @@ typealias SA128Int = StaticArray<A2X<A2X<A2X<A2X<A2X<A2X<A0<Int>>>>>>>>
// Make sure the optimizer does not optimize the compute away.
@inline(never)
public func sink(value: Int) { if False() { print(value) }}
public func sink(_ value: Int) { if False() { print(value) }}
@inline(never)
public func run_StaticArray(N: Int) {
public func run_StaticArray(_ N: Int) {
for _ in 1...N {
var staticArray = SA128Int(0)

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_StrComplexWalk(N: Int) {
public func run_StrComplexWalk(_ N: Int) {
var s = "निरन्तरान्धकारिता-दिगन्तर-कन्दलदमन्द-सुधारस-बिन्दु-सान्द्रतर-घनाघन-वृन्द-सन्देहकर-स्यन्दमान-मकरन्द-बिन्दु-बन्धुरतर-माकन्द-तरु-कुल-तल्प-कल्प-मृदुल-सिकता-जाल-जटिल-मूल-तल-मरुवक-मिलदलघु-लघु-लय-कलित-रमणीय-पानीय-शालिका-बालिका-करार-विन्द-गलन्तिका-गलदेला-लवङ्ग-पाटल-घनसार-कस्तूरिकातिसौरभ-मेदुर-लघुतर-मधुर-शीतलतर-सलिलधारा-निराकरिष्णु-तदीय-विमल-विलोचन-मयूख-रेखापसारित-पिपासायास-पथिक-लोकान्"
let ref_result = 379
for _ in 1...2000*N {

View File

@@ -15,7 +15,7 @@
import TestsUtils
@inline(never)
public func run_StrToInt(N: Int) {
public func run_StrToInt(_ N: Int) {
// 64 numbers from -500_000 to 500_000 generated randomly
let input = ["-237392", "293715", "126809", "333779", "-362824", "144198",
"-394973", "-163669", "-7236", "376965", "-400783", "-118670",
@@ -29,7 +29,7 @@ public func run_StrToInt(N: Int) {
"-316727", "483808", "300149", "-405877", "-98938", "283685",
"-247856", "-46975", "346060", "160085",]
let ref_result = 517492
func DoOneIter(arr: [String]) -> Int {
func DoOneIter(_ arr: [String]) -> Int {
var r = 0
for n in arr {
r += Int(n)!

View File

@@ -22,7 +22,7 @@ func buildString() -> String {
}
@inline(never)
public func run_StringBuilder(N: Int) {
public func run_StringBuilder(_ N: Int) {
for _ in 1...5000*N {
buildString()
}

View File

@@ -19,7 +19,7 @@ class RefTypePrintable : CustomStringConvertible {
}
@inline(never)
public func run_StringInterpolation(N: Int) {
public func run_StringInterpolation(_ N: Int) {
let reps = 100
let refResult = reps
let anInt: Int64 = 0x1234567812345678
@@ -29,11 +29,12 @@ public func run_StringInterpolation(N: Int) {
var result = 0
for _ in 1...reps {
let s = "\(anInt) abcdefdhijklmn \(aRefCountedObject) abcdefdhijklmn \u{01}"
let utf16 = s.utf16
// FIXME: if String is not stored as UTF-16 on this platform, then the
// following operation has a non-trivial cost and needs to be replaced
// with an operation on the native storage type.
result = result &+ Int(s.utf16[s.utf16.endIndex.predecessor()])
result = result &+ Int(utf16[utf16.index(before: utf16.endIndex)])
}
CheckResults(result == refResult, "IncorrectResults in StringInterpolation: \(result) != \(refResult)")
}

View File

@@ -9,10 +9,76 @@
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public func run_StringWithCString(N: Int) {
public func run_StringWithCString(_ N: Int) {
let str = String(repeating: "x" as UnicodeScalar, count: 100 * (1 << 16))
for _ in 0 ..< N {
str.withCString { _ in }
}
}
public func run_StringHasPrefix(_ N: Int) {
let prefix = "prefix"
let testString = "prefixedString"
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !testString.hasPrefix(prefix) {
CheckResults(false, "prefix check failed")
}
}
}
}
public func run_StringHasSuffix(_ N: Int) {
let suffix = "Suffixed"
let testString = "StringSuffixed"
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !testString.hasSuffix(suffix) {
CheckResults(false, "suffix check failed")
}
}
}
}
public func run_StringHasPrefixUnicode(_ N: Int) {
let prefix = "prefix"
let testString = "prefixedString"
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !testString.hasPrefix(prefix) {
CheckResults(false, "prefix check failed")
}
}
}
}
public func run_StringHasSuffixUnicode(_ N: Int) {
let suffix = "Suffixed"
let testString = "String❄Suffixed"
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !testString.hasSuffix(suffix) {
CheckResults(false, "suffix check failed")
}
}
}
}
@inline(never)
internal func compareEqual(_ str1: String, _ str2: String) -> Bool {
return str1 == str2
}
public func run_StringEqualPointerComparison(_ N: Int) {
let str1 = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. "
let str2 = str1
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !compareEqual(str1, str2) {
CheckResults(false, "Strings should be equal")
}
}
}
}

View File

@@ -22,14 +22,14 @@ import TestsUtils
var count: Int = 0
@inline(never) func countChars(s: String) {
@inline(never) func countChars(_ s: String) {
for _ in s.unicodeScalars {
count += 1
}
}
@inline(never)
public func run_StringWalk(N: Int) {
public func run_StringWalk(_ N: Int) {
let s = "siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig"
for _ in 1...50000*N {

View File

@@ -14,7 +14,7 @@
import TestsUtils
@inline(never)
public func run_SuperChars(N: Int) {
public func run_SuperChars(_ N: Int) {
// Permute some characters.
let alphabet: [Character] = [
"A", "B", "C", "D", "E", "F", "G",

View File

@@ -52,7 +52,7 @@ let array = [
]
@inline(never)
public func run_TwoSum(N: Int) {
public func run_TwoSum(_ N: Int) {
var i1: Int?
var i2: Int?
var Dict: Dictionary<Int, Int> = [:]

View File

@@ -27,15 +27,15 @@ protocol Pingable {}
struct Some1<T> {
init() {}
func foo(x: T) {}
func foo(_ x: T) {}
}
struct Some0<T> {
init() {}
func foo(x: T) {}
func foo(_ x: T) {}
}
@inline(never)
func flood<T>(x : T) {
func flood<T>(_ x: T) {
Some1<Some1<Some1<Some1<T>>>>() is Pingable
Some1<Some1<Some1<Some0<T>>>>() is Pingable
Some1<Some1<Some0<Some1<T>>>>() is Pingable
@@ -55,7 +55,7 @@ func flood<T>(x : T) {
}
@inline(never)
func flood3<T>(x : T) {
func flood3<T>(_ x: T) {
flood(Some1<Some1<Some1<Some1<T>>>>())
flood(Some1<Some1<Some1<Some0<T>>>>())
flood(Some1<Some1<Some0<Some1<T>>>>())
@@ -75,7 +75,7 @@ func flood3<T>(x : T) {
}
@inline(never)
func flood2<T>(x : T) {
func flood2<T>(_ x: T) {
flood3(Some1<Some1<Some1<Some1<T>>>>())
flood3(Some1<Some1<Some1<Some0<T>>>>())
flood3(Some1<Some1<Some0<Some1<T>>>>())
@@ -95,7 +95,7 @@ func flood2<T>(x : T) {
}
@inline(never)
public func run_TypeFlood(N: Int) {
public func run_TypeFlood(_ N: Int) {
for _ in 1...N {
flood3(Some1<Some1<Some1<Int>>>())

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_UTF8Decode(N: Int) {
public func run_UTF8Decode(_ N: Int) {
// 1-byte sequences
// This test case is the longest as it's the most performance sensitive.
let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."
@@ -25,9 +25,9 @@ public func run_UTF8Decode(N: Int) {
// Most commonly emoji, which are usually mixed with other text.
let emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭."
let strings = [ ascii, russian, japanese, emoji ].map { Array($0.utf8) }
let strings = [ascii, russian, japanese, emoji].map { Array($0.utf8) }
func isEmpty(result: UnicodeDecodingResult) -> Bool {
func isEmpty(_ result: UnicodeDecodingResult) -> Bool {
switch result {
case .emptyInput:
return true

View File

@@ -13,10 +13,10 @@
import TestsUtils
import Darwin
func IsPowerOfTwo(x: Int) -> Bool { return (x & (x - 1)) == 0 }
func IsPowerOfTwo(_ x: Int) -> Bool { return (x & (x - 1)) == 0 }
//Fast Walsh Hadamard Transform
func WalshTransform(data: inout [Double]) {
// Fast Walsh Hadamard Transform
func WalshTransform(_ data: inout [Double]) {
assert(IsPowerOfTwo(data.count), "Not a power of two")
var temp = [Double](repeating: 0, count: data.count)
var ret = WalshImpl(&data, &temp, 0, data.count)
@@ -25,18 +25,18 @@ func WalshTransform(data: inout [Double]) {
}
}
func Scale(data: inout [Double], _ scalar : Double) {
func Scale(_ data: inout [Double], _ scalar : Double) {
for i in 0..<data.count {
data[i] = data[i] * scalar
}
}
func InverseWalshTransform(data: inout [Double]) {
func InverseWalshTransform(_ data: inout [Double]) {
WalshTransform(&data)
Scale(&data, Double(1)/Double(data.count))
}
func WalshImpl(data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] {
func WalshImpl(_ data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] {
if (size == 1) { return data }
let stride = size/2
@@ -65,7 +65,7 @@ func checkCorrectness() {
}
@inline(never)
public func run_Walsh(N : Int) {
public func run_Walsh(_ N: Int) {
checkCorrectness()
// Generate data.

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_XorLoop(N: Int) {
public func run_XorLoop(_ N: Int) {
for _ in 1...5*N {
let size = 100000
let ref_result = 47813324

View File

@@ -0,0 +1,480 @@
//===--- ObjectiveCBridging.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
@inline(never)
public func forcedCast<NS, T>(_ ns: NS) -> T {
return ns as! T
}
@inline(never)
public func conditionalCast<NS, T>(_ ns: NS) -> T? {
return ns as? T
}
// === String === //
func createNSString() -> NSString {
return NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
}
@inline(never)
func testObjectiveCBridgeFromNSString() {
let nsString = createNSString()
var s: String?
for _ in 0 ..< 10_000 {
// Call _conditionallyBridgeFromObjectiveC.
let n : String? = conditionalCast(nsString)
if n != nil {
s = n!
}
}
CheckResults(s != nil && s == "NSString that does not fit in tagged pointer", "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSString()
}
}
@inline(never)
func testObjectiveCBridgeFromNSStringForced() {
let nsString = createNSString()
var s: String?
for _ in 0 ..< 10_000 {
// Call _forceBridgeFromObjectiveC
s = forcedCast(nsString)
}
CheckResults(s != nil && s == "NSString that does not fit in tagged pointer", "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSStringForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSStringForced()
}
}
@inline(never)
func testObjectiveCBridgeToNSString() {
let nativeString = String("Native")
var s: NSString?
for _ in 0 ..< 10_000 {
// Call _BridgedToObjectiveC
s = nativeString as NSString
}
CheckResults(s != nil && s == "Native", "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeToNSString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeToNSString()
}
}
// === Array === //
func createNSArray() -> NSArray {
let nsMutableArray = NSMutableArray()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
nsMutableArray.add(nsString)
return nsMutableArray.copy() as! NSArray
}
@inline(never)
func testObjectiveCBridgeFromNSArrayAnyObject() {
let nsArray = createNSArray()
var nativeString : String?
for _ in 0 ..< 10_000 {
if let nativeArray : [NSString] = conditionalCast(nsArray) {
nativeString = forcedCast(nativeArray[0])
}
}
CheckResults(nativeString != nil && nativeString! == "NSString that does not fit in tagged pointer", "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObject(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSArrayAnyObject()
}
}
@inline(never)
func testObjectiveCBridgeFromNSArrayAnyObjectForced() {
let nsArray = createNSArray()
var nativeString : String?
for _ in 0 ..< 10_000 {
let nativeArray : [NSString] = forcedCast(nsArray)
nativeString = forcedCast(nativeArray[0])
}
CheckResults(nativeString != nil && nativeString! == "NSString that does not fit in tagged pointer", "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSArrayAnyObjectForced()
}
}
@inline(never)
func testObjectiveCBridgeToNSArray() {
let nativeArray = ["abcde", "abcde", "abcde", "abcde", "abcde",
"abcde", "abcde", "abcde", "abcde", "abcde"]
var nsString : AnyObject?
for _ in 0 ..< 10_000 {
let nsArray = nativeArray as NSArray
nsString = nsArray.object(at: 0)
}
CheckResults(nsString != nil && (nsString! as! NSString).isEqual("abcde"), "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeToNSArray(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeToNSArray()
}
}
@inline(never)
func testObjectiveCBridgeFromNSArrayAnyObjectToString() {
let nsArray = createNSArray()
var nativeString : String?
for _ in 0 ..< 10_000 {
if let nativeArray : [String] = conditionalCast(nsArray) {
nativeString = nativeArray[0]
}
}
CheckResults(nativeString != nil && nativeString == "NSString that does not fit in tagged pointer", "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectToString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSArrayAnyObjectToString()
}
}
@inline(never)
func testObjectiveCBridgeFromNSArrayAnyObjectToStringForced() {
let nsArray = createNSArray()
var nativeString : String?
for _ in 0 ..< 10_000 {
let nativeArray : [String] = forcedCast(nsArray)
nativeString = nativeArray[0]
}
CheckResults(nativeString != nil && nativeString == "NSString that does not fit in tagged pointer", "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSArrayAnyObjectToStringForced()
}
}
// === Dictionary === //
func createNSDictionary() -> NSDictionary {
let nsMutableDictionary = NSMutableDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
let nsString2 = NSString(cString: "NSString that does not fit in tagged pointer 2", encoding: NSUTF8StringEncoding)!
let nsString3 = NSString(cString: "NSString that does not fit in tagged pointer 3", encoding: NSUTF8StringEncoding)!
let nsString4 = NSString(cString: "NSString that does not fit in tagged pointer 4", encoding: NSUTF8StringEncoding)!
let nsString5 = NSString(cString: "NSString that does not fit in tagged pointer 5", encoding: NSUTF8StringEncoding)!
let nsString6 = NSString(cString: "NSString that does not fit in tagged pointer 6", encoding: NSUTF8StringEncoding)!
let nsString7 = NSString(cString: "NSString that does not fit in tagged pointer 7", encoding: NSUTF8StringEncoding)!
let nsString8 = NSString(cString: "NSString that does not fit in tagged pointer 8", encoding: NSUTF8StringEncoding)!
let nsString9 = NSString(cString: "NSString that does not fit in tagged pointer 9", encoding: NSUTF8StringEncoding)!
let nsString10 = NSString(cString: "NSString that does not fit in tagged pointer 10", encoding: NSUTF8StringEncoding)!
nsMutableDictionary.setObject(1, forKey: nsString)
nsMutableDictionary.setObject(2, forKey: nsString2)
nsMutableDictionary.setObject(3, forKey: nsString3)
nsMutableDictionary.setObject(4, forKey: nsString4)
nsMutableDictionary.setObject(5, forKey: nsString5)
nsMutableDictionary.setObject(6, forKey: nsString6)
nsMutableDictionary.setObject(7, forKey: nsString7)
nsMutableDictionary.setObject(8, forKey: nsString8)
nsMutableDictionary.setObject(9, forKey: nsString9)
nsMutableDictionary.setObject(10, forKey: nsString10)
return nsMutableDictionary.copy() as! NSDictionary
}
@inline(never)
func testObjectiveCBridgeFromNSDictionaryAnyObject() {
let nsDictionary = createNSDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
var nativeInt : Int?
for _ in 0 ..< 10_000 {
if let nativeDictionary : [NSString : NSNumber] = conditionalCast(nsDictionary) {
nativeInt = forcedCast(nativeDictionary[nsString])
}
}
CheckResults(nativeInt != nil && nativeInt == 1, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObject(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSDictionaryAnyObject()
}
}
@inline(never)
func testObjectiveCBridgeFromNSDictionaryAnyObjectForced() {
let nsDictionary = createNSDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
var nativeInt : Int?
for _ in 0 ..< 10_000 {
if let nativeDictionary : [NSString : NSNumber] = forcedCast(nsDictionary) {
nativeInt = forcedCast(nativeDictionary[nsString])
}
}
CheckResults(nativeInt != nil && nativeInt == 1, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSDictionaryAnyObjectForced()
}
}
@inline(never)
func testObjectiveCBridgeToNSDictionary() {
let nativeDictionary = ["abcde1": 1, "abcde2": 2, "abcde3": 3, "abcde4": 4,
"abcde5": 5, "abcde6": 6, "abcde7": 7, "abcde8": 8, "abcde9": 9,
"abcde10": 10]
let key = "abcde1" as NSString
var nsNumber : AnyObject?
for _ in 0 ..< 10_000 {
let nsDict = nativeDictionary as NSDictionary
nsNumber = nsDict.object(forKey: key)
}
CheckResults(nsNumber != nil && (nsNumber as! Int) == 1, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeToNSDictionary(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeToNSDictionary()
}
}
@inline(never)
func testObjectiveCBridgeFromNSDictionaryAnyObjectToString() {
let nsDictionary = createNSDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
let nativeString = nsString as String
var nativeInt : Int?
for _ in 0 ..< 10_000 {
if let nativeDictionary : [String : Int] = conditionalCast(nsDictionary) {
nativeInt = nativeDictionary[nativeString]
}
}
CheckResults(nativeInt != nil && nativeInt == 1, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSDictionaryAnyObjectToString()
}
}
@inline(never)
func testObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced() {
let nsDictionary = createNSDictionary()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
let nativeString = nsString as String
var nativeInt : Int?
for _ in 0 ..< 10_000 {
if let nativeDictionary : [String : Int] = forcedCast(nsDictionary) {
nativeInt = nativeDictionary[nativeString]
}
}
CheckResults(nativeInt != nil && nativeInt == 1, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced()
}
}
// === Set === //
func createNSSet() -> NSSet {
let nsMutableSet = NSMutableSet()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
let nsString2 = NSString(cString: "NSString that does not fit in tagged pointer 2", encoding: NSUTF8StringEncoding)!
let nsString3 = NSString(cString: "NSString that does not fit in tagged pointer 3", encoding: NSUTF8StringEncoding)!
let nsString4 = NSString(cString: "NSString that does not fit in tagged pointer 4", encoding: NSUTF8StringEncoding)!
let nsString5 = NSString(cString: "NSString that does not fit in tagged pointer 5", encoding: NSUTF8StringEncoding)!
let nsString6 = NSString(cString: "NSString that does not fit in tagged pointer 6", encoding: NSUTF8StringEncoding)!
let nsString7 = NSString(cString: "NSString that does not fit in tagged pointer 7", encoding: NSUTF8StringEncoding)!
let nsString8 = NSString(cString: "NSString that does not fit in tagged pointer 8", encoding: NSUTF8StringEncoding)!
let nsString9 = NSString(cString: "NSString that does not fit in tagged pointer 9", encoding: NSUTF8StringEncoding)!
let nsString10 = NSString(cString: "NSString that does not fit in tagged pointer 10", encoding: NSUTF8StringEncoding)!
nsMutableSet.add(nsString)
nsMutableSet.add(nsString2)
nsMutableSet.add(nsString3)
nsMutableSet.add(nsString4)
nsMutableSet.add(nsString5)
nsMutableSet.add(nsString6)
nsMutableSet.add(nsString7)
nsMutableSet.add(nsString8)
nsMutableSet.add(nsString9)
nsMutableSet.add(nsString10)
return nsMutableSet.copy() as! NSSet
}
@inline(never)
func testObjectiveCBridgeFromNSSetAnyObject() {
let nsSet = createNSSet()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
var result : Bool?
for _ in 0 ..< 10_000 {
if let nativeSet : Set<NSString> = conditionalCast(nsSet) {
result = nativeSet.contains(nsString)
}
}
CheckResults(result != nil && result!, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObject(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSSetAnyObject()
}
}
@inline(never)
func testObjectiveCBridgeFromNSSetAnyObjectForced() {
let nsSet = createNSSet()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
var result : Bool?
for _ in 0 ..< 10_000 {
if let nativeSet : Set<NSString> = forcedCast(nsSet) {
result = nativeSet.contains(nsString)
}
}
CheckResults(result != nil && result!, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSSetAnyObjectForced()
}
}
@inline(never)
func testObjectiveCBridgeToNSSet() {
let nativeSet = Set<String>(["abcde1", "abcde2", "abcde3", "abcde4", "abcde5",
"abcde6", "abcde7", "abcde8", "abcde9", "abcde10"])
let key = "abcde1" as NSString
var nsString : AnyObject?
for _ in 0 ..< 10_000 {
let nsDict = nativeSet as NSSet
nsString = nsDict.member(key)
}
CheckResults(nsString != nil && (nsString as! String) == "abcde1", "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeToNSSet(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeToNSSet()
}
}
@inline(never)
func testObjectiveCBridgeFromNSSetAnyObjectToString() {
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
let nativeString = nsString as String
let nsSet = createNSSet()
var result : Bool?
for _ in 0 ..< 10_000 {
if let nativeSet : Set<String> = conditionalCast(nsSet) {
result = nativeSet.contains(nativeString)
}
}
CheckResults(result != nil && result!, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectToString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSSetAnyObjectToString()
}
}
@inline(never)
func testObjectiveCBridgeFromNSSetAnyObjectToStringForced() {
let nsSet = createNSSet()
let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: NSUTF8StringEncoding)!
let nativeString = nsString as String
var result : Bool?
for _ in 0 ..< 10_000 {
if let nativeSet : Set<String> = forcedCast(nsSet) {
result = nativeSet.contains(nativeString)
}
}
CheckResults(result != nil && result!, "Expected results did not match")
}
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSSetAnyObjectToStringForced()
}
}

View File

@@ -0,0 +1,91 @@
//===--- ObjectiveCBridgingStubs.swift ------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
import ObjectiveCTests
@inline(never)
func testObjectiveCBridgeStubFromNSString() {
let b = BridgeTester()
var str = ""
for _ in 0 ..< 10_000 {
str = b.testToString()
}
CheckResults(str != "" && str == "Default string value no tagged pointer", "Wrong value returned")
}
@inline(never)
public func run_ObjectiveCBridgeStubFromNSString(_ N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubFromNSString()
}
}
}
@inline(never)
func testObjectiveCBridgeStubToNSString() {
let b = BridgeTester()
let str = "hello world"
for _ in 0 ..< 10_000 {
b.test(from: str)
}
}
@inline(never)
public func run_ObjectiveCBridgeStubToNSString(_ N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubToNSString()
}
}
}
@inline(never)
func testObjectiveCBridgeStubFromArrayOfNSString() {
let b = BridgeTester()
var arr : [String] = []
var str = ""
for _ in 0 ..< 10_000 {
arr = b.testToArrayOfStrings()
str = arr[0]
}
CheckResults(str != "" && str == "Default string value no tagged pointer", "Wrong value returned")
}
@inline(never)
public func run_ObjectiveCBridgeStubFromArrayOfNSString(_ N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubFromArrayOfNSString()
}
}
}
@inline(never)
func testObjectiveCBridgeStubToArrayOfNSString() {
let b = BridgeTester()
let str = "hello world"
let arr = [str, str, str, str, str, str, str, str, str, str]
for _ in 0 ..< 10_000 {
b.test(fromArrayOf: arr)
}
}
@inline(never)
public func run_ObjectiveCBridgeStubToArrayOfNSString(_ N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubToArrayOfNSString()
}
}
}

View File

@@ -0,0 +1,39 @@
//===--- ObjectiveCNoBridgingStubs.swift ----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file is compiled with -Xfrontend -disable-swift-bridge-attr. No bridging
// of swift types happens.
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
import ObjectiveCTests
@inline(never)
func testObjectiveCBridgeStubFromNSStringRef() {
let b = BridgeTester()
var nsString : NSString = NSString()
for _ in 0 ..< 10_000 {
nsString = b.testToString()
}
CheckResults(nsString.isEqual(to: "Default string value no tagged pointer" as NSString), "Wrong value returned")
}
@inline(never)
public func run_ObjectiveCBridgeStubFromNSStringRef(N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubFromNSStringRef()
}
}
}

View File

@@ -3,7 +3,7 @@ protocol Proto {
}
@inline(never)
func testStackAllocation(p: Proto) -> Int {
func testStackAllocation(_ p: Proto) -> Int {
var a = [p, p, p]
var b = 0
a.withUnsafeMutableBufferPointer {
@@ -23,7 +23,7 @@ class Foo : Proto {
}
@inline(never)
func work(f: Foo) -> Int {
func work(_ f: Foo) -> Int {
var r = 0
for _ in 0..<100_000 {
r += testStackAllocation(f)
@@ -32,13 +32,13 @@ func work(f: Foo) -> Int {
}
@inline(never)
func hole(use: Int, _ N: Int) {
func hole(_ use: Int, _ N: Int) {
if (N == 0) {
print("use: \(use)")
}
}
public func run_StackPromo(N: Int) {
public func run_StackPromo(_ N: Int) {
let foo = Foo()
var r = 0
for i in 0..<N {

View File

@@ -35,7 +35,7 @@ public struct Arguments {
///
/// with opt-name and opt-value not containing any '=' signs. Any
/// other option passed in is assumed to be a positional argument.
public func parseArgs(validOptions: [String]? = nil)
public func parseArgs(_ validOptions: [String]? = nil)
-> Arguments? {
let progName = Process.arguments[0]
var positionalArgs = [String]()
@@ -55,7 +55,7 @@ public func parseArgs(validOptions: [String]? = nil)
continue
}
// Attempt to split it into two components separated by an equals sign.
let components = arg.componentsSeparated(by: "=")
let components = arg.components(separatedBy: "=")
let optionName = components[0]
if validOptions != nil && !validOptions!.contains(optionName) {
print("Invalid option: \(arg)")

View File

@@ -48,9 +48,9 @@ extension BenchResults : CustomStringConvertible {
struct Test {
let name: String
let index: Int
let f: (Int)->()
let f: (Int) -> ()
var run: Bool
init(name: String, n: Int, f: (Int)->()) {
init(name: String, n: Int, f: (Int) -> ()) {
self.name = name
self.index = n
self.f = f
@@ -58,8 +58,8 @@ struct Test {
}
}
public var precommitTests: [String : (Int)->()] = [:]
public var otherTests: [String : (Int)->()] = [:]
public var precommitTests: [String : (Int) -> ()] = [:]
public var otherTests: [String : (Int) -> ()] = [:]
enum TestAction {
case Run
@@ -182,7 +182,7 @@ struct TestConfig {
}
}
func internalMeanSD(inputs: [UInt64]) -> (UInt64, UInt64) {
func internalMeanSD(_ inputs: [UInt64]) -> (UInt64, UInt64) {
// If we are empty, return 0, 0.
if inputs.isEmpty {
return (0, 0)
@@ -211,7 +211,7 @@ func internalMeanSD(inputs: [UInt64]) -> (UInt64, UInt64) {
return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1))))
}
func internalMedian(inputs: [UInt64]) -> UInt64 {
func internalMedian(_ inputs: [UInt64]) -> UInt64 {
return inputs.sorted()[inputs.count / 2]
}
@@ -229,7 +229,7 @@ class SampleRunner {
init() {
mach_timebase_info(&info)
}
func run(name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
func run(_ name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
// Start the timer.
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
var str = name
@@ -250,7 +250,7 @@ class SampleRunner {
}
/// Invoke the benchmark entry point and return the run time in milliseconds.
func runBench(name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResults {
func runBench(_ name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResults {
var samples = [UInt64](repeating: 0, count: c.numSamples)
@@ -296,7 +296,7 @@ func runBench(name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResult
mean: mean, sd: sd, median: internalMedian(samples))
}
func printRunInfo(c: TestConfig) {
func printRunInfo(_ c: TestConfig) {
if c.verbose {
print("--- CONFIG ---")
print("NumSamples: \(c.numSamples)")
@@ -318,7 +318,7 @@ func printRunInfo(c: TestConfig) {
}
}
func runBenchmarks(c: TestConfig) {
func runBenchmarks(_ c: TestConfig) {
let units = "us"
print("#\(c.delim)TEST\(c.delim)SAMPLES\(c.delim)MIN(\(units))\(c.delim)MAX(\(units))\(c.delim)MEAN(\(units))\(c.delim)SD(\(units))\(c.delim)MEDIAN(\(units))")
var SumBenchResults = BenchResults()

View File

@@ -0,0 +1,30 @@
//===--- ObjectiveCTests.h ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface BridgeTester : NSObject {
NSString *myString;
NSArray<NSString *> *myArrayOfStrings;
}
- (id)init;
- (void)testFromString:(NSString *) str;
- (NSString *)testToString;
- (void)testFromArrayOfStrings:(NSArray<NSString *> *)arr;
- (NSArray<NSString *> *)testToArrayOfStrings;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,47 @@
//===--- ObjectiveCTests.m ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#import "ObjectiveCTests.h"
@implementation BridgeTester
- (id)init {
self = [super init];
if (!self)
return self;
myString = @"Default string value no tagged pointer";
id mutableArray = [NSMutableArray new];
for (int i = 0; i < 10; ++i) {
[mutableArray addObject: myString];
}
myArrayOfStrings = [mutableArray copy];
return self;
}
- (NSString *)testToString {
return myString;
}
- (void)testFromString:(NSString *)str {
unichar c = [str characterAtIndex:0];
}
- (void)testFromArrayOfStrings:(NSArray<NSString *> *)arr {
// Get an element to force lazy bridging to happen.
id str = [arr objectAtIndex:0];
}
- (NSArray<NSString *> *)testToArrayOfStrings {
return myArrayOfStrings;
}
@end

View File

@@ -0,0 +1,15 @@
//===--- module.map -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
module ObjectiveCTests {
header "ObjectiveCTests.h"
}

View File

@@ -45,7 +45,7 @@ public func Random() -> Int64 {
return lfsrRandomGenerator.randInt()
}
public func CheckResults(res: Bool, _ message: String = "") {
public func CheckResults(_ res: Bool, _ message: String = "") {
if res {
return
}

Some files were not shown because too many files have changed in this diff Show More