[gardening] Fix accidental trailing whitespace.

This commit is contained in:
practicalswift
2016-10-29 10:22:58 +02:00
parent 3616567dbd
commit cc852042c9
165 changed files with 1002 additions and 1002 deletions

View File

@@ -506,12 +506,12 @@ if(XCODE)
endif() endif()
# FIXME: the parameters we specify in SWIFT_SDKS are lacking architecture specifics, # FIXME: the parameters we specify in SWIFT_SDKS are lacking architecture specifics,
# so we need to hard-code it. For example, the SDK for Android is just 'ANDROID', # so we need to hard-code it. For example, the SDK for Android is just 'ANDROID',
# which we assume below to be armv7. # which we assume below to be armv7.
# The iOS SDKs all have their architectures hardcoded because they are just specified by name (e.g. 'IOS' or 'WATCHOS'). # The iOS SDKs all have their architectures hardcoded because they are just specified by name (e.g. 'IOS' or 'WATCHOS').
# We can't cross-compile the standard library for another linux architecture, # We can't cross-compile the standard library for another linux architecture,
# because the SDK list would just be 'LINUX' and we couldn't disambiguate it from the host. # because the SDK list would just be 'LINUX' and we couldn't disambiguate it from the host.
# #
# To fix it, we would need to append the architecture to the SDKs, # To fix it, we would need to append the architecture to the SDKs,
# for example: 'OSX-x86_64;IOS-armv7;...etc'. # for example: 'OSX-x86_64;IOS-armv7;...etc'.
# We could easily do that - we have all of that information in build-script-impl. # We could easily do that - we have all of that information in build-script-impl.
@@ -519,7 +519,7 @@ endif()
# Darwin targets cheat and use `xcrun`. # Darwin targets cheat and use `xcrun`.
if("${SWIFT_HOST_VARIANT_SDK}" STREQUAL "LINUX") if("${SWIFT_HOST_VARIANT_SDK}" STREQUAL "LINUX")
set(CMAKE_EXECUTABLE_FORMAT "ELF") set(CMAKE_EXECUTABLE_FORMAT "ELF")
set(SWIFT_HOST_VARIANT "linux" CACHE STRING set(SWIFT_HOST_VARIANT "linux" CACHE STRING
"Deployment OS for Swift host tools (the compiler) [linux].") "Deployment OS for Swift host tools (the compiler) [linux].")
@@ -550,7 +550,7 @@ if("${SWIFT_HOST_VARIANT_SDK}" STREQUAL "LINUX")
endif() endif()
elseif("${SWIFT_HOST_VARIANT_SDK}" STREQUAL "FREEBSD") elseif("${SWIFT_HOST_VARIANT_SDK}" STREQUAL "FREEBSD")
set(CMAKE_EXECUTABLE_FORMAT "ELF") set(CMAKE_EXECUTABLE_FORMAT "ELF")
set(SWIFT_HOST_VARIANT "freebsd" CACHE STRING set(SWIFT_HOST_VARIANT "freebsd" CACHE STRING
"Deployment OS for Swift host tools (the compiler) [freebsd].") "Deployment OS for Swift host tools (the compiler) [freebsd].")
@@ -563,13 +563,13 @@ elseif("${SWIFT_HOST_VARIANT_SDK}" STREQUAL "FREEBSD")
"x86_64-unknown-freebsd${FREEBSD_SYSTEM_VERSION}" "/") "x86_64-unknown-freebsd${FREEBSD_SYSTEM_VERSION}" "/")
set(SWIFT_PRIMARY_VARIANT_SDK_default "${SWIFT_HOST_VARIANT_SDK}") set(SWIFT_PRIMARY_VARIANT_SDK_default "${SWIFT_HOST_VARIANT_SDK}")
set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64") set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64")
elseif("${SWIFT_HOST_VARIANT_SDK}" STREQUAL "CYGWIN") elseif("${SWIFT_HOST_VARIANT_SDK}" STREQUAL "CYGWIN")
# set(CMAKE_EXECUTABLE_FORMAT "ELF") # set(CMAKE_EXECUTABLE_FORMAT "ELF")
set(SWIFT_HOST_VARIANT "windows" CACHE STRING set(SWIFT_HOST_VARIANT "windows" CACHE STRING
"Deployment OS for Swift host tools (the compiler) [windows].") "Deployment OS for Swift host tools (the compiler) [windows].")
configure_sdk_unix(CYGWIN "Cygwin" "windows" "cygwin" "windows" "x86_64-unknown-windows-cygnus" "/") configure_sdk_unix(CYGWIN "Cygwin" "windows" "cygwin" "windows" "x86_64-unknown-windows-cygnus" "/")
set(SWIFT_PRIMARY_VARIANT_SDK_default "${SWIFT_HOST_VARIANT_SDK}") set(SWIFT_PRIMARY_VARIANT_SDK_default "${SWIFT_HOST_VARIANT_SDK}")
set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64") set(SWIFT_PRIMARY_VARIANT_ARCH_default "x86_64")
@@ -579,7 +579,7 @@ elseif("${SWIFT_HOST_VARIANT_SDK}" MATCHES "(OSX|IOS*|TVOS*|WATCHOS*)")
set(SWIFT_HOST_VARIANT "macosx" CACHE STRING set(SWIFT_HOST_VARIANT "macosx" CACHE STRING
"Deployment OS for Swift host tools (the compiler) [macosx, iphoneos].") "Deployment OS for Swift host tools (the compiler) [macosx, iphoneos].")
# Display Xcode toolchain version. # Display Xcode toolchain version.
# The SDK configuration below prints each SDK version. # The SDK configuration below prints each SDK version.
execute_process( execute_process(
COMMAND "xcodebuild" "-version" COMMAND "xcodebuild" "-version"

View File

@@ -200,8 +200,8 @@
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
## Runtime Library Exception to the Apache 2.0 License: ## ## Runtime Library Exception to the Apache 2.0 License: ##

View File

@@ -90,7 +90,7 @@ Functions:
# replaced by Equatable / == # replaced by Equatable / ==
SwiftName: CGAffineTransform.__equalTo(self:_:) SwiftName: CGAffineTransform.__equalTo(self:_:)
SwiftPrivate: true SwiftPrivate: true
# CGBitmapContext # CGBitmapContext
- Name: CGBitmapContextCreateWithData - Name: CGBitmapContextCreateWithData
SwiftName: CGContext.init(data:width:height:bitsPerComponent:bytesPerRow:space:bitmapInfo:releaseCallback:releaseInfo:) SwiftName: CGContext.init(data:width:height:bitsPerComponent:bytesPerRow:space:bitmapInfo:releaseCallback:releaseInfo:)
@@ -114,7 +114,7 @@ Functions:
SwiftName: getter:CGContext.alphaInfo(self:) SwiftName: getter:CGContext.alphaInfo(self:)
- Name: CGBitmapContextCreateImage - Name: CGBitmapContextCreateImage
SwiftName: CGContext.makeImage(self:) SwiftName: CGContext.makeImage(self:)
# CGColor # CGColor
# #
- Name: CGColorCreate - Name: CGColorCreate
@@ -409,7 +409,7 @@ Functions:
- Name: CGGetLastMouseDelta - Name: CGGetLastMouseDelta
# replaced by a version that returns CGVector instead of using out-pointers # replaced by a version that returns CGVector instead of using out-pointers
SwiftPrivate: true SwiftPrivate: true
# CGEvent # CGEvent
- Name: CGEventCreateFromData - Name: CGEventCreateFromData
SwiftName: CGEvent.init(withDataAllocator:data:) SwiftName: CGEvent.init(withDataAllocator:data:)
@@ -421,7 +421,7 @@ Functions:
SwiftName: CGEvent.postToPid(_:self:) SwiftName: CGEvent.postToPid(_:self:)
- Name: CGEventCreateSourceFromEvent - Name: CGEventCreateSourceFromEvent
SwiftName: CGEventSource.init(event:) SwiftName: CGEventSource.init(event:)
# CGFont # CGFont
- Name: CGFontCreateWithDataProvider - Name: CGFontCreateWithDataProvider
SwiftName: CGFont.init(_:) SwiftName: CGFont.init(_:)
@@ -443,7 +443,7 @@ Functions:
SwiftName: CGFont.table(self:for:) SwiftName: CGFont.table(self:for:)
- Name: CGFontCreateCopyWithVariations - Name: CGFontCreateCopyWithVariations
SwiftName: CGFont.copy(self:withVariations:) SwiftName: CGFont.copy(self:withVariations:)
# CGGeometry # CGGeometry
- Name: CGPointCreateDictionaryRepresentation - Name: CGPointCreateDictionaryRepresentation
SwiftName: getter:CGPoint.dictionaryRepresentation(self:) SwiftName: getter:CGPoint.dictionaryRepresentation(self:)
@@ -474,7 +474,7 @@ Functions:
# hide in favor of an init (can't map to initializer because out-pointer) # hide in favor of an init (can't map to initializer because out-pointer)
SwiftName: CGRect.__setFromDictionaryRepresentation(_:_:) SwiftName: CGRect.__setFromDictionaryRepresentation(_:_:)
SwiftPrivate: true SwiftPrivate: true
# CGGradient # CGGradient
- Name: CGGradientCreateWithColorComponents - Name: CGGradientCreateWithColorComponents
SwiftName: CGGradient.init(colorSpace:colorComponents:locations:count:) SwiftName: CGGradient.init(colorSpace:colorComponents:locations:count:)
@@ -557,7 +557,7 @@ Functions:
# CGPSConverter # CGPSConverter
- Name: CGPSConverterIsConverting - Name: CGPSConverterIsConverting
SwiftName: getter:CGPSConverter.isConverting(self:) SwiftName: getter:CGPSConverter.isConverting(self:)
# CGPath # CGPath
- Name: CGPathCreateCopy - Name: CGPathCreateCopy
SwiftName: CGPath.copy(self:) SwiftName: CGPath.copy(self:)

View File

@@ -206,7 +206,7 @@ Classes:
- Selector: 'shuffledArrayWithRandomSource:' - Selector: 'shuffledArrayWithRandomSource:'
SwiftName: shuffled(using:) SwiftName: shuffled(using:)
MethodKind: Instance MethodKind: Instance
- Name: GKARC4RandomSource - Name: GKARC4RandomSource
Methods: Methods:
- Selector: 'dropValuesWithCount:' - Selector: 'dropValuesWithCount:'
SwiftName: dropValues(_:) SwiftName: dropValues(_:)

View File

@@ -11,7 +11,7 @@ API notes are organized into a set of `.apinotes` files. Each
written in YAML (FIXME: to be) described below. These YAML sources written in YAML (FIXME: to be) described below. These YAML sources
must be manually compiled into a binary representation (`.apinotesc`) must be manually compiled into a binary representation (`.apinotesc`)
that the Swift compiler will lazily load when it builds code, also that the Swift compiler will lazily load when it builds code, also
described below. described below.
# API Notes YAML Format # API Notes YAML Format
@@ -42,7 +42,7 @@ When updating API notes for a system module, recompile the API notes
and place the result in the appropriate directories listed above. The and place the result in the appropriate directories listed above. The
Swift compiler itself need not be recompiled except in rare cases Swift compiler itself need not be recompiled except in rare cases
where the changes affect how the SDK overlays are built. To recompile where the changes affect how the SDK overlays are built. To recompile
API notes for a given module `$MODULE` and place them into their API notes for a given module `$MODULE` and place them into their
### OS X ### OS X
``` ```

View File

@@ -95,7 +95,7 @@ endfunction()
# ANALYZE_CODE_COVERAGE analyze_code_coverage # ANALYZE_CODE_COVERAGE analyze_code_coverage
# RESULT_VAR_NAME result_var_name # RESULT_VAR_NAME result_var_name
# DEPLOYMENT_VERSION_IOS deployment_version_ios # If provided, overrides the default value of the iOS deployment target set by the Swift project for this compilation only. # DEPLOYMENT_VERSION_IOS deployment_version_ios # If provided, overrides the default value of the iOS deployment target set by the Swift project for this compilation only.
# #
# ) # )
function(_add_variant_c_compile_link_flags) function(_add_variant_c_compile_link_flags)
set(oneValueArgs SDK ARCH BUILD_TYPE RESULT_VAR_NAME ENABLE_LTO ANALYZE_CODE_COVERAGE DEPLOYMENT_VERSION_IOS) set(oneValueArgs SDK ARCH BUILD_TYPE RESULT_VAR_NAME ENABLE_LTO ANALYZE_CODE_COVERAGE DEPLOYMENT_VERSION_IOS)
@@ -104,7 +104,7 @@ function(_add_variant_c_compile_link_flags)
"${oneValueArgs}" "${oneValueArgs}"
"" ""
${ARGN}) ${ARGN})
set(result set(result
${${CFLAGS_RESULT_VAR_NAME}} ${${CFLAGS_RESULT_VAR_NAME}}
"-target" "${SWIFT_SDK_${CFLAGS_SDK}_ARCH_${CFLAGS_ARCH}_TRIPLE}") "-target" "${SWIFT_SDK_${CFLAGS_SDK}_ARCH_${CFLAGS_ARCH}_TRIPLE}")
@@ -1297,12 +1297,12 @@ function(add_swift_library name)
message(FATAL_ERROR message(FATAL_ERROR
"Either SHARED, STATIC, or OBJECT_LIBRARY must be specified") "Either SHARED, STATIC, or OBJECT_LIBRARY must be specified")
endif() endif()
if(SWIFTLIB_TARGET_LIBRARY) if(SWIFTLIB_TARGET_LIBRARY)
if(NOT SWIFT_BUILD_RUNTIME_WITH_HOST_COMPILER) if(NOT SWIFT_BUILD_RUNTIME_WITH_HOST_COMPILER)
list(APPEND SWIFTLIB_DEPENDS clang) list(APPEND SWIFTLIB_DEPENDS clang)
endif() endif()
# If we are building this library for targets, loop through the various # If we are building this library for targets, loop through the various
# SDKs building the variants of this library. # SDKs building the variants of this library.
list_intersect( list_intersect(
@@ -1675,7 +1675,7 @@ function(_add_swift_executable_single name)
# Determine compiler flags. # Determine compiler flags.
set(c_compile_flags) set(c_compile_flags)
set(link_flags) set(link_flags)
# Add variant-specific flags. # Add variant-specific flags.
_add_variant_c_compile_flags( _add_variant_c_compile_flags(
SDK "${SWIFTEXE_SINGLE_SDK}" SDK "${SWIFTEXE_SINGLE_SDK}"

View File

@@ -8,7 +8,7 @@ set(ICU_REQUIRED)
foreach(MODULE ${ICU_FIND_COMPONENTS}) foreach(MODULE ${ICU_FIND_COMPONENTS})
string(TOUPPER "${MODULE}" MODULE) string(TOUPPER "${MODULE}" MODULE)
string(TOLOWER "${MODULE}" module) string(TOLOWER "${MODULE}" module)
list(APPEND ICU_REQUIRED list(APPEND ICU_REQUIRED
ICU_${MODULE}_INCLUDE_DIR ICU_${MODULE}_LIBRARIES) ICU_${MODULE}_INCLUDE_DIR ICU_${MODULE}_LIBRARIES)
pkg_check_modules(PC_ICU_${MODULE} QUIET icu-${module}) pkg_check_modules(PC_ICU_${MODULE} QUIET icu-${module})

View File

@@ -29,7 +29,7 @@ Structs and tuples currently share the same layout algorithm, noted as the
is as follows: is as follows:
- Start with a **size** of **0** and an **alignment** of **1**. - Start with a **size** of **0** and an **alignment** of **1**.
- Iterate through the fields, in element order for tuples, or in ``var`` - Iterate through the fields, in element order for tuples, or in ``var``
declaration order for structs. For each field: declaration order for structs. For each field:
* Update **size** by rounding up to the **alignment of the field**, that is, * Update **size** by rounding up to the **alignment of the field**, that is,
@@ -41,7 +41,7 @@ is as follows:
**alignment of the field**. **alignment of the field**.
- The final **size** and **alignment** are the size and alignment of the - The final **size** and **alignment** are the size and alignment of the
aggregate. The **stride** of the type is the final **size** rounded up to aggregate. The **stride** of the type is the final **size** rounded up to
**alignment**. **alignment**.
Note that this differs from C or LLVM's normal layout rules in that *size* Note that this differs from C or LLVM's normal layout rules in that *size*
@@ -852,7 +852,7 @@ The first identifier in a ``<private-decl-name>`` is a string that represents
the file the original declaration came from. It should be considered unique the file the original declaration came from. It should be considered unique
within the enclosing module. The second identifier is the name of the entity. within the enclosing module. The second identifier is the name of the entity.
Not all declarations marked ``private`` declarations will use the Not all declarations marked ``private`` declarations will use the
``<private-decl-name>`` mangling; if the entity's context is enough to uniquely ``<private-decl-name>`` mangling; if the entity's context is enough to uniquely
identify the entity, the simple ``identifier`` form is preferred. identify the entity, the simple ``identifier`` form is preferred.
@@ -929,7 +929,7 @@ Types
type ::= 'b' type type // objc block function type type ::= 'b' type type // objc block function type
type ::= 'c' type type // C function pointer type type ::= 'c' type type // C function pointer type
type ::= 'F' throws-annotation? type type // function type type ::= 'F' throws-annotation? type type // function type
type ::= 'f' throws-annotation? type type // uncurried function type type ::= 'f' throws-annotation? type type // uncurried function type
type ::= 'G' type <type>+ '_' // generic type application type ::= 'G' type <type>+ '_' // generic type application
type ::= 'K' type type // @auto_closure function type type ::= 'K' type type // @auto_closure function type
type ::= 'M' type // metatype without representation type ::= 'M' type // metatype without representation

View File

@@ -25,7 +25,7 @@ This optimizes for the most common case—a single-target application
project—while not accidentally revealing entities to clients of a framework project—while not accidentally revealing entities to clients of a framework
module. module.
.. warning:: This document has not yet been updated for SE-0117, which adds the .. warning:: This document has not yet been updated for SE-0117, which adds the
"open" level of access. "open" level of access.
@@ -220,7 +220,7 @@ functionality beyond ``private``, ``fileprivate``, ``internal``, and ``public``.
limited with regards to extensions. Beyond that, however, a "class-only" limited with regards to extensions. Beyond that, however, a "class-only"
limit forces code to be declared within the class that might otherwise limit forces code to be declared within the class that might otherwise
naturally be a top-level helper or an extension method on another type. naturally be a top-level helper or an extension method on another type.
``private`` and ``fileprivate`` serve the use case of limiting access to the ``private`` and ``fileprivate`` serve the use case of limiting access to the
implementation details of a class (even from the rest of the module!) while implementation details of a class (even from the rest of the module!) while
not tying access to the notion of type. not tying access to the notion of type.
@@ -232,7 +232,7 @@ functionality beyond ``private``, ``fileprivate``, ``internal``, and ``public``.
plans for resilient APIs. Additionally, it increases the complexity of the plans for resilient APIs. Additionally, it increases the complexity of the
access control model for both the compiler and for developers, and like access control model for both the compiler and for developers, and like
"class-only" it is not immediately clear how it interacts with extensions. "class-only" it is not immediately clear how it interacts with extensions.
Though it is not compiler-enforced, members that might be considered Though it is not compiler-enforced, members that might be considered
"protected" are effectively publicly accessible, and thus should be marked "protected" are effectively publicly accessible, and thus should be marked
``public`` in Swift. They can still be documented as intended for overriding ``public`` in Swift. They can still be documented as intended for overriding

View File

@@ -42,18 +42,18 @@ if(LITRE_EXECUTABLE)
set(subdir_CMakeLists) set(subdir_CMakeLists)
foreach(rst ${rst_files}) foreach(rst ${rst_files})
# Prepare a testing directory containing a CMakeLists.txt # Prepare a testing directory containing a CMakeLists.txt
# and example files extracted from the .rst # and example files extracted from the .rst
set(test_dir "litre-tests/${rst}.litre-tests") set(test_dir "litre-tests/${rst}.litre-tests")
add_custom_command( add_custom_command(
OUTPUT OUTPUT
${test_dir}/CMakeLists.txt ${test_dir}/CMakeLists.txt
COMMAND COMMAND
${LITRE_EXECUTABLE} ${LITRE_EXECUTABLE}
--default_compiler=${CMAKE_BINARY_DIR}/bin/swift --default_compiler=${CMAKE_BINARY_DIR}/bin/swift
"--dump_dir=${test_dir}" "--dump_dir=${test_dir}"
--traceback --traceback
--report=severe # suppress most .rst errors. We have lots of them. --report=severe # suppress most .rst errors. We have lots of them.
${CMAKE_CURRENT_SOURCE_DIR}/${rst} ${CMAKE_CURRENT_SOURCE_DIR}/${rst}
DEPENDS DEPENDS
@@ -71,7 +71,7 @@ if(LITRE_EXECUTABLE)
OUTPUT OUTPUT
litre-top-CMakeLists.cmake litre-top-CMakeLists.cmake
COMMAND COMMAND
${CMAKE_COMMAND} -DOUTPUT=litre-top-CMakeLists.cmake ${CMAKE_COMMAND} -DOUTPUT=litre-top-CMakeLists.cmake
-DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR} -DSOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}
-P ${CMAKE_CURRENT_SOURCE_DIR}/GenerateTopLevelLitreCMakeLists.cmake -P ${CMAKE_CURRENT_SOURCE_DIR}/GenerateTopLevelLitreCMakeLists.cmake
${rst_files} ${rst_files}
@@ -134,7 +134,7 @@ if (LLVM_ENABLE_DOXYGEN)
if (DOXYGEN_FOUND) if (DOXYGEN_FOUND)
set(abs_srcdir ${CMAKE_CURRENT_SOURCE_DIR}) set(abs_srcdir ${CMAKE_CURRENT_SOURCE_DIR})
set(abs_builddir ${CMAKE_CURRENT_BINARY_DIR}) set(abs_builddir ${CMAKE_CURRENT_BINARY_DIR})
if (HAVE_DOT) if (HAVE_DOT)
set(DOT ${LLVM_PATH_DOT}) set(DOT ${LLVM_PATH_DOT})
endif() endif()
@@ -152,7 +152,7 @@ if (DOXYGEN_FOUND)
set(enable_external_search "NO") set(enable_external_search "NO")
set(extra_search_mappings "") set(extra_search_mappings "")
endif() endif()
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/doxygen.cfg.in configure_file(${CMAKE_CURRENT_SOURCE_DIR}/doxygen.cfg.in
${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg @ONLY) ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg @ONLY)
@@ -164,11 +164,11 @@ if (DOXYGEN_FOUND)
set(enable_server_based_search) set(enable_server_based_search)
set(enable_external_search) set(enable_external_search)
set(extra_search_mappings) set(extra_search_mappings)
add_custom_target(doxygen-swift add_custom_target(doxygen-swift
${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Generating swift doxygen documentation." VERBATIM) COMMENT "Generating swift doxygen documentation." VERBATIM)
if(LLVM_BUILD_DOCS) if(LLVM_BUILD_DOCS)
add_dependencies(doxygen doxygen-swift) add_dependencies(doxygen doxygen-swift)

View File

@@ -59,8 +59,8 @@ of an l-value, but Swift does, so it's pertinent.
In general, the terms "pass-by-X" and "call-by-X" are used In general, the terms "pass-by-X" and "call-by-X" are used
interchangeably. It's unfortunate, because these conventions are interchangeably. It's unfortunate, because these conventions are
argument specific, and functions can be passed multiple arguments argument specific, and functions can be passed multiple arguments
that are each handled in a different way. As such, we'll prefer that are each handled in a different way. As such, we'll prefer
"pass-by-X" for consistency and to emphasize that these conventions "pass-by-X" for consistency and to emphasize that these conventions
are argument-specific. are argument-specific.
Pass-by-reference Pass-by-reference

View File

@@ -70,8 +70,8 @@ A smoke test on Linux does the following:
Platform | Comment | Check Status Platform | Comment | Check Status
------------ | ------- | ------------ ------------ | ------- | ------------
All supported platforms | @swift-ci Please test | Swift Test Linux Platform (smoke test)<br>Swift Test OS X Platform (smoke test)<br>Swift Test Linux Platform<br>Swift Test OS X Platform<br> All supported platforms | @swift-ci Please test | Swift Test Linux Platform (smoke test)<br>Swift Test OS X Platform (smoke test)<br>Swift Test Linux Platform<br>Swift Test OS X Platform<br>
All supported platforms | @swift-ci Please clean test | Swift Test Linux Platform (smoke test)<br>Swift Test OS X Platform (smoke test)<br>Swift Test Linux Platform<br>Swift Test OS X Platform<br> All supported platforms | @swift-ci Please clean test | Swift Test Linux Platform (smoke test)<br>Swift Test OS X Platform (smoke test)<br>Swift Test Linux Platform<br>Swift Test OS X Platform<br>
All supported platforms | @swift-ci Please test and merge | Swift Test Linux Platform (smoke test)<br>Swift Test OS X Platform (smoke test)<br> Swift Test Linux Platform <br>Swift Test OS X Platform All supported platforms | @swift-ci Please test and merge | Swift Test Linux Platform (smoke test)<br>Swift Test OS X Platform (smoke test)<br> Swift Test Linux Platform <br>Swift Test OS X Platform
All supported platforms | @swift-ci Please clean test and merge | Swift Test Linux Platform (smoke test)<br>Swift Test OS X Platform (smoke test)<br> Swift Test Linux Platform <br>Swift Test OS X Platform All supported platforms | @swift-ci Please clean test and merge | Swift Test Linux Platform (smoke test)<br>Swift Test OS X Platform (smoke test)<br> Swift Test Linux Platform <br>Swift Test OS X Platform
OS X platform | @swift-ci Please test OS X platform | Swift Test OS X Platform (smoke test)<br>Swift Test OS X Platform OS X platform | @swift-ci Please test OS X platform | Swift Test OS X Platform (smoke test)<br>Swift Test OS X Platform
@@ -123,9 +123,9 @@ A validation test on Linux does the following:
## Cross Repository Testing ## Cross Repository Testing
Simply provide the URL from corresponding pull requests in the same comment as "@swift-ci Please test" phrase. List all of the pull requests and then provide the specific test phrase you would like to trigger. Currently, it will only merge the main pull request you requested testing from as opposed to all of the PR's. Simply provide the URL from corresponding pull requests in the same comment as "@swift-ci Please test" phrase. List all of the pull requests and then provide the specific test phrase you would like to trigger. Currently, it will only merge the main pull request you requested testing from as opposed to all of the PR's.
For example: For example:
``` ```
Please test with following pull request: Please test with following pull request:

View File

@@ -20,7 +20,7 @@ to is tantamount to a debug-time miscompile!
Kinds of Dependency Kinds of Dependency
=================== ===================
There are four major kinds of dependency between files: There are four major kinds of dependency between files:
- ``top-level``: use of an unqualified name that is looked up at module scope, - ``top-level``: use of an unqualified name that is looked up at module scope,
and definition of a name at module scope. This includes free functions, and definition of a name at module scope. This includes free functions,

View File

@@ -270,10 +270,10 @@ past that, so:
1. Generate an output file map that contains all the per-file outputs you care 1. Generate an output file map that contains all the per-file outputs you care
about. Most likely this is just the object files and incremental build about. Most likely this is just the object files and incremental build
dependency files; everything else is an intermediate. (There should probably dependency files; everything else is an intermediate. (There should probably
be a tool that does this, perhaps built on what the package manager does.) be a tool that does this, perhaps built on what the package manager does.)
2. Set TMPDIR to somewhere you don't mind uninteresting intermediate files 2. Set TMPDIR to somewhere you don't mind uninteresting intermediate files
going. going.
3. Do one of the following: 3. Do one of the following:

View File

@@ -24,10 +24,10 @@ Driver Stages
The compiler driver for Swift roughly follows the same design as Clang's The compiler driver for Swift roughly follows the same design as Clang's
compiler driver: compiler driver:
1. Parse: Command-line arguments are parsed into ``Arg``\ s. A ToolChain is 1. Parse: Command-line arguments are parsed into ``Arg``\ s. A ToolChain is
selected based on the current platform. selected based on the current platform.
2. Pipeline: Based on the arguments and inputs, a tree of ``Action``\ s is 2. Pipeline: Based on the arguments and inputs, a tree of ``Action``\ s is
generated. These are the high-level processing steps that need to occur, generated. These are the high-level processing steps that need to occur,
such as "compile this file" or "link the output of all compilation actions". such as "compile this file" or "link the output of all compilation actions".
3. Bind: The ToolChain converts the ``Action``\ s into a set of ``Job``\ s. 3. Bind: The ToolChain converts the ``Action``\ s into a set of ``Job``\ s.
These are individual commands that need to be run, such as These are individual commands that need to be run, such as

View File

@@ -78,16 +78,16 @@ convention:
- Methods default to *not* producing errors unless they are explicitly - Methods default to *not* producing errors unless they are explicitly
marked. marked.
- The control flow within a function is still mostly explicit: a - The control flow within a function is still mostly explicit: a
maintainer can tell exactly which statements can produce an error, maintainer can tell exactly which statements can produce an error,
and a simple inspection reveals how the function reacts to the and a simple inspection reveals how the function reacts to the
error. error.
- Throwing an error provides similar performance to allocating an - Throwing an error provides similar performance to allocating an
error and returning it -- it isn't an expensive, table-based stack error and returning it -- it isn't an expensive, table-based stack
unwinding process. unwinding process.
- Cocoa APIs using standard ``NSError`` patterns can be imported into - Cocoa APIs using standard ``NSError`` patterns can be imported into
this world automatically. Other common patterns (e.g. ``CFError``, this world automatically. Other common patterns (e.g. ``CFError``,
``errno``) can be added to the model in future versions of Swift. ``errno``) can be added to the model in future versions of Swift.
@@ -180,7 +180,7 @@ allowed to throw is rejected by the compiler.
It isn't possible to overload functions solely based on whether the It isn't possible to overload functions solely based on whether the
functions throw. That is, this is not legal:: functions throw. That is, this is not legal::
func foo() { func foo() {
func foo() throws { func foo() throws {
A throwing method cannot override a non-throwing method or satisfy a A throwing method cannot override a non-throwing method or satisfy a
@@ -299,7 +299,7 @@ generalized ``do`` statement::
// a conditionally-executed catch clause // a conditionally-executed catch clause
} catch _ { } catch _ {
// a catch-all clause. // a catch-all clause.
} }
As with ``switch`` statements, Swift makes an effort to understand As with ``switch`` statements, Swift makes an effort to understand

View File

@@ -777,7 +777,7 @@ not free:
to resume normal execution from the landing pad: if the landing pad to resume normal execution from the landing pad: if the landing pad
only has clean-ups and therefore always restarts propagation, those only has clean-ups and therefore always restarts propagation, those
registers will have been saved and restored further out. registers will have been saved and restored further out.
* Languages like C++, ObjC ARC, and Swift that have non-trivial * Languages like C++, ObjC ARC, and Swift that have non-trivial
clean-ups for many local variables tend to have many functions with clean-ups for many local variables tend to have many functions with
interesting frames. This means both that the context-saving interesting frames. This means both that the context-saving
@@ -1576,7 +1576,7 @@ wrapped around an arbitrary expression::
// This try applies to readBool(). // This try applies to readBool().
if try stream.readBool() { if try stream.readBool() {
// This try applies to both of these calls. // This try applies to both of these calls.
let x = try stream.readInt() + stream.readInt() let x = try stream.readInt() + stream.readInt()

View File

@@ -20,7 +20,7 @@ might be expressed as::
T value; T value;
Node *next; Node *next;
}; };
Node *first; Node *first;
}; };
@@ -35,7 +35,7 @@ such as a simple, linear search algorithm::
for (typename List<T>::Node *result = list.first; result; result = result->next) for (typename List<T>::Node *result = list.first; result; result = result->next)
if (result->value == value) if (result->value == value)
return result; return result;
return 0; return 0;
} }
@@ -259,7 +259,7 @@ As previously noted, protocols can contain both function requirements (which are
in effect requirements for instance methods) and associated type in effect requirements for instance methods) and associated type
requirements. Protocols can also contain operators, properties, and subscript requirements. Protocols can also contain operators, properties, and subscript
operators:: operators::
protocol RandomAccessContainer : Collection { protocol RandomAccessContainer : Collection {
var count: Int var count: Int
func == (lhs: Self, rhs: Self) func == (lhs: Self, rhs: Self)
@@ -284,16 +284,16 @@ example, given::
} }
One could write a Circle struct such as:: One could write a Circle struct such as::
struct Circle { struct Circle {
var center : Point var center : Point
var radius : Int var radius : Int
func draw() { func draw() {
// draw it // draw it
} }
} }
Circle provides a draw() method with the same input and result types as required Circle provides a draw() method with the same input and result types as required
by the Shape protocol. Therefore, Circle conforms to Shape. by the Shape protocol. Therefore, Circle conforms to Shape.
@@ -304,7 +304,7 @@ also know how to "draw!"::
struct Cowboy { struct Cowboy {
var gun : SixShooter var gun : SixShooter
func draw() { func draw() {
// draw! // draw!
} }
@@ -382,7 +382,7 @@ meet if it wants to conform to the protocol. There is a natural tension here,
then, between larger protocols that make it easier to write generic algorithms, then, between larger protocols that make it easier to write generic algorithms,
and smaller protocols that make it easier to write conforming types. For and smaller protocols that make it easier to write conforming types. For
example, should a Numeric protocol implement all operations, e.g.,:: example, should a Numeric protocol implement all operations, e.g.,::
protocol Numeric { protocol Numeric {
func +(lhs : Self, rhs : Self) -> Self func +(lhs : Self, rhs : Self) -> Self
func -(lhs : Self, rhs : Self) -> Self func -(lhs : Self, rhs : Self) -> Self
@@ -404,7 +404,7 @@ algorithms)? Both of the protocols express the same thing (semantically),
because one can use the core operations (binary +, unary -) to implement the because one can use the core operations (binary +, unary -) to implement the
other algorithms. However, it's far easier to allow the protocol itself to other algorithms. However, it's far easier to allow the protocol itself to
provide default implementations:: provide default implementations::
protocol Numeric { protocol Numeric {
func +(lhs : Self, rhs : Self) -> Self func +(lhs : Self, rhs : Self) -> Self
func -(lhs : Self, rhs : Self) -> Self { return lhs + -rhs } func -(lhs : Self, rhs : Self) -> Self { return lhs + -rhs }
@@ -452,7 +452,7 @@ to implement. We can now see how Self types interact with subtype
polymorphism. For example, say we have two values of type Comparable, and we try polymorphism. For example, say we have two values of type Comparable, and we try
to compare them:: to compare them::
var x : Comparable = ... var x : Comparable = ...
var y : Comparable = ... var y : Comparable = ...
if x.isEqual(y) { // well-typed? if x.isEqual(y) { // well-typed?
} }
@@ -465,7 +465,7 @@ mode (aborting, throwing an exception, etc.) if the dynamic type check fails.
To express types that meet the requirements of several protocols, one can just To express types that meet the requirements of several protocols, one can just
create a new protocol aggregating those protocols:: create a new protocol aggregating those protocols::
protocol SerializableDocument : Document, Serializable { } protocol SerializableDocument : Document, Serializable { }
var doc : SerializableDocument var doc : SerializableDocument
print(doc.title()) // okay: title() is part of the Document protocol, so we can call it print(doc.title()) // okay: title() is part of the Document protocol, so we can call it
@@ -508,13 +508,13 @@ polymorphism.
Protocols provide a natural way to express the constraints of a generic function Protocols provide a natural way to express the constraints of a generic function
in Swift. For example, one could define a generic linked list as:: in Swift. For example, one could define a generic linked list as::
struct ListNode<T> { struct ListNode<T> {
var Value : T var Value : T
enum NextNode { case Node : ListNode<T>, End } enum NextNode { case Node : ListNode<T>, End }
var Next : NextNode var Next : NextNode
} }
struct List<T > { struct List<T > {
var First : ListNode<T>::NextNode var First : ListNode<T>::NextNode
} }
@@ -553,12 +553,12 @@ able to constrain associated types. To do so, we introduce the notion of a
"where" clause, which follows the signature of the generic type or "where" clause, which follows the signature of the generic type or
function. For example, let's generalize our find algorithm to work on any function. For example, let's generalize our find algorithm to work on any
ordered collection:: ordered collection::
protocol OrderedCollection : Collection { protocol OrderedCollection : Collection {
func size() -> Int func size() -> Int
func getAt(_ index : Int) -> Element // Element is an associated type func getAt(_ index : Int) -> Element // Element is an associated type
} }
func find<C : OrderedCollection where C.Element : Comparable>( func find<C : OrderedCollection where C.Element : Comparable>(
_ collection : C, value : C.Element) -> Int _ collection : C, value : C.Element) -> Int
{ {
@@ -676,7 +676,7 @@ language (generic functions can be "virtual").
The translation model is fairly simple. Consider the generic find() we The translation model is fairly simple. Consider the generic find() we
implemented for lists, above:: implemented for lists, above::
func find<T : Comparable>(_ list : List<T>, value : T) -> Int { func find<T : Comparable>(_ list : List<T>, value : T) -> Int {
var index = 0 var index = 0
var current = list.First var current = list.First
@@ -766,7 +766,7 @@ Overloading
Generic functions can be overloaded based entirely on constraints. For example, Generic functions can be overloaded based entirely on constraints. For example,
consider a binary search algorithm:: consider a binary search algorithm::
func binarySearch< func binarySearch<
C : EnumerableCollection where C.Element : Comparable C : EnumerableCollection where C.Element : Comparable
>(_ collection : C, value : C.Element) >(_ collection : C, value : C.Element)
@@ -778,17 +778,17 @@ consider a binary search algorithm::
protocol RandomAccessEnumerator : Enumerator { protocol RandomAccessEnumerator : Enumerator {
// splits a range in half, returning both halves // splits a range in half, returning both halves
func split() -> (Enumerator, Enumerator) func split() -> (Enumerator, Enumerator)
} }
func binarySearch< func binarySearch<
C : EnumerableCollection C : EnumerableCollection
where C.Element : Comparable, where C.Element : Comparable,
C.EnumeratorType: RandomAccessEnumerator C.EnumeratorType: RandomAccessEnumerator
>(_ collection : C, value : C.Element) >(_ collection : C, value : C.Element)
-> C.EnumeratorType -> C.EnumeratorType
{ {
// We can perform log(N) comparisons and log(N) range splits, // We can perform log(N) comparisons and log(N) range splits,
// so this is logarithmic time // so this is logarithmic time
} }
@@ -806,7 +806,7 @@ minimal requirements::
C : EnumerableCollection where C.Element : Ordered C : EnumerableCollection where C.Element : Ordered
>( >(
_ collection : C, value : C.Element _ collection : C, value : C.Element
) -> C.EnumeratorType ) -> C.EnumeratorType
{ {
binarySearch(collection, value) binarySearch(collection, value)
} }
@@ -876,7 +876,7 @@ which can be interpreted as either::
(integer_literal 10))) (integer_literal 10)))
or:: or::
(constructor Matrix<Double> (constructor Matrix<Double>
(tuple (tuple
(integer_literal 10) (integer_literal 10)

View File

@@ -202,7 +202,7 @@ protocol Sequence {
} }
``` ```
### Default generic arguments ### Default generic arguments
Generic parameters could be given the ability to provide default arguments, which would be used in cases where the type argument is not specified and type inference could not determine the type argument. For example: Generic parameters could be given the ability to provide default arguments, which would be used in cases where the type argument is not specified and type inference could not determine the type argument. For example:
@@ -250,7 +250,7 @@ extension P {
} }
class C : P { class C : P {
// gets the protocol extension's // gets the protocol extension's
} }
class D : C { class D : C {
@@ -325,7 +325,7 @@ Variadic generics would allow us to abstract over a set of generic parameters. T
public struct ZipIterator<... Iterators : IteratorProtocol> : Iterator { // zero or more type parameters, each of which conforms to IteratorProtocol public struct ZipIterator<... Iterators : IteratorProtocol> : Iterator { // zero or more type parameters, each of which conforms to IteratorProtocol
public typealias Element = (Iterators.Element...) // a tuple containing the element types of each iterator in Iterators public typealias Element = (Iterators.Element...) // a tuple containing the element types of each iterator in Iterators
var (...iterators): (Iterators...) // zero or more stored properties, one for each type in Iterators var (...iterators): (Iterators...) // zero or more stored properties, one for each type in Iterators
var reachedEnd = false var reachedEnd = false
public mutating func next() -> Element? { public mutating func next() -> Element? {
@@ -343,7 +343,7 @@ public struct ZipIterator<... Iterators : IteratorProtocol> : Iterator { // zer
public struct ZipSequence<...Sequences : Sequence> : Sequence { public struct ZipSequence<...Sequences : Sequence> : Sequence {
public typealias Iterator = ZipIterator<Sequences.Iterator...> // get the zip iterator with the iterator types of our Sequences public typealias Iterator = ZipIterator<Sequences.Iterator...> // get the zip iterator with the iterator types of our Sequences
var (...sequences): (Sequences...) // zero or more stored properties, one for each type in Sequences var (...sequences): (Sequences...) // zero or more stored properties, one for each type in Sequences
// details ... // details ...
} }
@@ -352,7 +352,7 @@ public struct ZipSequence<...Sequences : Sequence> : Sequence {
Such a design could also work for function parameters, so we can pack together multiple function arguments with different types, e.g., Such a design could also work for function parameters, so we can pack together multiple function arguments with different types, e.g.,
```Swift ```Swift
public func zip<... Sequences : SequenceType>(... sequences: Sequences...) public func zip<... Sequences : SequenceType>(... sequences: Sequences...)
-> ZipSequence<Sequences...> { -> ZipSequence<Sequences...> {
return ZipSequence(sequences...) return ZipSequence(sequences...)
} }
@@ -453,7 +453,7 @@ func containsAll<S: Sequence where Sequence.Iterator.Element == Element>(element
One could move the `where` clause to the end of the signature, so that the most important parts—name, generic parameter, parameters, result type—precede it: One could move the `where` clause to the end of the signature, so that the most important parts—name, generic parameter, parameters, result type—precede it:
```Swift ```Swift
func containsAll<S: Sequence>(elements: S) -> Bool func containsAll<S: Sequence>(elements: S) -> Bool
where Sequence.Iterator.Element == Element where Sequence.Iterator.Element == Element
``` ```
@@ -616,7 +616,7 @@ The actual requested feature here is the ability to say "Any type that conforms
More importantly, modeling `Sequence` with generic parameters rather than associated types is tantalizing but wrong: you don't want a type conforming to `Sequence` in multiple ways, or (among other things) your `for..in` loops stop working, and you lose the ability to dynamically cast down to an existential `Sequence` without binding the `Element` type (again, see "Generalized existentials"). Use cases similar to the `ConstructibleFromValue` protocol above seem too few to justify the potential for confusion between associated types and generic parameters of protocols; we're better off not having the latter. More importantly, modeling `Sequence` with generic parameters rather than associated types is tantalizing but wrong: you don't want a type conforming to `Sequence` in multiple ways, or (among other things) your `for..in` loops stop working, and you lose the ability to dynamically cast down to an existential `Sequence` without binding the `Element` type (again, see "Generalized existentials"). Use cases similar to the `ConstructibleFromValue` protocol above seem too few to justify the potential for confusion between associated types and generic parameters of protocols; we're better off not having the latter.
### Private conformances ### Private conformances
Right now, a protocol conformance can be no less visible than the minimum of the conforming type's access and the protocol's access. Therefore, a public type conforming to a public protocol must provide the conformance publicly. One could imagine removing that restriction, so that one could introduce a private conformance: Right now, a protocol conformance can be no less visible than the minimum of the conforming type's access and the protocol's access. Therefore, a public type conforming to a public protocol must provide the conformance publicly. One could imagine removing that restriction, so that one could introduce a private conformance:

View File

@@ -289,9 +289,9 @@ string.concat(lhs: String, rhs: String) -> String
This operation can be optimized away in case of both operands This operation can be optimized away in case of both operands
being string literals. In this case, it can be replaced by being string literals. In this case, it can be replaced by
a string literal representing a concatenation of both operands. a string literal representing a concatenation of both operands.
string.makeUTF8(start: RawPointer, utf8CodeUnitCount: Word, isASCII: Int1) -> String string.makeUTF8(start: RawPointer, utf8CodeUnitCount: Word, isASCII: Int1) -> String
Converts a built-in UTF8-encoded string literal into a string. Converts a built-in UTF8-encoded string literal into a string.
string.makeUTF16(start: RawPointer, utf16CodeUnitCount: Word) -> String string.makeUTF16(start: RawPointer, utf16CodeUnitCount: Word) -> String

View File

@@ -16,12 +16,12 @@ aren't so complicated:
initializers, and (b) all properties have initial values. initializers, and (b) all properties have initial values.
| Convenience initializers delegate. | Convenience initializers delegate.
| Convenience initializers are inherited if all of the superclass's | Convenience initializers are inherited if all of the superclass's
designated initializers are present. designated initializers are present.
| If you want to call an initializer on a dynamic type, it must be marked | If you want to call an initializer on a dynamic type, it must be marked
required. required.
| Protocols are one way to do this, so initializers that satisfy protocol | Protocols are one way to do this, so initializers that satisfy protocol
requirements must be required. requirements must be required.
| If your superclass has a required initializer, you must provide it | If your superclass has a required initializer, you must provide it
somehow. somehow.
@@ -42,11 +42,11 @@ With all our rules, we actually rule out some important use cases, like this one
``initWithContentsOfURL:ofType:error:``. If you perform initializations that ``initWithContentsOfURL:ofType:error:``. If you perform initializations that
must be done when creating new documents but not when opening existing must be done when creating new documents but not when opening existing
documents, override ``initWithType:error:``. If you have any initializations documents, override ``initWithType:error:``. If you have any initializations
that apply only to documents that are opened, override that apply only to documents that are opened, override
``initWithContentsOfURL:ofType:error:``. If you have general ``initWithContentsOfURL:ofType:error:``. If you have general
initializations, override ``init``. In all three cases, be sure to invoke initializations, override ``init``. In all three cases, be sure to invoke
the superclass implementation as the first action. the superclass implementation as the first action.
-- `Document-Based App Programming Guide for Mac`__ -- `Document-Based App Programming Guide for Mac`__
__ https://developer.apple.com/library/mac/documentation/DataManagement/Conceptual/DocBasedAppProgrammingGuideForOSX/ManagingLifecycle/ManagingLifecycle.html#//apple_ref/doc/uid/TP40011179-CH4-SW11 __ https://developer.apple.com/library/mac/documentation/DataManagement/Conceptual/DocBasedAppProgrammingGuideForOSX/ManagingLifecycle/ManagingLifecycle.html#//apple_ref/doc/uid/TP40011179-CH4-SW11
@@ -73,7 +73,7 @@ there are some patterns that cannot be written in Swift, such as this one::
} }
// other generator stuff // other generator stuff
} }
class AnyGeneratorImpl<WrappedGenerator: GeneratorType> : class AnyGeneratorImpl<WrappedGenerator: GeneratorType> :
AnyGenerator<WrappedGenerator.Element> { AnyGenerator<WrappedGenerator.Element> {
var wrapped: WrappedGenerator var wrapped: WrappedGenerator
@@ -95,11 +95,11 @@ We've had a number of ideas for improving the state of the world, including
- Allow designated initializers to delegate to other designated initializers - Allow designated initializers to delegate to other designated initializers
(using static dispatch). This makes convenience initializers a niche feature. (using static dispatch). This makes convenience initializers a niche feature.
- Add the concept of factory initializers, which don't promise to return - Add the concept of factory initializers, which don't promise to return
``Self``. These are either never inherited or must always be overridden in a ``Self``. These are either never inherited or must always be overridden in a
subclass. subclass.
- Allow convenience initializers to chain to superclass convenience - Allow convenience initializers to chain to superclass convenience
initializers. This isn't strictly safe, but it permits the NSDocument idiom. initializers. This isn't strictly safe, but it permits the NSDocument idiom.
None of these solve all the initializer problems listed above on their own, and None of these solve all the initializer problems listed above on their own, and

View File

@@ -13,7 +13,7 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
.. note:: .. note::
This document uses Sphinx-specific features. If you are viewing this on This document uses Sphinx-specific features. If you are viewing this on
GitHub, you'll have to use raw mode, or download and build the docs GitHub, you'll have to use raw mode, or download and build the docs
yourself. yourself.
.. glossary:: .. glossary::
@@ -21,7 +21,7 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
archetype archetype
A placeholder for a generic parameter or an associated type within a A placeholder for a generic parameter or an associated type within a
generic context. Sometimes known as a "rigid type variable" in formal generic context. Sometimes known as a "rigid type variable" in formal
CS literature. Directly stores its conforming protocols and nested CS literature. Directly stores its conforming protocols and nested
archetypes, if any. archetypes, if any.
canonical SIL canonical SIL
@@ -40,18 +40,18 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
the AST level. See also `witness table`. the AST level. See also `witness table`.
contextual type contextual type
1. The expected type for a Swift sub-expression based on the rest of the 1. The expected type for a Swift sub-expression based on the rest of the
statement. For example, in the statement ``print(6 * 9)``, the contextual statement. For example, in the statement ``print(6 * 9)``, the contextual
type of the expression ``6 * 9`` is ``Any``. type of the expression ``6 * 9`` is ``Any``.
2. The type of a value or declaration from inside a potentially generic 2. The type of a value or declaration from inside a potentially generic
context. This type may contain `archetypes <archetype>` and cannot be context. This type may contain `archetypes <archetype>` and cannot be
used directly from outside the context. Compare with `interface type`. used directly from outside the context. Compare with `interface type`.
DI (definite initialization / definitive initialization) DI (definite initialization / definitive initialization)
The feature that no uninitialized variables, constants, or properties will The feature that no uninitialized variables, constants, or properties will
be read by a program, or the analysis pass that operates on SIL to be read by a program, or the analysis pass that operates on SIL to
guarantee this. This was `discussed on Apple's Swift blog`__. guarantee this. This was `discussed on Apple's Swift blog`__.
__ https://developer.apple.com/swift/blog/?id=28 __ https://developer.apple.com/swift/blog/?id=28
dup dup
@@ -71,7 +71,7 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
iff iff
"`if and only if`__". This term comes from mathematics. "`if and only if`__". This term comes from mathematics.
__ https://en.wikipedia.org/wiki/If_and_only_if __ https://en.wikipedia.org/wiki/If_and_only_if
interface type interface type
@@ -112,14 +112,14 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
The type of a value representing a type. Greg Parker has a good The type of a value representing a type. Greg Parker has a good
explanation of `Objective-C's "metaclasses"`__; because Swift has types explanation of `Objective-C's "metaclasses"`__; because Swift has types
that are *not* classes, a more general term is used. that are *not* classes, a more general term is used.
We also sometimes refer to a value representing a type as a "metatype We also sometimes refer to a value representing a type as a "metatype
object" or just "metatype", usually within low-level contexts like IRGen object" or just "metatype", usually within low-level contexts like IRGen
and LLDB. This is technically incorrect (it's just a "type object"), but and LLDB. This is technically incorrect (it's just a "type object"), but
the malapropism happened early in the project and has stuck around. the malapropism happened early in the project and has stuck around.
__ http://sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html __ http://sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html
model model
A type that conforms to a particular protocol. Sometimes "concrete A type that conforms to a particular protocol. Sometimes "concrete
model". Example: "Array and Set are both models of CollectionType". model". Example: "Array and Set are both models of CollectionType".
@@ -127,8 +127,8 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
module module
Has *many* uses in the Swift world. We may want to rename some of them. Has *many* uses in the Swift world. We may want to rename some of them.
#1 and #2 are the most common. #1 and #2 are the most common.
1. A unit of API distribution and grouping. The ``import`` declaration 1. A unit of API distribution and grouping. The ``import`` declaration
brings modules into scope. Represented as ModuleDecl in the compiler. brings modules into scope. Represented as ModuleDecl in the compiler.
2. A compilation unit; that is, source files that are compiled together. 2. A compilation unit; that is, source files that are compiled together.
These files may contain cross-references. Represented as "the main These files may contain cross-references. Represented as "the main
@@ -147,7 +147,7 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
7. Shorthand for a "precompiled module file"; effectively "precompiled 7. Shorthand for a "precompiled module file"; effectively "precompiled
headers" for an entire Clang module. Never used directly by Swift. headers" for an entire Clang module. Never used directly by Swift.
See also `module cache`. See also `module cache`.
__ http://clang.llvm.org/docs/Modules.html __ http://clang.llvm.org/docs/Modules.html
module cache module cache
@@ -167,7 +167,7 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
patches that change functionality. patches that change functionality.
open existential open existential
An `existential` value with its dynamic type pulled out, so that the An `existential` value with its dynamic type pulled out, so that the
compiler can do something with it. compiler can do something with it.
overlay overlay
@@ -177,10 +177,10 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
Apple has a number of overlays for its own SDKs in stdlib/public/SDK/. Apple has a number of overlays for its own SDKs in stdlib/public/SDK/.
PR PR
1. "Problem Report": An issue reported in `LLVM's bug tracker`__. 1. "Problem Report": An issue reported in `LLVM's bug tracker`__.
See also `SR`. See also `SR`.
2. "pull request" 2. "pull request"
__ https://llvm.org/bugs/ __ https://llvm.org/bugs/
primary file primary file
@@ -200,7 +200,7 @@ source code, tests, and commit messages. See also the `LLVM lexicon`_.
Radar Radar
`Apple's bug-tracking system`__, or an issue reported on that system. `Apple's bug-tracking system`__, or an issue reported on that system.
__ https://bugreport.apple.com __ https://bugreport.apple.com
raw SIL raw SIL

View File

@@ -180,7 +180,7 @@ versioning information as well. A *versioned entity* represents anything with a
runtime presence that a client may rely on; its version records when the entity runtime presence that a client may rely on; its version records when the entity
was first exposed publicly in its library. Put another way, it is the oldest was first exposed publicly in its library. Put another way, it is the oldest
version of the library where the entity may be used. version of the library where the entity may be used.
- Classes, structs, enums, and protocols may all be versioned entities. - Classes, structs, enums, and protocols may all be versioned entities.
- Methods, properties, subscripts, and initializers may be versioned entities. - Methods, properties, subscripts, and initializers may be versioned entities.
- Top-level functions, variables, and constants may be versioned entities. - Top-level functions, variables, and constants may be versioned entities.
@@ -555,7 +555,7 @@ clients to access them more efficiently. This restricts changes a fair amount:
break existing clients. break existing clients.
- Changing the body of an accessor is a `binary-compatible source-breaking - Changing the body of an accessor is a `binary-compatible source-breaking
change`. change`.
- Adding/removing observing accessors is likewise a `binary-compatible - Adding/removing observing accessors is likewise a `binary-compatible
source-breaking change`. source-breaking change`.
- Changing the initial value of a stored variable is still permitted. - Changing the initial value of a stored variable is still permitted.
- Changing the value of a constant is a `binary-compatible source-breaking - Changing the value of a constant is a `binary-compatible source-breaking
@@ -984,7 +984,7 @@ Finally, classes allow the following changes that do not apply to structs:
implementation. implementation.
- A non-final override of a method, subscript, property, or initializer may be - A non-final override of a method, subscript, property, or initializer may be
removed as long as the generic parameters, formal parameters, and return type removed as long as the generic parameters, formal parameters, and return type
*exactly* match the overridden declaration. Any existing callers should *exactly* match the overridden declaration. Any existing callers should
automatically use the superclass implementation. automatically use the superclass implementation.
- Within an ``open`` class, any public method, subscript, or property may be - Within an ``open`` class, any public method, subscript, or property may be
marked ``open`` if it is not already marked ``final``. marked ``open`` if it is not already marked ``final``.
@@ -1654,7 +1654,7 @@ Recompiling changes a protocol's implementation
@available(2.0) @available(2.0)
func equip() { print("Equipped.") } func equip() { print("Equipped.") }
} }
extension Wearable where Self: MagicType { extension Wearable where Self: MagicType {
@available(2.0) @available(2.0)
func equip() { print("You put it on.") } func equip() { print("You put it on.") }
@@ -1764,7 +1764,7 @@ Glossary
errors when a client is recompiled. In most cases, a client that *hasn't* errors when a client is recompiled. In most cases, a client that *hasn't*
been recompiled may use the new behavior or the old behavior, or even a been recompiled may use the new behavior or the old behavior, or even a
mix of both; however, this will always be deterministic (same behavior when mix of both; however, this will always be deterministic (same behavior when
a program is re-run) and will not break Swift's memory-safety and a program is re-run) and will not break Swift's memory-safety and
type-safety guarantees. It is recommended that these kinds of changes are type-safety guarantees. It is recommended that these kinds of changes are
avoided just like those that break binary compatibility. avoided just like those that break binary compatibility.

View File

@@ -42,7 +42,7 @@ library's CompilerProtocols.swift::
// Conforming types can be initialized with arbitrary string literals. // Conforming types can be initialized with arbitrary string literals.
public protocol ExpressibleByStringLiteral public protocol ExpressibleByStringLiteral
: ExpressibleByExtendedGraphemeClusterLiteral { : ExpressibleByExtendedGraphemeClusterLiteral {
typealias StringLiteralType : _ExpressibleByBuiltinStringLiteral typealias StringLiteralType : _ExpressibleByBuiltinStringLiteral
// Create an instance initialized to `value`. // Create an instance initialized to `value`.
init(stringLiteral value: StringLiteralType) init(stringLiteral value: StringLiteralType)
@@ -82,7 +82,7 @@ data from the literal, and the arguments describe that raw data.
So, the general runtime behavior is now clear: So, the general runtime behavior is now clear:
1. The compiler generates raw string data. 1. The compiler generates raw string data.
2. Some type conforming to _ExpressibleByBuiltinStringLiteral is constructed from 2. Some type conforming to _ExpressibleByBuiltinStringLiteral is constructed from
the raw string data. This will be a standard library type. the raw string data. This will be a standard library type.
3. Some type conforming to ExpressibleByStringLiteral is constructed from the 3. Some type conforming to ExpressibleByStringLiteral is constructed from the
object constructed in step 2. This may be a user-defined type. This is the object constructed in step 2. This may be a user-defined type. This is the
@@ -100,11 +100,11 @@ types.
This algorithm can go forwards or backwards, since it's actually defined in This algorithm can go forwards or backwards, since it's actually defined in
terms of constraints, but it's easiest to understand as a linear process. terms of constraints, but it's easiest to understand as a linear process.
1. Filter the types provided by the context to only include those that are 1. Filter the types provided by the context to only include those that are
ExpressibleByStringLiteral. ExpressibleByStringLiteral.
2. Using the associated StringLiteralType, find the appropriate 2. Using the associated StringLiteralType, find the appropriate
``_convertFromBuiltinStringLiteral``. ``_convertFromBuiltinStringLiteral``.
3. Using the type from step 1, find the appropriate 3. Using the type from step 1, find the appropriate
``convertFromStringLiteral``. ``convertFromStringLiteral``.
4. Build an expression tree with the appropriate calls. 4. Build an expression tree with the appropriate calls.

View File

@@ -39,7 +39,7 @@ You can also selectively import certain declarations from a module::
.. admonition:: Comparison with Other Languages .. admonition:: Comparison with Other Languages
Importing a module is much like importing a library in Ruby, Python, or Perl, Importing a module is much like importing a library in Ruby, Python, or Perl,
importing a class in Java, or including a header file in a C-family language. importing a class in Java, or including a header file in a C-family language.
However, unlike C, module files are not textually included and must be valid However, unlike C, module files are not textually included and must be valid
programs on their own, and may not be in a textual format at all. Unlike Java, programs on their own, and may not be in a textual format at all. Unlike Java,
declarations in a module are not visible at all until imported. And unlike the declarations in a module are not visible at all until imported. And unlike the
@@ -81,7 +81,7 @@ visible. If more than one imported module declares the same name, the full
The one exception to this rule is declarations that must be compatible with The one exception to this rule is declarations that must be compatible with
Objective-C. Such declarations follow the usual Objective-C rules for name Objective-C. Such declarations follow the usual Objective-C rules for name
conflicts: all classes must have unique names, all protocols must have unique conflicts: all classes must have unique names, all protocols must have unique
names, and all constructors, methods, and properties must have unique names names, and all constructors, methods, and properties must have unique names
within their class (including inherited methods and properties). within their class (including inherited methods and properties).
@@ -91,7 +91,7 @@ Modules may contain code
In addition to declarations, modules may contain implementations of the In addition to declarations, modules may contain implementations of the
functions they define. The compiler may choose to use this information when functions they define. The compiler may choose to use this information when
optimizing a user's program, usually by inlining the module code into a caller. optimizing a user's program, usually by inlining the module code into a caller.
In some cases [#]_, the compiler may even use a module's function In some cases [#]_, the compiler may even use a module's function
implementations to produce more effective diagnostics. implementations to produce more effective diagnostics.
Modules can also contain `autolinking` information, which the compiler passes Modules can also contain `autolinking` information, which the compiler passes
@@ -158,7 +158,7 @@ module names are conventionally capitalized.
Foundation.SupportType() // from the class or from the module? Foundation.SupportType() // from the class or from the module?
In both cases, the type takes priority over the module, but this should still In both cases, the type takes priority over the module, but this should still
be avoided. be avoided.
.. admonition:: TODO .. admonition:: TODO
@@ -216,7 +216,7 @@ loaded with ``import``, but with a few important differences:
.. admonition:: FIXME .. admonition:: FIXME
This wouldn't belong in the user model at all except for the implicit This wouldn't belong in the user model at all except for the implicit
visibility thing. Is there a better way to talk about this? visibility thing. Is there a better way to talk about this?
@@ -261,18 +261,18 @@ Submodules
For large projects, it is usually desirable to break a single application or For large projects, it is usually desirable to break a single application or
framework into subsystems, which Swift calls "submodules". A submodule is a framework into subsystems, which Swift calls "submodules". A submodule is a
development-time construct used for grouping within a module. By default, development-time construct used for grouping within a module. By default,
declarations within a submodule are considered "submodule-private", which declarations within a submodule are considered "submodule-private", which
means they are only visible within that submodule (rather than across the means they are only visible within that submodule (rather than across the
entire module). These declarations will not conflict with declarations in other entire module). These declarations will not conflict with declarations in other
submodules that may have the same name. submodules that may have the same name.
Declarations explicitly marked "whole-module" or "API" are still visible Declarations explicitly marked "whole-module" or "API" are still visible
across the entire module (even if declared within a submodule), and must have a across the entire module (even if declared within a submodule), and must have a
unique name within that space. unique name within that space.
The `qualified name` of a declaration within a submodule consists of the The `qualified name` of a declaration within a submodule consists of the
top-level module name, followed by the submodule name, followed by the top-level module name, followed by the submodule name, followed by the
declaration. declaration.
.. note:: .. note::
@@ -284,16 +284,16 @@ declaration.
We need to decide once and for all whether implicit visibility applies across We need to decide once and for all whether implicit visibility applies across
submodule boundaries, i.e. "can I access the public Swift.AST.Module from submodule boundaries, i.e. "can I access the public Swift.AST.Module from
Swift.Sema without an import, or do I have to say ``import Swift.AST``?" Swift.Sema without an import, or do I have to say ``import Swift.AST``?"
Advantages of module-wide implicit visibility: Advantages of module-wide implicit visibility:
- Better name conflict checking. (The alternative is a linker error, or worse - Better name conflict checking. (The alternative is a linker error, or worse
*no* linker error if the names have different manglings.) *no* linker error if the names have different manglings.)
- Less work if things move around. - Less work if things move around.
- Build time performance is consistent whether or not you use this feature. - Build time performance is consistent whether or not you use this feature.
Advantages of submodule-only implicit visibility: Advantages of submodule-only implicit visibility:
- Code completion will include names of public things you don't care about. - Code completion will include names of public things you don't care about.
- We haven't actually tested the build time performance of any large Swift - We haven't actually tested the build time performance of any large Swift
projects, so we don't know if we can actually handle targets that contain projects, so we don't know if we can actually handle targets that contain
@@ -303,7 +303,7 @@ declaration.
- In this mode, we could allow two "whole-module" declarations to have the - In this mode, we could allow two "whole-module" declarations to have the
same name, since they won't. (We could allow this in the other mode too same name, since they won't. (We could allow this in the other mode too
but then the qualified name would always be required.) but then the qualified name would always be required.)
Both cases still use "submodule-only" as the default access control, so this Both cases still use "submodule-only" as the default access control, so this
only affects the implicit visibility of whole-module and public declarations. only affects the implicit visibility of whole-module and public declarations.
@@ -337,7 +337,7 @@ Clang Submodules
---------------- ----------------
Clang also has a concept of "submodules", which are essentially hierarchically- Clang also has a concept of "submodules", which are essentially hierarchically-
named modules. Unlike Swift's :ref:`submodules`, Clang submodules are visible named modules. Unlike Swift's :ref:`submodules`, Clang submodules are visible
from outside the module. It is conventional for a top-level Clang module to from outside the module. It is conventional for a top-level Clang module to
re-export all of its submodules, but sometimes certain submodules are specified re-export all of its submodules, but sometimes certain submodules are specified
to require an explicit import:: to require an explicit import::
@@ -382,13 +382,13 @@ Accessing Swift declarations from Objective-C
Using the new ``@import`` syntax, Objective-C translation units can import Using the new ``@import`` syntax, Objective-C translation units can import
Swift modules as well. Swift declarations will be mirrored into Objective-C Swift modules as well. Swift declarations will be mirrored into Objective-C
and can be called natively, just as Objective-C declarations are mirrored into and can be called natively, just as Objective-C declarations are mirrored into
Swift for `Clang modules <Clang module>`. In this case, only the declarations Swift for `Clang modules <Clang module>`. In this case, only the declarations
compatible with Objective-C will be visible. compatible with Objective-C will be visible.
.. admonition:: TODO .. admonition:: TODO
We need to actually do this, but it requires working on a branch of Clang, so We need to actually do this, but it requires working on a branch of Clang, so
we're pushing it back in the schedule as far as possible. The workaround is we're pushing it back in the schedule as far as possible. The workaround is
to manually write header files for imported Swift classes. to manually write header files for imported Swift classes.
.. admonition:: TODO .. admonition:: TODO
@@ -412,7 +412,7 @@ Glossary
specify them at link time. specify them at link time.
Clang module Clang module
A module whose contents are generated from a C-family header or set of A module whose contents are generated from a C-family header or set of
headers. See Clang's Modules__ documentation for more information. headers. See Clang's Modules__ documentation for more information.
__ http://clang.llvm.org/docs/Modules.html __ http://clang.llvm.org/docs/Modules.html
@@ -427,7 +427,7 @@ Glossary
be created by users. be created by users.
import import
To locate and read a module, then make its declarations available in the To locate and read a module, then make its declarations available in the
current context. current context.
library library
@@ -457,15 +457,15 @@ Glossary
included the former module. included the former module.
serialized module serialized module
A particular encoding of a module that contains declarations that have A particular encoding of a module that contains declarations that have
already been processed by the compiler. It may also contain implementations already been processed by the compiler. It may also contain implementations
of some function declarations in `SIL` form. of some function declarations in `SIL` form.
SIL SIL
"Swift Intermediate Language", a stable IR for the distribution of "Swift Intermediate Language", a stable IR for the distribution of
inlineable code. inlineable code.
target target
A dynamic library, framework, plug-in, or application to be built. A dynamic library, framework, plug-in, or application to be built.
A natural LTO boundary, and roughly the same as what Xcode requires A natural LTO boundary, and roughly the same as what Xcode requires

View File

@@ -42,10 +42,10 @@ Consider::
What do we do with this? Since ``+=`` has an ``inout`` first What do we do with this? Since ``+=`` has an ``inout`` first
argument, we detect this situation statically (hopefully one day we'll argument, we detect this situation statically (hopefully one day we'll
have a better error message): have a better error message):
.. code-block:: swift-console .. code-block:: swift-console
<REPL Input>:1:9: error: expression does not type-check <REPL Input>:1:9: error: expression does not type-check
w.title += " (parenthesized remark)" w.title += " (parenthesized remark)"
~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -126,7 +126,7 @@ implicitly:
var x = Number(42) var x = Number(42)
x.increment() // mutating operation x.increment() // mutating operation
* passing it to a function attributed with ``@assignment``:: * passing it to a function attributed with ``@assignment``::
var y = 31 var y = 31
@@ -162,7 +162,7 @@ A subscript or property access expression is an rvalue if
value type value type
For example, consider this extension to our ``Number`` struct: For example, consider this extension to our ``Number`` struct:
.. parsed-literal:: .. parsed-literal::
extension Number { extension Number {
@@ -223,9 +223,9 @@ The Big Rule
.. Error:: A program that applies a mutating operation to an rvalue is ill-formed .. Error:: A program that applies a mutating operation to an rvalue is ill-formed
:class: warning :class: warning
For example: For example:
.. parsed-literal:: .. parsed-literal::
clay = 43 // OK; a var is always assignable clay = 43 // OK; a var is always assignable

View File

@@ -70,7 +70,7 @@ example, the following is a valid initializer::
completeInit() completeInit()
} }
func completeInit() { /* ... */ } func completeInit() { /* ... */ }
} }
After all stored properties have been initialized, one is free to use After all stored properties have been initialized, one is free to use
@@ -96,7 +96,7 @@ in that order. For example, consider a subclass ``B`` of ``A``::
completeInitForB() // perform other tasks completeInitForB() // perform other tasks
} }
func completeInitForB() { /* ... */ } func completeInitForB() { /* ... */ }
} }
Consider the following construction of an object of type ``B``:: Consider the following construction of an object of type ``B``::
@@ -109,7 +109,7 @@ Consider the following construction of an object of type ``B``::
initialize stored properties *before* chaining to the superclass initialize stored properties *before* chaining to the superclass
initializer. This is part of Swift's memory safety guarantee, and initializer. This is part of Swift's memory safety guarantee, and
is discussed further in the section on `Three-Phase is discussed further in the section on `Three-Phase
Initialization`_. Initialization`_.
Initialization proceeds in several steps: Initialization proceeds in several steps:
@@ -164,7 +164,7 @@ to construct objects, using the same syntax. For example, the ``A``
initializer above can be used to build a new ``A`` object without any initializer above can be used to build a new ``A`` object without any
arguments:: arguments::
var a2 = A() // uses convenience initializer var a2 = A() // uses convenience initializer
Initializer Inheritance Initializer Inheritance
~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
@@ -189,14 +189,14 @@ Initialization proceeds as follows:
``B``'s designated initializer. ``B``'s designated initializer.
4. ``B``'s designated initializer initializes the stored property 4. ``B``'s designated initializer initializes the stored property
``d`` to ``17.0``. ``d`` to ``17.0``.
5. ``B``'s designated initializer chains to ``A``'s designated 5. ``B``'s designated initializer chains to ``A``'s designated
initializer. initializer.
6. ``A``'s designated initializer initialize's the stored properties 6. ``A``'s designated initializer initialize's the stored properties
``i`` and ``s``'. ``i`` and ``s``'.
7. ``A``'s designated initializer calls ``completeInit()``, then 7. ``A``'s designated initializer calls ``completeInit()``, then
returns. returns.
8. ``B``'s designated initializer calls ``completeInitForB()``, then 8. ``B``'s designated initializer calls ``completeInitForB()``, then
returns. returns.
9. ``A``'s convenience initializer returns. 9. ``A``'s convenience initializer returns.
Convenience initializers are only inherited under certain Convenience initializers are only inherited under certain
@@ -276,7 +276,7 @@ When a particular class does not specify any designated initializers,
the implementation will synthesize initializers for the class when all the implementation will synthesize initializers for the class when all
of the class's stored properties have initial values in the class. The of the class's stored properties have initial values in the class. The
form of the synthesized initializers depends on the superclass (if form of the synthesized initializers depends on the superclass (if
present). present).
When a superclass is present, the compiler synthesizes a new When a superclass is present, the compiler synthesizes a new
designated initializer in the subclass for each designated initializer designated initializer in the subclass for each designated initializer
@@ -356,8 +356,8 @@ the subclass might have taken over its own initialization (as with
particular initializer, use the ``required`` attribute as follows:: particular initializer, use the ``required`` attribute as follows::
class View { class View {
@required init frame(Rect) { @required init frame(Rect) {
/* initialize view */ /* initialize view */
} }
} }
@@ -444,7 +444,7 @@ itself during initialization, one can write a de-initializer using
The statements within a de-initializer (here, the call to ``close``) The statements within a de-initializer (here, the call to ``close``)
execute first, then the superclass's de-initializer is execute first, then the superclass's de-initializer is
called. Finally, stored properties are released and the object is called. Finally, stored properties are released and the object is
deallocated. deallocated.
Methods Returning ``Self`` Methods Returning ``Self``
~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -560,7 +560,7 @@ call to the superclass initializer::
resilient to ``nil`` objects, this default behavior eliminates (or resilient to ``nil`` objects, this default behavior eliminates (or
hides) many such initialization bugs. In Swift, however, the hides) many such initialization bugs. In Swift, however, the
zero-initialized state is less likely to be valid, and the memory zero-initialized state is less likely to be valid, and the memory
safety goals are stronger, so zero-initialization does not suffice. safety goals are stronger, so zero-initialization does not suffice.
When initializing a ``B`` object, the ``NSLog`` statement will print:: When initializing a ``B`` object, the ``NSLog`` statement will print::
@@ -576,10 +576,10 @@ of the current class (not its superclasses!). Additionally, this
initialization directly writes to the storage of the stored initialization directly writes to the storage of the stored
properties, and does not call any setter or ``willSet``/``didSet`` properties, and does not call any setter or ``willSet``/``didSet``
method. In this phase, it is not possible to read any of the stored method. In this phase, it is not possible to read any of the stored
properties. properties.
2. Call to superclass initializer, if any. As with the first step, 2. Call to superclass initializer, if any. As with the first step,
``self`` cannot be accessed at all. ``self`` cannot be accessed at all.
3. Perform any additional initialization tasks, which may call methods 3. Perform any additional initialization tasks, which may call methods
on ``self``, access properties, and so on. on ``self``, access properties, and so on.

View File

@@ -360,21 +360,21 @@ about 10 times.
:: ::
/// --------------- /// ---------------
/// Framework.swift /// Framework.swift
public protocol Pingable { func ping() -> Self } public protocol Pingable { func ping() -> Self }
public protocol Playable { func play() } public protocol Playable { func play() }
extension Int : Pingable { extension Int : Pingable {
public func ping() -> Int { return self + 1 } public func ping() -> Int { return self + 1 }
} }
public class Game<T : Pingable> : Playable { public class Game<T : Pingable> : Playable {
var t : T var t : T
public init (_ v : T) {t = v} public init (_ v : T) {t = v}
@_specialize(Int) @_specialize(Int)
public func play() { public func play() {
for _ in 0...100_000_000 { t = t.ping() } for _ in 0...100_000_000 { t = t.ping() }
@@ -599,7 +599,7 @@ Footnotes
.. [#] i.e. a direct load of a class's field or a direct call to a function. .. [#] i.e. a direct load of a class's field or a direct call to a function.
.. [#] An optimization technique in which a copy will be made if and only if .. [#] An optimization technique in which a copy will be made if and only if
a modification happens to the original copy, otherwise a pointer will be given. a modification happens to the original copy, otherwise a pointer will be given.
.. [#] In certain cases the optimizer is able to via inlining and ARC .. [#] In certain cases the optimizer is able to via inlining and ARC

View File

@@ -21,7 +21,7 @@ When type theorists consider a programming language, we break it down like this:
Swift has a pretty small set of types right now: Swift has a pretty small set of types right now:
* Fundamental types: currently i1, i8, i16, i32, and i64; * Fundamental types: currently i1, i8, i16, i32, and i64;
float and double; eventually maybe others. float and double; eventually maybe others.
* Function types. * Function types.
* Tuples. Heterogeneous fixed-length products. Swift's system * Tuples. Heterogeneous fixed-length products. Swift's system
@@ -297,7 +297,7 @@ braces end up causing a lot of unnecessary vertical whitespace, like so::
case .bar { case .bar {
// … // …
} }
So instead, let's require the switch statement to have braces, and So instead, let's require the switch statement to have braces, and
we'll allow the cases to be written without them:: we'll allow the cases to be written without them::
@@ -441,7 +441,7 @@ I think this should bind looser than any binary operators except assignments;
effectively we should have:: effectively we should have::
expr-binary ::= # most of the current expr grammar expr-binary ::= # most of the current expr grammar
expr ::= expr-binary expr ::= expr-binary
expr ::= expr-binary 'is' expr-primary pattern-guard? expr ::= expr-binary 'is' expr-primary pattern-guard?

View File

@@ -23,7 +23,7 @@ information that only pertains to ObjC interop, are marked **ObjC-only**.
Entry points in this section are intended to be removed or internalized before Entry points in this section are intended to be removed or internalized before
ABI stabilization. ABI stabilization.
### Exported C++ symbols ### Exported C++ symbols
**ABI TODO**: Any exported C++ symbols are implementation details that are not **ABI TODO**: Any exported C++ symbols are implementation details that are not
intended to be part of the stable runtime interface. intended to be part of the stable runtime interface.

View File

@@ -12,13 +12,13 @@ Abstract
SIL is an SSA-form IR with high-level semantic information designed to implement SIL is an SSA-form IR with high-level semantic information designed to implement
the Swift programming language. SIL accommodates the following use cases: the Swift programming language. SIL accommodates the following use cases:
- A set of guaranteed high-level optimizations that provide a predictable - A set of guaranteed high-level optimizations that provide a predictable
baseline for runtime and diagnostic behavior. baseline for runtime and diagnostic behavior.
- Diagnostic dataflow analysis passes that enforce Swift language requirements, - Diagnostic dataflow analysis passes that enforce Swift language requirements,
such as definitive initialization of variables and constructors, code such as definitive initialization of variables and constructors, code
reachability, switch coverage. reachability, switch coverage.
- High-level optimization passes, including retain/release optimization, - High-level optimization passes, including retain/release optimization,
dynamic method devirtualization, closure inlining, memory allocation promotion, dynamic method devirtualization, closure inlining, memory allocation promotion,
and generic function instantiation. and generic function instantiation.
- A stable distribution format that can be used to distribute "fragile" - A stable distribution format that can be used to distribute "fragile"
inlineable or generic code with Swift library modules, to be optimized into inlineable or generic code with Swift library modules, to be optimized into
@@ -80,8 +80,8 @@ predictable.
of which performs capture analysis to promote ``alloc_box`` instructions to of which performs capture analysis to promote ``alloc_box`` instructions to
``alloc_stack``, and the second of which promotes non-address-exposed ``alloc_stack`` ``alloc_stack``, and the second of which promotes non-address-exposed ``alloc_stack``
instructions to SSA registers. instructions to SSA registers.
- **Constant propagation** folds constant expressions and propagates the constant values. - **Constant propagation** folds constant expressions and propagates the constant values.
If an arithmetic overflow occurs during the constant expression computation, a diagnostic If an arithmetic overflow occurs during the constant expression computation, a diagnostic
is issued. is issued.
- **Return analysis** verifies that each function returns a value on every - **Return analysis** verifies that each function returns a value on every
code path and doesn't "fall of the end" of its definition, which is an error. code path and doesn't "fall of the end" of its definition, which is an error.
@@ -375,7 +375,7 @@ Addresses of address-only types (see below) can only be used with
instructions that manipulate their operands indirectly by address, such instructions that manipulate their operands indirectly by address, such
as ``copy_addr`` or ``destroy_addr``, or as arguments to functions. as ``copy_addr`` or ``destroy_addr``, or as arguments to functions.
It is illegal to have a value of type ``$T`` if ``T`` is address-only. It is illegal to have a value of type ``$T`` if ``T`` is address-only.
Addresses are not reference-counted pointers like class values are. They Addresses are not reference-counted pointers like class values are. They
cannot be retained or released. cannot be retained or released.
@@ -492,7 +492,7 @@ number of ways:
instructions. These arguments appear in the order in which they appear instructions. These arguments appear in the order in which they appear
in the result list, always before any parameters. in the result list, always before any parameters.
Direct results correspond to direct return values of type ``T``. A Direct results correspond to direct return values of type ``T``. A
SIL function type has a ``return type`` derived from its direct results SIL function type has a ``return type`` derived from its direct results
in the following way: when there is a single direct result, the return in the following way: when there is a single direct result, the return
type is the type of that result; otherwise, it is the tuple type of the type is the type of that result; otherwise, it is the tuple type of the
@@ -653,7 +653,7 @@ types. Function types are transformed in order to encode additional attributes:
@convention(*convention*) @convention(*convention*)
attribute. This is similar to the language-level ``@convention`` attribute. This is similar to the language-level ``@convention``
attribute, though SIL extends the set of supported conventions with attribute, though SIL extends the set of supported conventions with
additional distinctions not exposed at the language level: additional distinctions not exposed at the language level:
- ``@convention(thin)`` indicates a "thin" function reference, which uses - ``@convention(thin)`` indicates a "thin" function reference, which uses
@@ -872,7 +872,7 @@ Some SIL instructions need to reference Swift declarations directly. These
references are introduced with the ``#`` sigil followed by the fully qualified references are introduced with the ``#`` sigil followed by the fully qualified
name of the Swift declaration. Some Swift declarations are name of the Swift declaration. Some Swift declarations are
decomposed into multiple entities at the SIL level. These are distinguished by decomposed into multiple entities at the SIL level. These are distinguished by
following the qualified name with ``!`` and one or more ``.``-separated component following the qualified name with ``!`` and one or more ``.``-separated component
entity discriminators: entity discriminators:
- ``getter``: the getter function for a ``var`` declaration - ``getter``: the getter function for a ``var`` declaration
@@ -935,7 +935,7 @@ different SIL modules are *linked*, i.e. treated as the same object.
A linkage is *external* if it ends with the suffix ``external``. An A linkage is *external* if it ends with the suffix ``external``. An
object must be a definition if its linkage is not external. object must be a definition if its linkage is not external.
All functions, global variables, and witness tables have linkage. All functions, global variables, and witness tables have linkage.
The default linkage of a definition is ``public``. The default linkage of a The default linkage of a definition is ``public``. The default linkage of a
declaration is ``public_external``. (These may eventually change to ``hidden`` declaration is ``public_external``. (These may eventually change to ``hidden``
and ``hidden_external``, respectively.) and ``hidden_external``, respectively.)
@@ -1292,7 +1292,7 @@ separate arguments, both in the entry point basic block of the callee, and
in the ``apply`` instructions used by callers:: in the ``apply`` instructions used by callers::
func foo(_ x:Int, y:Int) func foo(_ x:Int, y:Int)
sil @foo : $(x:Int, y:Int) -> () { sil @foo : $(x:Int, y:Int) -> () {
entry(%x : $Int, %y : $Int): entry(%x : $Int, %y : $Int):
... ...
@@ -1619,10 +1619,10 @@ Consider the following SIL::
} }
struct S1 { struct S1 {
var elt: Element var elt: Element
} }
struct S2 { struct S2 {
var elt: Element var elt: Element
} }
%adr1 = struct_element_addr %ptr1 : $*S1, #S.elt %adr1 = struct_element_addr %ptr1 : $*S1, #S.elt
%adr2 = struct_element_addr %ptr2 : $*S2, #S.elt %adr2 = struct_element_addr %ptr2 : $*S2, #S.elt
@@ -1811,7 +1811,7 @@ of the allocated memory.
If a type is runtime-sized, the compiler must emit code to potentially If a type is runtime-sized, the compiler must emit code to potentially
dynamically allocate memory. So there is no guarantee that the allocated dynamically allocate memory. So there is no guarantee that the allocated
memory is really located on the stack. memory is really located on the stack.
``alloc_stack`` marks the start of the lifetime of the value; the ``alloc_stack`` marks the start of the lifetime of the value; the
allocation must be balanced with a ``dealloc_stack`` instruction to allocation must be balanced with a ``dealloc_stack`` instruction to
@@ -1892,7 +1892,7 @@ for ``alloc_ref``. See ``alloc_ref`` for details.
alloc_box alloc_box
````````` `````````
:: ::
sil-instruction ::= 'alloc_box' sil-type (',' debug-var-attr)* sil-instruction ::= 'alloc_box' sil-type (',' debug-var-attr)*
%1 = alloc_box $T %1 = alloc_box $T
@@ -2095,9 +2095,9 @@ debug_value
:: ::
sil-instruction ::= debug_value sil-operand (',' debug-var-attr)* sil-instruction ::= debug_value sil-operand (',' debug-var-attr)*
debug_value %1 : $Int debug_value %1 : $Int
This indicates that the value of a declaration with loadable type has changed This indicates that the value of a declaration with loadable type has changed
value to the specified operand. The declaration in question is identified by value to the specified operand. The declaration in question is identified by
the SILLocation attached to the debug_value instruction. the SILLocation attached to the debug_value instruction.
@@ -2122,9 +2122,9 @@ debug_value_addr
:: ::
sil-instruction ::= debug_value_addr sil-operand (',' debug-var-attr)* sil-instruction ::= debug_value_addr sil-operand (',' debug-var-attr)*
debug_value_addr %7 : $*SomeProtocol debug_value_addr %7 : $*SomeProtocol
This indicates that the value of a declaration with address-only type This indicates that the value of a declaration with address-only type
has changed value to the specified operand. The declaration in has changed value to the specified operand. The declaration in
question is identified by the SILLocation attached to the question is identified by the SILLocation attached to the
@@ -2468,7 +2468,7 @@ bind_memory
Binds memory at ``Builtin.RawPointer`` value ``%0`` to type ``$T`` with enough Binds memory at ``Builtin.RawPointer`` value ``%0`` to type ``$T`` with enough
capacity to hold ``%1`` values. See SE-0107: UnsafeRawPointer. capacity to hold ``%1`` values. See SE-0107: UnsafeRawPointer.
Reference Counting Reference Counting
~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~
@@ -2508,7 +2508,7 @@ for several reasons:
strong_retain strong_retain
````````````` `````````````
:: ::
sil-instruction ::= 'strong_retain' sil-operand sil-instruction ::= 'strong_retain' sil-operand
strong_retain %0 : $T strong_retain %0 : $T
@@ -2547,7 +2547,7 @@ execution of this instruction.
strong_retain_unowned strong_retain_unowned
````````````````````` `````````````````````
:: ::
sil-instruction ::= 'strong_retain_unowned' sil-operand sil-instruction ::= 'strong_retain_unowned' sil-operand
strong_retain_unowned %0 : $@unowned T strong_retain_unowned %0 : $@unowned T
@@ -2559,7 +2559,7 @@ is still positive, then increases it by one.
unowned_retain unowned_retain
`````````````` ``````````````
:: ::
sil-instruction ::= 'unowned_retain' sil-operand sil-instruction ::= 'unowned_retain' sil-operand
unowned_retain %0 : $@unowned T unowned_retain %0 : $@unowned T
@@ -2570,7 +2570,7 @@ Increments the unowned reference count of the heap object underlying ``%0``.
unowned_release unowned_release
``````````````` ```````````````
:: ::
sil-instruction ::= 'unowned_release' sil-operand sil-instruction ::= 'unowned_release' sil-operand
unowned_release %0 : $@unowned T unowned_release %0 : $@unowned T
@@ -2881,7 +2881,7 @@ If:
- the referenced method is not a ``foreign`` method, - the referenced method is not a ``foreign`` method,
- and the static type of the class instance is known, or the method is known - and the static type of the class instance is known, or the method is known
to be final, to be final,
then the instruction is a candidate for devirtualization optimization. A then the instruction is a candidate for devirtualization optimization. A
devirtualization pass can consult the module's `VTables`_ to find the devirtualization pass can consult the module's `VTables`_ to find the
SIL function that implements the method and promote the instruction to a SIL function that implements the method and promote the instruction to a
@@ -2893,7 +2893,7 @@ super_method
sil-instruction ::= 'super_method' sil-method-attributes? sil-instruction ::= 'super_method' sil-method-attributes?
sil-operand ',' sil-decl-ref ':' sil-type sil-operand ',' sil-decl-ref ':' sil-type
%1 = super_method %0 : $T, #Super.method!1.foreign : $@convention(thin) U -> V %1 = super_method %0 : $T, #Super.method!1.foreign : $@convention(thin) U -> V
// %0 must be of a non-root class type or class metatype $T // %0 must be of a non-root class type or class metatype $T
// #Super.method!1.foreign must be a reference to an ObjC method of T's // #Super.method!1.foreign must be a reference to an ObjC method of T's
@@ -2941,7 +2941,7 @@ dynamic_method
// #X.method!1 must be a reference to an @objc method of any class // #X.method!1 must be a reference to an @objc method of any class
// or protocol type // or protocol type
// //
// The "self" argument of the method type $@convention(thin) U -> V must be // The "self" argument of the method type $@convention(thin) U -> V must be
// Builtin.UnknownObject // Builtin.UnknownObject
Looks up the implementation of an Objective-C method with the same Looks up the implementation of an Objective-C method with the same
@@ -2954,13 +2954,13 @@ It is undefined behavior if the dynamic type of the operand does not
have an implementation for the Objective-C method with the selector to have an implementation for the Objective-C method with the selector to
which the ``dynamic_method`` instruction refers, or if that which the ``dynamic_method`` instruction refers, or if that
implementation has parameter or result types that are incompatible implementation has parameter or result types that are incompatible
with the method referenced by ``dynamic_method``. with the method referenced by ``dynamic_method``.
This instruction should only be used in cases where its result will be This instruction should only be used in cases where its result will be
immediately consumed by an operation that performs the selector check immediately consumed by an operation that performs the selector check
itself (e.g., an ``apply`` that lowers to ``objc_msgSend``). itself (e.g., an ``apply`` that lowers to ``objc_msgSend``).
To query whether the operand has an implementation for the given To query whether the operand has an implementation for the given
method and safely handle the case where it does not, use method and safely handle the case where it does not, use
`dynamic_method_br`_. `dynamic_method_br`_.
Function Application Function Application
~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
@@ -3112,7 +3112,7 @@ following example::
} }
lowers to an uncurried entry point and is curried in the enclosing function:: lowers to an uncurried entry point and is curried in the enclosing function::
func @bar : $@convention(thin) (Int, @box Int, *Int) -> Int { func @bar : $@convention(thin) (Int, @box Int, *Int) -> Int {
entry(%y : $Int, %x_box : $@box Int, %x_address : $*Int): entry(%y : $Int, %x_box : $@box Int, %x_address : $*Int):
// ... body of bar ... // ... body of bar ...
@@ -3319,7 +3319,7 @@ autorelease_value
tuple tuple
````` `````
:: ::
sil-instruction ::= 'tuple' sil-tuple-elements sil-instruction ::= 'tuple' sil-tuple-elements
sil-tuple-elements ::= '(' (sil-operand (',' sil-operand)*)? ')' sil-tuple-elements ::= '(' (sil-operand (',' sil-operand)*)? ')'
sil-tuple-elements ::= sil-type '(' (sil-value (',' sil-value)*)? ')' sil-tuple-elements ::= sil-type '(' (sil-value (',' sil-value)*)? ')'
@@ -3479,10 +3479,10 @@ discriminator and is done with the `switch_enum`_ terminator::
sil @switch_foo : $(Foo) -> () { sil @switch_foo : $(Foo) -> () {
entry(%foo : $Foo): entry(%foo : $Foo):
switch_enum %foo : $Foo, case #Foo.A!enumelt.1: a_dest, case #Foo.B!enumelt.1: b_dest switch_enum %foo : $Foo, case #Foo.A!enumelt.1: a_dest, case #Foo.B!enumelt.1: b_dest
a_dest(%a : $Int): a_dest(%a : $Int):
/* use %a */ /* use %a */
b_dest(%b : $String): b_dest(%b : $String):
/* use %b */ /* use %b */
} }
@@ -3497,11 +3497,11 @@ projecting the enum value with `unchecked_take_enum_data_addr`_::
entry(%foo : $*Foo<T>): entry(%foo : $*Foo<T>):
switch_enum_addr %foo : $*Foo<T>, case #Foo.A!enumelt.1: a_dest, \ switch_enum_addr %foo : $*Foo<T>, case #Foo.A!enumelt.1: a_dest, \
case #Foo.B!enumelt.1: b_dest case #Foo.B!enumelt.1: b_dest
a_dest: a_dest:
%a = unchecked_take_enum_data_addr %foo : $*Foo<T>, #Foo.A!enumelt.1 %a = unchecked_take_enum_data_addr %foo : $*Foo<T>, #Foo.A!enumelt.1
/* use %a */ /* use %a */
b_dest: b_dest:
%b = unchecked_take_enum_data_addr %foo : $*Foo<T>, #Foo.B!enumelt.1 %b = unchecked_take_enum_data_addr %foo : $*Foo<T>, #Foo.B!enumelt.1
/* use %b */ /* use %b */
@@ -3749,7 +3749,7 @@ more expensive ``alloc_existential_box``::
init_existential_addr init_existential_addr
````````````````````` `````````````````````
:: ::
sil-instruction ::= 'init_existential_addr' sil-operand ',' sil-type sil-instruction ::= 'init_existential_addr' sil-operand ',' sil-type
%1 = init_existential_addr %0 : $*P, $T %1 = init_existential_addr %0 : $*P, $T
@@ -3795,8 +3795,8 @@ open_existential_addr
%1 = open_existential_addr %0 : $*P to $*@opened P %1 = open_existential_addr %0 : $*P to $*@opened P
// %0 must be of a $*P type for non-class protocol or protocol composition // %0 must be of a $*P type for non-class protocol or protocol composition
// type P // type P
// $*@opened P must be a unique archetype that refers to an opened // $*@opened P must be a unique archetype that refers to an opened
// existential type P. // existential type P.
// %1 will be of type $*P // %1 will be of type $*P
Obtains the address of the concrete value inside the existential Obtains the address of the concrete value inside the existential
@@ -3829,14 +3829,14 @@ open_existential_ref
%1 = open_existential_ref %0 : $P to $@opened P %1 = open_existential_ref %0 : $P to $@opened P
// %0 must be of a $P type for a class protocol or protocol composition // %0 must be of a $P type for a class protocol or protocol composition
// $@opened P must be a unique archetype that refers to an opened // $@opened P must be a unique archetype that refers to an opened
// existential type P // existential type P
// %1 will be of type $@opened P // %1 will be of type $@opened P
Extracts the class instance reference from a class existential Extracts the class instance reference from a class existential
container. The protocol conformances associated with this existential container. The protocol conformances associated with this existential
container are associated directly with the archetype ``@opened P``. This container are associated directly with the archetype ``@opened P``. This
pointer can be used with any operation on archetypes, such as pointer can be used with any operation on archetypes, such as
``witness_method``. When the operand is of metatype type, the result ``witness_method``. When the operand is of metatype type, the result
will be the metatype of the opened archetype. will be the metatype of the opened archetype.
@@ -3926,7 +3926,7 @@ Projects the address of the value inside a boxed existential container, and
uses the enclosed type and protocol conformance metadata to bind the uses the enclosed type and protocol conformance metadata to bind the
opened archetype ``$@opened P``. The result address is dependent on both opened archetype ``$@opened P``. The result address is dependent on both
the owning box and the enclosing function; in order to "open" a boxed the owning box and the enclosing function; in order to "open" a boxed
existential that has directly adopted a class reference, temporary scratch existential that has directly adopted a class reference, temporary scratch
space may need to have been allocated. space may need to have been allocated.
dealloc_existential_box dealloc_existential_box
@@ -4122,7 +4122,7 @@ heap object reference to an address using ``pointer_to_address``.
raw_pointer_to_ref raw_pointer_to_ref
`````````````````` ``````````````````
:: ::
sil-instruction ::= 'raw_pointer_to_ref' sil-operand 'to' sil-type sil-instruction ::= 'raw_pointer_to_ref' sil-operand 'to' sil-type
%1 = raw_pointer_to_ref %0 : $Builtin.RawPointer to $C %1 = raw_pointer_to_ref %0 : $Builtin.RawPointer to $C
@@ -4408,7 +4408,7 @@ a basic block.
unreachable unreachable
``````````` ```````````
:: ::
sil-terminator ::= 'unreachable' sil-terminator ::= 'unreachable'
unreachable unreachable
@@ -4421,7 +4421,7 @@ no-return function.
return return
`````` ``````
:: ::
sil-terminator ::= 'return' sil-operand sil-terminator ::= 'return' sil-operand
return %0 : $T return %0 : $T
@@ -4441,7 +4441,7 @@ A function must not contain more than one ``return`` instruction.
throw throw
````` `````
:: ::
sil-terminator ::= 'throw' sil-operand sil-terminator ::= 'throw' sil-operand
throw %0 : $T throw %0 : $T
@@ -4668,7 +4668,7 @@ dynamic_method_br
````````````````` `````````````````
:: ::
sil-terminator ::= 'dynamic_method_br' sil-operand ',' sil-decl-ref sil-terminator ::= 'dynamic_method_br' sil-operand ',' sil-decl-ref
',' sil-identifier ',' sil-identifier ',' sil-identifier ',' sil-identifier
dynamic_method_br %0 : $P, #X.method!1, bb1, bb2 dynamic_method_br %0 : $P, #X.method!1, bb1, bb2
@@ -4738,7 +4738,7 @@ transferred to ``bb2``.
try_apply try_apply
````````` `````````
:: ::
sil-terminator ::= 'try_apply' sil-value sil-terminator ::= 'try_apply' sil-value
sil-apply-substitution-list? sil-apply-substitution-list?
'(' (sil-value (',' sil-value)*)? ')' '(' (sil-value (',' sil-value)*)? ')'
@@ -4749,7 +4749,7 @@ try_apply
normal bb1, error bb2 normal bb1, error bb2
bb1(%3 : R): bb1(%3 : R):
bb2(%4 : E): bb2(%4 : E):
// Note that the type of the callee '%0' is specified *after* the arguments // Note that the type of the callee '%0' is specified *after* the arguments
// %0 must be of a concrete function type $(A, B, ...) -> (R, @error E) // %0 must be of a concrete function type $(A, B, ...) -> (R, @error E)
// %1, %2, etc. must be of the argument types $A, $B, etc. // %1, %2, etc. must be of the argument types $A, $B, etc.

View File

@@ -86,7 +86,7 @@ something like this::
protocol NaiveIteratorProtocol { protocol NaiveIteratorProtocol {
typealias Element typealias Element
var current() -> Element // get the current element var current() -> Element // get the current element
mutating func advance() // advance to the next element mutating func advance() // advance to the next element
var isExhausted: Bool // detect whether there are more elements var isExhausted: Bool // detect whether there are more elements
} }
@@ -123,7 +123,7 @@ implement a generic `for`\ …\ `in` loop.
support for buffering would fit nicely into the scheme, should it support for buffering would fit nicely into the scheme, should it
prove important:: prove important::
public protocol BufferedIteratorProtocol public protocol BufferedIteratorProtocol
: IteratorProtocol { : IteratorProtocol {
var latest: Element? {get} var latest: Element? {get}
} }
@@ -140,7 +140,7 @@ implement a generic `for`\ …\ `in` loop.
} }
public func next() -> Element? { public func next() -> Element? {
latest = _baseIterator.next() ?? latest latest = _baseIterator.next() ?? latest
return latest return latest
} }
public private(set) var latest: I.Element? public private(set) var latest: I.Element?
private var _baseIterator: I private var _baseIterator: I
@@ -156,7 +156,7 @@ end. For example::
// Return an array containing the elements of `source`, with // Return an array containing the elements of `source`, with
// `separator` interposed between each consecutive pair. // `separator` interposed between each consecutive pair.
func array<S: SequenceType>( func array<S: SequenceType>(
_ source: S, _ source: S,
withSeparator separator: S.Iterator.Element withSeparator separator: S.Iterator.Element
) -> [S.Iterator.Element] { ) -> [S.Iterator.Element] {
var result: [S.Iterator.Element] = [] var result: [S.Iterator.Element] = []
@@ -215,7 +215,7 @@ Collections
A **collection** is a stable sequence with addressable "positions," A **collection** is a stable sequence with addressable "positions,"
represented by an associated `Index` type:: represented by an associated `Index` type::
protocol CollectionType : SequenceType { protocol CollectionType : SequenceType {
typealias Index : ForwardIndexType // a position typealias Index : ForwardIndexType // a position
subscript(i: Index) -> Iterator.Element {get} subscript(i: Index) -> Iterator.Element {get}

View File

@@ -31,7 +31,7 @@ The First Parameter
* The first parameter to a function, method, or initializer typically * The first parameter to a function, method, or initializer typically
does not have an argument label: does not have an argument label:
.. parsed-literal:: .. parsed-literal::
alligators.insert(fred) // yes alligators.insert(fred) // yes
@@ -64,21 +64,21 @@ The First Parameter
aPosition.distance\ **To**\ (otherPosition) aPosition.distance\ **To**\ (otherPosition)
// we're not "indexing x" // we're not "indexing x"
if let position = aSet.index\ **Of**\ (x) { ... } if let position = aSet.index\ **Of**\ (x) { ... }
* Argument labels are used on first parameters to denote special * Argument labels are used on first parameters to denote special
cases: cases:
.. parsed-literal:: .. parsed-literal::
// Normal case: result has same value as argument (traps on overflow) // Normal case: result has same value as argument (traps on overflow)
Int(aUInt) Int(aUInt)
// Special: interprets the sign bit as a high bit, changes value // Special: interprets the sign bit as a high bit, changes value
Int(**bitPattern**: aUInt) Int(**bitPattern**: aUInt)
// Special: keeps only the bits that fit, losing information // Special: keeps only the bits that fit, losing information
Int32(**truncatingBitPattern**: anInt64) Int32(**truncatingBitPattern**: anInt64)
Subsequent Parameters Subsequent Parameters
--------------------- ---------------------
@@ -91,7 +91,7 @@ Subsequent Parameters
x.replaceSubrange(r, **with:** someElements) x.replaceSubrange(r, **with:** someElements)
p.initializeFrom(q, **count:** n) p.initializeFrom(q, **count:** n)
* Second and later parameters are always labeled except in cases where * Second and later parameters are always labeled except in cases where
there's no useful distinction of roles:: there's no useful distinction of roles::
@@ -101,7 +101,7 @@ Subsequent Parameters
Other Differences Other Differences
----------------- -----------------
* We don't use namespace prefixes such as "`NS`", relying instead on * We don't use namespace prefixes such as "`NS`", relying instead on
the language's own facilities. the language's own facilities.
@@ -168,10 +168,10 @@ library, but are compatible with the Cocoa guidelines.
/// ///
/// Complexity: O(\`count\`) /// Complexity: O(\`count\`)
mutating func reserveCapacity(_ **minimumCapacity**: Int) mutating func reserveCapacity(_ **minimumCapacity**: Int)
* Type parameter names of generic types describe the role of the * Type parameter names of generic types describe the role of the
parameter, e.g. parameter, e.g.
.. parsed-literal:: .. parsed-literal::
struct Dictionary<**Key**, **Value**> { // *not* Dictionary<**K**, **V**> struct Dictionary<**Key**, **Value**> { // *not* Dictionary<**K**, **V**>
@@ -208,7 +208,7 @@ Prefixes and Suffixes
* `Any` is used as a prefix to denote "type erasure," * `Any` is used as a prefix to denote "type erasure,"
e.g. `AnySequence<T>` wraps any sequence with element type `T`, e.g. `AnySequence<T>` wraps any sequence with element type `T`,
conforms to `SequenceType` itself, and forwards all operations to the conforms to `SequenceType` itself, and forwards all operations to the
wrapped sequence. When handling the wrapper, the specific type of wrapped sequence. When handling the wrapper, the specific type of
the wrapped sequence is fully hidden. the wrapped sequence is fully hidden.
* `Custom` is used as a prefix for special protocols that will always * `Custom` is used as a prefix for special protocols that will always

View File

@@ -11,7 +11,7 @@ Stored and Computed Variables
Variables are declared using the ``var`` keyword. These declarations are valid Variables are declared using the ``var`` keyword. These declarations are valid
at the top level, within types, and within code bodies, and are respectively at the top level, within types, and within code bodies, and are respectively
known as *global variables,* *member variables,* and *local variables.* known as *global variables,* *member variables,* and *local variables.*
Member variables are commonly referred to as *properties.* Member variables are commonly referred to as *properties.*
Every variable declaration can be classified as either *stored* or *computed.* Every variable declaration can be classified as either *stored* or *computed.*
Member variables inherited from a superclass obey slightly different rules. Member variables inherited from a superclass obey slightly different rules.
@@ -187,7 +187,7 @@ in the usual way::
return .Black return .Black
} }
} }
class Colorful : Base { class Colorful : Base {
var color : Color var color : Color
} }
@@ -199,7 +199,7 @@ The new stored variable may have observing accessors::
class MemoryColorful : Base { class MemoryColorful : Base {
var oldColors : Array<Color> = [] var oldColors : Array<Color> = []
var color : Color { var color : Color {
willSet { willSet {
oldColors.append(color) oldColors.append(color)
@@ -239,7 +239,7 @@ A subclass may override the superclass's variable with a new computed variable::
} }
} }
} }
class BrightlyColored : ColorBase { class BrightlyColored : ColorBase {
var color : Color { var color : Color {
get { get {
@@ -265,7 +265,7 @@ member variable::
class TrackingColored : ColorBase { class TrackingColored : ColorBase {
var prevColor : Color? var prevColor : Color?
var color : Color { var color : Color {
willSet { willSet {
prevColor = color prevColor = color

View File

@@ -4,8 +4,8 @@
.. raw:: html .. raw:: html
<style> <style>
.repl, .repl,
.emph, .emph,
.look { .look {
@@ -64,7 +64,7 @@
background: gray; background: gray;
-moz-border-radius:10px; -moz-border-radius:10px;
-webkit-border-radius:10px; -webkit-border-radius:10px;
border-radius:10px; border-radius:10px;
color: #fff; color: #fff;
z-index: 1; z-index: 1;
} }
@@ -103,7 +103,7 @@ Swift String Design
.. Admonition:: This Document .. Admonition:: This Document
:class: note :class: note
* contains interactive HTML commentary that does not * contains interactive HTML commentary that does not
currently appear in printed output. Hover your mouse over currently appear in printed output. Hover your mouse over
elements with a dotted pink underline to view the hidden elements with a dotted pink underline to view the hidden
@@ -118,9 +118,9 @@ Swift String Design
.. warning:: This document was used in planning Swift 1.0; it has not been kept .. warning:: This document was used in planning Swift 1.0; it has not been kept
up to date and does not describe the current or planned behavior of Swift. up to date and does not describe the current or planned behavior of Swift.
.. contents:: .. contents::
:depth: 3 :depth: 3
Introduction Introduction
============ ============
@@ -196,10 +196,10 @@ Strings are **Mutable**
except that *some languages make all strings immutable*, as a way except that *some languages make all strings immutable*, as a way
of working around problems that Swift has defined away—by making of working around problems that Swift has defined away—by making
strings pure values (see below). strings pure values (see below).
.. parsed-literal:: .. parsed-literal::
|swift| extension String { |swift| extension String {
func addEcho() { func addEcho() {
self += self self += self
} }
} }
@@ -298,7 +298,7 @@ Strings neither carry their own locale information, nor provide
behaviors that depend on a global locale setting. Thus, for any pair behaviors that depend on a global locale setting. Thus, for any pair
of strings ``s1`` and ``s2``, "``s1 == s2``" yields the same result of strings ``s1`` and ``s2``, "``s1 == s2``" yields the same result
regardless of system state. Strings *do* provide a suitable regardless of system state. Strings *do* provide a suitable
foundation on which to build locale-aware interfaces.\ [#locales]_ foundation on which to build locale-aware interfaces.\ [#locales]_
Strings are **Containers** Strings are **Containers**
-------------------------- --------------------------
@@ -375,13 +375,13 @@ end, strings support properties for more-specific segmentations:
`Extended Grapheme Cluster: f` `Extended Grapheme Cluster: f`
`Extended Grapheme Cluster: o` `Extended Grapheme Cluster: o`
`Extended Grapheme Cluster: o` `Extended Grapheme Cluster: o`
|swift| for c in s.collationCharacters { |swift| for c in s.collationCharacters {
print("Collation Grapheme Cluster: \(c)") print("Collation Grapheme Cluster: \(c)")
} }
`Collation Grapheme Cluster: f` `Collation Grapheme Cluster: f`
`Collation Grapheme Cluster: o` `Collation Grapheme Cluster: o`
`Collation Grapheme Cluster: o` `Collation Grapheme Cluster: o`
|swift| for c in s.searchCharacters { |swift| for c in s.searchCharacters {
print("Search Grapheme Cluster: \(c)") print("Search Grapheme Cluster: \(c)")
} }
`Search Grapheme Cluster: f` `Search Grapheme Cluster: f`
@@ -414,7 +414,7 @@ Strings are **Sliceable**
`// r5 : String = "awe"` `// r5 : String = "awe"`
|swift| s[r] = "hand" |swift| s[r] = "hand"
|swift| s |swift| s
`// s : String = "Strings are` :look:`handsome`\ :aside:`slice replacement can resize the string`\ `"` `// s : String = "Strings are` :look:`handsome`\ :aside:`slice replacement can resize the string`\ `"`
.. _extending: .. _extending:
@@ -495,7 +495,7 @@ Reference Manual
Cocoa Bridging Strategy Cocoa Bridging Strategy
======================= =======================
.. ..
Rationales Rationales
@@ -526,7 +526,7 @@ programmers well; so, why does Swift have its own string type?
* Error Prone Mutability * Error Prone Mutability
Reference semantics don't line up with how people think about strings Reference semantics don't line up with how people think about strings
* 2 is too many string types. * 2 is too many string types.
two APIs two APIs
duplication of effort duplication of effort
documentation documentation
@@ -634,7 +634,7 @@ API Breadth
The ``NSString`` interface clearly shows the effects of 20 years of The ``NSString`` interface clearly shows the effects of 20 years of
evolution through accretion. It is broad, with functionality evolution through accretion. It is broad, with functionality
addressing encodings, paths, URLs, localization, and more. By addressing encodings, paths, URLs, localization, and more. By
contrast, the interface to Swift's ``String`` is much narrower. contrast, the interface to Swift's ``String`` is much narrower.
.. _TBD: .. _TBD:
@@ -717,7 +717,7 @@ Indexing
In Swift, by convention, ``x.length`` is used to represent In Swift, by convention, ``x.length`` is used to represent
the number of elements in a container, and since ``String`` is a the number of elements in a container, and since ``String`` is a
container of abstract |Character|_\ s, ``length`` would have to container of abstract |Character|_\ s, ``length`` would have to
count those. count those.
This meaning of ``length`` is unimplementable in O(1). It can be This meaning of ``length`` is unimplementable in O(1). It can be
cached, although not in the memory block where the characters are cached, although not in the memory block where the characters are
@@ -728,7 +728,7 @@ Indexing
even if ``length`` were provided, doing things with ``String`` even if ``length`` were provided, doing things with ``String``
that depend on a specific numeric ``length`` is error-prone. that depend on a specific numeric ``length`` is error-prone.
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSUInteger)\ **length** \- (NSUInteger)\ **length**
@@ -745,12 +745,12 @@ Indexing
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSRange)\ **rangeOfComposedCharacterSequenceAtIndex:**\ (NSUInteger)index; \- (NSRange)\ **rangeOfComposedCharacterSequenceAtIndex:**\ (NSUInteger)index;
\- (NSRange)\ **rangeOfComposedCharacterSequencesForRange:**\ (NSRange)range; \- (NSRange)\ **rangeOfComposedCharacterSequencesForRange:**\ (NSRange)range;
:Swift: :Swift:
.. parsed-literal:: .. parsed-literal::
typealias IndexType = ... typealias IndexType = ...
func **indices**\ () -> Range<IndexType> func **indices**\ () -> Range<IndexType>
@@ -774,7 +774,7 @@ Indexing
Slicing Slicing
~~~~~~~ ~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (void)\ **getCharacters:**\ (unichar \*)\ **buffer range:**\ (NSRange)aRange; \- (void)\ **getCharacters:**\ (unichar \*)\ **buffer range:**\ (NSRange)aRange;
@@ -786,7 +786,7 @@ Slicing
Indexing Indexing
~~~~~~~~ ~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **substringToIndex:**\ (NSUInteger)to; \- (NSString \*)\ **substringToIndex:**\ (NSUInteger)to;
\- (NSString \*)\ **substringFromIndex:**\ (NSUInteger)from; \- (NSString \*)\ **substringFromIndex:**\ (NSUInteger)from;
@@ -812,7 +812,7 @@ Indexing
Comparison Comparison
~~~~~~~~~~~~ ~~~~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (BOOL)\ **isEqualToString:**\ (NSString \*)aString; \- (BOOL)\ **isEqualToString:**\ (NSString \*)aString;
\- (NSComparisonResult)\ **compare:**\ (NSString \*)string; \- (NSComparisonResult)\ **compare:**\ (NSString \*)string;
@@ -842,7 +842,7 @@ all contexts.
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSComparisonResult)\ **compare:**\ (NSString \*)string \ **options:**\ (NSStringCompareOptions)mask; \- (NSComparisonResult)\ **compare:**\ (NSString \*)string \ **options:**\ (NSStringCompareOptions)mask;
\- (NSComparisonResult)\ **compare:**\ (NSString \*)string \ **options:**\ (NSStringCompareOptions)mask \ **range:**\ (NSRange)compareRange; \- (NSComparisonResult)\ **compare:**\ (NSString \*)string \ **options:**\ (NSStringCompareOptions)mask \ **range:**\ (NSRange)compareRange;
@@ -853,7 +853,7 @@ all contexts.
* As noted above__, instead of passing sub-range arguments, we expect * As noted above__, instead of passing sub-range arguments, we expect
Swift users to compose slicing_ with whole-string operations. Swift users to compose slicing_ with whole-string operations.
__ range_ __ range_
* Other details of these interfaces are distinguished by an * Other details of these interfaces are distinguished by an
``NSStringCompareOptions`` mask, of which ``NSStringCompareOptions`` mask, of which
@@ -902,7 +902,7 @@ all contexts.
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSComparisonResult)\ **localizedCompare:**\ (NSString \*)string; \- (NSComparisonResult)\ **localizedCompare:**\ (NSString \*)string;
\- (NSComparisonResult)\ **localizedCaseInsensitiveCompare:**\ (NSString \*)string; \- (NSComparisonResult)\ **localizedCaseInsensitiveCompare:**\ (NSString \*)string;
@@ -920,19 +920,19 @@ Searching
variants of ``startsWith``/\ ``endsWith``. There's no reason Swift variants of ``startsWith``/\ ``endsWith``. There's no reason Swift
should deviate from de-facto industry standards here. should deviate from de-facto industry standards here.
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (BOOL)\ **hasPrefix:**\ (NSString \*)aString; \- (BOOL)\ **hasPrefix:**\ (NSString \*)aString;
\- (BOOL)\ **hasSuffix:**\ (NSString \*)aString; \- (BOOL)\ **hasSuffix:**\ (NSString \*)aString;
:Swift: :Swift:
.. parsed-literal:: .. parsed-literal::
func **startsWith**\ (_ prefix: String) func **startsWith**\ (_ prefix: String)
func **endsWith**\ (_ suffix: String) func **endsWith**\ (_ suffix: String)
---- ----
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSRange)\ **rangeOfString:**\ (NSString \*)aString; \- (NSRange)\ **rangeOfString:**\ (NSString \*)aString;
@@ -948,7 +948,7 @@ Searching
---- ----
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSRange)\ **rangeOfCharacterFromSet:**\ (NSCharacterSet \*)aSet; \- (NSRange)\ **rangeOfCharacterFromSet:**\ (NSCharacterSet \*)aSet;
@@ -972,7 +972,7 @@ Searching
----- -----
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSRange)\ **rangeOfString:**\ (NSString \*)aString \ **options:**\ (NSStringCompareOptions)mask; \- (NSRange)\ **rangeOfString:**\ (NSString \*)aString \ **options:**\ (NSStringCompareOptions)mask;
\- (NSRange)\ **rangeOfString:**\ (NSString \*)aString \ **options:**\ (NSStringCompareOptions)mask \ **range:**\ (NSRange)searchRange; \- (NSRange)\ **rangeOfString:**\ (NSString \*)aString \ **options:**\ (NSStringCompareOptions)mask \ **range:**\ (NSRange)searchRange;
@@ -988,7 +988,7 @@ Searching
Building Building
~~~~~~~~ ~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **stringByAppendingString:**\ (NSString \*)aString; \- (NSString \*)\ **stringByAppendingString:**\ (NSString \*)aString;
@@ -1008,7 +1008,7 @@ Building
Dynamic Formatting Dynamic Formatting
~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **stringByAppendingFormat:**\ (NSString \*)format, ... NS_FORMAT_FUNCTION(1,2); \- (NSString \*)\ **stringByAppendingFormat:**\ (NSString \*)format, ... NS_FORMAT_FUNCTION(1,2);
@@ -1017,7 +1017,7 @@ Dynamic Formatting
Extracting Numeric Values Extracting Numeric Values
~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (double)doubleValue; \- (double)doubleValue;
\- (float)floatValue; \- (float)floatValue;
@@ -1034,7 +1034,7 @@ Extracting Numeric Values
Splitting Splitting
~~~~~~~~~ ~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSArray \*)\ **componentsSeparatedByString:**\ (NSString \*)separator; \- (NSArray \*)\ **componentsSeparatedByString:**\ (NSString \*)separator;
\- (NSArray \*)\ **componentsSeparatedByCharactersInSet:**\ (NSCharacterSet \*)separator; \- (NSArray \*)\ **componentsSeparatedByCharactersInSet:**\ (NSCharacterSet \*)separator;
@@ -1055,7 +1055,7 @@ Splitting
.. parsed-literal:: .. parsed-literal::
func **split**\ <Seq: Sliceable, IsSeparator: Predicate func **split**\ <Seq: Sliceable, IsSeparator: Predicate
where IsSeparator.Arguments == Seq.Element where IsSeparator.Arguments == Seq.Element
>(_ seq: Seq, isSeparator: IsSeparator, maxSplit: Int = Int.max(), >(_ seq: Seq, isSeparator: IsSeparator, maxSplit: Int = Int.max(),
allowEmptySlices: Bool = false) -> [Seq] allowEmptySlices: Bool = false) -> [Seq]
@@ -1063,7 +1063,7 @@ Splitting
Splitting Splitting
~~~~~~~~~ ~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **commonPrefixWithString:**\ (NSString \*)aString \ **options:**\ (NSStringCompareOptions)mask; \- (NSString \*)\ **commonPrefixWithString:**\ (NSString \*)aString \ **options:**\ (NSStringCompareOptions)mask;
@@ -1074,7 +1074,7 @@ Splitting
Upper/Lowercase Upper/Lowercase
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **uppercaseString**; \- (NSString \*)\ **uppercaseString**;
\- (NSString \*)\ **uppercaseStringWithLocale:**\ (NSLocale \*)locale; \- (NSString \*)\ **uppercaseStringWithLocale:**\ (NSLocale \*)locale;
@@ -1090,11 +1090,11 @@ Upper/Lowercase
.. parsed-literal:: .. parsed-literal::
func **toUpper**\ () -> String func **toUpper**\ () -> String
func **toLower**\ () -> String func **toLower**\ () -> String
Capitalization Capitalization
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **capitalizedString**; \- (NSString \*)\ **capitalizedString**;
\- (NSString \*)\ **capitalizedStringWithLocale:**\ (NSLocale \*)locale; \- (NSString \*)\ **capitalizedStringWithLocale:**\ (NSLocale \*)locale;
@@ -1114,7 +1114,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **stringByTrimmingCharactersInSet:**\ (NSCharacterSet \*)set; \- (NSString \*)\ **stringByTrimmingCharactersInSet:**\ (NSCharacterSet \*)set;
@@ -1132,17 +1132,17 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **stringByPaddingToLength:**\ (NSUInteger)newLength \ **withString:**\ (NSString \*)padString \ **startingAtIndex:**\ (NSUInteger)padIndex; \- (NSString \*)\ **stringByPaddingToLength:**\ (NSUInteger)newLength \ **withString:**\ (NSString \*)padString \ **startingAtIndex:**\ (NSUInteger)padIndex;
:Swift: :Swift:
.. parsed-literal:: *Not provided*. It's not clear whether this is .. parsed-literal:: *Not provided*. It's not clear whether this is
useful at all for non-ASCII strings, and useful at all for non-ASCII strings, and
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (void)\ **getLineStart:**\ (NSUInteger \*)startPtr \ **end:**\ (NSUInteger \*)lineEndPtr \ **contentsEnd:**\ (NSUInteger \*)contentsEndPtr \ **forRange:**\ (NSRange)range; \- (void)\ **getLineStart:**\ (NSUInteger \*)startPtr \ **end:**\ (NSUInteger \*)lineEndPtr \ **contentsEnd:**\ (NSUInteger \*)contentsEndPtr \ **forRange:**\ (NSRange)range;
@@ -1152,7 +1152,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSRange)\ **lineRangeForRange:**\ (NSRange)range; \- (NSRange)\ **lineRangeForRange:**\ (NSRange)range;
@@ -1162,7 +1162,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (void)\ **getParagraphStart:**\ (NSUInteger \*)startPtr \ **end:**\ (NSUInteger \*)parEndPtr \ **contentsEnd:**\ (NSUInteger \*)contentsEndPtr \ **forRange:**\ (NSRange)range; \- (void)\ **getParagraphStart:**\ (NSUInteger \*)startPtr \ **end:**\ (NSUInteger \*)parEndPtr \ **contentsEnd:**\ (NSUInteger \*)contentsEndPtr \ **forRange:**\ (NSRange)range;
@@ -1172,7 +1172,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSRange)\ **paragraphRangeForRange:**\ (NSRange)range; \- (NSRange)\ **paragraphRangeForRange:**\ (NSRange)range;
@@ -1182,7 +1182,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (void)\ **enumerateSubstringsInRange:**\ (NSRange)range \ **options:**\ (NSStringEnumerationOptions)opts \ **usingBlock:**\ (void (^)(NSString \*substring, NSRange substringRange, NSRange enclosingRange, BOOL \*stop))block; \- (void)\ **enumerateSubstringsInRange:**\ (NSRange)range \ **options:**\ (NSStringEnumerationOptions)opts \ **usingBlock:**\ (void (^)(NSString \*substring, NSRange substringRange, NSRange enclosingRange, BOOL \*stop))block;
@@ -1192,7 +1192,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (void)\ **enumerateLinesUsingBlock:**\ (void (^)(NSString \*line, BOOL \*stop))block; \- (void)\ **enumerateLinesUsingBlock:**\ (void (^)(NSString \*line, BOOL \*stop))block;
@@ -1202,7 +1202,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)description; \- (NSString \*)description;
@@ -1212,7 +1212,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSUInteger)hash; \- (NSUInteger)hash;
@@ -1222,7 +1222,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSStringEncoding)fastestEncoding; \- (NSStringEncoding)fastestEncoding;
@@ -1232,7 +1232,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSStringEncoding)smallestEncoding; \- (NSStringEncoding)smallestEncoding;
@@ -1242,7 +1242,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSData \*)\ **dataUsingEncoding:**\ (NSStringEncoding)encoding \ **allowLossyConversion:**\ (BOOL)lossy; \- (NSData \*)\ **dataUsingEncoding:**\ (NSStringEncoding)encoding \ **allowLossyConversion:**\ (BOOL)lossy;
@@ -1252,7 +1252,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSData \*)\ **dataUsingEncoding:**\ (NSStringEncoding)encoding; \- (NSData \*)\ **dataUsingEncoding:**\ (NSStringEncoding)encoding;
@@ -1265,7 +1265,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (__strong const char \*)\ **cStringUsingEncoding:**\ (NSStringEncoding)encoding NS_RETURNS_INNER_POINTER; \- (__strong const char \*)\ **cStringUsingEncoding:**\ (NSStringEncoding)encoding NS_RETURNS_INNER_POINTER;
@@ -1275,7 +1275,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (BOOL)\ **getCString:**\ (char \*)buffer \ **maxLength:**\ (NSUInteger)maxBufferCount \ **encoding:**\ (NSStringEncoding)encoding; \- (BOOL)\ **getCString:**\ (char \*)buffer \ **maxLength:**\ (NSUInteger)maxBufferCount \ **encoding:**\ (NSStringEncoding)encoding;
@@ -1285,7 +1285,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (BOOL)\ **getBytes:**\ (void \*)buffer \ **maxLength:**\ (NSUInteger)maxBufferCount \ **usedLength:**\ (NSUInteger \*)usedBufferCount \ **encoding:**\ (NSStringEncoding)encoding \ **options:**\ (NSStringEncodingConversionOptions)options \ **range:**\ (NSRange)range \ **remainingRange:**\ (NSRangePointer)leftover; \- (BOOL)\ **getBytes:**\ (void \*)buffer \ **maxLength:**\ (NSUInteger)maxBufferCount \ **usedLength:**\ (NSUInteger \*)usedBufferCount \ **encoding:**\ (NSStringEncoding)encoding \ **options:**\ (NSStringEncodingConversionOptions)options \ **range:**\ (NSRange)range \ **remainingRange:**\ (NSRangePointer)leftover;
@@ -1295,7 +1295,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSUInteger)\ **maximumLengthOfBytesUsingEncoding:**\ (NSStringEncoding)enc; \- (NSUInteger)\ **maximumLengthOfBytesUsingEncoding:**\ (NSStringEncoding)enc;
@@ -1305,7 +1305,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSUInteger)\ **lengthOfBytesUsingEncoding:**\ (NSStringEncoding)enc; \- (NSUInteger)\ **lengthOfBytesUsingEncoding:**\ (NSStringEncoding)enc;
@@ -1315,7 +1315,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)decomposedStringWithCanonicalMapping; \- (NSString \*)decomposedStringWithCanonicalMapping;
@@ -1325,7 +1325,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)precomposedStringWithCanonicalMapping; \- (NSString \*)precomposedStringWithCanonicalMapping;
@@ -1335,7 +1335,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)decomposedStringWithCompatibilityMapping; \- (NSString \*)decomposedStringWithCompatibilityMapping;
@@ -1345,7 +1345,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)precomposedStringWithCompatibilityMapping; \- (NSString \*)precomposedStringWithCompatibilityMapping;
@@ -1355,7 +1355,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **stringByFoldingWithOptions:**\ (NSStringCompareOptions)options \ **locale:**\ (NSLocale \*)locale; \- (NSString \*)\ **stringByFoldingWithOptions:**\ (NSStringCompareOptions)options \ **locale:**\ (NSLocale \*)locale;
@@ -1365,7 +1365,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **stringByReplacingOccurrencesOfString:**\ (NSString \*)target \ **withString:**\ (NSString \*)replacement \ **options:**\ (NSStringCompareOptions)options \ **range:**\ (NSRange)searchRange; \- (NSString \*)\ **stringByReplacingOccurrencesOfString:**\ (NSString \*)target \ **withString:**\ (NSString \*)replacement \ **options:**\ (NSStringCompareOptions)options \ **range:**\ (NSRange)searchRange;
@@ -1375,7 +1375,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **stringByReplacingOccurrencesOfString:**\ (NSString \*)target \ **withString:**\ (NSString \*)replacement; \- (NSString \*)\ **stringByReplacingOccurrencesOfString:**\ (NSString \*)target \ **withString:**\ (NSString \*)replacement;
@@ -1385,14 +1385,14 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSString \*)\ **stringByReplacingCharactersInRange:**\ (NSRange)range \ **withString:**\ (NSString \*)replacement; \- (NSString \*)\ **stringByReplacingCharactersInRange:**\ (NSRange)range \ **withString:**\ (NSString \*)replacement;
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (__strong const char \*)UTF8String NS_RETURNS_INNER_POINTER; \- (__strong const char \*)UTF8String NS_RETURNS_INNER_POINTER;
@@ -1402,7 +1402,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (NSStringEncoding)defaultCStringEncoding; \+ (NSStringEncoding)defaultCStringEncoding;
@@ -1412,7 +1412,7 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (const NSStringEncoding \*)availableStringEncodings; \+ (const NSStringEncoding \*)availableStringEncodings;
@@ -1422,32 +1422,32 @@ Capitalization
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (NSString \*)\ **localizedNameOfStringEncoding:**\ (NSStringEncoding)encoding; \+ (NSString \*)\ **localizedNameOfStringEncoding:**\ (NSStringEncoding)encoding;
Constructors Constructors
~~~~~~~~~~~~ ~~~~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)init; \- (instancetype)init;
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithString:**\ (NSString \*)aString; \- (instancetype)\ **initWithString:**\ (NSString \*)aString;
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (instancetype)string; \+ (instancetype)string;
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (instancetype)\ **stringWithString:**\ (NSString \*)string; \+ (instancetype)\ **stringWithString:**\ (NSString \*)string;
@@ -1455,7 +1455,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithCharactersNoCopy:**\ (unichar \*)characters \ **length:**\ (NSUInteger)length \ **freeWhenDone:**\ (BOOL)freeBuffer; \- (instancetype)\ **initWithCharactersNoCopy:**\ (unichar \*)characters \ **length:**\ (NSUInteger)length \ **freeWhenDone:**\ (BOOL)freeBuffer;
@@ -1465,7 +1465,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithCharacters:**\ (const unichar \*)characters \ **length:**\ (NSUInteger)length; \- (instancetype)\ **initWithCharacters:**\ (const unichar \*)characters \ **length:**\ (NSUInteger)length;
@@ -1475,7 +1475,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithUTF8String:**\ (const char \*)nullTerminatedCString; \- (instancetype)\ **initWithUTF8String:**\ (const char \*)nullTerminatedCString;
@@ -1485,7 +1485,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithFormat:**\ (NSString \*)format, ... NS_FORMAT_FUNCTION(1,2); \- (instancetype)\ **initWithFormat:**\ (NSString \*)format, ... NS_FORMAT_FUNCTION(1,2);
@@ -1495,7 +1495,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithFormat:**\ (NSString \*)format \ **arguments:**\ (va_list)argList NS_FORMAT_FUNCTION(1,0); \- (instancetype)\ **initWithFormat:**\ (NSString \*)format \ **arguments:**\ (va_list)argList NS_FORMAT_FUNCTION(1,0);
@@ -1505,7 +1505,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithFormat:**\ (NSString \*)format \ **locale:**\ (id)locale, ... NS_FORMAT_FUNCTION(1,3); \- (instancetype)\ **initWithFormat:**\ (NSString \*)format \ **locale:**\ (id)locale, ... NS_FORMAT_FUNCTION(1,3);
@@ -1515,7 +1515,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithFormat:**\ (NSString \*)format \ **locale:**\ (id)locale \ **arguments:**\ (va_list)argList NS_FORMAT_FUNCTION(1,0); \- (instancetype)\ **initWithFormat:**\ (NSString \*)format \ **locale:**\ (id)locale \ **arguments:**\ (va_list)argList NS_FORMAT_FUNCTION(1,0);
@@ -1525,7 +1525,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithData:**\ (NSData \*)data \ **encoding:**\ (NSStringEncoding)encoding; \- (instancetype)\ **initWithData:**\ (NSData \*)data \ **encoding:**\ (NSStringEncoding)encoding;
@@ -1535,7 +1535,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithBytes:**\ (const void \*)bytes \ **length:**\ (NSUInteger)len \ **encoding:**\ (NSStringEncoding)encoding; \- (instancetype)\ **initWithBytes:**\ (const void \*)bytes \ **length:**\ (NSUInteger)len \ **encoding:**\ (NSStringEncoding)encoding;
@@ -1545,7 +1545,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithBytesNoCopy:**\ (void \*)bytes \ **length:**\ (NSUInteger)len \ **encoding:**\ (NSStringEncoding)encoding \ **freeWhenDone:**\ (BOOL)freeBuffer; \- (instancetype)\ **initWithBytesNoCopy:**\ (void \*)bytes \ **length:**\ (NSUInteger)len \ **encoding:**\ (NSStringEncoding)encoding \ **freeWhenDone:**\ (BOOL)freeBuffer;
@@ -1555,7 +1555,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (instancetype)\ **stringWithCharacters:**\ (const unichar \*)characters \ **length:**\ (NSUInteger)length; \+ (instancetype)\ **stringWithCharacters:**\ (const unichar \*)characters \ **length:**\ (NSUInteger)length;
@@ -1565,7 +1565,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (instancetype)\ **stringWithUTF8String:**\ (const char \*)nullTerminatedCString; \+ (instancetype)\ **stringWithUTF8String:**\ (const char \*)nullTerminatedCString;
@@ -1575,7 +1575,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (instancetype)\ **stringWithFormat:**\ (NSString \*)format, ... NS_FORMAT_FUNCTION(1,2); \+ (instancetype)\ **stringWithFormat:**\ (NSString \*)format, ... NS_FORMAT_FUNCTION(1,2);
@@ -1585,7 +1585,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (instancetype)\ **localizedStringWithFormat:**\ (NSString \*)format, ... NS_FORMAT_FUNCTION(1,2); \+ (instancetype)\ **localizedStringWithFormat:**\ (NSString \*)format, ... NS_FORMAT_FUNCTION(1,2);
@@ -1595,7 +1595,7 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (instancetype)\ **initWithCString:**\ (const char \*)nullTerminatedCString \ **encoding:**\ (NSStringEncoding)encoding; \- (instancetype)\ **initWithCString:**\ (const char \*)nullTerminatedCString \ **encoding:**\ (NSStringEncoding)encoding;
@@ -1605,15 +1605,15 @@ Not available (too error prone)
--------- ---------
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\+ (instancetype)\ **stringWithCString:**\ (const char \*)cString \ **encoding:**\ (NSStringEncoding)enc; \+ (instancetype)\ **stringWithCString:**\ (const char \*)cString \ **encoding:**\ (NSStringEncoding)enc;
Linguistic Analysis Linguistic Analysis
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
:Cocoa: :Cocoa:
.. parsed-literal:: .. parsed-literal::
\- (NSArray \*)\ **linguisticTagsInRange:**\ (NSRange)range \ **scheme:**\ (NSString \*)tagScheme \ **options:**\ (NSLinguisticTaggerOptions)opts \ **orthography:**\ (NSOrthography \*)orthography \ **tokenRanges:**\ (NSArray \*\*)tokenRanges; \- (NSArray \*)\ **linguisticTagsInRange:**\ (NSRange)range \ **scheme:**\ (NSString \*)tagScheme \ **options:**\ (NSLinguisticTaggerOptions)opts \ **orthography:**\ (NSOrthography \*)orthography \ **tokenRanges:**\ (NSArray \*\*)tokenRanges;
\- (void)\ **enumerateLinguisticTagsInRange:**\ (NSRange)range \ **scheme:**\ (NSString \*)tagScheme \ **options:**\ (NSLinguisticTaggerOptions)opts \ **orthography:**\ (NSOrthography \*)orthography \ **usingBlock:**\ (void (^)(NSString \*tag, NSRange tokenRange, NSRange sentenceRange, BOOL \*stop))block; \- (void)\ **enumerateLinguisticTagsInRange:**\ (NSRange)range \ **scheme:**\ (NSString \*)tagScheme \ **options:**\ (NSLinguisticTaggerOptions)opts \ **orthography:**\ (NSOrthography \*)orthography \ **usingBlock:**\ (void (^)(NSString \*tag, NSRange tokenRange, NSRange sentenceRange, BOOL \*stop))block;

View File

@@ -57,7 +57,7 @@ Non-Goals
* **Dynamic format strings** are beyond the scope of this proposal. * **Dynamic format strings** are beyond the scope of this proposal.
* **Matching the terseness of C**\ 's ``printf`` is a non-goal. * **Matching the terseness of C**\ 's ``printf`` is a non-goal.
CustomStringConvertible Types CustomStringConvertible Types
----------------------------- -----------------------------
@@ -66,7 +66,7 @@ CustomStringConvertible Types
printed with ``print(x)``, and can be converted to ``String`` with printed with ``print(x)``, and can be converted to ``String`` with
``x.toString()``. ``x.toString()``.
The simple extension story for beginners is as follows: The simple extension story for beginners is as follows:
"To make your type ``CustomStringConvertible``, simply declare conformance to "To make your type ``CustomStringConvertible``, simply declare conformance to
``CustomStringConvertible``:: ``CustomStringConvertible``::
@@ -258,14 +258,14 @@ The following code is a scaled-down version of the formatting code
used for ``Int``. It represents an example of how a relatively used for ``Int``. It represents an example of how a relatively
complicated ``format(…)`` might be written:: complicated ``format(…)`` might be written::
protocol CustomStringConvertibleInteger protocol CustomStringConvertibleInteger
: ExpressibleByIntegerLiteral, Comparable, SignedNumber, CustomStringConvertible { : ExpressibleByIntegerLiteral, Comparable, SignedNumber, CustomStringConvertible {
func %(lhs: Self, rhs: Self) -> Self func %(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self
constructor(x: Int) constructor(x: Int)
func toInt() -> Int func toInt() -> Int
func format(_ radix: Int = 10, fill: String = " ", width: Int = 0) func format(_ radix: Int = 10, fill: String = " ", width: Int = 0)
-> RadixFormat<This> { -> RadixFormat<This> {
return RadixFormat(this, radix: radix, fill: fill, width: width) return RadixFormat(this, radix: radix, fill: fill, width: width)

View File

@@ -103,7 +103,7 @@ the Swift type system:
An equality constraint requires two types to be identical. For An equality constraint requires two types to be identical. For
example, the constraint ``T0 == T1`` effectively ensures that ``T0`` and example, the constraint ``T0 == T1`` effectively ensures that ``T0`` and
``T1`` get the same concrete type binding. There are two different ``T1`` get the same concrete type binding. There are two different
flavors of equality constraints: flavors of equality constraints:
- Exact equality constraints, or "binding", written ``T0 := X`` - Exact equality constraints, or "binding", written ``T0 := X``
for some type variable ``T0`` and type ``X``, which requires for some type variable ``T0`` and type ``X``, which requires
@@ -153,7 +153,7 @@ the Swift type system:
second, i.e., for ``x as T``. second, i.e., for ``x as T``.
**Applicable function** **Applicable function**
An applicable function requires that both types are function types An applicable function requires that both types are function types
with the same input and output types. It is used when the function with the same input and output types. It is used when the function
type on the left-hand side is being split into its input and output type on the left-hand side is being split into its input and output
types for function application purposes. Note, that it does not types for function application purposes. Note, that it does not
@@ -201,7 +201,7 @@ The process of constraint generation produces a constraint system
that relates the types of the various subexpressions within an that relates the types of the various subexpressions within an
expression. Programmatically, constraint generation walks an expression. Programmatically, constraint generation walks an
expression from the leaves up to the root, assigning a type (which expression from the leaves up to the root, assigning a type (which
often involves type variables) to each subexpression as it goes. often involves type variables) to each subexpression as it goes.
Constraint generation is driven by the syntax of the Constraint generation is driven by the syntax of the
expression, and each different kind of expression---function expression, and each different kind of expression---function
@@ -224,7 +224,7 @@ and types generated from the primary expression kinds are:
section. Additionally, when the name refers to a generic function or section. Additionally, when the name refers to a generic function or
a generic type, the declaration reference may introduce new type a generic type, the declaration reference may introduce new type
variables; see the `Polymorphic Types`_ section for more information. variables; see the `Polymorphic Types`_ section for more information.
**Member reference** **Member reference**
A member reference expression ``a.b`` is assigned the type ``T0`` A member reference expression ``a.b`` is assigned the type ``T0``
for a fresh type variable ``T0``. In addition, the expression for a fresh type variable ``T0``. In addition, the expression
@@ -351,7 +351,7 @@ variable (call it ``T0``) for the type of the reference to an
overloaded declaration. Then, a disjunction constraint is introduced, overloaded declaration. Then, a disjunction constraint is introduced,
in which each term binds that type variable (via an exact equality in which each term binds that type variable (via an exact equality
constraint) to the type produced by one of the overloads in the constraint) to the type produced by one of the overloads in the
overload set. In our negate example, the disjunction is overload set. In our negate example, the disjunction is
``T0 := (Int) -> Int or T0 := (Double) -> Double``. The constraint ``T0 := (Int) -> Int or T0 := (Double) -> Double``. The constraint
solver, discussed in the later section on `Constraint Solving`_, solver, discussed in the later section on `Constraint Solving`_,
explores both possible bindings, and the overloaded reference resolves explores both possible bindings, and the overloaded reference resolves
@@ -572,7 +572,7 @@ produce derived constraint systems that explore the solution space.
Overload Selection Overload Selection
''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''
Overload selection is the simplest way to make an assumption. For an Overload selection is the simplest way to make an assumption. For an
overload set that introduced a disjunction constraint overload set that introduced a disjunction constraint
``T0 := A1 or T0 := A2 or ... or T0 := AN`` into the constraint ``T0 := A1 or T0 := A2 or ... or T0 := AN`` into the constraint
system, each term in the disjunction will be visited separately. Each system, each term in the disjunction will be visited separately. Each
solver state binds the type variable ``T0`` and explores solver state binds the type variable ``T0`` and explores
@@ -598,7 +598,7 @@ placed on it that relate it to concrete types, e.g., ``T0 <c Int`` or
starting point to make educated guesses for the type ``T0``. starting point to make educated guesses for the type ``T0``.
To determine an appropriate guess, the relational constraints placed To determine an appropriate guess, the relational constraints placed
on the type variable are categorized. Given a relational constraint of the form on the type variable are categorized. Given a relational constraint of the form
``T0 <? A`` (where ``<?`` is one of ``<``, ``<t``, or ``<c``), where ``T0 <? A`` (where ``<?`` is one of ``<``, ``<t``, or ``<c``), where
``A`` is some concrete type, ``A`` is said to be "above" ``A`` is some concrete type, ``A`` is said to be "above"
``T0``. Similarly, given a constraint of the form ``B <? T0`` for a ``T0``. Similarly, given a constraint of the form ``B <? T0`` for a

View File

@@ -96,7 +96,7 @@ Having header files for public API is nice for a couple of reasons:
headers but not the implementation of system classes. This allows "jump to headers but not the implementation of system classes. This allows "jump to
definition" to go to the declaration of an API in the header, which is definition" to go to the declaration of an API in the header, which is
conveniently co-located with headerdoc. conveniently co-located with headerdoc.
On the other hand, headers have a number of disadvantages including: On the other hand, headers have a number of disadvantages including:
1. It is plain code duplication, with all the negative effects of it. It slows 1. It is plain code duplication, with all the negative effects of it. It slows

View File

@@ -146,7 +146,7 @@ Guidelines:
.. [#] If you explicitly want to expose a Swift method to Objective-C, but it .. [#] If you explicitly want to expose a Swift method to Objective-C, but it
is not part of an existing protocol, you can mark the method as "API" and is not part of an existing protocol, you can mark the method as "API" and
include the ``[objc]`` attribute:: include the ``[objc]`` attribute::
// Note: This syntax is not final! // Note: This syntax is not final!
func [API, objc] accessibilityDescription { func [API, objc] accessibilityDescription {
return "\(self.givenName) \(self.familyName)" return "\(self.givenName) \(self.familyName)"
@@ -436,7 +436,7 @@ Arguments
Objective-C currently requires that the first argument be ``self`` and the Objective-C currently requires that the first argument be ``self`` and the
second be ``_cmd``. The explicit arguments to a method come after ``_cmd``. second be ``_cmd``. The explicit arguments to a method come after ``_cmd``.
Swift only requires that the first argument be ``self``. The explicit Swift only requires that the first argument be ``self``. The explicit
arguments come after ``self``. arguments come after ``self``.
@@ -497,21 +497,21 @@ Overloading
// 1. foo:baz: // 1. foo:baz:
func foo(Int bar, Int baz); func foo(Int bar, Int baz);
// 2. foo:qux: // 2. foo:qux:
func foo(Int bar, Int qux); func foo(Int bar, Int qux);
// 3. foo:qux: (same as above) // 3. foo:qux: (same as above)
func foo(Int bar) qux(Int quux); func foo(Int bar) qux(Int quux);
// 4. foo:baz: (but different type!) // 4. foo:baz: (but different type!)
func foo(Int bar, UnicodeScalar baz); func foo(Int bar, UnicodeScalar baz);
a.foo(1, 2) // ambiguous in Swift (#1 or #2?) a.foo(1, 2) // ambiguous in Swift (#1 or #2?)
a.foo(1, baz=2) // calls #1 a.foo(1, baz=2) // calls #1
a.foo(1, qux=2) // calls #2/3 (the same method) a.foo(1, qux=2) // calls #2/3 (the same method)
a.foo(1, 'C') // calls #4, not ambiguous in Swift! a.foo(1, 'C') // calls #4, not ambiguous in Swift!
[a foo:1 baz:2]; // ambiguous in Objective-C (#1 or #4?) [a foo:1 baz:2]; // ambiguous in Objective-C (#1 or #4?)
[a foo:1 qux:2]; // calls #2/3 (the same method) [a foo:1 qux:2]; // calls #2/3 (the same method)
@@ -533,7 +533,7 @@ Note: the answer might be "Swift objects can't generally be referenced with
``isa`` Pointers ``isa`` Pointers
---------------- ----------------
The first word of every Objective-C object is a pointer to its class. The first word of every Objective-C object is a pointer to its class.
We might want to use a more compact representation for Swift objects... We might want to use a more compact representation for Swift objects...
...but we can't; see below. ...but we can't; see below.

View File

@@ -317,14 +317,14 @@ Swift's struct layout algorithm takes as input a list of fields, and does the
following: following:
1. The fields are ranked: 1. The fields are ranked:
* The universally fragile fields rank higher than the others. * The universally fragile fields rank higher than the others.
* If two fields A and B are both universally fragile, * If two fields A and B are both universally fragile,
* If no other condition applies, fields that appear earlier in the original * If no other condition applies, fields that appear earlier in the original
sequence have higher rank. sequence have higher rank.
2. The size of the structure is initially 0. 2. The size of the structure is initially 0.
representations and A's type is more aligned than B's type, or otherwise if A representations and A's type is more aligned than B's type, or otherwise if A
@@ -466,25 +466,25 @@ range of generic operations can be
1. the size and layout of first-class objects: 1. the size and layout of first-class objects:
* local variables * local variables
* global variables * global variables
* dynamically*allocated objects * dynamically*allocated objects
* member sub*objects of a structure * member sub*objects of a structure
* base sub*objects of a class * base sub*objects of a class
* element sub*objects of an array * element sub*objects of an array
* parameters of functions * parameters of functions
* results of functions * results of functions
2. the set of operations on an object: 2. the set of operations on an object:
* across all protocols * across all protocols
* for a particular protocol (?) * for a particular protocol (?)
3. the set of operations on an object 3. the set of operations on an object

View File

@@ -72,7 +72,7 @@ A.qindexHL:hover {
background-color: #6666cc; background-color: #6666cc;
color: #ffffff; color: #ffffff;
} }
A.qindexHL:visited { A.qindexHL:visited {
text-decoration: none; background-color: #6666cc; color: #ffffff } text-decoration: none; background-color: #6666cc; color: #ffffff }
A.el { text-decoration: none; font-weight: bold } A.el { text-decoration: none; font-weight: bold }
A.elRef { font-weight: bold } A.elRef { font-weight: bold }
@@ -147,7 +147,7 @@ TD.indexvalue {
border: 1px solid #CCCCCC; border: 1px solid #CCCCCC;
} }
TR.memlist { TR.memlist {
background-color: #f0f0f0; background-color: #f0f0f0;
} }
P.formulaDsp { text-align: center; } P.formulaDsp { text-align: center; }
IMG.formulaDsp { } IMG.formulaDsp { }
@@ -311,7 +311,7 @@ HR { height: 1px;
border-top: 1px solid black; border-top: 1px solid black;
} }
/* /*
* LLVM Modifications. * LLVM Modifications.
* Note: Everything above here is generated with "doxygen -w html" command. See * Note: Everything above here is generated with "doxygen -w html" command. See
* "doxygen --help" for details. What follows are CSS overrides for LLVM * "doxygen --help" for details. What follows are CSS overrides for LLVM
@@ -326,7 +326,7 @@ HR { height: 1px;
vertical-align: middle; vertical-align: middle;
} }
.title { .title {
font-size: 25pt; font-size: 25pt;
color: black; color: black;
font-weight: bold; font-weight: bold;
border-width: 1px; border-width: 1px;

View File

@@ -3,16 +3,16 @@
/// @section main_intro Introduction /// @section main_intro Introduction
/// Welcome to Swift. /// Welcome to Swift.
/// ///
/// This documentation describes the @b internal software that makes /// This documentation describes the @b internal software that makes
/// up Swift, not the @b external use of Swift. There are no instructions /// up Swift, not the @b external use of Swift. There are no instructions
/// here on how to use Swift, only the APIs that make up the software. For usage /// here on how to use Swift, only the APIs that make up the software. For usage
/// instructions, please see the programmer's guide or reference manual. /// instructions, please see the programmer's guide or reference manual.
/// ///
/// @section main_caveat Caveat /// @section main_caveat Caveat
/// This documentation is generated directly from the source code with doxygen. /// This documentation is generated directly from the source code with doxygen.
/// Since Swift is constantly under active development, what you're about to /// Since Swift is constantly under active development, what you're about to
/// read is out of date! However, it may still be useful since certain portions /// read is out of date! However, it may still be useful since certain portions
/// of Swift are very stable. /// of Swift are very stable.
/// ///
/// @section main_changelog Change Log /// @section main_changelog Change Log
/// - Original content written 12/30/2003 by Reid Spencer for LLVM /// - Original content written 12/30/2003 by Reid Spencer for LLVM

View File

@@ -573,7 +573,7 @@ like this::
let pinToken = _pin() let pinToken = _pin()
return (slice, pinToken) return (slice, pinToken)
} }
// `setForMutation` receives two arguments--the result of the // `setForMutation` receives two arguments--the result of the
// mutation to write back, and the state value returned by // mutation to write back, and the state value returned by
// `getForMutation`. // `getForMutation`.
@@ -618,7 +618,7 @@ like this::
var foo: T { var foo: T {
get { return getValue() } get { return getValue() }
set { setValue(newValue) } set { setValue(newValue) }
// Perform a full in-out mutation. The `next` continuation is of // Perform a full in-out mutation. The `next` continuation is of
// type `(inout T) -> ()` and must be called exactly once // type `(inout T) -> ()` and must be called exactly once
// with the value to hand off to the nested mutation operation. // with the value to hand off to the nested mutation operation.
@@ -639,7 +639,7 @@ accessors::
next(&$0.memory) next(&$0.memory)
} }
} }
// A pinning mutator // A pinning mutator
mutate(next) { mutate(next) {
var slice = makeSlice() var slice = makeSlice()
@@ -648,7 +648,7 @@ accessors::
unpin(token) unpin(token)
writeBackSlice(slice) writeBackSlice(slice)
} }
For various semantic and implementation efficiency reasons, we don't want to For various semantic and implementation efficiency reasons, we don't want to
literally implement every access as a nesting of closures like this. Doing so literally implement every access as a nesting of closures like this. Doing so
would allow for semantic surprises (a mutate() operation never invoking its would allow for semantic surprises (a mutate() operation never invoking its
@@ -675,7 +675,7 @@ control flow path::
unpin(token) unpin(token)
writeBackSlice(slice) writeBackSlice(slice)
} }
This obviously requires more implementation infrastructure than we currently This obviously requires more implementation infrastructure than we currently
have, and raises language and library design issues (in particular, have, and raises language and library design issues (in particular,
lifetime-extending combinators like ``withUnsafePointer`` would need either lifetime-extending combinators like ``withUnsafePointer`` would need either

View File

@@ -14,10 +14,10 @@
===================================== =====================================
Bridging Swift Arrays to/from Cocoa Bridging Swift Arrays to/from Cocoa
===================================== =====================================
:Authors: Chris Lattner, Joe Groff, Dave Abrahams :Authors: Chris Lattner, Joe Groff, Dave Abrahams
:Summary: Unifying a fast C-style array with a Cocoa class cluster :Summary: Unifying a fast C-style array with a Cocoa class cluster
that can represent arbitrarily complex data structures is that can represent arbitrarily complex data structures is
challenging. In a space where no approach satisfies all challenging. In a space where no approach satisfies all

View File

@@ -12,7 +12,7 @@ and library facilities that enable the following uses of pointer
arguments: arguments:
- Const pointer arguments ``const int *``, including const pointers to ObjC - Const pointer arguments ``const int *``, including const pointers to ObjC
classes ``NSFoo * const *``, can be used as "in" array arguments, classes ``NSFoo * const *``, can be used as "in" array arguments,
as ``inout`` scalar arguments, or as ``UnsafeMutablePointer`` arguments. as ``inout`` scalar arguments, or as ``UnsafeMutablePointer`` arguments.
- Non-const pointer arguments to C types, ``int *``, can be used as ``inout`` - Non-const pointer arguments to C types, ``int *``, can be used as ``inout``
array or scalar arguments, or as ``UnsafeMutablePointer`` arguments. array or scalar arguments, or as ``UnsafeMutablePointer`` arguments.

View File

@@ -16,7 +16,7 @@ confusing jumble.
The best solution to this is to burn the user model into the language, giving The best solution to this is to burn the user model into the language, giving
function applications special powers to provide the user model for pointers. We function applications special powers to provide the user model for pointers. We
then provide only one set of plain pointer types, with then provide only one set of plain pointer types, with
special intrinsic behavior when used as function arguments. special intrinsic behavior when used as function arguments.
The Pointer Types The Pointer Types
@@ -176,7 +176,7 @@ You can call it as any of::
A type checker limitation prevents array literals from being passed directly A type checker limitation prevents array literals from being passed directly
to ``UnsafeRawPointer`` arguments without type annotation. As a to ``UnsafeRawPointer`` arguments without type annotation. As a
workaround, you can bind the array literal to a constant, as above, or workaround, you can bind the array literal to a constant, as above, or
specify the array type with ``as``:: specify the array type with ``as``::
zang([1.0, 2.0, 3.0] as [Double]) zang([1.0, 2.0, 3.0] as [Double])

View File

@@ -292,7 +292,7 @@ Streams are the only legitimate channel of communication between threads.
Streams can be shared by multiple tasks. These tasks can read from and write into the stream Streams can be shared by multiple tasks. These tasks can read from and write into the stream
concurrently. Reads from streams that contain no data and writes into full streams concurrently. Reads from streams that contain no data and writes into full streams
will be blocked, meaning that the operating system will put the calling thread to sleep and wait for will be blocked, meaning that the operating system will put the calling thread to sleep and wait for
new data to arrive to wake the sleeping thread. new data to arrive to wake the sleeping thread.
This property allows the Stream to be used as a synchronization mechanism. This property allows the Stream to be used as a synchronization mechanism.
@@ -648,11 +648,11 @@ length in the previous sections).
The ``accept`` method is executed by a user-space scheduler and not by live The ``accept`` method is executed by a user-space scheduler and not by live
thread and this allows the system to scale to tens of thousands of active thread and this allows the system to scale to tens of thousands of active
actors. actors.
The code below depicts the famous prime numbers sieve program using actors. The The code below depicts the famous prime numbers sieve program using actors. The
sieve is made of a long chain of actors that pass messages to one another. sieve is made of a long chain of actors that pass messages to one another.
Finally, a collector actor saves all of the messages into an array. Finally, a collector actor saves all of the messages into an array.
.. code-block:: swift .. code-block:: swift

View File

@@ -119,7 +119,7 @@ To address the problems with the current declaration type checker, we propose a
} }
struct X<T> : P { struct X<T> : P {
} }
func foo(_ x: X<Int>.Assoc) { } func foo(_ x: X<Int>.Assoc) { }

View File

@@ -80,7 +80,7 @@ to C programmers organically, starting from the familiar case that looks like
C:: C::
enum Foo { case A, B, C, D } enum Foo { case A, B, C, D }
func use(_ x:Foo) { func use(_ x:Foo) {
switch x { switch x {
case .A: case .A:
@@ -94,7 +94,7 @@ and then introducing the parallel new concepts of payloads and patterns
together:: together::
enum Foo { case A, B, C, D, Other(String) } enum Foo { case A, B, C, D, Other(String) }
func use(_ x:Foo) { func use(_ x:Foo) {
switch x { switch x {
case .A: case .A:
@@ -123,7 +123,7 @@ convention of 'First_*' and 'Last_*' sigils::
Lizard = First_Reptile, Lizard = First_Reptile,
Snake, Snake,
Last_Reptile = Snake, Last_Reptile = Snake,
First_Mammal, First_Mammal,
Cat = First_Mammal, Cat = First_Mammal,
Dog, Dog,

View File

@@ -12,10 +12,10 @@ superclass subobject gets initialized. The typical way to do so is
through the use of superclass delegation:: through the use of superclass delegation::
class A { class A {
var x: Int var x: Int
init(x: Int) { init(x: Int) {
self.x = x self.x = x
} }
} }
@@ -82,7 +82,7 @@ is initializing all of the instance variables of ``A``: new instance
variables could be added to ``A`` in a future version (these would not variables could be added to ``A`` in a future version (these would not
be properly initialized) and existing instance variables could become be properly initialized) and existing instance variables could become
computed properties (these would be initialized when they shouldn't computed properties (these would be initialized when they shouldn't
be). be).
Initializer Inheritance Initializer Inheritance
----------------------- -----------------------
@@ -255,14 +255,14 @@ init method. The existence of this init method allows object
construction from Objective-C (both directly via ``[[A alloc] construction from Objective-C (both directly via ``[[A alloc]
init:5]`` and indirectly via, e.g., ``[obj initWithCoder:coder]``) init:5]`` and indirectly via, e.g., ``[obj initWithCoder:coder]``)
and initialization of the superclass subobject when an Objective-C class and initialization of the superclass subobject when an Objective-C class
inherits from a Swift class (e.g., ``[super initWithCoder:coder]``). inherits from a Swift class (e.g., ``[super initWithCoder:coder]``).
Note that, while Swift's initializers are not inherited and cannot Note that, while Swift's initializers are not inherited and cannot
override, this is only true *in Swift code*. If a subclass defines an override, this is only true *in Swift code*. If a subclass defines an
initializer with the same Objective-C selector as an initializer in initializer with the same Objective-C selector as an initializer in
its superclass, the Objective-C init method produced for the former its superclass, the Objective-C init method produced for the former
will override the Objective-C init method produced for the will override the Objective-C init method produced for the
latter. latter.
Objective-C Restrictions Objective-C Restrictions
~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~

View File

@@ -61,7 +61,7 @@ The defining class of a subobject initializer is central to its
behavior. It can be soundly inherited by a class C only if is trivial behavior. It can be soundly inherited by a class C only if is trivial
to initialize the ivars of C, but it's convenient to ignore that and to initialize the ivars of C, but it's convenient to ignore that and
assume that subobjects will always trivially wrap and delegate to assume that subobjects will always trivially wrap and delegate to
superclass subobject initializers. superclass subobject initializers.
A subobject initializer must either (1) delegate to a peer subobject A subobject initializer must either (1) delegate to a peer subobject
initializer or (2) take responsibility for initializing all ivars of initializer or (2) take responsibility for initializing all ivars of
@@ -201,7 +201,7 @@ examples::
} }
class B3 : A { class B3 : A {
var counter: Int var counter: Int
init withInitialCount(initialCount: Int) { // subobject initializer init withInitialCount(initialCount: Int) { // subobject initializer
counter = initialCount counter = initialCount
@@ -214,7 +214,7 @@ examples::
self.init(withInitialCount: initialCount) self.init(withInitialCount: initialCount)
} }
// does not inherit A's init(), because init withTitle(String) is not // does not inherit A's init(), because init withTitle(String) is not
// overridden. // overridden.
} }
@@ -299,8 +299,8 @@ every subclass. For example::
class E2 : D { class E2 : D {
var title: String var title: String
@virtual init() { @virtual init() {
title = "Unnamed" title = "Unnamed"
super.init() super.init()
} }
@@ -310,11 +310,11 @@ every subclass. For example::
class E3 : D { class E3 : D {
var title: String var title: String
@virtual init() -> Self { @virtual init() -> Self {
self.init(withTitle: "Unnamed") self.init(withTitle: "Unnamed")
} }
init withTitle(title: String) { init withTitle(title: String) {
self.title = title self.title = title
super.init() super.init()
} }
@@ -393,4 +393,4 @@ diagnostic indicating that the initializer needs to be
implemented. implemented.
.. [#] Syntax suggestion from Joe Groff. .. [#] Syntax suggestion from Joe Groff.

View File

@@ -1,13 +1,13 @@
:orphan: :orphan:
.. highlight:: sil .. highlight:: sil
================================================ ================================================
Copy-On-Write Optimization of ``inout`` Values Copy-On-Write Optimization of ``inout`` Values
================================================ ================================================
:Authors: Dave Abrahams, Joe Groff :Authors: Dave Abrahams, Joe Groff
:Summary: Our writeback model interacts with Copy-On-Write (COW) to :Summary: Our writeback model interacts with Copy-On-Write (COW) to
cause some surprising inefficiencies, such as O(N) performance cause some surprising inefficiencies, such as O(N) performance
for ``x[0][0] = 1``. We propose a modified COW optimization for ``x[0][0] = 1``. We propose a modified COW optimization
@@ -21,7 +21,7 @@ The problem is caused as follows:
* COW depends on the programmer being able to mediate all writes (so * COW depends on the programmer being able to mediate all writes (so
she can copy if necessary) she can copy if necessary)
* Writes to container elements and slices are mediated through * Writes to container elements and slices are mediated through
subscript setters, so in :: subscript setters, so in ::
@@ -83,7 +83,7 @@ We need to prevent lvalues created in an ``inout`` context from
forcing a copy-on-write. To accomplish that: forcing a copy-on-write. To accomplish that:
* In the class instance header, we reserve a bit ``INOUT``. * In the class instance header, we reserve a bit ``INOUT``.
* When a unique reference to a COW buffer ``b`` is copied into * When a unique reference to a COW buffer ``b`` is copied into
an ``inout`` lvalue, we save the value of the ``b.INOUT`` bit and set it. an ``inout`` lvalue, we save the value of the ``b.INOUT`` bit and set it.
@@ -100,7 +100,7 @@ We believe this can be done with little user-facing change; the author
of a COW type would add an attribute to the property that stores the of a COW type would add an attribute to the property that stores the
buffer, and we would use a slightly different check for in-place buffer, and we would use a slightly different check for in-place
writability. writability.
Other Considered Solutions Other Considered Solutions
-------------------------- --------------------------

View File

@@ -34,7 +34,7 @@ written in terms of methods: [#operators]_ ::
When we started to look at the specifics, however, we ran into a When we started to look at the specifics, however, we ran into a
familiar pattern:: familiar pattern::
... ...
public func union(_ b: Set<Element>) -> Set<Element> // A B public func union(_ b: Set<Element>) -> Set<Element> // A B
public mutating func unionInPlace(_ b: Set<Element>) // A = B public mutating func unionInPlace(_ b: Set<Element>) // A = B
@@ -275,7 +275,7 @@ we can compile the statement
x\ **.=**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*) x\ **.=**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*)
as though it were written: as though it were written:
.. parsed-literal:: .. parsed-literal::
x **= x.**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*) x **= x.**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*)
@@ -306,10 +306,10 @@ we can compile the expression
**x.**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*) **x.**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*)
as though it were written: as though it were written:
.. parsed-literal:: .. parsed-literal::
{ {
(var y: X) -> X in (var y: X) -> X in
y\ **.=**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*) y\ **.=**\ *f*\ (a₀, p₁: a₁, p₂: a₂, …p\ *n*: a\ *n*)
return y return y
@@ -328,7 +328,7 @@ we can compile
x *op*\ **=** *expression* x *op*\ **=** *expression*
as though it were written: as though it were written:
.. parsed-literal:: .. parsed-literal::
x **=** x *op* (*expression*) x **=** x *op* (*expression*)
@@ -340,10 +340,10 @@ or
x *op* *expression* x *op* *expression*
as though it were written: as though it were written:
.. parsed-literal:: .. parsed-literal::
{ {
(var y: X) -> X in (var y: X) -> X in
y *op*\ **=**\ *expression* y *op*\ **=**\ *expression*
return y return y

View File

@@ -237,23 +237,23 @@ category replacing an existing method implementation is "rude"
actually a serious problem, if we . We can have some sort of actually a serious problem, if we . We can have some sort of
``@dynamic`` annotation for ``@dynamic`` annotation for
I don't think that requiring some sort of ``@dynamic`` I don't think that requiring some sort of ``@dynamic``
That one, central restriction is that we must remove or constrain the That one, central restriction is that we must remove or constrain the
ability to dynamically add and replace method implementations on ability to dynamically add and replace method implementations on
existing classes. It's reasonable to request some sort of ``@dynamic`` existing classes. It's reasonable to request some sort of ``@dynamic``
annotation for cases where this is absolutely required. annotation for cases where this is absolutely required.
One interesting corner case One interesting corner case
don't think anybody will weep too heavily if we scale back those ObjC don't think anybody will weep too heavily if we scale back those ObjC
runtime functions to say that either you can't use them on Swift classes runtime functions to say that either you can't use them on Swift classes
or or
restriction: removing the general ability to dynamically add and restriction: removing the general ability to dynamically add and
replace method implementations on an existing class. replace method implementations on an existing class.
There's a tension here. There's a tension here.
Point of Allocation Point of Allocation
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
@@ -280,10 +280,10 @@ We can reason forward from the point of allocation.
then we know the dynamic class at that point. That's relatively then we know the dynamic class at that point. That's relatively
easy to deal with. easy to deal with.
* *
If we can restrict the ability to If we can restrict the ability to
change the dynamic class, or at least restrict change the dynamic class, or at least restrict
Access Control Access Control
@@ -320,19 +320,19 @@ Using Swift Classes from Objective-C
open the question of open the question of
Because we intentionally hide the Because we intentionally hide the
difference between a stored property and its underlying storage, difference between a stored property and its underlying storage,
For another example, code For another example, code
class might access class might access
In both cases, t makes sense to organize the code that way, In both cases, t makes sense to organize the code that way,
but Objective-C punishes the performance of that code in order to but Objective-C punishes the performance of that code in order to
reserve the language's reserve the language's
@@ -345,7 +345,7 @@ logic can go in one place.
Reserving that Reserving that
flexibility in the code is often good sense, and reserving it across flexibility in the code is often good sense, and reserving it across
API boundaries is good language design, but it's silly API boundaries is good language design, but it's silly
not actually not actually
Well-factored object-oriented code often contains a large number of Well-factored object-oriented code often contains a large number of
@@ -356,22 +356,22 @@ easier to later extend or maintain, but serve no current purpose.
In In
typical object-oriented code, many operations are split into several typical object-oriented code, many operations are split into several
small methods in order to improve code organization and reserve the small methods in order to improve code organization and reserve the
ability to ability to
Conscientious developers
Conscientious developers
runtime calls runtime calls
cached-offset calculation for the ivar location. cached-offset calculation for the ivar location.
restriction, there's general acceptance that the restriction, there's general acceptance that the
is necessary to make ivar is necessary to make ivar
accesses not ridiculously expensive. Because of that, there's general accesses not ridiculously expensive. Because of that, there's general
@@ -414,25 +414,25 @@ not a valid object of the class
message send. This includes semantic annotations like ARC ownership message send. This includes semantic annotations like ARC ownership
conventions and the ``noreturn`` attribute. Otherwise, there are no conventions and the ``noreturn`` attribute. Otherwise, there are no
semantic restrictions on what any particular method can do. semantic restrictions on what any particular method can do.
signature of the method implementation's signature of the method implementation's
pr signature is not compatible with the signature at which the pr signature is not compatible with the signature at which the
method was invoked. method was invoked.
, in which case the runtime searches , in which case the runtime searches
the class hierarchy of the object, from most to least derived, the class hierarchy of the object, from most to least derived,
and calls the method and calls the method
In Objective-C, every object has a class and every class has a In Objective-C, every object has a class and every class has a
collection of methods. The high-level semantics are essentially collection of methods. The high-level semantics are essentially
those those
.. nonsense ReST .. nonsense ReST
class is essentially a hashtable of selectors to class is essentially a hashtable of selectors to
We propose a new attribute, ``@public``, that can adorn any We propose a new attribute, ``@public``, that can adorn any
declaration not local to a function. For the purpose of standard declaration not local to a function. For the purpose of standard
library development, even just parsing this attribute without library development, even just parsing this attribute without
@@ -520,14 +520,14 @@ conformance is not also declared ``@public``.::
func g() func g()
} }
struct X : P { // OK, X is not @public, so neither is its struct X : P { // OK, X is not @public, so neither is its
func f() {} // conformance to P, and therefore f func f() {} // conformance to P, and therefore f
func g() {} // can be non-@public func g() {} // can be non-@public
} }
protocol P1 {} protocol P1 {}
@public struct Y : P1 {} // Y is @public so its @public struct Y : P1 {} // Y is @public so its
// conformance to P1 is, too. // conformance to P1 is, too.
@public @public
@@ -549,7 +549,7 @@ A Related Naming Change
The existing ``@exported`` attribute for imports should be renamed The existing ``@exported`` attribute for imports should be renamed
``@public`` with no change in functionality. ``@public`` with no change in functionality.
Future Directions Future Directions
================= =================

View File

@@ -60,21 +60,21 @@ There are a few reasons this doesn't fly in C:
NSAlignMaxYInward = 1ULL << 3, NSAlignMaxYInward = 1ULL << 3,
NSAlignWidthInward = 1ULL << 4, NSAlignWidthInward = 1ULL << 4,
NSAlignHeightInward = 1ULL << 5, NSAlignHeightInward = 1ULL << 5,
NSAlignMinXOutward = 1ULL << 8, NSAlignMinXOutward = 1ULL << 8,
NSAlignMinYOutward = 1ULL << 9, NSAlignMinYOutward = 1ULL << 9,
NSAlignMaxXOutward = 1ULL << 10, NSAlignMaxXOutward = 1ULL << 10,
NSAlignMaxYOutward = 1ULL << 11, NSAlignMaxYOutward = 1ULL << 11,
NSAlignWidthOutward = 1ULL << 12, NSAlignWidthOutward = 1ULL << 12,
NSAlignHeightOutward = 1ULL << 13, NSAlignHeightOutward = 1ULL << 13,
NSAlignMinXNearest = 1ULL << 16, NSAlignMinXNearest = 1ULL << 16,
NSAlignMinYNearest = 1ULL << 17, NSAlignMinYNearest = 1ULL << 17,
NSAlignMaxXNearest = 1ULL << 18, NSAlignMaxXNearest = 1ULL << 18,
NSAlignMaxYNearest = 1ULL << 19, NSAlignMaxYNearest = 1ULL << 19,
NSAlignWidthNearest = 1ULL << 20, NSAlignWidthNearest = 1ULL << 20,
NSAlignHeightNearest = 1ULL << 21, NSAlignHeightNearest = 1ULL << 21,
NSAlignRectFlipped = 1ULL << 63, // pass this if the rect is in a flipped coordinate system. This allows 0.5 to be treated in a visually consistent way. NSAlignRectFlipped = 1ULL << 63, // pass this if the rect is in a flipped coordinate system. This allows 0.5 to be treated in a visually consistent way.
// convenience combinations // convenience combinations
@@ -264,7 +264,7 @@ bitwise operations can be applied to them.
// Swift, under this proposal // Swift, under this proposal
struct MyOptions : OptionSet { struct MyOptions : OptionSet {
var Foo, Bar, Bas : Bool = false var Foo, Bar, Bas : Bool = false
static func Foobar() -> MyOptions { static func Foobar() -> MyOptions {
return MyOptions(Foo: true, Bar: true) return MyOptions(Foo: true, Bar: true)
} }
@@ -273,7 +273,7 @@ bitwise operations can be applied to them.
var x: MyOptions = .Foobar() | MyOptions(Bas: true) var x: MyOptions = .Foobar() | MyOptions(Bas: true)
This nonuniformity could potentially be addressed by introducing additional This nonuniformity could potentially be addressed by introducing additional
implicit decls, such as adding implicit static properties corresponding to each implicit decls, such as adding implicit static properties corresponding to each
individual option:: individual option::
// Swift // Swift

View File

@@ -1,4 +1,4 @@
This directory contains proposals in various states. Note that we're This directory contains proposals in various states. Note that we're
not committed to making any of the changes in these proposals, and we not committed to making any of the changes in these proposals, and we
may have also decided they are a bad idea. Until one of these gets may have also decided they are a bad idea. Until one of these gets
pulled into the main docs directory, assume they aren't going to happen. pulled into the main docs directory, assume they aren't going to happen.

View File

@@ -91,7 +91,7 @@ It defines typestates with syntax that looks like it is defining types::
state OpenFile case of File = { state OpenFile case of File = {
val filePtr; val filePtr;
method read() { ... } method read() { ... }
method close() { this <- ClosedFile; } method close() { this <- ClosedFile; }
} }

View File

@@ -262,7 +262,7 @@ linked list::
class Node { class Node {
constructor(Int) { next = this; prev = this } constructor(Int) { next = this; prev = this }
// link two circular lists into one big cycle. // link two circular lists into one big cycle.
func join(_ otherNode : Node) -> () { ... } func join(_ otherNode : Node) -> () { ... }
@@ -274,8 +274,8 @@ We can measure the length of a cycle in these nodes as follows::
cycle_length(someNode, (x: [inout] Node){ x = x.next }) cycle_length(someNode, (x: [inout] Node){ x = x.next })
This is why so many generic algorithms seem to work on both This is why so many generic algorithms seem to work on both
``class``\ es and non-``class``\ es: ``class`` *identities* ``class``\ es and non-``class``\ es: ``class`` *identities*
work just fine as values. work just fine as values.
The Role of Moves The Role of Moves
@@ -333,7 +333,7 @@ How to Build an Interesting Type with Value Semantics
===================================================== =====================================================
Suppose we want to build a variable-sized data structure ``X`` with Suppose we want to build a variable-sized data structure ``X`` with
(mutable) value semantics? How do we do it? (mutable) value semantics? How do we do it?
If we make ``X` a ``class``, we automatically get reference semantics, so If we make ``X` a ``class``, we automatically get reference semantics, so
its value must be copied before each mutation, which is tedious and its value must be copied before each mutation, which is tedious and

View File

@@ -7,7 +7,7 @@ Swift Memory and Concurrency Model
================================== ==================================
.. warning:: This is a very early design document discussing the features of .. warning:: This is a very early design document discussing the features of
a possible Swift concurrency model. It should not be taken as a plan of a possible Swift concurrency model. It should not be taken as a plan of
record. record.
The goal of this writeup is to provide a safe and efficient way to model, The goal of this writeup is to provide a safe and efficient way to model,
@@ -118,14 +118,14 @@ definition. These kinds are:
func do_mandelbrot(_ x : float, y : float) -> int { func do_mandelbrot(_ x : float, y : float) -> int {
// details elided // details elided
} }
actor MandelbrotCalculator { actor MandelbrotCalculator {
func compute(_ x : float, y : float, Driver D) { func compute(_ x : float, y : float, Driver D) {
var num_iters = do_mandelbrot(x, y) var num_iters = do_mandelbrot(x, y)
D.collect_point(x, y, num_iters) D.collect_point(x, y, num_iters)
} }
} }
actor Driver { actor Driver {
var result : image; // result and numpoints are mutable per-actor data. var result : image; // result and numpoints are mutable per-actor data.
var numpoints : int; var numpoints : int;
@@ -140,7 +140,7 @@ definition. These kinds are:
} }
} }
} }
func collect_point(_ x : float, y : float, num_iters : int) { func collect_point(_ x : float, y : float, num_iters : int) {
result.setPoint(x, y, Color(num_iters, num_iters, num_iters)) result.setPoint(x, y, Color(num_iters, num_iters, num_iters))
if (--numpoints == 0) if (--numpoints == 0)
@@ -310,7 +310,7 @@ to access the ivar. Silly example::
var title : string; // string is an immutable by-ref type. var title : string; // string is an immutable by-ref type.
... ...
} }
... ...
var x = new Window; var x = new Window;
print(x.title) // ok, all stores will be atomic, an (recursively) immutable data is valid in all actors, so this is fine to load. print(x.title) // ok, all stores will be atomic, an (recursively) immutable data is valid in all actors, so this is fine to load.

View File

@@ -9,7 +9,7 @@ Swift Program Structure and Compilation Model
============================================= =============================================
.. warning:: This is a very early design document discussing the features of .. warning:: This is a very early design document discussing the features of
a Swift build model and modules system. It should not be taken as a plan of a Swift build model and modules system. It should not be taken as a plan of
record. record.
Commentary Commentary

View File

@@ -1,4 +1,4 @@
:orphan: :orphan:
Unified Function Syntax via Selector Splitting Unified Function Syntax via Selector Splitting
============================================== ==============================================
@@ -19,7 +19,7 @@ as well as what its various arguments are. For example,
- (void)moveRowAtIndex:(NSInteger)oldIndex toIndex:(NSInteger)newIndex; - (void)moveRowAtIndex:(NSInteger)oldIndex toIndex:(NSInteger)newIndex;
Note that there are three pieces of information in the selector Note that there are three pieces of information in the selector
``moveRowAtIndex:toIndex:``: ``moveRowAtIndex:toIndex:``:
1. What the method is doing ("moving a row"). 1. What the method is doing ("moving a row").
2. What the first argument is ("the index of the row we're moving"). 2. What the first argument is ("the index of the row we're moving").
@@ -151,7 +151,7 @@ To refer to the complete method name, place the method name in
backticks, as in this reference to an optional method in a delegate:: backticks, as in this reference to an optional method in a delegate::
if let method = delegate.`tableView(_:viewForTableColumn:row:)` { if let method = delegate.`tableView(_:viewForTableColumn:row:)` {
// ... // ...
} }
Initializers Initializers
@@ -230,7 +230,7 @@ Optionality and Ordering of Keyword Arguments
A number of programming languages have keyword arguments in one form A number of programming languages have keyword arguments in one form
or another, including Ada, C#, Fortran 95, Lua, OCaml, or another, including Ada, C#, Fortran 95, Lua, OCaml,
Perl 6, Python, and Ruby. Objective-C and Smalltalk's use of selectors Perl 6, Python, and Ruby. Objective-C and Smalltalk's use of selectors
is roughly equivalent, in the sense that the arguments get names. is roughly equivalent, in the sense that the arguments get names.
The languages with keyword arguments (but not Objective-C and The languages with keyword arguments (but not Objective-C and
Smalltalk) all allow re-ordering of Smalltalk) all allow re-ordering of
arguments at the call site, and many allow one to arguments at the call site, and many allow one to

View File

@@ -41,7 +41,7 @@ guarantees. Many ``NSArray`` implementations are lazy,
such as those over KVO properties or Core Data aggregates, and such as those over KVO properties or Core Data aggregates, and
transforming them to concrete ``Array``\ s would have unintended semantic transforming them to concrete ``Array``\ s would have unintended semantic
effects. And on the other side, the overhead of having to accommodate an effects. And on the other side, the overhead of having to accommodate an
arbitrary ``NSArray`` implementation inside ``Array`` destroys ``Array`` arbitrary ``NSArray`` implementation inside ``Array`` destroys ``Array``
as a simple, high-performance container. Attempting to bridge these two types as a simple, high-performance container. Attempting to bridge these two types
will result in an unattractive compromise to both sides, weakening the will result in an unattractive compromise to both sides, weakening the
algorithmic guarantees of Array while forgoing the full flexibility of algorithmic guarantees of Array while forgoing the full flexibility of
@@ -168,7 +168,7 @@ naturally with generic Swift containers. Assuming we had support for
} }
} }
``NSArray`` has reference semantics in ObjC, which is a mismatch with ``NSArray`` has reference semantics in ObjC, which is a mismatch with
Swift's value semantics, but because ``NSArray`` is a value class, this is Swift's value semantics, but because ``NSArray`` is a value class, this is
probably not a problem in practice, because it will be ``copy``-ed as probably not a problem in practice, because it will be ``copy``-ed as
necessary as a best practice. There also needs to be a special case for bridging necessary as a best practice. There also needs to be a special case for bridging

View File

@@ -33,10 +33,10 @@ of its subclasses. This leads to a soundness problem:
@interface Subclass : Superclass @interface Subclass : Superclass
- (void)subclassMethod - (void)subclassMethod
@end @end
@implementation Subclass : Superclass @implementation Subclass : Superclass
char\* **name**\ ; // never initialized char\* **name**\ ; // never initialized
- (void)print { printf(\ **name**\ ); } // oops - (void)print { printf(\ **name**\ ); } // oops
@end @end
@@ -150,7 +150,7 @@ Here are the proposed rules:
It allows superclasses to break their subclasses by adding It allows superclasses to break their subclasses by adding
``init`` methods. ``init`` methods.
Summary Summary
======= =======

View File

@@ -34,7 +34,7 @@ one has to engage in some kind of wrapping and forwarding::
struct MyClassVal { struct MyClassVal {
var [clone] value : MyClass var [clone] value : MyClass
constructor(x : A, y : B) { constructor(x : A, y : B) {
value = new MyClass(x, y) value = new MyClass(x, y)
} }
@@ -110,12 +110,12 @@ all ordinary instance variables, and a ``clone()`` of all instance
variables marked ``[clone]``:: variables marked ``[clone]``::
class FooValue : Clonable {} class FooValue : Clonable {}
class Bar {} class Bar {}
class Foo : Clonable { class Foo : Clonable {
var count : Int var count : Int
var [clone] myValue : FooValue var [clone] myValue : FooValue
var somethingIJustReferTo : Bar var somethingIJustReferTo : Bar
} }
@@ -130,7 +130,7 @@ initialization, assignment, or function argument passing), even as
part of a larger ``struct``, its ``[clone]`` member is ``clone()``\ d. part of a larger ``struct``, its ``[clone]`` member is ``clone()``\ d.
Because ``Foo`` itself has a ``[clone]`` member, that is ``clone()``\ d Because ``Foo`` itself has a ``[clone]`` member, that is ``clone()``\ d
also. Therefore copying a ``Baz`` object ``clone()``\ s a ``Foo`` and also. Therefore copying a ``Baz`` object ``clone()``\ s a ``Foo`` and
``clone()``\ ing a ``Foo`` ``clone()``\ s a ``FooValue``. ``clone()``\ ing a ``Foo`` ``clone()``\ s a ``FooValue``.
All ``struct``\ s are ``Clonable`` by default, with ``clone()`` delivering All ``struct``\ s are ``Clonable`` by default, with ``clone()`` delivering
ordinary copy semantics. Therefore, :: ordinary copy semantics. Therefore, ::

View File

@@ -69,10 +69,10 @@ subclass whose own ``init`` has not completed. A contrived example::
} }
-(NSString *)description { -(NSString *)description {
return self->title; return self->title;
} }
@end @end
During the second phase of initialization, A's ``-init`` method During the second phase of initialization, A's ``-init`` method
invokes the ``-description`` method, which ends up in B's invokes the ``-description`` method, which ends up in B's
``-description``. Here, ``title`` will be ``nil`` even though the ``-description``. Here, ``title`` will be ``nil`` even though the
@@ -88,7 +88,7 @@ A's ``-init`` sends the ``description`` message, it would invoke A's
``-description``. This is somewhat safer than two-phase ``-description``. This is somewhat safer than two-phase
initialization, because the programmer does not have to deal with the initialization, because the programmer does not have to deal with the
possibility of executing one's methods before the initialization of possibility of executing one's methods before the initialization of
one's instance variables have completed. It is also less flexible. one's instance variables have completed. It is also less flexible.
Designated Initializers Designated Initializers
~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
@@ -140,7 +140,7 @@ aforementioned "Concepts in Objective-C Programming" document)::
The first initializer is the designated initializer, which directly The first initializer is the designated initializer, which directly
initializes the instance variables from its parameters. The second two initializes the instance variables from its parameters. The second two
initializers are secondary initializers, which delegate to other initializers are secondary initializers, which delegate to other
initializers, eventually reaching the designated initializer. initializers, eventually reaching the designated initializer.
A subclass should override all of its superclass's designated A subclass should override all of its superclass's designated
initializers, but it need not override the secondary initializers. We initializers, but it need not override the secondary initializers. We
@@ -156,8 +156,8 @@ instance variable::
@implementation PackagedTask @implementation PackagedTask
- (id)initWithTitle:(NSString *)aTitle date:(NSDate *)aDate { - (id)initWithTitle:(NSString *)aTitle date:(NSDate *)aDate {
return [self initWithTitle:aTitle return [self initWithTitle:aTitle
date:aDate date:aDate
queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)]; queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
} }
@@ -282,7 +282,7 @@ definite initialization analysis. For example, the Swift
class PackagedTask : Task { class PackagedTask : Task {
var queue : dispatch_queue_t var queue : dispatch_queue_t
constructor(title : String, date : NSDate = NSDate(), constructor(title : String, date : NSDate = NSDate(),
queue : dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { queue : dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
super.constructor(title:title, date:date) super.constructor(title:title, date:date)
self.queue = queue self.queue = queue
@@ -335,7 +335,7 @@ This model complicates constructor inheritance considerably. A
secondary initializer in Objective-C works by delegating to secondary initializer in Objective-C works by delegating to
(eventually) a designated initializer, which is overridden by the (eventually) a designated initializer, which is overridden by the
subclass. Following the C++/Java/C# precedent breaks this pattern, subclass. Following the C++/Java/C# precedent breaks this pattern,
because the overriding designated initializer will never be invoked. because the overriding designated initializer will never be invoked.
Constructor Inheritance Constructor Inheritance
~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
@@ -359,7 +359,7 @@ presence of class extensions.
One potential approach is to bring Objective-C's notion of designated One potential approach is to bring Objective-C's notion of designated
and secondary initializers into Swift. A "designated" constructor is and secondary initializers into Swift. A "designated" constructor is
responsible for calling the superclass constructor and then responsible for calling the superclass constructor and then
initializing its own instance variables. initializing its own instance variables.
A "secondary" constructor can be written in the class definition or an A "secondary" constructor can be written in the class definition or an
extension. A secondary constructor must delegate to another extension. A secondary constructor must delegate to another
@@ -374,7 +374,7 @@ override all of the designated constructors of their
superclass. Therefore, we require that designated constructors be superclass. Therefore, we require that designated constructors be
written within the class definition [#]_. Secondary constructors can written within the class definition [#]_. Secondary constructors can
be written in either the class definition or an be written in either the class definition or an
extension. extension.
In Objective-C, classes generally only have one or two designated In Objective-C, classes generally only have one or two designated
initializers, so having to override them doesn't seem too onerous. If initializers, so having to override them doesn't seem too onerous. If
@@ -399,7 +399,7 @@ constructors in class extensions.
Class Clusters and Assignment to Self Class Clusters and Assignment to Self
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TBD. TBD.
Objective-C Interoperability Objective-C Interoperability
@@ -446,7 +446,7 @@ selector for the Objective-C entry point is formed by:
For example, given the Swift constructor:: For example, given the Swift constructor::
constructor withTitle(aTitle : String) date(aDate : NSDate) { constructor withTitle(aTitle : String) date(aDate : NSDate) {
// ... // ...
} }
@@ -504,19 +504,19 @@ Nil and Re-assigned Self
An Objective-C initializer can return a self pointer that is different An Objective-C initializer can return a self pointer that is different
than the one it was called with. When this happens, it is either due than the one it was called with. When this happens, it is either due
to an error (in which case it will return nil) or because the object to an error (in which case it will return nil) or because the object
is being substituted for another object. is being substituted for another object.
In both cases, we are left with a partially-constructed object that In both cases, we are left with a partially-constructed object that
then needs to be destroyed, even though its instance variables may not then needs to be destroyed, even though its instance variables may not
yet have been initialized. This is also a problem for Objective-C, yet have been initialized. This is also a problem for Objective-C,
which makes returning anything other than the original ''self'' which makes returning anything other than the original ''self''
brittle. brittle.
In Swift, we will have a separate error-handling mechanism to report In Swift, we will have a separate error-handling mechanism to report
failures. A Swift constructor will not be allowed to return a value; failures. A Swift constructor will not be allowed to return a value;
rather, it should raise an error if an error occurs, and that error rather, it should raise an error if an error occurs, and that error
will be propagated however we eventually decide to implement error will be propagated however we eventually decide to implement error
propagation. propagation.
Object substitution is the more complicated feature. I propose that we Object substitution is the more complicated feature. I propose that we
do not initially support object substitution within Swift do not initially support object substitution within Swift

View File

@@ -473,7 +473,7 @@ __ https://doc.rust-lang.org/book/box-syntax-and-patterns.html
============================================== ==============================================
It is *possible* to build a struct with reference semantics. For It is *possible* to build a struct with reference semantics. For
example, example,
..parsed-literal:: ..parsed-literal::
@@ -556,7 +556,7 @@ example:
* ``var`` is only one character different from ``val``. Is that too * ``var`` is only one character different from ``val``. Is that too
confusable? Syntax highlighting can help, but it might not be enough. confusable? Syntax highlighting can help, but it might not be enough.
* What about ``let`` as a replacement for ``var``? * What about ``let`` as a replacement for ``var``?
There's always the dreaded ``auto``. There's always the dreaded ``auto``.
* Should we drop ``let``\ /``var``\ /``auto`` for ivars, because it * Should we drop ``let``\ /``var``\ /``auto`` for ivars, because it

View File

@@ -21,9 +21,9 @@ function onload_handler() {
function generateTOC() { function generateTOC() {
var navbar = document.getElementById('nav'); var navbar = document.getElementById('nav');
if (!navbar) { return; } if (!navbar) { return; }
var toc_items = []; var toc_items = [];
var i; var i;
for (i = 0; i < navbar.parentNode.childNodes.length; i++) { for (i = 0; i < navbar.parentNode.childNodes.length; i++) {
var node = navbar.parentNode.childNodes[i]; var node = navbar.parentNode.childNodes[i];
@@ -33,16 +33,16 @@ function generateTOC() {
} }
var text = godocs_nodeToText(node); var text = godocs_nodeToText(node);
if (!text) { continue; } if (!text) { continue; }
var textNode = document.createTextNode(text); var textNode = document.createTextNode(text);
var link = document.createElement('a'); var link = document.createElement('a');
link.href = '#' + node.id; link.href = '#' + node.id;
link.appendChild(textNode); link.appendChild(textNode);
// Then create the item itself // Then create the item itself
var item = document.createElement('dt'); var item = document.createElement('dt');
item.appendChild(link); item.appendChild(link);
toc_items.push(item); toc_items.push(item);
} }
@@ -52,53 +52,53 @@ function generateTOC() {
} }
var text = godocs_nodeToText(node); var text = godocs_nodeToText(node);
if (!text) { continue; } if (!text) { continue; }
var textNode = document.createTextNode(text); var textNode = document.createTextNode(text);
var link = document.createElement('a'); var link = document.createElement('a');
link.href = '#' + node.id; link.href = '#' + node.id;
link.appendChild(textNode); link.appendChild(textNode);
// Then create the item itself // Then create the item itself
var item = document.createElement('dd'); var item = document.createElement('dd');
item.appendChild(link); item.appendChild(link);
toc_items.push(item); toc_items.push(item);
} }
} }
if (!toc_items.length) { return; } if (!toc_items.length) { return; }
var dl1 = document.createElement('dl'); var dl1 = document.createElement('dl');
var dl2 = document.createElement('dl'); var dl2 = document.createElement('dl');
var split_index = (toc_items.length / 2) + 1; var split_index = (toc_items.length / 2) + 1;
if (split_index < 8) { if (split_index < 8) {
split_index = toc_items.length; split_index = toc_items.length;
} }
for (i = 0; i < split_index; i++) { for (i = 0; i < split_index; i++) {
dl1.appendChild(toc_items[i]); dl1.appendChild(toc_items[i]);
} }
for (/* keep using i */; i < toc_items.length; i++) { for (/* keep using i */; i < toc_items.length; i++) {
dl2.appendChild(toc_items[i]); dl2.appendChild(toc_items[i]);
} }
var tocTable = document.createElement('table'); var tocTable = document.createElement('table');
navbar.appendChild(tocTable); navbar.appendChild(tocTable);
tocTable.className = 'unruled'; tocTable.className = 'unruled';
var tocBody = document.createElement('tbody'); var tocBody = document.createElement('tbody');
tocTable.appendChild(tocBody); tocTable.appendChild(tocBody);
var tocRow = document.createElement('tr'); var tocRow = document.createElement('tr');
tocBody.appendChild(tocRow); tocBody.appendChild(tocRow);
// 1st column // 1st column
var tocCell = document.createElement('td'); var tocCell = document.createElement('td');
tocCell.className = 'first'; tocCell.className = 'first';
tocRow.appendChild(tocCell); tocRow.appendChild(tocCell);
tocCell.appendChild(dl1); tocCell.appendChild(dl1);
// 2nd column // 2nd column
tocCell = document.createElement('td'); tocCell = document.createElement('td');
tocRow.appendChild(tocCell); tocRow.appendChild(tocCell);
@@ -110,7 +110,7 @@ function generateTOC() {
*/ */
function godocs_nodeToText(node) { function godocs_nodeToText(node) {
var TEXT_NODE = 3; // Defined in Mozilla but not MSIE :( var TEXT_NODE = 3; // Defined in Mozilla but not MSIE :(
var text = ''; var text = '';
for (var j = 0; j != node.childNodes.length; j++) { for (var j = 0; j != node.childNodes.length; j++) {
var child = node.childNodes[j]; var child = node.childNodes[j];
@@ -135,11 +135,11 @@ function addTopLinks() {
if (!top) { if (!top) {
document.body.id = 'top'; document.body.id = 'top';
} }
if (!document.getElementsByTagName) return; // no browser support if (!document.getElementsByTagName) return; // no browser support
var headers = document.getElementsByTagName('h2'); var headers = document.getElementsByTagName('h2');
for (var i = 0; i < headers.length; i++) { for (var i = 0; i < headers.length; i++) {
var span = document.createElement('span'); var span = document.createElement('span');
span.className = 'navtop'; span.className = 'navtop';

View File

@@ -73,7 +73,7 @@ METADATAKIND(ExistentialMetatype, 15)
/// A foreign class, such as a Core Foundation class. /// A foreign class, such as a Core Foundation class.
METADATAKIND(ForeignClass, 16) METADATAKIND(ForeignClass, 16)
/// A heap-allocated local variable using statically-generated metadata. /// A heap-allocated local variable using statically-generated metadata.
METADATAKIND(HeapLocalVariable, 64) METADATAKIND(HeapLocalVariable, 64)

View File

@@ -40,7 +40,7 @@ BUILTIN_CAST_OPERATION(BitCast , "bitcast", "n")
#undef BUILTIN_CAST_OPERATION #undef BUILTIN_CAST_OPERATION
/// Cast-or-bitcast operations have type T1 -> T2. /// Cast-or-bitcast operations have type T1 -> T2.
/// T1 and T2 may be the same size, unlike the corresponding true casts. /// T1 and T2 may be the same size, unlike the corresponding true casts.
#ifndef BUILTIN_CAST_OR_BITCAST_OPERATION #ifndef BUILTIN_CAST_OR_BITCAST_OPERATION
#define BUILTIN_CAST_OR_BITCAST_OPERATION(Id, Name, Attrs) BUILTIN(Id, Name, Attrs) #define BUILTIN_CAST_OR_BITCAST_OPERATION(Id, Name, Attrs) BUILTIN(Id, Name, Attrs)
@@ -77,7 +77,7 @@ BUILTIN_BINARY_OPERATION(FRem, "frem", "n", FloatOrVector)
BUILTIN_BINARY_OPERATION(Xor, "xor", "n", IntegerOrVector) BUILTIN_BINARY_OPERATION(Xor, "xor", "n", IntegerOrVector)
#undef BUILTIN_BINARY_OPERATION #undef BUILTIN_BINARY_OPERATION
/// These builtins are analogous the similarly named llvm intrinsics. The /// These builtins are analogous the similarly named llvm intrinsics. The
/// difference between the two is that these are not expected to overflow, /// difference between the two is that these are not expected to overflow,
/// so we should produce a compile time error if we can statically prove /// so we should produce a compile time error if we can statically prove
/// that they do. /// that they do.
@@ -151,7 +151,7 @@ BUILTIN_BINARY_PREDICATE(FCMP_UNO, "fcmp_uno", "n", FloatOrVector)
// BUILTIN_SIL_OPERATION - Operations that can be lowered to SIL instructions. // BUILTIN_SIL_OPERATION - Operations that can be lowered to SIL instructions.
// These have various types. // These have various types.
// Since these operations will be lowered to SIL Instructions, we do not // Since these operations will be lowered to SIL Instructions, we do not
// assign any attributes on them. // assign any attributes on them.
#ifndef BUILTIN_SIL_OPERATION #ifndef BUILTIN_SIL_OPERATION
#define BUILTIN_SIL_OPERATION(Id, Name, Overload) BUILTIN(Id, Name, "") #define BUILTIN_SIL_OPERATION(Id, Name, Overload) BUILTIN(Id, Name, "")
@@ -371,7 +371,7 @@ BUILTIN_RUNTIME_CALL(IsOptionalType, "isOptional", "")
#define BUILTIN_MISC_OPERATION(Id, Name, Attrs, Overload) \ #define BUILTIN_MISC_OPERATION(Id, Name, Attrs, Overload) \
BUILTIN(Id, Name, Attrs) BUILTIN(Id, Name, Attrs)
#endif #endif
/// Sizeof has type T.Type -> Int /// Sizeof has type T.Type -> Int
BUILTIN_MISC_OPERATION(Sizeof, "sizeof", "n", Special) BUILTIN_MISC_OPERATION(Sizeof, "sizeof", "n", Special)
@@ -423,10 +423,10 @@ BUILTIN_MISC_OPERATION(AssertConf, "assert_configuration", "n", Special)
/// Special truncation builtins that check for sign and overflow errors. These /// Special truncation builtins that check for sign and overflow errors. These
/// take an integer as an input and return a tuple of the truncated result and /// take an integer as an input and return a tuple of the truncated result and
/// an error bit. The name of each builtin is extended with the "from" /// an error bit. The name of each builtin is extended with the "from"
/// (sign-agnostic) builtin integer type and the "to" integer type. /// (sign-agnostic) builtin integer type and the "to" integer type.
/// We require the source type size to be larger than the destination type size /// We require the source type size to be larger than the destination type size
/// (number of bits). /// (number of bits).
BUILTIN_MISC_OPERATION(UToSCheckedTrunc, "u_to_s_checked_trunc", "n", Special) BUILTIN_MISC_OPERATION(UToSCheckedTrunc, "u_to_s_checked_trunc", "n", Special)
BUILTIN_MISC_OPERATION(SToSCheckedTrunc, "s_to_s_checked_trunc", "n", Special) BUILTIN_MISC_OPERATION(SToSCheckedTrunc, "s_to_s_checked_trunc", "n", Special)
@@ -434,11 +434,11 @@ BUILTIN_MISC_OPERATION(SToUCheckedTrunc, "s_to_u_checked_trunc", "n", Special)
BUILTIN_MISC_OPERATION(UToUCheckedTrunc, "u_to_u_checked_trunc", "n", Special) BUILTIN_MISC_OPERATION(UToUCheckedTrunc, "u_to_u_checked_trunc", "n", Special)
/// Checked conversions for signed <-> unsigned integers of the same size. /// Checked conversions for signed <-> unsigned integers of the same size.
/// Returns a tuple containing the conversion result as well as /// Returns a tuple containing the conversion result as well as
/// the sign error / overflow bit. /// the sign error / overflow bit.
BUILTIN_MISC_OPERATION(SUCheckedConversion, BUILTIN_MISC_OPERATION(SUCheckedConversion,
"s_to_u_checked_conversion", "n", Special) "s_to_u_checked_conversion", "n", Special)
BUILTIN_MISC_OPERATION(USCheckedConversion, BUILTIN_MISC_OPERATION(USCheckedConversion,
"u_to_s_checked_conversion", "n", Special) "u_to_s_checked_conversion", "n", Special)
/// IntToFPWithOverflow has type (Integer) -> Float /// IntToFPWithOverflow has type (Integer) -> Float

View File

@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// //
// This file defines diagnostics for the Clang importer. // This file defines diagnostics for the Clang importer.
// Each diagnostic is described using one of three kinds (error, warning, or // Each diagnostic is described using one of three kinds (error, warning, or
// note) along with a unique identifier, category, options, and text, and is // note) along with a unique identifier, category, options, and text, and is
// followed by a signature describing the diagnostic argument kinds. // followed by a signature describing the diagnostic argument kinds.
// //

View File

@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// //
// This file defines diagnostics that can be emitted across the whole compiler. // This file defines diagnostics that can be emitted across the whole compiler.
// Each diagnostic is described using one of three kinds (error, warning, or // Each diagnostic is described using one of three kinds (error, warning, or
// note) along with a unique identifier, category, options, and text, and is // note) along with a unique identifier, category, options, and text, and is
// followed by a signature describing the diagnostic argument kinds. // followed by a signature describing the diagnostic argument kinds.
// //
@@ -49,7 +49,7 @@ ERROR(error_no_group_info,none,
"no group info found for file: '%0'", (StringRef)) "no group info found for file: '%0'", (StringRef))
NOTE(previous_decldef,none, NOTE(previous_decldef,none,
"previous %select{declaration|definition}0 of %1 is here", "previous %select{declaration|definition}0 of %1 is here",
(bool, Identifier)) (bool, Identifier))

View File

@@ -12,7 +12,7 @@
// //
// This file defines driver-only diagnostics emitted in processing // This file defines driver-only diagnostics emitted in processing
// command-line arguments and setting up compilation. // command-line arguments and setting up compilation.
// Each diagnostic is described using one of three kinds (error, warning, or // Each diagnostic is described using one of three kinds (error, warning, or
// note) along with a unique identifier, category, options, and text, and is // note) along with a unique identifier, category, options, and text, and is
// followed by a signature describing the diagnostic argument kinds. // followed by a signature describing the diagnostic argument kinds.
// //

View File

@@ -12,7 +12,7 @@
// //
// This file defines diagnostics emitted in processing command-line arguments // This file defines diagnostics emitted in processing command-line arguments
// and setting up compilation. // and setting up compilation.
// Each diagnostic is described using one of three kinds (error, warning, or // Each diagnostic is described using one of three kinds (error, warning, or
// note) along with a unique identifier, category, options, and text, and is // note) along with a unique identifier, category, options, and text, and is
// followed by a signature describing the diagnostic argument kinds. // followed by a signature describing the diagnostic argument kinds.
// //

View File

@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// //
// This file defines diagnostics emitted during IR generation. // This file defines diagnostics emitted during IR generation.
// Each diagnostic is described using one of three kinds (error, warning, or // Each diagnostic is described using one of three kinds (error, warning, or
// note) along with a unique identifier, category, options, and text, and is // note) along with a unique identifier, category, options, and text, and is
// followed by a signature describing the diagnostic argument kinds. // followed by a signature describing the diagnostic argument kinds.
// //

View File

@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// //
// This file defines diagnostics emitted during lexing and parsing. // This file defines diagnostics emitted during lexing and parsing.
// Each diagnostic is described using one of three kinds (error, warning, or // Each diagnostic is described using one of three kinds (error, warning, or
// note) along with a unique identifier, category, options, and text, and is // note) along with a unique identifier, category, options, and text, and is
// followed by a signature describing the diagnostic argument kinds. // followed by a signature describing the diagnostic argument kinds.
// //
@@ -163,7 +163,7 @@ ERROR(expected_identifier_in_decl,none,
ERROR(expected_identifier_after_case_comma,none, ERROR(expected_identifier_after_case_comma,none,
"expected identifier after comma in enum 'case' declaration", ()) "expected identifier after comma in enum 'case' declaration", ())
ERROR(decl_redefinition,none, ERROR(decl_redefinition,none,
"%select{declaration|definition}0 conflicts with previous value", "%select{declaration|definition}0 conflicts with previous value",
(bool)) (bool))
ERROR(let_cannot_be_computed_property,none, ERROR(let_cannot_be_computed_property,none,
"'let' declarations cannot be computed properties", ()) "'let' declarations cannot be computed properties", ())

View File

@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// //
// This file defines diagnostics emitted during SIL (dataflow) analysis. // This file defines diagnostics emitted during SIL (dataflow) analysis.
// Each diagnostic is described using one of three kinds (error, warning, or // Each diagnostic is described using one of three kinds (error, warning, or
// note) along with a unique identifier, category, options, and text, and is // note) along with a unique identifier, category, options, and text, and is
// followed by a signature describing the diagnostic argument kinds. // followed by a signature describing the diagnostic argument kinds.
// //

View File

@@ -12,7 +12,7 @@
// //
// This file defines diagnostics emitted during semantic analysis and type // This file defines diagnostics emitted during semantic analysis and type
// checking. // checking.
// Each diagnostic is described using one of three kinds (error, warning, or // Each diagnostic is described using one of three kinds (error, warning, or
// note) along with a unique identifier, category, options, and text, and is // note) along with a unique identifier, category, options, and text, and is
// followed by a signature describing the diagnostic argument kinds. // followed by a signature describing the diagnostic argument kinds.
// //
@@ -1036,7 +1036,7 @@ ERROR(optional_attribute_non_protocol,none,
ERROR(optional_attribute_non_objc_protocol,none, ERROR(optional_attribute_non_objc_protocol,none,
"'optional' can only be applied to members of an @objc protocol", ()) "'optional' can only be applied to members of an @objc protocol", ())
ERROR(optional_attribute_missing_explicit_objc,none, ERROR(optional_attribute_missing_explicit_objc,none,
"'optional' requirements are an Objective-C compatibility feature; add '@objc'", "'optional' requirements are an Objective-C compatibility feature; add '@objc'",
()) ())
ERROR(optional_attribute_initializer,none, ERROR(optional_attribute_initializer,none,
"'optional' cannot be applied to an initializer", ()) "'optional' cannot be applied to an initializer", ())
@@ -1048,11 +1048,11 @@ ERROR(missing_in_class_init_1,none,
"@NSManaged}1", (Identifier, bool)) "@NSManaged}1", (Identifier, bool))
ERROR(missing_in_class_init_2,none, ERROR(missing_in_class_init_2,none,
"stored properties %0 and %1 require initial values%select{| or should " "stored properties %0 and %1 require initial values%select{| or should "
"be @NSManaged}2", "be @NSManaged}2",
(Identifier, Identifier, bool)) (Identifier, Identifier, bool))
ERROR(missing_in_class_init_3plus,none, ERROR(missing_in_class_init_3plus,none,
"stored properties %0, %1, %select{and %2|%2, and others}3 " "stored properties %0, %1, %select{and %2|%2, and others}3 "
"require initial values%select{| or should be @NSManaged}4", "require initial values%select{| or should be @NSManaged}4",
(Identifier, Identifier, Identifier, bool, bool)) (Identifier, Identifier, Identifier, bool, bool))
NOTE(requires_stored_property_inits_here,none, NOTE(requires_stored_property_inits_here,none,
"%select{superclass|class}1 %0 requires all stored properties to have " "%select{superclass|class}1 %0 requires all stored properties to have "
@@ -1297,12 +1297,12 @@ ERROR(witness_argument_name_mismatch,none,
"required by protocol %2 (%3)", (bool, DeclName, Type, DeclName)) "required by protocol %2 (%3)", (bool, DeclName, Type, DeclName))
ERROR(witness_initializer_not_required,none, ERROR(witness_initializer_not_required,none,
"initializer requirement %0 can only be satisfied by a `required` " "initializer requirement %0 can only be satisfied by a `required` "
"initializer in%select{| the definition of}1 non-final class %2", "initializer in%select{| the definition of}1 non-final class %2",
(DeclName, bool, Type)) (DeclName, bool, Type))
ERROR(witness_initializer_failability,none, ERROR(witness_initializer_failability,none,
"non-failable initializer requirement %0" "non-failable initializer requirement %0"
"%select{| in Objective-C protocol}1 cannot be satisfied by a " "%select{| in Objective-C protocol}1 cannot be satisfied by a "
"failable initializer ('init%select{?|!}1')", "failable initializer ('init%select{?|!}1')",
(DeclName, bool)) (DeclName, bool))
ERROR(witness_self_non_subtype,none, ERROR(witness_self_non_subtype,none,
"protocol %0 requirement %1 cannot be satisfied by a non-final class " "protocol %0 requirement %1 cannot be satisfied by a non-final class "
@@ -1502,7 +1502,7 @@ ERROR(circular_protocol_def,none,
"circular protocol inheritance %0", (StringRef)) "circular protocol inheritance %0", (StringRef))
NOTE(protocol_here,none, NOTE(protocol_here,none,
"protocol %0 declared here", (Identifier)) "protocol %0 declared here", (Identifier))
ERROR(protocol_composition_not_protocol,none, ERROR(protocol_composition_not_protocol,none,
"non-protocol type %0 cannot be used within a protocol composition", (Type)) "non-protocol type %0 cannot be used within a protocol composition", (Type))
ERROR(objc_protocol_inherits_non_objc_protocol,none, ERROR(objc_protocol_inherits_non_objc_protocol,none,
"@objc protocol %0 cannot refine non-@objc protocol %1", (Type, Type)) "@objc protocol %0 cannot refine non-@objc protocol %1", (Type, Type))
@@ -2017,7 +2017,7 @@ NOTE(attr_ApplicationMain_script_here,none,
#undef SELECT_APPLICATION_MAIN #undef SELECT_APPLICATION_MAIN
#undef SELECT_APPLICATION_DELEGATE #undef SELECT_APPLICATION_DELEGATE
// lazy // lazy
ERROR(lazy_not_on_let,none, ERROR(lazy_not_on_let,none,
"'lazy' cannot be used on a let", ()) "'lazy' cannot be used on a let", ())
ERROR(lazy_not_on_computed,none, ERROR(lazy_not_on_computed,none,
@@ -2131,7 +2131,7 @@ ERROR(dynamic_construct_class,none,
"constructing an object of class type %0 with a metatype value must use " "constructing an object of class type %0 with a metatype value must use "
"a 'required' initializer", (Type)) "a 'required' initializer", (Type))
NOTE(note_nonrequired_initializer,none, NOTE(note_nonrequired_initializer,none,
"selected %select{non-required|implicit}0 initializer %1", "selected %select{non-required|implicit}0 initializer %1",
(bool, DeclName)) (bool, DeclName))
ERROR(construct_protocol_value,none, ERROR(construct_protocol_value,none,
"value of type %0 is a protocol; it cannot be instantiated", "value of type %0 is a protocol; it cannot be instantiated",
@@ -2818,7 +2818,7 @@ ERROR(sil_metatype_without_repr,none,
"metatypes in SIL must have @thin, @thick, or @objc_metatype attribute", "metatypes in SIL must have @thin, @thick, or @objc_metatype attribute",
()) ())
ERROR(sil_metatype_multiple_reprs,none, ERROR(sil_metatype_multiple_reprs,none,
"metatypes in SIL can only be one of @thin, @thick, or @objc_metatype", "metatypes in SIL can only be one of @thin, @thick, or @objc_metatype",
()) ())
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@@ -3230,7 +3230,7 @@ WARNING(variable_never_read, none,
(Identifier, unsigned)) (Identifier, unsigned))
WARNING(extraneous_default_args_in_call, none, WARNING(extraneous_default_args_in_call, none,
"call to %0 has extraneous arguments that could use defaults", "call to %0 has extraneous arguments that could use defaults",
(DeclName)) (DeclName))
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------

View File

@@ -24,7 +24,7 @@
/// This type is always canonical. The default behavior is TYPE(id, parent). /// This type is always canonical. The default behavior is TYPE(id, parent).
/// BUILTIN_TYPE(id, parent) /// BUILTIN_TYPE(id, parent)
/// This type is a builtin type. The default behavior is /// This type is a builtin type. The default behavior is
/// ALWAYS_CANONICAL_TYPE(id, parent). /// ALWAYS_CANONICAL_TYPE(id, parent).
/// SUGARED_TYPE(id, parent) /// SUGARED_TYPE(id, parent)

View File

@@ -230,7 +230,7 @@ def import_cf_types : Flag<["-"], "import-cf-types">,
def solver_memory_threshold : Separate<["-"], "solver-memory-threshold">, def solver_memory_threshold : Separate<["-"], "solver-memory-threshold">,
Flags<[FrontendOption, HelpHidden, DoesNotAffectIncrementalBuild]>, Flags<[FrontendOption, HelpHidden, DoesNotAffectIncrementalBuild]>,
HelpText<"Set the upper bound for memory consumption, in bytes, by the constraint solver">; HelpText<"Set the upper bound for memory consumption, in bytes, by the constraint solver">;
def disable_swift_bridge_attr : Flag<["-"], "disable-swift-bridge-attr">, def disable_swift_bridge_attr : Flag<["-"], "disable-swift-bridge-attr">,
Flags<[FrontendOption, HelpHidden]>, Flags<[FrontendOption, HelpHidden]>,

View File

@@ -25,7 +25,7 @@
/// PASS_RANGE(RANGE_ID, START, END) /// PASS_RANGE(RANGE_ID, START, END)
/// Pass IDs between PassKind::START and PassKind::END, inclusive, /// Pass IDs between PassKind::START and PassKind::END, inclusive,
/// fall within the set known as /// fall within the set known as
#ifndef PASS_RANGE #ifndef PASS_RANGE
#define PASS_RANGE(Id, First, Last) #define PASS_RANGE(Id, First, Last)
#endif #endif

View File

@@ -9,7 +9,7 @@
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// This file lists words that map to various parts of speech. // This file lists words that map to various parts of speech.
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#if !defined(PREPOSITION) && !defined(VERB) #if !defined(PREPOSITION) && !defined(VERB)

View File

@@ -185,7 +185,7 @@ bool Task::execute() {
if (Pid == 0) if (Pid == 0)
return true; return true;
#endif #endif
return false; return false;
} }

View File

@@ -136,7 +136,7 @@ MAP_STDLIB_TYPE("SInt", SignedInt, 32, "CInt", false, DoNothing)
// Dispatch types. // Dispatch types.
MAP_TYPE("dispatch_block_t", Block, 0, "Dispatch", "dispatch_block_t", MAP_TYPE("dispatch_block_t", Block, 0, "Dispatch", "dispatch_block_t",
true, DoNothing) true, DoNothing)
MAP_TYPE("__swift_shims_dispatch_block_t", Block, 0, "Dispatch", "_DispatchBlock", MAP_TYPE("__swift_shims_dispatch_block_t", Block, 0, "Dispatch", "_DispatchBlock",
true, DoNothing) true, DoNothing)
MAP_TYPE("__swift_shims_dispatch_data_t", ObjCId, 0, "Dispatch", "dispatch_data_t", MAP_TYPE("__swift_shims_dispatch_data_t", ObjCId, 0, "Dispatch", "dispatch_data_t",
true, DoNothing) true, DoNothing)

View File

@@ -7,6 +7,6 @@ set(ARC_SOURCES
ARC/GlobalARCSequenceDataflow.cpp ARC/GlobalARCSequenceDataflow.cpp
ARC/GlobalLoopARCSequenceDataflow.cpp ARC/GlobalLoopARCSequenceDataflow.cpp
ARC/RCStateTransition.cpp ARC/RCStateTransition.cpp
ARC/RCStateTransitionVisitors.cpp ARC/RCStateTransitionVisitors.cpp
ARC/RefCountState.cpp ARC/RefCountState.cpp
PARENT_SCOPE) PARENT_SCOPE)

View File

@@ -47,7 +47,7 @@ public struct PrefixThroughTest {
public let position: Int public let position: Int
public let expected: [Int] public let expected: [Int]
public let loc: SourceLoc public let loc: SourceLoc
init( init(
collection: [Int], position: Int, expected: [Int], collection: [Int], position: Int, expected: [Int],
file: String = #file, line: UInt = #line file: String = #file, line: UInt = #line
@@ -153,7 +153,7 @@ public let subscriptRangeTests = [
collection: [ 1010, 2020, 3030, 4040, 5050 ], collection: [ 1010, 2020, 3030, 4040, 5050 ],
bounds: 0..<2, bounds: 0..<2,
count: 5), count: 5),
// Slice an empty suffix. // Slice an empty suffix.
SubscriptRangeTest( SubscriptRangeTest(
expected: [], expected: [],
@@ -332,7 +332,7 @@ public struct IndexOffsetByTest {
public let distance: Int public let distance: Int
public let limit: Int? public let limit: Int?
public let expectedOffset: Int? public let expectedOffset: Int?
public let loc: SourceLoc public let loc: SourceLoc
public init( public init(
@@ -404,7 +404,7 @@ public struct IndexAfterTest {
public init(start: Int, end: Int, file: String = #file, line: UInt = #line) { public init(start: Int, end: Int, file: String = #file, line: UInt = #line) {
self.start = start self.start = start
self.end = end self.end = end
self.loc = SourceLoc(file, line, self.loc = SourceLoc(file, line,
comment: "index(after:) and formIndex(after:) test data") comment: "index(after:) and formIndex(after:) test data")
} }
} }
@@ -471,7 +471,7 @@ internal enum _SubSequenceSubscriptOnRangeMode {
%{ %{
from gyb_stdlib_support import collectionForTraversal from gyb_stdlib_support import collectionForTraversal
def testConstraints(protocol): def testConstraints(protocol):
return ''' return '''
C : %(protocol)s, C : %(protocol)s,
CollectionWithEquatableElement : %(protocol)s, CollectionWithEquatableElement : %(protocol)s,
CollectionWithEquatableElement.SubSequence : Collection, CollectionWithEquatableElement.SubSequence : Collection,
@@ -507,16 +507,16 @@ internal enum _SubSequenceSubscriptOnRangeMode {
resiliencyChecks: CollectionMisuseResiliencyChecks = .all, resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1, outOfBoundsIndexOffset: Int = 1,
outOfBoundsSubscriptOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1,
collectionIsBidirectional: Bool collectionIsBidirectional: Bool
''' '''
import re import re
forwardTestArgs = ',\n '.join( forwardTestArgs = ',\n '.join(
[ x.group(1) + ': ' + x.group(1) [ x.group(1) + ': ' + x.group(1)
for x in re.finditer(r'([a-zA-Z0-9_]+):', testParams) ] for x in re.finditer(r'([a-zA-Z0-9_]+):', testParams) ]
).replace('testNamePrefix: ', '\n ') ).replace('testNamePrefix: ', '\n ')
}% }%
extension TestSuite { extension TestSuite {
public func addCollectionTests< public func addCollectionTests<
C, CollectionWithEquatableElement C, CollectionWithEquatableElement
@@ -1209,7 +1209,7 @@ extension TestSuite {
// index(before: of i: Index) -> Index // index(before: of i: Index) -> Index
// formIndex(before: i: inout Index) // formIndex(before: i: inout Index)
// FIXME: swift-3-indexing-model - // FIXME: swift-3-indexing-model -
// enhance the following for negative direction? // enhance the following for negative direction?
// advance(i: Index, by n: IndexDistance) -> Index // advance(i: Index, by n: IndexDistance) -> Index
// advance( // advance(
@@ -1516,7 +1516,7 @@ extension TestSuite {
} }
addBidirectionalCollectionTests(${forwardTestArgs}) addBidirectionalCollectionTests(${forwardTestArgs})
testNamePrefix += String(describing: C.Type.self) testNamePrefix += String(describing: C.Type.self)
func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C {

View File

@@ -712,7 +712,7 @@ self.test("\(testNamePrefix).partition/InvalidOrderings") {
CollectionWithEquatableElement.SubSequence.Iterator.Element CollectionWithEquatableElement.SubSequence.Iterator.Element
== CollectionWithEquatableElement.Iterator.Element, == CollectionWithEquatableElement.Iterator.Element,
CollectionWithComparableElement.Iterator.Element : Comparable { CollectionWithComparableElement.Iterator.Element : Comparable {
var testNamePrefix = testNamePrefix var testNamePrefix = testNamePrefix
if !checksAdded.insert( if !checksAdded.insert(
@@ -869,7 +869,7 @@ self.test("\(testNamePrefix).partition/DispatchesThrough_withUnsafeMutableBuffer
== CollectionWithEquatableElement.Iterator.Element, == CollectionWithEquatableElement.Iterator.Element,
CollectionWithComparableElement.Iterator.Element : Comparable, CollectionWithComparableElement.Iterator.Element : Comparable,
CollectionWithComparableElement.SubSequence.Indices.Iterator.Element == CollectionWithComparableElement.Index { CollectionWithComparableElement.SubSequence.Indices.Iterator.Element == CollectionWithComparableElement.Index {
var testNamePrefix = testNamePrefix var testNamePrefix = testNamePrefix
if !checksAdded.insert( if !checksAdded.insert(

View File

@@ -31,7 +31,7 @@ extension LoggingType {
public var log: Log.Type { public var log: Log.Type {
return Log.self return Log.self
} }
public var selfType: Any.Type { public var selfType: Any.Type {
return type(of: self) return type(of: self)
} }
@@ -54,16 +54,16 @@ public struct LoggingIterator<Base : IteratorProtocol>
: IteratorProtocol, LoggingType { : IteratorProtocol, LoggingType {
public typealias Log = IteratorLog public typealias Log = IteratorLog
public init(wrapping base: Base) { public init(wrapping base: Base) {
self.base = base self.base = base
} }
public mutating func next() -> Base.Element? { public mutating func next() -> Base.Element? {
Log.next[selfType] += 1 Log.next[selfType] += 1
return base.next() return base.next()
} }
public var base: Base public var base: Base
} }
@@ -257,7 +257,7 @@ public struct ${Self}<
Log.dropLast[selfType] += 1 Log.dropLast[selfType] += 1
return base.dropLast(n) return base.dropLast(n)
} }
public func drop( public func drop(
while predicate: (Base.Iterator.Element) throws -> Bool while predicate: (Base.Iterator.Element) throws -> Bool
) rethrows -> SubSequence { ) rethrows -> SubSequence {
@@ -269,7 +269,7 @@ public struct ${Self}<
Log.prefixMaxLength[selfType] += 1 Log.prefixMaxLength[selfType] += 1
return base.prefix(maxLength) return base.prefix(maxLength)
} }
public func prefix( public func prefix(
while predicate: (Base.Iterator.Element) throws -> Bool while predicate: (Base.Iterator.Element) throws -> Bool
) rethrows -> SubSequence { ) rethrows -> SubSequence {

View File

@@ -464,7 +464,7 @@ public func expectRandomAccessCollectionAssociatedTypes<X : RandomAccessCollecti
X.Indices.Iterator.Element == X.Index, X.Indices.Iterator.Element == X.Index,
X.Indices.Index == X.Index, X.Indices.Index == X.Index,
X.Indices.SubSequence == X.Indices {} X.Indices.SubSequence == X.Indices {}
public struct AssertionResult : CustomStringConvertible { public struct AssertionResult : CustomStringConvertible {
init(isPass: Bool) { init(isPass: Bool) {
self._isPass = isPass self._isPass = isPass
@@ -643,7 +643,7 @@ func _childProcess() {
} else { } else {
print("*** [StdlibUnittest] Terminating due to uncaught exception: " + print("*** [StdlibUnittest] Terminating due to uncaught exception: " +
"\(exception)", "\(exception)",
to: &stderr) to: &stderr)
} }
} }
#endif #endif
@@ -2146,11 +2146,11 @@ public func checkComparable<Instances : Collection>(
// FIXME(ABI)#91 (Associated Types with where clauses): these constraints should be applied to // FIXME(ABI)#91 (Associated Types with where clauses): these constraints should be applied to
// associated types of Collection. // associated types of Collection.
Instances.Indices.Iterator.Element == Instances.Index { Instances.Indices.Iterator.Element == Instances.Index {
// Also checks that equality is consistent with comparison and that // Also checks that equality is consistent with comparison and that
// the oracle obeys the equality laws // the oracle obeys the equality laws
checkEquatable(instances, oracle: { oracle($0, $1).isEQ() }, ${trace}) checkEquatable(instances, oracle: { oracle($0, $1).isEQ() }, ${trace})
for i in instances.indices { for i in instances.indices {
let x = instances[i] let x = instances[i]
@@ -2178,15 +2178,15 @@ public func checkComparable<Instances : Collection>(
for j in instances.indices where i != j { for j in instances.indices where i != j {
let y = instances[j] let y = instances[j]
let expected = oracle(i, j) let expected = oracle(i, j)
expectEqual( expectEqual(
expected.flip(), oracle(j, i), expected.flip(), oracle(j, i),
"bad oracle: missing antisymmetry: " "bad oracle: missing antisymmetry: "
+ "(\(String(reflecting: i)), \(String(reflecting: j)))", + "(\(String(reflecting: i)), \(String(reflecting: j)))",
stackTrace: ${stackTrace}) stackTrace: ${stackTrace})
expectEqual(expected.isLT(), x < y, expectEqual(expected.isLT(), x < y,
"x < y\n" + "x < y\n" +
"lhs (at index \(i)): \(String(reflecting: x))\n" + "lhs (at index \(i)): \(String(reflecting: x))\n" +
@@ -2265,11 +2265,11 @@ public func checkStrideable<Instances : Collection, Strides : Collection>(
return d < 0 ? .lt : d == 0 ? .eq : .gt return d < 0 ? .lt : d == 0 ? .eq : .gt
}, },
${trace}) ${trace})
for i in instances.indices { for i in instances.indices {
let x = instances[i] let x = instances[i]
expectEqual(x, x.advanced(by: 0)) expectEqual(x, x.advanced(by: 0))
for j in strides.indices { for j in strides.indices {
let y = strides[j] let y = strides[j]
expectEqual(advanceOracle(i, j), x.advanced(by: y)) expectEqual(advanceOracle(i, j), x.advanced(by: y))
@@ -2304,7 +2304,7 @@ public func expectEqualSequence<
) where ) where
Expected.Iterator.Element == Actual.Iterator.Element, Expected.Iterator.Element == Actual.Iterator.Element,
Expected.Iterator.Element : Equatable { Expected.Iterator.Element : Equatable {
expectEqualSequence(expected, actual, ${trace}) { $0 == $1 } expectEqualSequence(expected, actual, ${trace}) { $0 == $1 }
} }
@@ -2351,7 +2351,7 @@ public func expectEqualsUnordered<
-> ExpectedComparisonResult -> ExpectedComparisonResult
) where ) where
Expected.Iterator.Element == Actual.Iterator.Element { Expected.Iterator.Element == Actual.Iterator.Element {
let x: [Expected.Iterator.Element] = let x: [Expected.Iterator.Element] =
expected.sorted(by: compose(compare, { $0.isLT() })) expected.sorted(by: compose(compare, { $0.isLT() }))
let y: [Actual.Iterator.Element] = let y: [Actual.Iterator.Element] =
@@ -2498,7 +2498,7 @@ public func expectEqualUnicodeScalars(
_ expected: [UInt32], _ actual: String, ${TRACE}) { _ expected: [UInt32], _ actual: String, ${TRACE}) {
let actualUnicodeScalars = Array( let actualUnicodeScalars = Array(
actual.unicodeScalars.lazy.map { $0.value }) actual.unicodeScalars.lazy.map { $0.value })
if !expected.elementsEqual(actualUnicodeScalars) { if !expected.elementsEqual(actualUnicodeScalars) {
expectationFailure( expectationFailure(
"expected elements: \"\(asHex(expected))\"\n" "expected elements: \"\(asHex(expected))\"\n"

View File

@@ -127,7 +127,7 @@ public struct CGFloat {
public static var signalingNaN: CGFloat { public static var signalingNaN: CGFloat {
return CGFloat(NativeType.signalingNaN) return CGFloat(NativeType.signalingNaN)
} }
@available(*, unavailable, renamed: "nan") @available(*, unavailable, renamed: "nan")
public static var quietNaN: CGFloat { public static var quietNaN: CGFloat {
fatalError("unavailable") fatalError("unavailable")
@@ -353,13 +353,13 @@ extension CGFloat : CustomReflectable {
@_transparent extension Double { @_transparent extension Double {
public init(_ value: CGFloat) { public init(_ value: CGFloat) {
self = Double(value.native) self = Double(value.native)
} }
} }
@_transparent extension Float { @_transparent extension Float {
public init(_ value: CGFloat) { public init(_ value: CGFloat) {
self = Float(value.native) self = Float(value.native)
} }
} }
@@ -758,9 +758,9 @@ extension CGFloat : _CVarArgPassedAsDouble, _CVarArgAligned {
return native._cVarArgEncoding return native._cVarArgEncoding
} }
/// Return the required alignment in bytes of /// Return the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`. /// the value returned by `_cVarArgEncoding`.
public var _cVarArgAlignment: Int { public var _cVarArgAlignment: Int {
return native._cVarArgAlignment return native._cVarArgAlignment
} }
} }

View File

@@ -97,20 +97,20 @@ extern NSError *_NSErrorWithFilePathAndErrno(NSInteger posixErrno, id pathOrURL,
SWIFT_CC(swift) SWIFT_CC(swift)
BOOL _NSWriteDataToFile_Swift(NSURL * NS_RELEASES_ARGUMENT url, NSData * NS_RELEASES_ARGUMENT data, NSDataWritingOptions writingOptions, NSError **errorPtr) { BOOL _NSWriteDataToFile_Swift(NSURL * NS_RELEASES_ARGUMENT url, NSData * NS_RELEASES_ARGUMENT data, NSDataWritingOptions writingOptions, NSError **errorPtr) {
assert((writingOptions & NSDataWritingAtomic) == 0); assert((writingOptions & NSDataWritingAtomic) == 0);
NSString *path = url.path; NSString *path = url.path;
char cpath[1026]; char cpath[1026];
if (![path getFileSystemRepresentation:cpath maxLength:1024]) { if (![path getFileSystemRepresentation:cpath maxLength:1024]) {
if (errorPtr) *errorPtr = _NSErrorWithFilePath(NSFileWriteInvalidFileNameError, path); if (errorPtr) *errorPtr = _NSErrorWithFilePath(NSFileWriteInvalidFileNameError, path);
return NO; return NO;
} }
int protectionClass = 0; int protectionClass = 0;
#if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
protectionClass = __NSFileProtectionClassForOptions(writingOptions); protectionClass = __NSFileProtectionClassForOptions(writingOptions);
#endif #endif
int flags = O_WRONLY|O_CREAT|O_TRUNC; int flags = O_WRONLY|O_CREAT|O_TRUNC;
if (writingOptions & NSDataWritingWithoutOverwriting) { if (writingOptions & NSDataWritingWithoutOverwriting) {
flags |= O_EXCL; flags |= O_EXCL;
@@ -122,7 +122,7 @@ BOOL _NSWriteDataToFile_Swift(NSURL * NS_RELEASES_ARGUMENT url, NSData * NS_RELE
[data release]; [data release];
return NO; return NO;
} }
__block BOOL writingFailed = NO; __block BOOL writingFailed = NO;
__block int32_t saveerr = 0; __block int32_t saveerr = 0;
NSUInteger dataLength = [data length]; NSUInteger dataLength = [data length];

View File

@@ -41,7 +41,7 @@ NS_Swift_NSFileManager_enumeratorAt_includingPropertiesForKeys_options_errorHand
NSArray *NS_RELEASES_ARGUMENT _Nullable keys, NSArray *NS_RELEASES_ARGUMENT _Nullable keys,
NSUInteger options, NSUInteger options,
BOOL (^_Nonnull errorHandler)(NSURL * _Nonnull url, NSError * _Nonnull error) ) { BOOL (^_Nonnull errorHandler)(NSURL * _Nonnull url, NSError * _Nonnull error) ) {
NSDirectoryEnumerator *result = [self_ enumeratorAtURL:url NSDirectoryEnumerator *result = [self_ enumeratorAtURL:url
includingPropertiesForKeys:keys includingPropertiesForKeys:keys
options:(NSDirectoryEnumerationOptions)options options:(NSDirectoryEnumerationOptions)options

View File

@@ -236,7 +236,7 @@ extension CGFloat : _ObjectiveCBridgeable {
precondition(tag == .SwiftCGFloat, precondition(tag == .SwiftCGFloat,
"NSNumber does not contain right type to be cast to CGFloat") "NSNumber does not contain right type to be cast to CGFloat")
} }
result = CGFloat(x) result = CGFloat(x)
} }

View File

@@ -97,7 +97,7 @@ extension GLKQuaternion {
public var _tuple: _Tuple { public var _tuple: _Tuple {
@inline(__always) get { return unsafeBitCast(self, to: _Tuple.self) } @inline(__always) get { return unsafeBitCast(self, to: _Tuple.self) }
} }
public var v: GLKVector3 { public var v: GLKVector3 {
@inline(__always) get { @inline(__always) get {
let (i, j, k, _) = _tuple let (i, j, k, _) = _tuple

View File

@@ -17,7 +17,7 @@
extension ${Self} : CustomPlaygroundQuickLookable { extension ${Self} : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook { public var customPlaygroundQuickLook: PlaygroundQuickLook {
// this code comes straight from the quicklooks // this code comes straight from the quicklooks
let data = (self as AnyObject)._copyImageData?() let data = (self as AnyObject)._copyImageData?()
// we could send a Raw, but I don't want to make a copy of the // we could send a Raw, but I don't want to make a copy of the
// bytes for no good reason make an NSImage out of them and // bytes for no good reason make an NSImage out of them and

View File

@@ -19,12 +19,12 @@ from gyb_foundation_support import ObjectiveCBridgeableImplementationForNSValue
// UITableView extensions // UITableView extensions
public extension IndexPath { public extension IndexPath {
/// Initialize for use with `UITableView` or `UICollectionView`. /// Initialize for use with `UITableView` or `UICollectionView`.
public init(row: Int, section: Int) { public init(row: Int, section: Int) {
self.init(indexes: [section, row]) self.init(indexes: [section, row])
} }
/// The section of this index path, when used with `UITableView`. /// The section of this index path, when used with `UITableView`.
/// ///
/// - precondition: The index path must have exactly two elements. /// - precondition: The index path must have exactly two elements.
@@ -38,7 +38,7 @@ public extension IndexPath {
self[0] = newValue self[0] = newValue
} }
} }
/// The row of this index path, when used with `UITableView`. /// The row of this index path, when used with `UITableView`.
/// ///
/// - precondition: The index path must have exactly two elements. /// - precondition: The index path must have exactly two elements.
@@ -56,7 +56,7 @@ public extension IndexPath {
// UICollectionView extensions // UICollectionView extensions
public extension IndexPath { public extension IndexPath {
/// Initialize for use with `UITableView` or `UICollectionView`. /// Initialize for use with `UITableView` or `UICollectionView`.
public init(item: Int, section: Int) { public init(item: Int, section: Int) {
self.init(indexes: [section, item]) self.init(indexes: [section, item])
@@ -77,7 +77,7 @@ public extension IndexPath {
}} }}
public extension URLResourceValues { public extension URLResourceValues {
/// Returns a dictionary of UIImage objects keyed by size. /// Returns a dictionary of UIImage objects keyed by size.
@available(iOS 8.0, *) @available(iOS 8.0, *)
public var thumbnailDictionary : [URLThumbnailSizeKey : UIImage]? { public var thumbnailDictionary : [URLThumbnailSizeKey : UIImage]? {

View File

@@ -672,10 +672,10 @@ public struct ${Self}<Element>
public subscript(index: Int) -> Element { public subscript(index: Int) -> Element {
get { get {
// This call may be hoisted or eliminated by the optimizer. If // This call may be hoisted or eliminated by the optimizer. If
// there is an inout violation, this value may be stale so needs to be // there is an inout violation, this value may be stale so needs to be
// checked again below. // checked again below.
let wasNativeTypeChecked = _hoistableIsNativeTypeChecked() let wasNativeTypeChecked = _hoistableIsNativeTypeChecked()
// Make sure the index is in range and wasNativeTypeChecked is // Make sure the index is in range and wasNativeTypeChecked is
// still valid. // still valid.
let token = _checkSubscript( let token = _checkSubscript(
@@ -687,7 +687,7 @@ public struct ${Self}<Element>
} }
mutableAddressWithPinnedNativeOwner { mutableAddressWithPinnedNativeOwner {
_makeMutableAndUniqueOrPinned() // makes the array native, too _makeMutableAndUniqueOrPinned() // makes the array native, too
_checkSubscript_native(index) _checkSubscript_native(index)
return (_getElementAddress(index), Builtin.tryPin(_getOwner_native())) return (_getElementAddress(index), Builtin.tryPin(_getOwner_native()))
} }
} }
@@ -770,7 +770,7 @@ public struct ${Self}<Element>
// We are hiding the access to '_buffer.owner' behind // We are hiding the access to '_buffer.owner' behind
// _getOwner() to help the compiler hoist uniqueness checks in // _getOwner() to help the compiler hoist uniqueness checks in
// the case of class or Objective-C existential typed array // the case of class or Objective-C existential typed array
// elements. // elements.
return _getOwnerWithSemanticLabel_native() return _getOwnerWithSemanticLabel_native()
} }
#endif #endif
@@ -1018,12 +1018,12 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// func cacheImagesWithNames(names: [String]) { /// func cacheImagesWithNames(names: [String]) {
/// // custom image loading and caching /// // custom image loading and caching
/// } /// }
/// ///
/// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,
/// "Gold": 50, "Cerise": 320] /// "Gold": 50, "Cerise": 320]
/// let colorNames = Array(namedHues.keys) /// let colorNames = Array(namedHues.keys)
/// cacheImagesWithNames(colorNames) /// cacheImagesWithNames(colorNames)
/// ///
/// print(colorNames) /// print(colorNames)
/// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"
/// ///
@@ -1110,11 +1110,11 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
internal static func _adoptStorage( internal static func _adoptStorage(
_ storage: _ContiguousArrayStorage<Element>, count: Int _ storage: _ContiguousArrayStorage<Element>, count: Int
) -> (Array, UnsafeMutablePointer<Element>) { ) -> (Array, UnsafeMutablePointer<Element>) {
let innerBuffer = _ContiguousArrayBuffer<Element>( let innerBuffer = _ContiguousArrayBuffer<Element>(
count: count, count: count,
storage: storage) storage: storage)
return ( return (
Array( Array(
_buffer: _Buffer(_buffer: innerBuffer, shiftedToStartIndex: 0)), _buffer: _Buffer(_buffer: innerBuffer, shiftedToStartIndex: 0)),
@@ -1684,7 +1684,7 @@ extension _ArrayBufferProtocol {
bounds.lowerBound - startIndex, insertCount, bounds.lowerBound - startIndex, insertCount,
_InitializeMemoryFromCollection(newValues) _InitializeMemoryFromCollection(newValues)
) )
} }
} }
/// A _debugPrecondition check that `i` has exactly reached the end of /// A _debugPrecondition check that `i` has exactly reached the end of

View File

@@ -547,7 +547,7 @@ ${subscriptCommentPost}
} }
% end % end
} }
${subscriptCommentPre} ${subscriptCommentPre}
${subscriptCommentMid} ${subscriptCommentMid}
${subscriptCommentPost} ${subscriptCommentPost}
@@ -565,7 +565,7 @@ ${subscriptCommentPost}
% end % end
//===--- Unavailable stuff ------------------------------------------------===// //===--- Unavailable stuff ------------------------------------------------===//
extension MutableCollection where Self : RandomAccessCollection { extension MutableCollection where Self : RandomAccessCollection {
@available(*, unavailable, message: "call partition(by:)") @available(*, unavailable, message: "call partition(by:)")
public mutating func partition( public mutating func partition(

View File

@@ -205,7 +205,7 @@ internal class _AnyRandomAccessCollectionBox<Element>
) rethrows -> _Any${Kind}Box<Element> { ) rethrows -> _Any${Kind}Box<Element> {
_abstract() _abstract()
} }
internal ${override} func _dropFirst(_ n: Int) -> _Any${Kind}Box<Element> { internal ${override} func _dropFirst(_ n: Int) -> _Any${Kind}Box<Element> {
_abstract() _abstract()
} }
@@ -217,7 +217,7 @@ internal class _AnyRandomAccessCollectionBox<Element>
internal ${override} func _prefix(_ maxLength: Int) -> _Any${Kind}Box<Element> { internal ${override} func _prefix(_ maxLength: Int) -> _Any${Kind}Box<Element> {
_abstract() _abstract()
} }
internal ${override} func _prefix( internal ${override} func _prefix(
while predicate: (Element) throws -> Bool while predicate: (Element) throws -> Bool
) rethrows -> _Any${Kind}Box<Element> { ) rethrows -> _Any${Kind}Box<Element> {
@@ -237,33 +237,33 @@ internal class _AnyRandomAccessCollectionBox<Element>
% if Kind == 'Collection': % if Kind == 'Collection':
internal subscript(i: _AnyIndexBox) -> Element { _abstract() } internal subscript(i: _AnyIndexBox) -> Element { _abstract() }
internal func _index(after i: _AnyIndexBox) -> _AnyIndexBox { _abstract() } internal func _index(after i: _AnyIndexBox) -> _AnyIndexBox { _abstract() }
internal func _formIndex(after i: _AnyIndexBox) { _abstract() } internal func _formIndex(after i: _AnyIndexBox) { _abstract() }
internal func _index( internal func _index(
_ i: _AnyIndexBox, offsetBy n: IntMax _ i: _AnyIndexBox, offsetBy n: IntMax
) -> _AnyIndexBox { ) -> _AnyIndexBox {
_abstract() _abstract()
} }
internal func _index( internal func _index(
_ i: _AnyIndexBox, offsetBy n: IntMax, limitedBy limit: _AnyIndexBox _ i: _AnyIndexBox, offsetBy n: IntMax, limitedBy limit: _AnyIndexBox
) -> _AnyIndexBox? { ) -> _AnyIndexBox? {
_abstract() _abstract()
} }
internal func _formIndex(_ i: inout _AnyIndexBox, offsetBy n: IntMax) { internal func _formIndex(_ i: inout _AnyIndexBox, offsetBy n: IntMax) {
_abstract() _abstract()
} }
internal func _formIndex( internal func _formIndex(
_ i: inout _AnyIndexBox, offsetBy n: IntMax, limitedBy limit: _AnyIndexBox _ i: inout _AnyIndexBox, offsetBy n: IntMax, limitedBy limit: _AnyIndexBox
) -> Bool { ) -> Bool {
_abstract() _abstract()
} }
internal func _distance( internal func _distance(
from start: _AnyIndexBox, to end: _AnyIndexBox from start: _AnyIndexBox, to end: _AnyIndexBox
) -> IntMax { ) -> IntMax {
@@ -807,7 +807,7 @@ public struct ${Self}<Element>
// public typealias Indices // public typealias Indices
// = Default${Traversal.replace('Forward', '')}Indices<${Self}> // = Default${Traversal.replace('Forward', '')}Indices<${Self}>
internal init(_box: _${Self}Box<Element>) { internal init(_box: _${Self}Box<Element>) {
self._box = _box self._box = _box
} }

View File

@@ -55,7 +55,7 @@ public struct LazyFilterIterator<
public var base: Base { return _base } public var base: Base { return _base }
internal var _base: Base internal var _base: Base
/// The predicate used to determine which elements produced by /// The predicate used to determine which elements produced by
/// `base` are also produced by `self`. /// `base` are also produced by `self`.
internal let _predicate: (Base.Element) -> Bool internal let _predicate: (Base.Element) -> Bool
@@ -68,7 +68,7 @@ public struct LazyFilterIterator<
/// is a `LazyFilterSequence`. /// is a `LazyFilterSequence`.
public struct LazyFilterSequence<Base : Sequence> public struct LazyFilterSequence<Base : Sequence>
: LazySequenceProtocol { : LazySequenceProtocol {
/// Returns an iterator over the elements of this sequence. /// Returns an iterator over the elements of this sequence.
/// ///
/// - Complexity: O(1). /// - Complexity: O(1).
@@ -102,7 +102,7 @@ public struct LazyFilterSequence<Base : Sequence>
/// `p` in its underlying collection `c` such that `c[p]` /// `p` in its underlying collection `c` such that `c[p]`
/// satisfies the predicate with which the `LazyFilterIndex` was /// satisfies the predicate with which the `LazyFilterIndex` was
/// initialized. /// initialized.
/// ///
/// - Note: The performance of advancing a `LazyFilterIndex` /// - Note: The performance of advancing a `LazyFilterIndex`
/// depends on how sparsely the filtering predicate is satisfied, /// depends on how sparsely the filtering predicate is satisfied,
/// and may not offer the usual performance given by models of /// and may not offer the usual performance given by models of
@@ -172,7 +172,7 @@ extension LazyFilterIndex : Comparable {
/// - Note: The performance of accessing `startIndex`, `first`, any methods /// - Note: The performance of accessing `startIndex`, `first`, any methods
/// that depend on `startIndex`, or of advancing a `LazyFilterIndex` depends /// that depend on `startIndex`, or of advancing a `LazyFilterIndex` depends
/// on how sparsely the filtering predicate is satisfied, and may not offer /// on how sparsely the filtering predicate is satisfied, and may not offer
/// the usual performance given by `Collection`. Be aware, therefore, that /// the usual performance given by `Collection`. Be aware, therefore, that
/// general operations on `LazyFilterCollection` instances may not have the /// general operations on `LazyFilterCollection` instances may not have the
/// documented complexity. /// documented complexity.
public struct ${Self}< public struct ${Self}<

View File

@@ -460,7 +460,7 @@ fixed_fixed_conversion_function = gyb.parse_template("fixed_fixed_conversion_fun
% else: # Smaller size input, unsigned to signed or unsigned to unsigned. % else: # Smaller size input, unsigned to signed or unsigned to unsigned.
result = (Builtin.${srcExt}_Int${srcBits}_Int${bits}(src), false._value) result = (Builtin.${srcExt}_Int${srcBits}_Int${bits}(src), false._value)
% end % end
% %
% if not safelyConvertible: % if not safelyConvertible:
${error_check} ${error_check}
% end % end
@@ -487,11 +487,11 @@ extension ${Self} {
) )
} }
} }
% if safelyConvertible: % if safelyConvertible:
@available(*, message: "Converting ${Src} to ${Self} will always succeed.") @available(*, message: "Converting ${Src} to ${Self} will always succeed.")
% end % end
@_transparent @_transparent
public init?(exactly value: ${Src}) { public init?(exactly value: ${Src}) {
${gyb.execute_template( ${gyb.execute_template(
fixed_fixed_conversion_function, fixed_fixed_conversion_function,

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