Commit Graph

615 Commits

Author SHA1 Message Date
John McCall
cc2863c136 Merge pull request #36878 from rjmccall/custom-executors
Introduce basic support for custom executors
2021-04-30 13:54:02 -04:00
Hamish Knight
f439275380 Mark imported @completionHandlerAsync attrs as implicit
Mark imported `@completionHandlerAsync` attrs as
implicit, which avoids printing them in generated
interfaces. And for the sake of completion,
serialize the implicit bit in case it's used
elsewhere in the future.

To make sure we continue to print
`@completionHandlerAsync` attributes explicitly
written by the user in Swift, add a SourceKit
interface test.

Resolves rdar://76685011
2021-04-30 11:14:50 +01:00
John McCall
769c2e76f1 Add a utility to clone an @available attribute. 2021-04-30 03:11:43 -04:00
Richard Wei
82886bf77a [AutoDiff] Fix mangling of '@noDerivative' in function types.
`@noDerivative` was not mangled in function types, and was resolved incorrectly when there's an ownership specifier. It is fixed by this patch with the following changes:

* Add `NoDerivative` demangle node represented by a `k` operator.
    ```
    list-type ::= type identifier? 'k'? 'z'? 'h'? 'n'? 'd'?  // type with optional label, '@noDerivative', inout convention, shared convention, owned convention, and variadic specifier
    ```
* Fix `NoDerivative`'s overflown offset in `ParameterTypeFlags` (`7` -> `6`).
* In type decoder and type resolver where attributed type nodes are processed, add support for nested attributed nodes, e.g. `inout @noDerivative T`.
* Add `TypeResolverContext::InoutFunctionInput` so that when we resolve an `inout @noDerivative T` parameter, the `@noDerivative T` checking logic won't get a `TypeResolverContext::None` set by the caller.

Resolves rdar://75916833.
2021-04-07 15:42:12 -07:00
Ben Barham
3de83aca66 [ClangImporter] Add @completionHandlerAsync for imported decls
Implicitly add the @completionHandlerAsync attribute for ObjCMethodDecl
that have a completion handler. Adds a link from the non-async to the
async function for use in diagnostics and refactorings.

Resolves rdar://74665226
2021-03-31 08:39:12 +10:00
Becca Royal-Gordon
1f134c1160 Soften general attr diagnostics for access notes 2021-03-24 14:55:06 -07:00
Becca Royal-Gordon
69fb104244 Diagnose access note @objc failures using remarks
This commit adds an ObjCReason::ExplicitlyObjCByAccessNote value which diagnoses invalid uses, but using remarks instead of errors so that the failures don’t block builds even with -warnings-as-errors enabled.

This commit also adds annotations to attr/attr_objc.swift to generate a ton of access note test cases from it. In this commit, many of these test cases don’t pass yet. Subsequent commits will fix these bugs.
2021-03-24 14:51:44 -07:00
Doug Gregor
f7800fde31 Propagate parsed type attributes to TypeAttributes.
Propagate parsed type attributes to the TypeAttributes structure, so they
persist in the AST and can be processed by the type checker. Move the
"unknown attribute" diagnostic for custom attributes on types into
the type checker.
2021-03-16 19:52:16 -07:00
Evan Wilde
eaab395973 Remove ExplicitCompletionHandlerIndex flag
Assuming that we don't typecheck a deserialized module, we don't
actually need the ExplicitCompletionHandlerIndex. We used this flag to
determine whether we could trust the number stored in the handler index
or just take the last parameter of the function we're attached to.

Since we only typecheck it before serialization, we can safely check
that the completion handler location is valid before choosing whether we
should trust it or not.
2021-03-13 13:38:15 -08:00
Evan Wilde
9f412616d8 Remove AsyncFunctionName from serialization
We can get the DeclName of the async function from the resolved function
decl itself, so we don't actually need to serialize it. This patch pulls
the declNameRef from the serialization.
2021-03-13 13:38:15 -08:00
Evan Wilde
2b0def501f Replace @hasAsyncAlt with @completionHandlerAsync
This patch replaces the @hasAsyncAlternative attribute with
@completionHandlerAsync. The @completionHandlerAsync attribute takes the
function decl name of the async function and optionally the index of the
completion hander parameter in the function that it's attached to.
If the completion handler index is not provided, it's assumed to be the
last parameter in the parameter list.

We resolve the async function while typechecking the attribute. Before
resolving, we verify that the function the attribute is attached to
isn't async, that it has enough parameters to at least have the
indicated completion handler referenced by the index, that the
completion handler is an escaping non-auto-closure function that returns
Void.

The async function declaration resolution isn't perfect yet, but I want
to get this patch up and we can refine it later. It pulls all of the
delcs with the specified declname in the same context as the
function that the attribute is attached to. Going through that list, it
keeps any that are async functions. If there are none, we emit an error
saying that there are no viable functions, if there are multiple we emit
an error saying that the decl name is ambiguous, and if there is one
function, we keep that as the resolve async function declaration.

This does not take into account the data types of the completion handler
or the async function. There are some complexities to making this
mapping. Here are the pieces:
 - If the completion handler takes a single data type, the async
   function should return that type. (easy case)
 - If the completion handler takes a `Result<T, Error>`, the async
   function is a throwing function that returns a T. (Medium difficulty)
 - If the completion handler looks like `(T?, Error?) -> Void`, we have
   an ambiguous situation between the following async functions:
   - func foo() async throws -> T
   - func foo() async throws -> T?
   That is, we cannot tell whether the `T?` in the completion handler is
   optional because it will be nil on an error, or if it is intended to
   be optional.

This can be done later if it becomes a problem.
2021-03-13 13:38:15 -08:00
Doug Gregor
7feafbdb9e Merge pull request #36177 from DougGregor/global-actor-unsafe 2021-02-26 07:24:06 -08:00
Doug Gregor
451e6cc1f5 [Concurrency] Add support for @GlobalActor(unsafe).
Allow us to tag declarations that are meant to be in a global actor, but
for which we don't yet want to enforce everything. This will be used for
better staging-in of global actor annotations, but for now it's a fancy
way to document @actorIndependent(unsafe).

Stages in the syntax for rdar://74241687 without really implementing it.
2021-02-25 22:41:32 -08:00
Holly Borla
8bdc8f9dde [Property Wrappers] Use the TypeExpr instead of the TypeRepr of the
property wrapper custom attribute to get the backing wrapper type
in CSApply.

This is necessary because implicit custom attributes do not have
TypeReprs, but they always have TypeExprs.
2021-02-25 18:35:13 -08:00
Ben Barham
3a7bf2301b [AST] Add a new attribute @hasAsyncAlternative
This attribute marks a function has having an async alternative,
optionally providing the name of that function as a string. Intended to
be used to allow warnings when using a function with an async
alternative in an asynchronous context, to make the async refactorings
more accurate, and for documentation.
2021-02-18 16:18:38 +10:00
Richard Wei
af8942d940 [AutoDiff] Rename '@differentiable' to '@differentiable(reverse)'.
Compiler:
- Add `Forward` and `Reverse` to `DifferentiabilityKind`.
- Expand `DifferentiabilityMask` in `ExtInfo` to 3 bits so that it now holds all 4 cases of `DifferentiabilityKind`.
- Parse `@differentiable(reverse)` and `@differentiable(_forward)` declaration attributes and type attributes.
- Emit a warning for `@differentiable` without `reverse`.
- Emit an error for `@differentiable(_forward)`.
- Rename `@differentiable(linear)` to `@differentiable(_linear)`.
- Make `@differentiable(reverse)` type lowering go through today's `@differentiable` code path. We will specialize it to reverse-mode in a follow-up patch.

ABI:
- Add `Forward` and `Reverse` to `FunctionMetadataDifferentiabilityKind`.
- Extend `TargetFunctionTypeFlags` by 1 bit to store the highest bit of differentiability kind (linear). Note that there is a 2-bit gap in `DifferentiabilityMask` which is reserved for `AsyncMask` and `ConcurrentMask`; `AsyncMask` is ABI-stable so we cannot change that.

_Differentiation module:
- Replace all occurrences of `@differentiable` with `@differentiable(reverse)`.
- Delete `_transpose(of:)`.

Resolves rdar://69980056.
2021-02-07 14:09:46 -08:00
Kavon Farvardin
34d22105b8 implemented parsing and typechecking for @actorIndependent(unsafe)
[broken] first impl of @actorIndependent in the type checker.

[broken] fixed mistake in my parsing code wrt invalid source range

[broken] found another spot where ActorIndependent needs custom handling

[broken] incomplete set of @actorIndependent(unsafe) tests

updates to ActorIndependentUnsafe

[fixed] add FIXME plus simple handling of IndependentUnsafe context

finished @actorIndependent(unsafe) regression tests

added wip serialization / deserialization test

focus test to just one actor class

round-trip serialize/deserialize test for @actorIndependent

serialize -> deserialize -> serialize -> compare to original

most of doug's comments

addressed robert's comments

fix printing bug; add module printing to regression test

[nfc] update comment for ActorIsolation::IndependentUnsafe
2020-10-19 15:20:24 -07:00
Arnold Schwaighofer
2a2cf91dcd Add support for marking a _specialize attribute as SPI
```
  @_specialize(exported: true, spi: SPIGroupName, where T == Int)
  public func myFunc() { }
```

The specialized entry point is only visible for modules that import
using `_spi(SPIGroupName) import ModuleDefiningMyFunc `.

rdar://64993425
2020-10-12 09:19:29 -07:00
Arnold Schwaighofer
b994bf3191 Add support for _specialize(exported: true, ...)
This attribute allows to define a pre-specialized entry point of a
generic function in a library.

The following definition provides a pre-specialized entry point for
`genericFunc(_:)` for the parameter type `Int` that clients of the
library can call.

```
@_specialize(exported: true, where T == Int)
public func genericFunc<T>(_ t: T) { ... }
```

Pre-specializations of internal `@inlinable` functions are allowed.

```
@usableFromInline
internal struct GenericThing<T> {
  @_specialize(exported: true, where T == Int)
  @inlinable
  internal func genericMethod(_ t: T) {
  }
}
```

There is syntax to pre-specialize a method from a different module.

```
import ModuleDefiningGenericFunc

@_specialize(exported: true, target: genericFunc(_:), where T == Double)
func prespecialize_genericFunc(_ t: T) { fatalError("dont call") }

```

Specially marked extensions allow for pre-specialization of internal
methods accross module boundries (respecting `@inlinable` and
`@usableFromInline`).

```
import ModuleDefiningGenericThing
public struct Something {}

@_specializeExtension
extension GenericThing {
  @_specialize(exported: true, target: genericMethod(_:), where T == Something)
  func prespecialize_genericMethod(_ t: T) { fatalError("dont call") }
}
```

rdar://64993425
2020-10-12 09:19:29 -07:00
Doug Gregor
22a350b1ac [Concurrency] Add parsing support for actor classes.
Introduce the "actor class" syntax. Ensure that it is only used for
root classes or classes that inherit from other actor classes.
2020-09-09 20:46:30 -07:00
Slava Pestov
995eb66aa7 AST: Rename SpecializeAttr::getSpecializedSgnature() 2020-08-24 19:16:36 -04:00
Dan Zheng
bf47403162 [AutoDiff] Serialize and print @derivative and @transpose accessor kind. (#32839)
Serialize and print the optional accessor kind in `@derivative` and `@transpose`
attributes.

Resolves TF-1293.
2020-07-12 15:04:49 -07:00
ematejska
fbec91a1b5 [Autodiff] Derivative Registration for the Get and Set Accessors (#32614)
* initial changes

* Add tests, undo unnecessary changes.

* Fixing up computed properties accessors and adding tests for getters.

* Adding nested type testcase

* Fixing error message for when accessor is referenced but not acutally found.

* Cleanup.

- Improve diagnostic message.
- Clean up code and tests.
- Delete unrelated nested type `@derivative` attribute tests.

* Temporarily disable class subscript setter derivative registration test.

Blocked by SR-13096.

* Adding libsyntax integration and fixing up an error message.

* Added a helper function for checking if the next token is an accessor label.

* Update utils/gyb_syntax_support/AttributeNodes.py

Co-authored-by: Dan Zheng <danielzheng@google.com>

* Update lib/Parse/ParseDecl.cpp

Co-authored-by: Dan Zheng <danielzheng@google.com>

* Add end-to-end derivative registration tests.

* NFC: run `git clang-format`.

* NFC: clean up formatting.

Re-apply `git clang-format`.

* Clarify parsing ambiguity FIXME comments.

* Adding couple of more testcases and fixing up error message for when accessor is not found on functions resolved.

* Update lib/Sema/TypeCheckAttr.cpp

Co-authored-by: Dan Zheng <danielzheng@google.com>

Co-authored-by: Dan Zheng <danielzheng@google.com>
2020-07-01 20:14:58 -07:00
Robert Widmann
29cdbe87f1 Strip TypeEraserAttr of its TypeLoc 2020-06-10 19:33:31 -07:00
Robert Widmann
80d3a32ff5 Strip ImplementsAttr of its TypeLoc 2020-06-10 19:33:07 -07:00
Robert Widmann
fb8fdd9644 Replace resolveCustomAttrType with a Request 2020-06-10 19:31:41 -07:00
Joe Groff
c5863ac0f3 SILOptimizer: Constant fold the _kvcKeyPathString of literal key paths.
Eliminate the intermediate key path object when a literal key path is passed to a function that
just wants its KVC string to pass down to an ObjC API.
2020-05-07 13:33:01 -07:00
Marc Rasi
7abf8ae305 actually set the lazy resolver 2020-04-07 15:05:27 -07:00
Marc Rasi
78ac5eb0a3 add PointerUnion for parsed vs deserialized derivative attr 2020-04-07 10:25:30 -07:00
Dan Zheng
83f6714334 [AutoDiff] Start fixing SR-12526.
Start fixing SR-12526: `@derivative` attribute cross-module deserialization
crash. Remove original `AbstractFunctionDecl *` from `DerivativeAttr` and store
`DeclID` instead, mimicking `DynamicReplacementAttr`.
2020-04-06 06:37:23 -07:00
Robert Widmann
27b211c1f9 Lazy-load the eraser of @_typeEraser where possible
Type erasure requires a circular construction by its very nature:

@_typeEraser(AnyProto)
protocol Proto { /**/ }
public struct AnyProto : Proto {}

If we eagerly resolve AnyProto, the chain of resolution steps that
deserialization must make goes a little something like this:

Lookup(Proto)
    -> Deserialize(@_typeEraser(AnyProto))
    -> Lookup(AnyProto)
    -> DeserializeInheritedStuff(AnyProto)
    -> Lookup(Proto)

This cycle could be broken if the order of incremental inputs was
such that we had already cached the lookup of Proto.

Resolve this cycle in any case by suspending the deserialization of the
type eraser until the point it's demanded by adding
ResolveTypeEraserTypeRequest.

rdar://61270195
2020-04-03 14:52:21 -07:00
Dan Zheng
07596cbc9b [AutoDiff upstream] Relax @differentiable for protocol witnesses. (#30629)
Previously, all witnesses of a `@differentiable` protocol requirement were
required to have the same attribute (or one with superset parameter indices).

However, this leads to many annotations on witnesses and is not ideal for
usability. `@differentiable` attributes are really only significant on
public witnesses, so that they are clearly `@differentiable` at a glance (in
source code, interface files, and API documentation), without looking through
protocol conformance hierarchies.

Now, only *public* witnesses of `@differentiable` protocol requirements are
required to have the same attribute (or one with superset parameter indices).
For less-visible witnesses, an implicit `@differentiable` attribute is created
with the same configuration as the requirement's.

Resolves TF-1117.
Upstreams #29771 from tensorflow branch.
2020-03-25 08:13:27 -07:00
marcrasi
1be86adbfc [AutoDiff] forbid derivative registration using @differentiable (#30001)
Delete `@differentiable` attribute `jvp:` and `vjp:` arguments for derivative
registration. `@derivative` attribute is now the canonical way to register
derivatives.

Resolves TF-1001.
2020-03-24 00:41:27 -07:00
Holly Borla
9f09add09b Merge pull request #29966 from hborla/type-check-type-eraser-attribute
[Sema] Implement type checking for the `_typeEraser` attribute
2020-02-21 14:12:59 -08:00
Holly Borla
ebb727c0a3 [TypeCheckAttr] Allow a type eraser initializer to have more than one
generic requirement.
2020-02-19 17:07:30 -08:00
Alexis Laferrière
0e7029dfb5 Use "SPI group" for the name used in an @_spi attribute 2020-02-19 14:18:11 -08:00
Alexis Laferrière
d5969a9f3a [AST] Intro SPI attribute for access control and imports 2020-02-19 14:17:08 -08:00
Brent Royal-Gordon
5d74978268 [NFC] Heavily refactor NameBinding
This commit refactors NameBinding.cpp virtually to the point of a rewrite. The goal is to make the import handling code process a struct containing information extracted from an ImportDecl, rather than the ImportDecl itself, so that a future commit can perform the same processing on imports that are not directly represented by an ImportDecl. The result takes more code, but it disentangles a knot of complicated logic into separate threads.

One semi-functional change is that validation of scoped imports (i.e. checking that the declaration actually exists) is now deferred until all of the file’s imports have been processed. Once cross-imports are supported, this will be necessary because scoped imports can select declarations from cross-import overlays, and the full set of cross-import overlays can’t be known until all imports have been seen.

Some comments refer to things that won’t exist until the next commit, like the visibleModules property. I’ll let you in on a litlte secret: I didn’t really do this all in one go.
2020-02-18 11:08:36 -08:00
Holly Borla
c0d936ec8d [Sema] Implement type checking for the typeEraser attribute. 2020-02-14 17:47:23 -08:00
Holly Borla
ffba71b889 [Parse] Add an attribute for typeEraser.
This will be used for compiler-driven type erasure for dynamic
replacement of functions with an opaque return type. For now, just
parse the attribute and ignore it.
2020-02-11 17:30:21 -08:00
Devin Coughlin
082421048a [AST/Sema] Add availability attributes for macCatalyst
Add a platform kind and availability attributes for macCatalyst. macCatalyst
uses iOS version numbers and inherits availability from iOS attributes unless
a macCatalyst attribute is explicitly provided.
2020-01-21 20:27:14 -08:00
Dan Zheng
44d937d7c2 [AutoDiff upstream] Add @differentiable declaration attribute type-checking. (#29231)
The `@differentiable` attribute marks a function as differentiable.

Example:
```
@differentiable(wrt: x, jvp: derivativeFoo where T: Differentiable)
func id<T>(_ x: T) -> T { x }
```

The `@differentiable` attribute has an optional `wrt:` clause specifying the
parameters that are differentiated "with respect to", i.e. the differentiability
parameters. The differentiability parameters must conform to the
`Differentiable` protocol.

If the `wrt:` clause is unspecified, the differentiability parameters are
currently inferred to be all parameters that conform to `Differentiable`.

The `@differentiable` attribute also has optional `jvp:` and `vjp:` labels
for registering derivative functions. These labels are deprecated in favor of
the `@derivative` attribute and will be removed soon.

The `@differentiable` attribute also has an optional `where` clause, specifying
extra differentiability requirements for generic functions.

The `@differentiable` attribute is gated by the
`-enable-experimental-differentiable-programming` flag.

Code changes:
- Add `DifferentiableAttributeTypeCheckRequest`.
  - Currently, the request returns differentiability parameter indices, while
    also resolving `JVPFunction`, `VJPFunction`, and
    `DerivativeGenericSignature` and mutating them in-place in
    `DifferentiableAttr`. This was the simplest approach that worked without
    introducing request cycles.
- Add "is type-checked" bit to `DifferentiableAttr`.
  - Alternatively, I tried changing `DifferentiableAttributeTypeCheckRequest` to
    use `CacheKind::Cache` instead of `CacheKind::SeparatelyCached`, but it did
    not seem to work: `@differentiable` attributes in non-primary-files were
    left unchecked.

Type-checking rules (summary):
- `@differentiable` attribute must be declared on a function-like "original"
  declaration: `func`, `init`, `subscript`, `var` (computed properties only).
- Parsed differentiability parameters must be valid (if they exist).
- Parsed `where` clause must be valid (if it exists).
- Differentiability parameters must all conform to `Differentiable`.
- Original result must all conform to `Differentiable`.
- If JVP/VJP functions are specified, they must match the expected type.
  - `@differentiable(jvp:vjp:)` for derivative registration is deprecated in
    favor of `@derivative` attribute, and will be removed soon.
- Duplicate `@differentiable` attributes with the same differentiability
  parameters are invalid.
- For protocol requirements and class members with `@differentiable` attribute,
  conforming types and subclasses must have the same `@differentiable` attribute
  (or one with a superset of differentiability parameter indices) on
  implementing/overriding declarations.
2020-01-19 12:23:04 -08:00
Xi Ge
3ee9b1175c TBDGen: when previous install name map is specified, emit $ld$previous linker directives.
Progress towards: rdar://58281536
2020-01-17 15:57:25 -08:00
Xi Ge
80d6230105 Merge pull request #29241 from nkcsgexi/refactor-originally-defined
TBDGen: some refactoring to allow multiple platform kinds for linker directives. NFC
2020-01-16 13:16:00 -08:00
Xi Ge
caf88fb1eb TBDGen: some refactoring to allow multiple platform kinds for linker directives.
Tentatively fixing: rdar://58569201
2020-01-16 11:42:03 -08:00
Brent Royal-Gordon
0c478b6be6 Revert "Merge pull request #28665 from CodaFi/the-phantom-menace"
This reverts commit 43a3ab7e35, reversing
changes made to 4f39d9c749.

# Conflicts:
#	include/swift/AST/Attr.def
#	lib/AST/Attr.cpp
#	lib/Serialization/Deserialization.cpp
#	lib/Serialization/ModuleFormat.h
#	lib/Serialization/Serialization.cpp
2020-01-15 15:28:42 -08:00
Dan Zheng
6a7f84048d [AutoDiff upstream] Store @differentiable original declaration. (#29082)
Store in `DifferentiableAttr` the original declaration on which the attribute
is declared.

The original declaration is resolved during parsing and deserialization
(not yet upstreamed).

Progress towards TF-828: upstream `@differentiable` attribute type-checking.
2020-01-09 10:33:22 -08:00
Dan Zheng
033ddffe42 [AutoDiff] NFC: gardening. (#28928)
Upstream minor changes from `tensorflow` branch.
2020-01-09 07:05:20 -08:00
Dan Zheng
c9c51beda3 [AutoDiff] Attribute gardening. (#29050)
Upstream changes from `tensorflow` branch:
- https://github.com/apple/swift/pull/28932: deprecate `@differentiable(jvp:vjp)` arguments.
- https://github.com/apple/swift/pull/29038: gardening.

Additional gardening included.
2020-01-07 19:24:52 -08:00
Kita, Maksim
a2cce2b293 SR-11889: Fixed code review issues 2019-12-20 17:19:00 +03:00