Commit Graph

187 Commits

Author SHA1 Message Date
Alex Hoppen
931f3394d7 [Parse] Create SwitchStmt nodes for switch statements with errors
At the moment, if there is an error in the `switch` statement expression or if the `{` is missing, we return `nullptr` from `parseStmtSwitch`, but we consume tokens while trying to parse the `switch` statement. This causes the AST to not contain any nodes for the tokens that were consumed while trying to parse the `switch` statement.

While this doesn’t cause any issues during compilation (compiling fails anyway so not having the `switch` statement in the AST is not a problem) this causes issues when trying to complete inside an expression that was consumed while trying to parse the `switch` statement but doesn’t have a representation in the AST. The solver-based completion approach can’t find the expression that contains the completion token (because it’s not part of the AST) and thus return empty results.

To fix this, make sure we are always creating a `SwitchStmt` when consuming tokens for it.

Previously, one could always assume that a `SwitchStmt` had a valid `LBraceLoc` and `RBraceLoc`. This is no longer the case because of the recovery. In order to form the `SwitchStmt`’s `SourceRange`, I needed to add a `EndLoc` property to `SwitchStmt` that keeps track of the last token in the `SwitchStmt`. Theoretically we should be able to compute this location by traversing the right brace, case stmts, subject expression, … in reverse order until we find something that’s not missing. But if the `SubjectExpr` is an `ErrorExpr`, representing a missing expression, it might have a source range that points to one after the last token in the statement (this is due to the way the `ErrorExpr` is being constructed), therefore returning an invalid range. So overall I thought it was easier and safer to add another property.

Fixes rdar://76688441 [SR-14490]
2021-04-15 18:37:25 +02:00
Dario Rexin
e42cf5b154 [Frontend] Remove enable-experimental-enum-codable-derivation flag
SE-295 has been accepted, so we don't need to hide the feature behind a flag anymore.
2021-03-25 15:26:21 -07:00
Dario Rexin
8e0a260414 [Sema]: Add Codable synthesis for enums with associated values (#34855)
* [Sema]: Add Codable synthesis for enums with associated values

* Incorporate review feedback for enum Codable synthesis

* Implement enum specific versions of existing Codable tests

* Encode parameterless enum cases as

* Add test for overloaded case identifiers

* Align code generation with latest proposal revision

* Put enum codable derivation behind flag

* clang-format sources

* Address review feedback and fix tests

* Add diagnostic for conflicting parameter identifiers

* Restructure code after rebase
2021-02-26 17:20:34 -08:00
Robert Widmann
6c9fb0d55c Undo Bogus DiagnosticTransactions in Codable Synthesis
The order of diagnostic emission absolutely does not matter. What this transaction was actually doing was suppressing valid diagnostics. This is a deeply unsound thing to do since if errors are emitted but Codable synthesis succeeds then invalid code can make its way past Sema.

rdar://74392492
2021-02-19 16:58:38 -08:00
Robert Widmann
fa8f0300dd Split CodingKeys Synthesis From Validation 2021-02-19 16:04:01 -08:00
Robert Widmann
6df3fcf3ad Add Missing Definitions of canDerive{En,De}codable 2021-02-19 16:03:32 -08:00
Ben Barham
33bc38cdb8 [IDE] SourceEntityWalker should walk all explicit declarations
`SourceEntityWalker` had an unbalanced `walkToDeclPre` and
`walkToDeclPost`, ie. `walkToDeclPost` could be called even though
`walkToDeclPre` was not. Specifically, this would occur for both
`OperatorDecl` and `PrecedenceGroupDecl` declarations.

These could both be added to the `if` in `walkToDeclPost`, but this
seems fairly errorprone in general - especially as new decls are added.
Indeed, there's already declarations that are being skipped because they
aren't explicitly tested for in `walkToDeclPre`, ie.
`PatternBindingDecl`.

Instead of skipping if not explcitly handled, only skip running the
`SEWalker` walk methods if the declaration is implicit (and not a
constructor decl, see TODO). This should probably also always visit
children, with various decls changed to become implicit (eg.
TopLevelCodeDecl), but we can do that later - breaks too many tests for
now.

This change exposed a few parameter declarations that were missing their
implicit flag, as well as unbalanced walk methods in `RangeResolver`.
2021-02-11 10:34:07 +10:00
Doug Gregor
3dc4c7868c Mark more declarations as synthesized 2021-01-20 12:56:31 -08:00
Robert Widmann
4351bd374a Use The Location of the Pattern Binding in Codable Fixit
The code here used to use the location of the nearest place to insert
attributes, which makes no sense. Use the pattern binding's location
instead to ensure that we actually replace the 'let' part of the
pattern every time.

rdar://69971194
2020-10-13 14:12:19 -07:00
Robert Widmann
ff8d5bc2c8 [NFC] MutableArrayRef<TypeLoc> -> ArrayRef<TypeLoc>
The first step on the road to splitting the semantic type information here from the syntactic information in the other half of the TypeLoc.
2020-10-09 15:29:55 -07:00
Doug Gregor
6af690aaba Eliminate HasCircularInheritanceRequest.
This is now reliably detected by SuperclassDeclRequest.
2020-09-29 17:42:17 -07:00
Slava Pestov
d7f4b1a1bd AST: Capture list bindings now point back to their parent CaptureListExpr
We'll need this to get the right 'selfDC' when name lookup
finds a 'self' declaration in a capture list, eg

class C {
  func bar() {}
  func foo() {
    _ = { [self] in bar() }
  }
}
2020-09-18 02:59:15 -04:00
Anthony Latsis
efa8f86193 [NFC] FuncDecl: Strip factory constructors out of TypeLocs 2020-08-19 00:09:10 +03:00
Robert Widmann
aada983ceb Replace supersuperclassConformsTo
This more powerful primitive is capable of
1) Detecting invalid classes
2) Detecting invalid superclasses
3) Detecting circularity in inheritance hierarchies

The attached crasher demonstrates the reason we need to validate all of these predicates. Simply put, a circular class hierarchy is always going to report the superclass conforms to any protocol with a declaration in the source. Leveraging this, one could construct any circular class hierarchy, and a conformance to Codable would immediately crash because we got as far as trying to build a CodingKeys enum with an absolutely nonsensical structure.

This also has the added benefit of de-complecting an enormous amount of codable conformance code.

rdar://66588925
2020-08-10 14:38:29 -07:00
Robert Widmann
3b9b5400c2 Clean up modeling of CodingKeysValidity
The quad-state here is completely superfluous. Break it down into an enum class that encodes the relevant cases we care about and clean up its sole caller.
2020-08-10 14:37:20 -07:00
Robert Widmann
05f418a025 Remove CodableConformanceType
This complexity is due to the implementation constraints of Codable synthesis at a time when the type checker could return partially-validated results. This is no longer the case, so all of this code is just technical debt.
2020-08-10 14:29:58 -07:00
Robert Widmann
c077455756 Use a SmallMapVector instead of a SmallDenseMap
validateCodingKeysEnum cannot iterate over a hashed collection without ordering guarantees.
2020-08-10 13:30:38 -07:00
Slava Pestov
45fc0bc4db Sema: Replace some calls to getDeclaredType() with getDeclaredInterfaceType() 2020-07-31 13:39:02 -04:00
Doug Gregor
f6e9f352f0 [Concurrency] Add async to the Swift type system.
Add `async` to the type system. `async` can be written as part of a
function type or function declaration, following the parameter list, e.g.,

  func doSomeWork() async { ... }

`async` functions are distinct from non-`async` functions and there
are no conversions amongst them. At present, `async` functions do not
*do* anything, but this commit fully supports them as a distinct kind
of function throughout:

* Parsing of `async`
* AST representation of `async` in declarations and types
* Syntactic type representation of `async`
* (De-/re-)mangling of function types involving 'async'
* Runtime type representation and reconstruction of function types
involving `async`.
* Dynamic casting restrictions for `async` function types
* (De-)serialization of `async` function types
* Disabling overriding, witness matching, and conversions with
differing `async`
2020-07-27 18:18:03 -07:00
Nikhil
6428c1f9bb [Diagnostic] Fix diagnostic when checking conformance for IUO of gene… (#32987)
* [Diagnostic] Fix diagnostic when checking conformance for IUO of generic parameter

Prints TypeRepr in diagnostic if possible to throw
accurate diagnostic for IUO conformance checking
Fixes [rdar://problem/64953106]. Fixes SR-13119

* Nested name lookup tests update

Name lookup will see the innermost name anyway and
preferred over fully qualified name. Hence the test
cases are also updated.

* Replaced a letter in test case that inadvertently got added

* Code format, corrections and better comments

This commit includes better comments for easy
understanding, formatted the bug fix code with
clang-format and fixes wrong variables inadvertently
introduced.

* [Test] Update type in struct codable test

This commit changes diagnostic type from error type
to Int. Although this diagnostic updated is incorrect, this will
be resolved when 32371 gets pulled.
2020-07-21 09:07:44 -07:00
Slava Pestov
422fd41396 Sema: Fix assertion when synthesizing Codable with an IUO stored property
Fixes <https://bugs.swift.org/browse/SR-13118>.
2020-06-29 22:27:38 -04:00
Slava Pestov
b50789404b Sema: Fix a few places where we built AST that had to go through SanitizeExpr before type checking 2020-06-26 07:42:21 -04:00
Anthony Latsis
c337757964 [NFC] Sema: get rid of redundant DeclContext parameter to checkConformancesInContext 2020-05-20 02:38:24 +03:00
Robert Widmann
0342855e50 [NFC] Debride Pattern.h of Implicit Tri-State
Remove all of this in favor of explicit constructors to preserve the one-liners, or distribute the setImplicit() calls to the callsites if necessary.
2020-04-30 22:03:55 -07:00
Robert Widmann
a6fc9b3679 Merge pull request #31253 from CodaFi/casting-call
Strip TypeExpr of its TypeLoc
2020-04-28 09:45:53 -07:00
Slava Pestov
742bd98402 Sema: Remove ConformanceCheckOptions::SkipConditionalRequirements
All callers can trivially be refactored to use ModuleDecl::lookupConformance()
instead. Since this was the last flag in ConformanceCheckOptions, we can remove
that, too.
2020-04-25 00:14:24 -04:00
Robert Widmann
7ed188216e Remodel the Interface for Implicit TypeExprs
Make it slightly easier to enforce the invariant that implicit TypeExpr
nodes have a contextual type set.
2020-04-23 17:04:38 -07:00
Robert Widmann
09db2902d2 Strip TypeExpr of its TypeLoc
Remove duplication in the modeling of TypeExpr. The type of a TypeExpr
node is always a metatype corresponding to the contextual
type of the type it's referencing. For some reason, the instance type
was also stored in this TypeLoc at random points in semantic analysis.

Under the assumption that this instance type is always going to be the
instance type of the contextual type of the expression, introduce
a number of simplifications:

1) Explicit TypeExpr nodes must be created with a TypeRepr node
2) Implicit TypeExpr nodes must be created with a contextual type
3) The typing rules for implicit TypeExpr simply opens this type
2020-04-23 17:04:38 -07:00
Anthony Latsis
74252028ca AST: Rename getFullName -> getName on ValueDecl & MissingMemberDecl 2020-04-23 05:16:55 +03:00
Doug Gregor
9a37a2a62c [Codable] Fix crash-on-invalid with codable synthesis and implicitly unwrapped optionals
Fixes rdar://problem/60985179.
2020-04-01 10:15:32 -07:00
Robert Widmann
630d0f631a Merge pull request #30606 from AnthonyLatsis/rename-getfullname
[NFC] Preparations to address the «Rename to getName?» TODO on ValueDecl::getFullName
2020-04-01 09:00:04 -07:00
Suyash Srijan
95f0651cbb [Diagnostics] Emit a warning when an immutable decodable property has an initial value (#30218)
* [Diagnostics] Emit a warning when an immutable decodable property has an initial value

* [Sema] Use Decl::diagnose instead of Diags.diagnose

* [AST] Remove property name from 'decodable_property_will_not_be_decoded' diagnostic

* [Test] Update tests

* [Test] Update existing codable tests
2020-03-31 23:16:08 +01:00
Anthony Latsis
d0ae3ee580 [AST] Replace FuncDecl::getName & EnumElementDecl::getName with ValueDecl::getBaseIdentifier 2020-03-29 00:35:51 +03: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
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
1df792ae9f [NFC] Convert TypeRepr to use DeclName(Loc)?
Replaces `ComponentIdentTypeRepr::getIdentifier()` and `getIdLoc()` with `getNameRef()` and `getNameLoc()`, which use `DeclName` and `DeclNameRef` respectively.
2019-12-11 00:45:08 -08:00
Brent Royal-Gordon
a3035eb925 [NFC] Add helpers for unresolved AST node synthesis
This change adds UnresolvedDotExpr::createImplicit() and UnresolvedDeclRefExpr::createImplicit() helpers. These calls simplify several tedious bits of code synthesis that would otherwise become even more tedious with DeclNameRef in the picture.
2019-12-11 00:45:07 -08:00
Robert Widmann
fbdd907a1f Add a way to just synthesize CodingKeys 2019-12-10 16:28:51 -08:00
Robert Widmann
9c234d5d17 Make deriving CodingKeys Cheap
The semantic checks for CodingKeys are being duplicated across the value witness synthesis code paths.  Just synthesize a CodingKeys enum and let validateCodingKeysEnum do the heavy lifting when we actually need to go emit diagnostics.
2019-12-10 16:28:51 -08:00
Robert Widmann
fefb800e74 Eliminate CodableConformanceType
CodableConformanceType::TypeNotValidated is unused since the InterfaceTypeRequest changes went through.  We can just use the validity of the ProtocolConformanceRef here.
2019-12-10 16:28:51 -08:00
Robert Widmann
2f2b8afad8 Remove the list of synthesized decls"
This used to be a lot more relevant a long time ago when typeCheckFunctionsAndExternalDecls actually did type check external functions defined in C.  Now, it serves no purpose.

The validation order change from just type checking these things eagerly doesn't seem to affect anything.
2019-11-11 11:33:59 -08:00
Slava Pestov
ae8c85ef80 Sema: Remove some unnecessary (void) getInterfaceType() calls 2019-11-04 14:59:01 -05:00
Robert Widmann
572bc52be0 Drop the type checker out of the multi-conformance checker 2019-11-01 17:58:49 -07:00
Robert Widmann
7993f2ffeb Downgrade the TypeChecker in DerivedConformance to an ASTContext 2019-10-30 12:55:42 -07:00
Robert Widmann
da2b063af9 Make calls to lookupMember actually look static 2019-10-30 12:55:42 -07:00
Robert Widmann
b849e51768 Use operator bool to claw back some readability 2019-10-29 16:56:21 -07:00
Robert Widmann
3e1a61f425 [NFC] Fold The Tri-State In Optional<ProtocolConformanceRef>
ProtocolConformanceRef already has an invalid state.  Drop all of the
uses of Optional<ProtocolConformanceRef> and just use
ProtocolConformanceRef::forInvalid() to represent it.  Mechanically
translate all of the callers and callsites to use this new
representation.
2019-10-29 16:55:56 -07:00
Robert Widmann
497a2227ba [NFC] Remove AbstractFunctionDecl::computeType()
Its functionality is entirely subsumed by InterfaceTypeRequest.
2019-10-21 12:15:50 -07:00
Robert Widmann
742f6b2102 Drastically Simplify VarDecl Validation
This is an amalgam of simplifications to the way VarDecls are checked
and assigned interface types.

First, remove TypeCheckPattern's ability to assign the interface and
contextual types for a given var decl.  Instead, replace it with the
notion of a "naming pattern".  This is the pattern that semantically
binds a given VarDecl into scope, and whose type will be used to compute
the interface type. Note that not all VarDecls have a naming pattern
because they may not be canonical.

Second, remove VarDecl's separate contextual type member, and force the
contextual type to be computed the way it always was: by mapping the
interface type into the parent decl context.

Third, introduce a catch-all diagnostic to properly handle the change in
the way that circularity checking occurs.  This is also motivated by
TypeCheckPattern not being principled about which parts of the AST it
chooses to invalidate, especially the parent pattern and naming patterns
for a given VarDecl.  Once VarDecls are invalidated along with their
parent patterns, a large amount of this diagnostic churn can disappear.
Unfortunately, if this isn't here, we will fail to catch a number of
obviously circular cases and fail to emit a diagnostic.
2019-10-14 12:06:50 -07:00