Commit Graph

689 Commits

Author SHA1 Message Date
Arnold Schwaighofer
081bb95bee Synthesize accessors for dynamic global variables 2018-11-14 07:57:45 -08:00
Jordan Rose
40cfc458e2 Fix synthesis of 'override' and 'required' on initializers (#20548)
This is actually two separate problems:
- 'override' wasn't getting added to initializers in deserialization
- 'override' was getting added when inheriting a 'required' initializer,
  even though it's normally an error to write that

Needed for parseable interfaces.
2018-11-13 16:54:53 -08:00
Pavel Yaskevich
f462521078 [ConstraintSystem] Refactor arg/param matching to handle autoclosures
Make sure that presence of `@autoclosure` attribute handled
in one place - `matchCallArguments`, which makes it possible
to remove the rest of (now redundant) autoclosure related
logic scattered throughout solver.
2018-11-10 11:59:28 -08:00
Slava Pestov
c7338d06ca AST: Remove owning addressors 2018-11-09 20:49:44 -05:00
John McCall
4758b2f58e Fix a bug with class vs. protocol @_borrowed mismatches. 2018-11-08 02:16:47 -05:00
Arnold Schwaighofer
c158106329 Allow dynamic without @objc in -swift-version 5
Dynamic functions will allow replacement of their implementation at
runtime.
2018-11-06 09:53:21 -08:00
John McCall
90ca9fe8b4 Fix a bunch of minor issues with read accessors. 2018-11-05 20:57:58 -05:00
Brent Royal-Gordon
9bd1a26089 Implementation for SE-0228: Fix ExpressibleByStringInterpolation (#20214)
* [CodeCompletion] Restrict ancestor search to brace

This change allows ExprParentFinder to restrict certain searches for parents to just AST nodes within the nearest surrounding BraceStmt. In the string interpolation rework, BraceStmts can appear in new places in the AST; this keeps code completion from looking at irrelevant context.

NFC in this commit, but keeps code completion from crashing once TapExpr is introduced.

* Remove test relying on ExpressibleByStringInterpolation being deprecated

Since soon enough, it won’t be anymore.

* [AST] Introduce TapExpr

TapExpr allows a block of code to to be inserted between two expressions, accessing and potentially mutating the result of its subexpression before giving it to its parent expression. It’s roughly equivalent to this function:

  func _tap<T>(_ value: T, do body: (inout T) throws -> Void) rethrows -> T {
    var copy = value
    try body(&copy)
    return copy
  }

Except that it doesn’t use a closure, so no variables are captured and no call frame is (even notionally) added.

This commit does not include tests because nothing in it actually uses TapExpr yet. It will be used by string interpolation.

* SE-0228: Fix ExpressibleByStringInterpolation

This is the bulk of the implementation of the string interpolation rework. It includes a redesigned AST node, new parsing logic, new constraints and post-typechecking code generation, and new standard library types and members.

* [Sema] Rip out typeCheckExpressionShallow()

With new string interpolation in place, it is no longer used by anything in the compiler.

* [Sema] Diagnose invalid StringInterpolationProtocols

StringInterpolationProtocol informally requires conforming types to provide at least one method with the base name “appendInterpolation” with no (or a discardable) return value and visibility at least as broad as the conforming type’s. This change diagnoses an error when a conforming type does not have a method that meets those criteria.

* [Stdlib] Fix map(String.init) source break

Some users, including some in the source compatibility suite, accidentally used init(stringInterpolationSegment:) by writing code like `map(String.init)`. Now that these intializers have been removed, the remaining initializers often end up tying during overload resolution. This change adds several overloads of `String.init(describing:)` which will break these ties in cases where the compiler previously selected `String.init(stringInterpolationSegment:)`.

* [Sema] Make callWitness() take non-mutable arrays

It doesn’t actually need to mutate them.

* [Stdlib] Improve floating-point interpolation performance

This change avoids constructing a String when interpolating a Float, Double, or Float80. Instead, we write the characters to a fixed-size buffer and then append them directly to the string’s storage.

This seems to improve performance for all three types, but especially for Double and Float80, which cannot always fit into a small string when stringified.

* [NameLookup] Improve MemberLookupTable invalidation

In rare cases usually involving generated code, an overload added by an extension in the middle of a file would not be visible below it if the type had lazy members and the same base name had already been referenced above the extension. This change essentially dirties a type’s member lookup table whenever an extension is added to it, ensuring the entries in it will be updated.

This change also includes some debugging improvements for NameLookup.

* [SILOptimizer] XFAIL dead object removal failure

The DeadObjectRemoval pass in SILOptimizer does not currently remove reworked string interpolations as well as the old design because their effects cannot be described by @_effects(readonly). That causes a test failure on Linux. This change temporarily silences that test. The SILOptimizer issue has been filed as SR-9008.

* Confess string interpolation’s source stability sins

* [Parser] Parse empty interpolations

Previously, the parser had an odd asymmetry which caused the same function to accept foo(), but reject “\()”. This change fixes the issue.

Already tested by test/Parse/try.swift, which uses this construct in one of its throwing interpolation tests.

* [Sema] Fix batch-mode-only lazy var bug

The temporary variable used by string interpolation needs to be recontextualized when it’s inserted into a synthesized getter. Fixes a compilation failure in Alamofire.

I’ll probably follow up on this bug a bit more after merging.
2018-11-02 19:16:03 -07:00
Doug Gregor
04e2f347bf [Type checker] Ensure that synthesized accessors get generic parameter lists.
When we synthesize the declaration for getters and setters from (e.g.) an
addressor, ensure that we clone the generic parameter list when we have a
generic subscript. Fixes rdar://problem/45046969.
2018-10-05 11:14:03 -07:00
MIZUNO Hiroki
f2bdce8251 [SR-8340]Improve fix-it for var and subscript in Protocol (#19660)
* [Parser] Improve fix-it for subscription in protocol
* [Sema] Add fix-it for property in protocol

https://bugs.swift.org/browse/SR-8340
2018-10-05 07:50:03 +09:00
Doug Gregor
56cfd84b6a [Type checker] Move accessor creation out of validateDecl().
Creating accessors for a storage declaration within validateDecl() caused
circular dependencies detected by the request-evaluator. Separate out
accessor creation to break the dependency.

Fixes SR-8656 / rdar://problem/43951634.
2018-09-11 16:20:12 -07:00
Harlan
eb75ad80dc [AST] Remove stored TypeLoc from TypedPattern (#19175)
* [AST] Remove stored TypeLoc from TypedPattern

TypedPattern was only using this TypeLoc as a means to a TypeRepr, which
caused it to store the pattern type twice (through the superclass and through
the TypeLoc itself.)

This also fixes a bug where deserializing a TypedPattern doesn't store
the type correctly and generally cleans up TypedPattern initialization.

Resolves rdar://44144435

* Address review comments
2018-09-07 21:14:04 -07:00
Slava Pestov
ec804a2d01 SIL: Accessors synthesized on-demand are serialized when visible outside the module
Second part of <https://bugs.swift.org/browse/SR-8657> /
<rdar://problem/43951732>.
2018-09-06 13:17:18 -07:00
Slava Pestov
71cafe46c9 Sema: Simplify accessor synthesis a bit 2018-09-06 11:59:20 -07:00
Harlan
ad7e1d0e67 [InterfaceGen] Print private/internal properties (#19127)
* [Interface] Print private/internal properties

All properties which contribute to the storage of a type should be
printed, and their names should be hidden from interfaces. Print them
with '_' as their name, and teach the parser to recognize these special
patterns when parsing interface files.

Partially resolves rdar://43810647

* Address review comments

* Disable accessor generation for nameless vars

* Test to ensure interface files preserve type layout

* Ignore attribute differences on Linux
2018-09-06 09:58:33 -07:00
John McCall
b80618fc80 Replace materializeForSet with the modify coroutine.
Most of this patch is just removing special cases for materializeForSet
or other fairly mechanical replacements.  Unfortunately, the rest is
still a fairly big change, and not one that can be easily split apart
because of the quite reasonable reliance on metaprogramming throughout
the compiler.  And, of course, there are a bunch of test updates that
have to be sync'ed with the actual change to code-generation.

This is SR-7134.
2018-08-27 03:24:43 -04:00
Slava Pestov
c360c82850 AST: Automatically create the 'self' parameter when needed
Parsed declarations would create an untyped 'self' parameter;
synthesized, imported and deserialized declarations would get a
typed one.

In reality the type, if any, depends completely on the properties
of the function in question, so we can just lazily create the
'self' parameter when needed.

If the function already has a type, we give it a type right there;
otherwise, we check if a 'self' was already created when we
compute a function's type and set the type of 'self' then.
2018-08-25 10:44:55 -07:00
John McCall
a30d91e3cb Implement vararg expansion well enough to support argument forwarding.
I needed this for materializeForSet remission, but it makes inherited
variadic initializers work, too.

I tried to make this a reasonable starting point for a real language
feature.  Here's what's still missing:

- syntax
- semantic restrictions to ensure that the expression isn't written in
  invalid places or arbitrarily converted
- SILGen support for expansions that aren't the only variadic argument

rdar://16331406
2018-08-22 06:46:08 -04:00
Doug Gregor
8dc20dfcac [Type checker] Move TypeChecker::resolveType() into TypeResolution.
Now that type resolution is (almost completely) separated from the type
checker instance, move resolveType() out to TypeResolution where it
belongs.
2018-08-20 22:31:59 -07:00
Doug Gregor
7fa4f1df54 Merge pull request #18859 from DougGregor/type-resolution-stage
[Type Checker] Add TypeResolution(Stage) to describe type computations.
2018-08-20 18:44:31 -07:00
Doug Gregor
79a55895de [Type Checker] Replace GenericTypeResolver with a TypeResolution.
Replace the GenericTypeResolver type hierarchy with TypeResolution,
which more simply encapsulates the information needed to resolve
dependent types and makes explicit those places where we are
using resolution to contextual types.
2018-08-20 16:53:44 -07:00
Slava Pestov
527ff375dc AST: Rename old form of {Generic,}FunctionType::get() to getOld()
This makes it easier to grep for and eventually remove the
remaining usages.

It also allows you to write FunctionType::get({}, ...) to call the
ArrayRef overload empty parameter list, instead of picking the Type
overload and calling it with an empty Type() value.

While I"m at it, in a few places instead of renaming just clean up
usages where it was completely mechanical to do so.
2018-08-17 19:28:17 -04:00
Slava Pestov
a54251074c AST: ExtInfo just wraps an unsigned integer, no need to pass it by reference 2018-08-17 19:27:43 -04:00
Jordan Rose
537954fb93 [AST] Rename several DeclContext methods to be clearer and shorter (#18798)
- getAsDeclOrDeclExtensionContext -> getAsDecl

This is basically the same as a dyn_cast, so it should use a 'getAs'
name like TypeBase does.

- getAsNominalTypeOrNominalTypeExtensionContext -> getSelfNominalTypeDecl
- getAsClassOrClassExtensionContext -> getSelfClassDecl
- getAsEnumOrEnumExtensionContext -> getSelfEnumDecl
- getAsStructOrStructExtensionContext -> getSelfStructDecl
- getAsProtocolOrProtocolExtensionContext -> getSelfProtocolDecl
- getAsTypeOrTypeExtensionContext -> getSelfTypeDecl (private)

These do /not/ return some form of 'this'; instead, they get the
extended types when 'this' is an extension. They started off life with
'is' names, which makes sense, but changed to this at some point.  The
names I went with match up with getSelfInterfaceType and
getSelfTypeInContext, even though strictly speaking they're closer to
what getDeclaredInterfaceType does. But it didn't seem right to claim
that an extension "declares" the ClassDecl here.

- getAsProtocolExtensionContext -> getExtendedProtocolDecl

Like the above, this didn't return the ExtensionDecl; it returned its
extended type.

This entire commit is a mechanical change: find-and-replace, followed
by manual reformatted but no code changes.
2018-08-17 14:05:24 -07:00
John McCall
5d8252b8c6 Pass around whether storage is mutable as an enum instead of a bool. 2018-08-16 02:13:54 -04:00
David Zarzycki
6b6ef5af24 [Sema] NFC: Refactor most TypeResolutionFlags into a traditional enum
TypeResolutionFlags is overly complicated at the moment because the vast
majority of flag combinations are impossible and nonsensical. With this
patch, we create a new TypeResolverContext type that is a classic enum
and far easier to reason about. It also enables "exhaustive enum"
checking, unlike the "flags" based approach.
2018-08-13 08:18:40 -04:00
Slava Pestov
4b258e86e6 AST: Stop setting contextual types on ParamDecls
VarDecl::getType() lazily maps the interface type into context if needed.
2018-08-10 13:33:12 -07:00
John McCall
ebed6afd59 Make it easy to iterate over all the opaque accessors of a declaration. 2018-08-08 22:44:47 -04:00
Doug Gregor
9eb9898321 Merge pull request #18364 from DougGregor/name-lookup-requests
[Name lookup] Introduce requests for several name lookup operations.
2018-07-31 13:23:38 -07:00
Doug Gregor
2860557a77 [Name lookup] Use the declaration-based lookupQualified() where it’s easy.
Switch a number of callers of the Type-based lookupQualified() over to
the newer (and preferred) declaration-based lookupQualified(). These are
the easy ones; NFC.
2018-07-31 10:14:44 -07:00
Slava Pestov
2bd217e58a AST: Change AbstractStorageDecl::getValueInterfaceType() to strip off reference storage qualifiers
Also, remove AbstractStorageDecl::getStorageInterfaceType(), which was
almost identical.
2018-07-31 00:38:09 -07:00
Slava Pestov
463a467046 Merge pull request #18026 from slavapestov/inherited-availability-attribute-part-2
Sema: Fix availability of inherited designated initializers, part 2
2018-07-30 18:40:11 -07:00
Jordan Rose
2e4501105a Merge pull request #18048 from jrose-apple/finding-ways-to-scope
Limit ValueDecl::getFormalAccess and get rid of adjustAccessLevelForProtocolExtension
2018-07-25 16:43:41 -07:00
Slava Pestov
336f51e5bc Sema: Fix availability of inherited designated initializers, part 2
We need to explicitly handle nested types here.

Fixes the (re-opened) <rdar://problem/40853731>,
<https://bugs.swift.org/browse/SR-7881>.
2018-07-24 16:13:45 -07:00
John McCall
70e2aea266 Merge pull request #18156 from rjmccall/generalized-accessors
Implement generalized accessors using yield-once coroutines
2018-07-23 22:58:25 -04:00
Jordan Rose
ca14d6c84d Take away some of ValueDecl::getFormalAccess's capabilities
...to push people towards getFormalAccessScope. The one use case that
isn't covered by that is checking whether a declaration behaves as
'open' in the current file; I've added ValueDecl::hasOpenAccess to
handle that specific case.

No intended functionality change.
2018-07-23 16:36:16 -07:00
John McCall
7a4aeed570 Implement generalized accessors using yield-once coroutines.
For now, the accessors have been underscored as `_read` and `_modify`.
I'll prepare an evolution proposal for this feature which should allow
us to remove the underscores or, y'know, rename them to `purple` and
`lettuce`.

`_read` accessors do not make any effort yet to avoid copying the
value being yielded.  I'll work on it in follow-up patches.

Opaque accesses to properties and subscripts defined with `_modify`
accessors will use an inefficient `materializeForSet` pattern that
materializes the value to a temporary instead of accessing it in-place.
That will be fixed by migrating to `modify` over `materializeForSet`,
which is next up after the `read` optimizations.

SIL ownership verification doesn't pass yet for the test cases here
because of a general fault in SILGen where borrows can outlive their
borrowed value due to being cleaned up on the general cleanup stack
when the borrowed value is cleaned up on the formal-access stack.
Michael, Andy, and I discussed various ways to fix this, but it seems
clear to me that it's not in any way specific to coroutine accesses.

rdar://35399664
2018-07-23 18:59:58 -04:00
Slava Pestov
f6b96da3e2 Move TypeChecker::configureInterfaceType() to {AbstractFunction,Subscript}Decl::computeType()
It doesn't actually depend on the type checker, and using
it on synthesized declarations will eliminate a lot of
boilerplate.
2018-07-23 02:09:43 -07:00
Slava Pestov
bfc4121971 AST: Rework AbstractFunctionDecl construction away from multiple parameter lists
There are two general constructor forms here:

- One took the number of parameter lists, to be filled in later.
  Now, this takes a boolean indicating if there is an implicit
  'self'.

- The other one took the actual parameter lists and filled them
  in right away. This now takes a separate 'self' ParamDecl and
  ParameterList.

Instead of storing the number of parameter lists, an
AbstractFunctionDecl now only needs to store if there is a 'self'
or not.

I've updated most places that construct AbstractFunctionDecls to
properly use these new forms. In the ClangImporter, there is
more code that remains to be untangled, so we continue to build
multiple ParameterLists and unpack them into a ParamDecl and
ParameterList at the last minute.
2018-07-21 07:30:30 -07:00
Slava Pestov
e1da265873 Sema: Remove uses of AbstractFunctionDecl::getParameterLists() 2018-07-19 21:21:17 -07:00
Doug Gregor
8741a886fa [Type checker] Allow implicitly-generated initializers to not be @objc.
When an implicitly-generated override of an @objc initializer cannot
be represented in Objective-C, implicitly add @nonobjc. These issues
will be diagnosed early on.

Similarly, when we implicitly create an initializer, allow it to not
be @objc even under Swift 3’s inference rules.
2018-07-18 14:50:41 -07:00
Doug Gregor
d9faa7415c [Type Checker] Add a request kind for ‘dynamic’.
Separate out the semantic state for the ‘dynamic’ check (from the
presence of the attribute), and move all of the computation of the
‘dynamic’ bit into the request-evaluator.

In the process, this fixes a bug where implicitly-synthesized initializers
in subclasses of imported classes would not be implicitly made ‘final’.
2018-07-18 14:50:39 -07:00
Doug Gregor
b70466dc63 [Type Checker] Add a request kind for computing 'ValueDecl::isObjC()'.
Still a WIP
2018-07-18 14:50:39 -07:00
Doug Gregor
0b5ec6f180 [Type Checker] Don’t explicit set overridden decls of accessors.
The overridden declarations of accessors are computed; they don’t need to
be set explicitly.
2018-07-18 14:50:38 -07:00
David Zarzycki
b29d2784ed [AST] NFC: Formalize Decl validation tracking via RAII
After this change, RAII ensures that the validation state is accurate as
possible.
2018-07-12 10:30:26 -04:00
Slava Pestov
381483bd74 AST: Remove Expr's LValueAccessKind 2018-07-05 23:54:13 -07:00
Doug Gregor
d99799486d [Type Checker] Upgrade ObjCReason to a class wrapping an enum.
Provide more information in ObjCReason for the case where we are
@objc because we are a witness to an @objc requirement, by carrying the
@objc requirement in the reason. Use this to eliminate the type checker
parameter from describeObjCReason().
2018-07-05 10:32:59 -07:00
Doug Gregor
f4359b73f9 Merge pull request #17729 from DougGregor/minimize-override-checking
[Type checker] Minimize checking needed to compute the set of overridden declarations
2018-07-05 06:38:46 -07:00
Ben Cohen
2b04e9f105 Suppress a number of warnings in no-assert builds (#17721)
* Supress a number of warnings about things used only in asserts

* Re-use a couple of variables instead of supressing the warning
2018-07-04 07:15:14 -07:00
Doug Gregor
7279eeeeac [Type checker] Perform more minimal checking in resolveOverriddenDecl().
Rather than deferring to the heavyweight validateDeclForNameLookup()
to perform the “get overridden decls” operation, perform a much more
minimal validation that only looks for exact matches when the ‘override’
modifier is present.

The more-extensive checking (e.g., that one didn’t forget an override
modifier) is only performed as part of the “full” type checking of
a declaration, which will typically only be done within the same source
file as the declaration. The intent here is to reduce the amount of
work performed to check overrides cross-file, and limit the dependencies
of the “get overridden decls” operation.
2018-07-03 17:26:38 -07:00