Commit Graph

38 Commits

Author SHA1 Message Date
Doug Gregor
236418dbf8 Make the "typechecked function body" request more central and resilient
The "typechecked function body" request was defined to type-check a
function body that is known to be present, and not skipped, and would
assert these conditions, requiring its users to check whether a body
was expected. Often, this means that callers would use `getBody()`
instead, which retrieves the underlying value in whatever form it
happens to be, and assume it has been mutated appropriately.

Make the "typechecked function body" request, triggered by
`getTypecheckedBody()`, more resilient and central. A `NULL` result is
now acceptable, signifying that there is no body. Clients will need to
tolerate NULL results.

* When there is no body but should be one, produce an appropriate
error.
* When there shouldn't be a body but is, produce an appropriate error
* Handle skipping of function bodies here, rather than elsewhere.

Over time, we should move clients off of `getBody` and `hasBody`
entirely, and toward `getTypecheckedBody` or some yet-to-be-introduced
forms like `getBodyAsWritten` for the pre-typechecked body.
2023-11-26 09:09:29 -08:00
Doug Gregor
5ad39c84e0 [Typed throws] Record thrown error types and conversions in the AST
For any operation that can throw an error, such as calls, property
accesses, and non-exhaustive do..catch statements, record the thrown
error type along with the conversion from that thrown error to the
error type expected in context, as appropriate. This will prevent
later stages from having to re-compute the conversion sequences.
2023-10-24 12:40:22 -07:00
Doug Gregor
ef642098f2 [Typed throws] Parsing and AST representation for typed errors
Parse typed throw specifiers as `throws(X)` in every place where there
are effects specified, and record the resulting thrown error type in
the AST except the type system. This includes:
* `FunctionTypeRepr`, for the parsed representation of types
* `AbstractFunctionDecl`, for various function-like declarations
* `ClosureExpr`, for closures
* `ArrowExpr`, for parsing of types within expression context

This also introduces some serialization logic for the thrown error
type of function-like declarations, along with an API to extract the
thrown interface type from one of those declarations, although right
now it will either be `Error` or empty.
2023-09-29 10:51:51 -07:00
Doug Gregor
593c2364e8 [Macros] "Subsume" the initializer when an accessor macros adds non-observers
When an accessor macro adds a non-observing accessor to a property, it
subsumes the initializer. We had previously modeled this as removing
the initializer, but doing so means that the initializer could not be
used for type inference and was lost in the AST.

Explicitly mark the initializer as "subsumed" here, and be more
careful when querying the initializer to distinguish between "the
initializer that was written" and "the initializer that will execute"
in more places. This distinction already existed at the
pattern-binding level, but not at the variable-declaration level.

This is the proper fix for the circular reference issue described in
rdar://108565923 (test case in the prior commit).
2023-04-28 09:50:00 -07:00
Doug Gregor
200f2340d9 [Macros] Be deliberate about walking macro arguments vs. expansions
Provide ASTWalker with a customization point to specify whether to
check macro arguments (which are type checked but never emitted), the
macro expansion (which is the result of applying the macro and is
actually emitted into the source), or both. Provide answers for the
~115 different ASTWalker visitors throughout the code base.

Fixes rdar://104042945, which concerns checking of effects in
macro arguments---which we shouldn't do.
2023-02-28 17:48:23 -08:00
Doug Gregor
402ba1492f Set closure descriminators via a request.
Rather than set closure discriminators in both the parser (for explicit
closures) and then later as part of contextualizing closures (for
autoclosures), do so via a request that sets all of the discriminators
for a given context.
2022-12-19 15:23:45 -08:00
Doug Gregor
0b78b9a0b0 [Macros] Ensure that macro expansion parsing has appropriate context.
The parser needs context to do completely reasonable things like... parse
closures.
2022-11-07 16:34:18 -08:00
Hamish Knight
4716f61fba [AST] Introduce explicit actions for ASTWalker
Replace the use of bool and pointer returns for
`walkToXXXPre`/`walkToXXXPost`, and instead use
explicit actions such as `Action::Continue(E)`,
`Action::SkipChildren(E)`, and `Action::Stop()`.
There are also conditional variants, e.g
`Action::SkipChildrenIf`, `Action::VisitChildrenIf`,
and `Action::StopIf`.

There is still more work that can be done here, in
particular:

- SourceEntityWalker still needs to be migrated.
- Some uses of `return false` in pre-visitation
methods can likely now be replaced by
`Action::Stop`.
- We still use bool and pointer returns internally
within the ASTWalker traversal, which could likely
be improved.

But I'm leaving those as future work for now as
this patch is already large enough.
2022-09-13 10:35:29 +01:00
Pavel Yaskevich
b337360d63 [Sema] DebuggerTestingTransform: avoid re-using AST nodes in generated code
While building a closure to inject `checkExpect` code, clone member
references associated with assignment. Re-using AST nodes is generally
invalid. This is visible with multi-statement closure inference enabled,
because the body is type-checked together with enclosing context
and both elements end up sharing `DeclRefExpr` and `MemberRefExpr`s.
2021-12-03 10:53:40 -08:00
Pavel Yaskevich
bc54bc6bb7 Revert "[TypeChecker] SE-0326: Enable multi-statement closure inference by default" 2021-11-29 17:26:08 -08:00
Pavel Yaskevich
990d8c8bce [Sema] DebuggerTestingTransform: avoid re-using AST nodes in generated code
While building a closure to inject `checkExpect` code, clone member
references associated with assignment. Re-using AST nodes is generally
invalid. This is visible with multi-statement closure inference enabled,
because the body is type-checked together with enclosing context
and both elements end up sharing `DeclRefExpr` and `MemberRefExpr`s.
2021-11-15 16:42:04 -08:00
Hamish Knight
47754822c7 [CodeSynthesis] Adopt ArgumentList
Most of this should be fairly mechanical, the
changes in PlaygroundTransform are a little more
involved though.
2021-09-01 18:40:26 +01:00
Hamish Knight
c70f280e4a [AST] Add CallExpr::createImplicitEmpty
Add a convenience constructor for an implicit
nullary call. This will become more useful when
the argument parameter starts taking an
ArgumentList.
2021-07-28 23:14:43 +01:00
Doug Gregor
8448e61b3a Add support for attributes on closures. 2021-02-16 22:19:43 -08:00
Pavel Yaskevich
0b648fb455 [TypeChecker] NFC: Include constraint system into TypeChecker header
Avoids having to include ConstraintSystem.h in TypeCheck*.cpp
files to gain access to ContextualInfo and related classes.
2020-10-06 15:42:46 -07:00
Pavel Yaskevich
05b223aa0b [Sema] Switch typeCheckExpression to use ContextualTypeInfo 2020-10-06 12:21:07 -07:00
Doug Gregor
5dd1bfea8d [Concurrency] Add support for 'async' closures.
Closurea can become 'async' in one of two ways:
* They can be explicitly marked 'async' prior to the 'in'
* They can be inferred as 'async' if they include 'await' in the body
2020-08-11 13:59:59 -07:00
Slava Pestov
3aa33250ec Sema: Sink DiscriminatorFinder down into DebuggerTestingTransform 2020-06-25 19:35:06 -04:00
Dan Zheng
f9c5d7ae6c [AutoDiff] Derive Differentiable.zeroTangentVectorInitializer. (#31823)
`Differentiable` conformance derivation now supports
`Differentiable.zeroTangentVectorInitializer`.

There are two potential cases:
1. Memberwise derivation: done when `TangentVector` can be initialized memberwise.
2. `{ TangentVector.zero }` derivation: done as a fallback.

`zeroTangentVectorInitializer` is a closure that produces a zero tangent vector,
capturing minimal necessary information from `self`.

It is an instance property, unlike the static property `AdditiveArithmetic.zero`,
and should be used by the differentiation transform for correctness.

Remove `Differentiable.zeroTangentVectorInitializer` dummy default implementation.

Update stdlib `Differentiable` conformances and tests.
Clean up DerivedConformanceDifferentiable.cpp cruft.

Resolves TF-1007.
Progress towards TF-1008: differentiation correctness for projection operations.
2020-05-29 01:59:52 -07:00
Robert Widmann
5b3060318e [NFC] Strip ClosureExpr of its TypeLoc 2020-04-28 20:10:10 -07:00
Anthony Latsis
74252028ca AST: Rename getFullName -> getName on ValueDecl & MissingMemberDecl 2020-04-23 05:16:55 +03:00
Robert Widmann
6d60d01420 [NFC] Remove the Legacy Semantic Queries Bit
Clients that wish to avoid semantic requests should decline to register
those requests.
2020-03-19 11:04:12 -07:00
Robert Widmann
70b6bbcb13 Remove swift::createTypeChecker
Replace it with the "legacy semantic queries" bit. The remaining client
of this bit is SourceKit, which appears to require this bit be set
conditionally so certain semantic property wrapper requests return
a sentinel value.

We should migrate these requests to a syntactic interface as soon as
possible.

rdar://60516325
2020-03-16 19:20:22 -07:00
Robert Widmann
96b3b9f0f4 [NFC] Hide SourceFile::Decls
In preparation for installing some stable paths infrastructure here,
hide access to the array of top-level decls.
2020-01-03 14:14:00 -08:00
Frederick Kellison-Linn
71697c37ca Allow implicit self in escaping closures when self usage is unlikely to cause cycle (#23934)
* WIP implementation

* Cleanup implementation

* Install backedge rather than storing array reference

* Add diagnostics

* Add missing parameter to ResultFinderForTypeContext constructor

* Fix tests for correct fix-it language

* Change to solution without backedge, change lookup behavior

* Improve diagnostics for weak captures and captures under different names

* Remove ghosts of implementations past

* Address review comments

* Reorder member variable initialization

* Fix typos

* Exclude value types from explicit self requirements

* Add tests

* Add implementation for AST lookup

* Add tests

* Begin addressing review comments

* Re-enable AST scope lookup

* Add fixme

* Pull fix-its into a separate function

* Remove capturedSelfContext tracking from type property initializers

* Add const specifiers to arguments

* Address review comments

* Fix string literals

* Refactor implicit self diagnostics

* Add comment

* Remove trailing whitespace

* Add tests for capture list across multiple lines

* Add additional test

* Fix typo

* Remove use of ?: to fix linux build

* Remove second use of ?:

* Rework logic for finding nested self contexts
2019-12-20 02:38:41 +00:00
Brent Royal-Gordon
6a8598a99c [NFC] Remove DeclNameRef staging calls 2019-12-11 00:55:18 -08:00
Brent Royal-Gordon
addbe3e5ed [NFC] Thread DeclNameRef through most of the compiler
This huge commit contains as many of the mechanical changes as possible.
2019-12-11 00:55:18 -08:00
Brent Royal-Gordon
36b949c555 [NFC] Improve identifier usage in AST transforms
Change the various AST transforms to use prebuilt DeclName constants more heavily rather than an ad-hoc mix of Identifiers, string literals, std::strings, and StringRefs with questionable memory management.
2019-12-11 00:45:08 -08:00
Robert Widmann
d21424b58b Make typeCheckExpression a utility 2019-11-10 12:40:09 -08:00
Robert Widmann
2b08d1b834 [NFC] ASTContext::getLazyResolver -> ASTContext::getLegacyGlobalTypeChecker 2019-11-05 14:44:41 -08:00
Jordan Rose
8d7f1b7c5d [AST] Separate SourceFile from FileUnit.h
Like the last commit, SourceFile is used a lot by Parse and Sema, but
less so by the ClangImporter and (de)Serialization. Split it out to
cut down on recompilation times when something changes.

This commit does /not/ split the implementation of SourceFile out of
Module.cpp, which is where most of it lives. That might also be a
reasonable change, but the reason I was reluctant to is because a
number of SourceFile members correspond to the entry points in
ModuleDecl. Someone else can pick this up later if they decide it's a
good idea.

No functionality change.
2019-09-17 17:54:41 -07:00
Jordan Rose
853caa66d4 [AST] Split FileUnit and its subclasses out of Module.h
Most of AST, Parse, and Sema deal with FileUnits regularly, but SIL
and IRGen certainly don't. Split FileUnit out into its own header to
cut down on recompilation times when something changes.

No functionality change.
2019-09-17 17:54:41 -07:00
Slava Pestov
c1adfed00d Sema: TypeChecker::computeCaptures() and friends should be static 2019-08-07 00:35:50 -04:00
Slava Pestov
a532a325e1 AST: Move a few methods from VarDecl down to ParamDecl 2019-07-22 20:19:09 -04:00
Doug Gregor
6526cfa8d4 Memberwise initializer synthesis for properties with attached delegates. 2019-04-23 11:31:58 -07:00
Doug Gregor
599e07e5d9 [Type checker] Keep the type checker alive as long as the ASTContext is.
It is possible for the SIL optimizers, IRGen, etc. to request information
from the AST that only the type checker can provide, but the type checker
is typically torn down after the “type checking” phase. This can lead to
various crashes late in the compilation cycle.

Keep the type checker instance around as long as the ASTContext is alive
or until someone asks for it to be destroyed.

Fixes SR-285 / rdar://problem/23677338.
2018-10-10 16:44:42 -07:00
Vedant Kumar
e30c5b249d [Debugger] Teach the testing transform about assignments to members (#16222)
This teaches the debugger testing transform how to instrument
assignments to class members.
2018-04-27 14:38:41 -07:00
Vedant Kumar
ca27e829ba Add a transform to help test lldb expression evaluation
The initial version of the debugger testing transform instruments
assignments in a way that allows the debugger to sanity-check its
expression evaluator.

Given an assignment expression of the form:

```
  a = b
```

The transform rewrites the relevant bits of the AST to look like this:

```
  { () -> () in
    a = b
    checkExpect("a", stringForPrintObject(a))
  }()
```

The purpose of the rewrite is to make it easier to exercise the
debugger's expression evaluator in new contexts. This can be automated
by having the debugger set a breakpoint on checkExpect, running `expr
$Varname`, and comparing the result to the expected value generated by
the runtime.

While the initial version of this testing transform only supports
instrumenting assignments, it should be simple to teach it to do more
interesting rewrites.

There's a driver script available in SWIFT_BIN_DIR/lldb-check-expect to
simplfiy the process of launching and testing instrumented programs.

rdar://36032055
2018-03-30 16:50:31 -07:00