Commit Graph

847 Commits

Author SHA1 Message Date
Doug Gregor
66e20116f2 Extend ErrorType with an "original type" and use it to clean up substitution.
Type::subst()'s "IgnoreMissing" option was fairly unprincipled, dropping
unsubstituted types into the resulting AST without any indication
whatsoever that anything went wrong. Replace this notion with a new
form of ErrorType that explicitly tracks which substituted type caused
the problem. It's still an ErrorType, but it prints like the
substituted type (which is important for code completion) and allows
us to step back to the substituted type if needed (which is used by
associated type inference). Then, allow Type::subst(), when the new
UseErrorTypes flag is passed, to form partially-substituted types that
contain errors, which both code completion and associated type
inference relied on.

Over time, I hope we can use error-types-with-original-types more
often to eliminate "<<error type>>" from diagnostics and teach
Type::subst() never to return a "null" type. Clients can check
"hasError()" to deal with failure cases rather than checking null.
2016-10-06 16:40:28 -07:00
Doug Gregor
8fab641da0 [AST] Simplify DependentMemberType creation and use isTypeParameter() more. NFC 2016-10-06 14:24:55 -07:00
Joe Groff
a506af06c7 Merge pull request #4933 from jckarter/nsnumber-bridging
SE-0139: Bridge all standard number types to NSNumber.
2016-09-23 13:06:43 -07:00
Joe Groff
9b1f238e5b SE-0139: Bridge all standard number types to NSNumber.
Extend NSNumber bridging to cover not only `Int`, `UInt`, `Double`, and `Bool`, but all of the standard types as well. Extend the `TypePreservingNSNumber` subclass to accommodate all of these types, so that we preserve type identity for `AnyHashable` and dynamic casting of Swift-bridged NSNumbers. If a pure Cocoa NSNumber is cast, just trust that the user knows what they're doing.

This XFAILs a couple of serialization tests that attempt to build the Foundation overlay, but which don't properly handle `gyb` files.
2016-09-23 10:34:22 -07:00
Slava Pestov
a9c68c0736 AST: Remove archetype from AbstractTypeParamDecl
There's a bit of a hack to deal with generic typealiases, but
overall this makes things more logical.

This is the last big refactoring before we can allow constrained
extensions to make generic parameters concrete. All that remains
is a small set of changes to SIL type lowering, and retooling
some diagnostics in Sema.
2016-09-22 19:48:30 -07:00
Michael Ilseman
0bb868a539 [ParameterTypeFlags] Incorporate review feedback 2016-09-22 12:24:37 -07:00
Michael Ilseman
ed2522b384 [AST] Create ParameterTypeFlags and put them on function params
Long term, we want to refactor the AST to reflect the current
programming model in Swift. This would include refactoring
FunctionType to take a list of ParameterTypeElt, or something with a
better name, that can contain both the type and flags/bits that are
only specific to types in parameter position, such as @autoclosure and
@escaping. At the same time, noescape-by-default has severely hurt our
ability to print types without significant context, as we either have
to choose to too aggressively print @escaping or not print it in every
situation it occurs, or both.

As a gentle step towards the final solution, without uprooting our
overall AST structure, and as a way towards fixing the @escaping
printing ails, put these bits on the TupleTypeElt and ParenType, which
will serve as a model for what ParameterTypeElt will be like in the
future. Re-use these flags on CallArgParam, to leverage shared
knowledge in the type system. It is a little painful to tack onto
these types, but it's minor and will be overhauled soon, which will
eventually result in size savings and less complexity overall.

This includes all the constraint system adjustments to make these
types work and influence type equality and overload resolution as
desired. They are encoded in the module format. Additional tests
added.
2016-09-22 12:24:02 -07:00
Joe Groff
b0e3c0be59 Merge pull request #4865 from jckarter/nsvalue-bridging
SE-0139: NSValue bridging
2016-09-22 09:13:47 -07:00
Slava Pestov
3ec1fe0b2e SIL Combiner: Some fixes and improvements for partial_apply/apply peephole
- We were bailing out if the partial_apply's substitutions
  contained archetypes, but there was no inherent reason
  to do this. After fixing an issue with opened existential
  tracking, this started to work.

- We were also bailing out if the callee was not a static
  function_ref. Again, there's no reason to do this, because
  we also emit partial_apply to form closures from
  class_method and witness_method calls.

- There was a bug in the code for extending lifetimes of
  @in parameters. Even if a parameter was an input parameter
  to the method and not an alloc_stack, we have to copy
  it into a new alloc_stack, because there might be
  multiple invocations of an apply for a single partial_apply.

- There was also a bug where we would proceed to apply the
  peephole to @unowned_inner_pointer functions, which is wrong.
  IRGen's lowering of partial_apply has special handling there
  and the resulting function type has an @owned result.
2016-09-21 23:42:02 -07:00
Joe Groff
86fbeee285 SE-0139: Bridge Cocoa framework structs to NSValue.
For every struct type for which the frameworks provides an NSValue category for boxing and unboxing values of that type, provide an _ObjectiveCBridgeable conformance in the Swift overlay that bridges that struct to NSValue, allowing the structs to be used naturally with id-as-Any APIs and Cocoa container classes. This is mostly a matter of gyb-ing out boilerplate using `NSValue.init(bytes:objCType:)` to construct the instance, `NSValue.objCType` to check its type when casting, and `NSValue.getValue(_:)` to extract the unboxed value, though there are a number of special snowflake cases that need special accommodation:

- To maintain proper layering, CoreGraphics structs need to be bridged in the Foundation overlay.
- AVFoundation provides the NSValue boxing categories for structs owned by CoreMedia, but it does so using its own internal subclasses of NSValue, and these subclasses do not interop properly with the standard `NSValue` subclasses instantiated by Foundation. To do the right thing, we therefore have to let AVFoundation provide the bridging implementation for the CoreMedia types, and we have to use its category methods to do so.
- SceneKit provides NSValue categories to box and unbox SCNVector3, SCNVector4, and SCNMatrix4; however, the methods it provides do so in an unusual way. SCNVector3 and SCNVector4 are packaged into `CGRect`s and then the CGRect is boxed using `valueWithCGRect:`. SCNMatrix4 is copied into a CATransform3D, which is then boxed using `valueWithCATransform3D:` from CoreAnimation. To be consistent with what SceneKit does, use its category methods for these types as well, and when casting, check the type against the type encoding SceneKit uses rather than the type encoding of the expected type.
2016-09-21 19:26:10 -07:00
Joe Groff
1a52e3f2c2 SR-0140: Bridge Optionals to nonnull ObjC objects by bridging their payload, or using a sentinel.
id-as-Any lets you pass Optional to an ObjC API that takes `nonnull id`, and also lets you bridge containers of `Optional` to `NSArray` etc. When this occurs, we can unwrap the value and bridge it so that inhabited optionals still pass into ObjC in the expected way, but we need something to represent `none` other than the `nil` pointer. Cocoa provides `NSNull` as the canonical "null for containers" object, which is the least bad of many possible answers. If we happen to have the rare nested optional `T??`, there is no precedented analog for these in Cocoa, so just generate a unique sentinel object to preserve the `nil`-ness depth so we at least don't lose information round-tripping across the ObjC-Swift bridge.

Making Optional conform to _ObjectiveCBridgeable is more or less enough to make this all work, though there are a few additional edge case things that need to be fixed up. We don't want to accept `AnyObject??` as an @objc-compatible type, so special-case Optional in `getForeignRepresentable`.

Implements SR-0140 (rdar://problem/27905315).
2016-09-20 13:04:09 -07:00
Greg Parker
cd9a8afd5d Revert "SR-0140: Bridge Optionals to nonnull ObjC objects by bridging their payload, or using a sentinel." (#4820) 2016-09-15 18:18:07 -07:00
Joe Groff
3441fe8ca4 Merge pull request #4782 from jckarter/bridging-enhancements
SR-0140: Bridge Optionals to nonnull ObjC objects by bridging their payload, or using a sentinel.
2016-09-15 13:06:01 -07:00
Joe Groff
cfa9cd9a08 SR-0140: Bridge Optionals to nonnull ObjC objects by bridging their payload, or using a sentinel.
id-as-Any lets you pass Optional to an ObjC API that takes `nonnull id`, and also lets you bridge containers of `Optional` to `NSArray` etc. When this occurs, we can unwrap the value and bridge it so that inhabited optionals still pass into ObjC in the expected way, but we need something to represent `none` other than the `nil` pointer. Cocoa provides `NSNull` as the canonical "null for containers" object, which is the least bad of many possible answers. If we happen to have the rare nested optional `T??`, there is no precedented analog for these in Cocoa, so just generate a unique sentinel object to preserve the `nil`-ness depth so we at least don't lose information round-tripping across the ObjC-Swift bridge.

Making Optional conform to _ObjectiveCBridgeable is more or less enough to make this all work, though there are a few additional edge case things that need to be fixed up. We don't want to accept `AnyObject??` as an @objc-compatible type, so special-case Optional in `getForeignRepresentable`.

Implements SR-0140 (rdar://problem/27905315).
2016-09-14 15:50:13 -07:00
John McCall
34fb15e375 Abstract the object type of an optional type according to the
abstraction pattern of the type rather than always using the
most-general pattern, and erase ImplicitlyUnwrappedOptional from
the SIL type system.
2016-09-08 23:26:19 -07:00
Slava Pestov
6e77f62585 AST: Add some handy assertions to GenericSignature 2016-09-06 11:52:24 -07:00
Slava Pestov
3b1721795f AST: Nuke GenericSignature::getCanonicalManglingSignature()
Now that the previous patches have shaken out implicit assumptions
about the order of generic requirements and substitutions, we can
make a more radical change, dropping redundant protocol requirements
when building the original generic signature.

This means that the canonical ordering and minimization that we
used to only perform when building the mangling signature is done
all of the time, and hence getCanonicalManglingSignature() can go
away.

Usages now either call getCanonicalSignature(), or operate on the
original signature directly.
2016-09-06 11:51:14 -07:00
Slava Pestov
21ad46b3f6 AST: Replace ArchetypeBuilder's adoptArchetypes flag with generic environment
Preparation for removing AbstractTypeParamDecl::Archetype.

Also a few other cleanups in related code.
2016-09-06 11:51:11 -07:00
Doug Gregor
78b007f178 Always create a DefaultArgumentInitializer for a parameter with a default argument.
As with pattern binding initializer contexts, we were trying to
optimize away these contexts, leading to an unpredictable AST.
2016-09-02 13:51:00 -07:00
Doug Gregor
85537fd66b Murder ExprHandle in cold blood. NFC
ExprHandle is a relic from a horrible time when expressions made their
way into the type system via default arguments. It's been unnecessary
for a long time, so get rid of it.
2016-09-02 10:39:19 -07:00
Doug Gregor
4eac3ea2e7 Always create initializer contexts for pattern binding entries in non-local scopes.
We were optimizing away unused pattern binding initializer contexts in
both the parser and in semantic analysis, which led to a
somewhat-unpredictable set of DeclContexts in the AST. Normalize
everything by always creating these contexts.
2016-09-02 10:39:19 -07:00
Slava Pestov
1c1ab0b83a AST: Introduce new GenericEnvironment class
A GenericEnvironment stores the mapping between GenericTypeParamTypes
and context archetypes (or eventually, concrete types, once we allow
extensions to constrain a generic parameter to a concrete type).

The goals here are two-fold:

- Eliminate the GenericTypeParamDecl::getArchetype() method, and
  always use mapTypeIntoContext() instead

- Replace SILFunction::ContextGenericParams with a GenericEnvironment

This patch adds the new data type as well as serializer and AST
verifier support. but nothing else uses it yet.

Note that GenericSignature::get() now asserts if there are no
generic parameters, instead of returning null. This requires a
few tweaks here and there.
2016-08-28 13:51:36 -07:00
Greg Parker
f50b1e73dc Revert "Make all CF types Equatable and Hashable." 2016-08-20 04:33:55 -07:00
Doug Gregor
95820e3339 Merge pull request #4431 from DougGregor/remove-code
Remove a bunch of dead language options
2016-08-19 23:44:44 -07:00
Doug Gregor
51529ae888 Eliminate the -enable-id-as-any flag; it's always on now anyway.
Simplify e.g., ASTContext::getBridgedToObjC(), which no longer needs
the optional return.

Eliminate the now-unused constraint kind for checking bridging to
Objective-C.
2016-08-19 21:17:09 -07:00
Slava Pestov
66ce63b466 AST: Remove a few easy usages of getAll{Nested,}Archetypes(), NFC 2016-08-19 16:01:38 -07:00
Jordan Rose
361ab62454 Make all CF types Equatable and Hashable. (#4394)
Like NSObject, CFType has primitive operations CFEqual and CFHash,
so Swift should allow those types to show up in Hashable positions
(like dictionaries). The most general way to do this was to
introduce a new protocol, _CFObject, and then have the importer
automatically make all CF types conform to it.

This did require one additional change: the == implementation that
calls through to CFEqual is in a new CoreFoundation overlay, but the
conformance is in the underlying Clang module. Therefore, operator
lookup for conformances has been changed to look in the overlay for
an imported declaration (if there is one).

https://bugs.swift.org/browse/SR-2388
2016-08-19 13:21:24 -07:00
Slava Pestov
677e72a9c4 AST: Remove GenericParamList::getPrimaryArchetypes(), NFC 2016-08-18 18:43:41 -07:00
Joe Groff
8ef5f40eae Merge pull request #3974 from jckarter/cvararg-post-0072
Make bridged String and collection types conform to CVarArg.
2016-08-05 09:44:25 -07:00
Joe Groff
7535acc86b Make bridged String and collection types conform to CVarArg.
This allows String, Array, Dictionary, and Set to be passed as variadic arguments to Cocoa APIs like NSLog, NSPredicate, stringWithFormat:, etc. rdar://problem/27651717
2016-08-04 07:14:55 -07:00
Doug Gregor
75e85dc5bd [NSError bridging] Extract embedded NSError from an Error consistently.
When emitting an existential erasure to Error from an archetype, use
the _getEmbeddedNSError() witness. If it produces an NSError, erase
that; otherwise, go through the normal erasure path.

Of course, make NSError and CFError implement _getEmbeddedNSError() so
this kicks in for the obvious cases as well as the more obscure ones.

Fixes the rest of SR-1562 / rdar://problem/26370984.
2016-08-03 14:01:02 -07:00
Jordan Rose
b5aca663bc [ClangImporter] Remove importer-based NS stripping. (#3880)
* [ClangImporter] Remove importer-based NS stripping.

As Tony puts it, in the end we wound up with more Foundation
declarations imported as members or keeping "NS" than those that
dropped it, and any further decisions will be made on a case-by-case
basis. Move all of the existing cases of prefix-stripping into
Foundation's API notes and drop the logic from the compiler.

Tested by dumping the generated interface for Foundation and its
submodules for both macOS and the iOS simulator, and comparing the
results. A few cases did slip through here because of the interaction
between "SwiftName" and "Availability: nonswift".

The next commit will re-add "NS" to some stragglers that we missed.

rdar://problem/26880017

* APINotes: Add "NS" back to a few types.

NSKeyedUnarchiverDelegate
NSKeyedArchiverDelegate
NSTextCheckingTypes
NSBinarySearchingOptions
NSEnumerationOptions
NSSortOptions

More rdar://problem/26880017

* Remove now-redundant SwiftNames from API notes.

No change observed in the generated interface of Foundation and its
submodules.

Finishes rdar://problem/26880017.
2016-08-01 20:54:26 -07:00
Arnold Schwaighofer
0322600f92 Merge pull request #3782 from aschwaighofer/fix_astcontext_getbridgedtoobjc
Fix ASTContext::getBridgedToObjC to not return None under id-as-any
2016-07-26 17:22:12 -07:00
Joe Groff
5b3f2af297 Merge pull request #3756 from jckarter/turn-on-anyhashable
Turn on AnyHashable
2016-07-26 15:45:13 -07:00
Arnold Schwaighofer
f6e3f67293 Fix ASTContext::getBridgedToObjC to not return None under id-as-any
This would lead us to conclude that a check-cast-branch fails when it does not.

rdar://27536049
2016-07-26 14:19:03 -07:00
John McCall
c8c41b385c Implement SE-0077: precedence group declarations.
What I've implemented here deviates from the current proposal text
in the following ways:

- I had to introduce a FunctionArrowPrecedence to capture the parsing
  of -> in expression contexts.

- I found it convenient to continue to model the assignment property
  explicitly.

- The comparison and casting operators have historically been
  non-associative; I have chosen to preserve that, since I don't
  think this proposal intended to change it.

- This uses the precedence group names and higherThan/lowerThan
  as agreed in discussion.
2016-07-26 14:04:57 -07:00
Joe Groff
1e8dd0e34b ClangImporter: Import unbounded NSSets and NSDictionaries using AnyHashable. 2016-07-26 13:36:05 -07:00
Joe Groff
e884ab737d Foundation: Make AnyHashable bridge to NSObject. 2016-07-26 13:36:05 -07:00
Joe Groff
bbdca55dd0 Sema: Containers of any type can bridge when id-as-Any is enabled.
We no longer need to constrain the generic parameters to be ObjC-bridgeable.
2016-07-25 06:01:21 -07:00
practicalswift
2c56367a93 Remove unused AnyDecl (declaration of Swift.Any). 2016-07-24 22:13:32 +02:00
Andrew Trick
ecc6bd51ad Type system support for raw pointer conversion. (#3685)
* [Type System] Handle raw pointer conversion.

As proposed in SE-0107: UnsafeRawPointer.
https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md#implicit-argument-conversion

UnsafeMutablePointer<T> -> UnsafeMutableRawPointer
UnsafeMutablePointer<T> -> UnsafeRawPointer
UnsafePointer<T> -> UnsafeRawPointer
UnsafeMutableRawPointer -> UnsafeRawPointer

inout:
&anyVar -> UnsafeMutableRawPointer
&anyVar -> UnsafeRawPointer

array -> UnsafeRawPointer
string -> UnsafeRawPointer

varArray -> UnsafeMutableRawPointer

* Rename expectEqual(_, _, sameValue:) to expectEqualTest to workaround a type system bug.

<rdar://26058520> Generic type constraints incorrectly applied to functions with the same name

This is exposed by additions to the type system for UnsafeRawPointer.

Warning: unit tests fail very confusingly without this fix.
2016-07-23 11:30:49 -07:00
Slava Pestov
4022624dba stdlib: Rename _unimplemented_initializer to _unimplementedInitializer, NFC
This addresses a FIXME.
2016-07-22 14:55:45 -07:00
Slava Pestov
6ff02a9fe2 AST/SIL: Add a new Never type, and a TypeBase::isNever() check
Mostly NFC, this is just plumbing for the next patch.
Note that isNever() returns true for any uninhabited
enum.

It should be generalized so that stuff like (Never, Int)
is also known to be uninhabited, or even to support
generic substitutions that yield uninhabited types,
but for now I really see no reason to go that far, and
the current check for an enum with no cases seems
perfectly adequate.
2016-07-22 14:55:45 -07:00
Doug Gregor
211c580158 [Cleanup] Eliminate DerivedFileUnit.
The only client of DerivedFileUnit was synthesized global '=='
operators for Equatable conformances, which has since been removed.
2016-07-21 12:54:27 -07:00
Doug Gregor
0bf7c005b3 [SE-0091 Follow-up] Move global operators for non-generic concrete types into the type.
In various cases where we had global operators for non-generic
concrete types (such as String + String), move those operators into
the type. This should not affect the sources, but makes the exposition
of the library cleaner.

Plus, it's a good test for the compiler, which uncovered a few issues
where the compiler was coupled with the library.
2016-07-21 12:54:27 -07:00
Joe
7b9e5de7b7 [SE-0095] simplifyTypeExpr for composition expressions
Also adds:
- Any is caught before doing an unconstrained lookup, and the
protocol<> type is emitted
- composition expressions can be handled by
`PreCheckExpression::simplifyTypeExpr` to so you can do lookups like (P
& Q).self
- Fixits corrected & new tests added
- Typeref lowering cases should have been optional
- This fixes a failing test case.
2016-07-19 12:01:37 -07:00
Joe
a6dad0091b [SE-0095] Initial parsing implementation for '&' composition syntax
This commit defines the ‘Any’ keyword, implements parsing for composing
types with an infix ‘&’, and provides a fixit to convert ‘protocol<>’

- Updated tests & stdlib for new composition syntax
- Provide errors when compositions used in inheritance.
Any is treated as a contextual keyword. The name ‘Any’
is used emit the empty composition type. We have to
stop user declaring top level types spelled ‘Any’ too.
2016-07-19 12:01:02 -07:00
Doug Gregor
5a83c86455 Eliminate default arguments from TupleType.
In Swift, default arguments are associated with a function or
initializer's declaration---not with its type. This was not always the
case, and TupleType's ability to store a default argument kind is a
messy holdover from those dark times.

Eliminate the default argument kind from TupleType, which involves
migrating a few more clients over to declaration-centric handling of
default arguments. Doing so is usually a bug-fix anyway: without the
declaration, one didn't really have

The SILGen test changes are due to a name-mangling fix that fell out
of this change: a tuple type is mangled differently than a non-tuple
type, and having a default argument would make the parameter list of a
single-parameter function into a tuple type. Hence,

  func foo(x: Int = 5)

would get a different mangling from

  func foo(x: Int)

even though we didn't actually allow overloading.

Fixes rdar://problem/24016341, and helps us along the way to SE-0111
(removing the significance of argument labels) because argument labels
are also declaration-centric, and need the same information.
2016-07-15 13:55:53 -07:00
Doug Gregor
823c24b355 [SE-0112] Rename ErrorProtocol to Error.
This is bullet (5) of the proposed solution in SE-0112, and the last
major piece to be implemented.
2016-07-12 10:53:52 -07:00
Doug Gregor
b86b8126a7 [SE-0112] Import an Objective-C error enum as a struct wrapping NSError.
A given Objective-C error enum, which is effectively an NS_ENUM that
specifies its corresponding error domain, will now be mapped to an
ErrorProtocol-conforming struct that wraps an NSError, much like
NSCocoaError does. The actual enum is mapped to a nested "Code"
enum. For example, CoreLocation's CLError becomes:

  struct CLError : ErrorProtocol {
    let _nsError: NSError
    // ...
   @objc enum Code : Int {
     case ...
   }
  }

This implements bullet (2) in the proposed solution of SE-0112, so
that Cocoa error types are mapped into structures that maintain the
underlying NSError to allow more information to be extracted from it.
2016-07-12 10:53:52 -07:00