Commit Graph

216 Commits

Author SHA1 Message Date
Huon Wilson
41942c9276 [Sema] Create a "DerivedConformance" class, to store common values.
Instead of passing around a TypeChecker and three Decls (the nominal type, the
protocol, and the decl declaring the conformance) everywhere, we can just pass
one object.

This should be [NFC].
2018-05-07 09:10:06 +10:00
Karoy Lorentey
23c1b24e6a [SE-0206][Sema] Update Hashable synthesizer to support hash(into:)
This removes the default implementation of hash(into:), and replaces it with automatic synthesis built into the compiler. Hashable can now be implemented by defining either hashValue or hash(into:) -- the compiler supplies the missing half automatically, in all cases.

To determine which hash(into:) implementation to generate, the synthesizer resolves hashValue -- if it finds a synthesized definition for it, then the generated hash(into:) body implements hashing from scratch, feeding components into the hasher. Otherwise, the body implements hash(into:) in terms of hashValue.
2018-04-24 17:42:42 +01:00
Jordan Rose
28a1dc7770 Use 'fileprivate' for synthesized members of 'private' decls (#15980)
Since 'private' means "limit to the enclosing scope (and extensions
thereof)", putting it on a member means that the member can't be
accessed everywhere the type might show up. That's normally a good
thing, but it's not the desired effect for synthesized members used
for derived conformances, and when it comes to class initializers this
actually violates AST invariants.

rdar://problem/39478298
2018-04-17 15:19:35 -07:00
Slava Pestov
634f4924ed Sema: The synthesized rawValue PBD should be fully type-checked 2018-04-02 23:17:59 -07:00
Slava Pestov
3bcdf1a027 AST: New ASTContext::addSynthesizedDecl() method
This adds the declaration to the external declarations list only
if it was part of an imported declaration, eliminating some
boilerplate.
2018-04-02 23:17:58 -07:00
Slava Pestov
e1f50b2d36 SE-0193: Rename @_inlineable to @inlinable, @_versioned to @usableFromInline 2018-03-30 21:55:30 -07:00
Slava Pestov
a8602f8eb8 Sema: Call setValidationStarted() on various synthesized FuncDecls 2018-03-21 23:54:47 -07:00
Robert Widmann
dac06898e9 [SE-0194] Deriving Collections of Enum Cases
Implements the minimum specified by the SE-proposal.

* Add the CaseIterable protocol with AllCases associatedtype and
allCases requirement
* Automatic synthesis occurs for "simple" enums
    - Caveat: Availability attributes suppress synthesis.  This can be
              lifted in the future
    - Caveat: Conformance must be stated on the original type
              declaration (just like synthesizing Equatable/Hashable)
    - Caveat: Synthesis generates an [T].  A more efficient collection
              - possibly even a lazy one - should be put here.
2018-03-09 00:22:55 -05:00
Noah Gilmore
80045ad7af Fix a typo in DerivedConformances 2018-01-18 12:08:01 -08:00
John McCall
7f0f8830cd Split AccessorDecl out from FuncDecl. NFC.
This has three principal advantages:

- It gives some additional type-safety when working
  with known accessors.

- It makes it significantly easier to test whether a declaration
  is an accessor and encourages the use of a common idiom.

- It saves a small amount of memory in both FuncDecl and its
  serialized form.
2018-01-12 14:20:27 -05:00
Graydon Hoare
6d46fb144f [AST] Move copyFormalAccess to ValueDecl. 2017-11-06 14:31:21 -08:00
Tony Allevato
f2c434a038 Merge branch 'master' into synthesize-equatable-hashable 2017-09-21 22:54:36 -07:00
Slava Pestov
10bd85cb34 Sema: Fix Equatable, Hashable, RawRepresentable derivation for @_versioned enums
The synthesized declarations should inherit the @_versioned attribute
from the type, just like they inherit access control.

Fixes <rdar://problem/34342955>.
2017-09-17 21:35:55 -07:00
Slava Pestov
39872d9a96 Sema: Remove "at least internal" check for derived conformance declarations
It looks like at some point derived conformances were in their own
FileUnit, but this is no longer the case.
2017-09-17 21:35:55 -07:00
Tony Allevato
3731382bf6 Merge branch 'master' into synthesize-equatable-hashable 2017-09-09 14:23:13 -07:00
Jordan Rose
1c651973c3 Excise "Accessibility" from the compiler (2/3)
"Accessibility" has a different meaning for app developers, so we've
already deliberately excised it from our diagnostics in favor of terms
like "access control" and "access level". Do the same in the compiler
now that we aren't constantly pulling things into the release branch.

This commit changes the 'Accessibility' enum to be named 'AccessLevel'.
2017-08-28 11:34:44 -07:00
Jordan Rose
5f30eac288 Excise "Accessibility" from the compiler (1/3)
"Accessibility" has a different meaning for app developers, so we've
already deliberately excised it from our diagnostics in favor of terms
like "access control" and "access level". Do the same in the compiler
now that we aren't constantly pulling things into the release branch.

This commit changes the names of methods, fields, a few local
variables, and even a swift-ide-test flag. The full list is below.

accessibilityForDiagnostics -> accessLevelForDiagnostics
checkAccessibility -> checkAccess
checkGenericParamAccessibility -> checkGenericParamAccess
checkTypeAccessibility -> checkTypeAccess
checkWitnessAccessibility -> checkWitnessAccessibility
computeAccessibility -> computeAccessLevel
computeDefaultAccessibility -> computeDefaultAccessLevel
fixItAccessibility -> fixItAccess
getAccessibilityString -> getAccessLevelString
getAccessibilityStrictly -> getAccessLevelStrictly
getAccessibilityUID -> getAccessLevelUID
getActualAccessibility -> getActualAccessLevel
getDefaultAccessibility -> getDefaultAccessLevel
getMaxAccessibility -> getMaxAccessLevel
getOverridableAccessibility -> getOverridableAccessLevel
getRawStableAccessibility -> getRawStableAccessLevel
getSetterAccessibility -> getSetterFormalAccess
hasAccessibility -> hasAccess
hasDefaultAccessibility -> hasDefaultAccessLevel
inferAccessibility -> inferAccessLevel
inferDefaultAccessibility -> inferDefaultAccessLevel
inferSetterAccessibility -> inferSetterAccessLevel
overwriteAccessibility -> overwriteAccess
overwriteSetterAccessibility -> overwriteSetterAccess
printAccessibility -> printAccess
requiredAccessibilityForDiagnostics -> requiredAccessForDiagnostics
resolveAccessibility -> resolveAccessControl
setAccessibility -> setAccess
setSetterAccessibility -> setSetterAccess
setDefaultAndMaxAccessibility -> setDefaultAndMaxAccess
validateAccessibility -> validateAccessControl

Accessibility -> AccessLevel
AccessibilityFilter -> AccessFilter
IgnoreAccessibility -> IgnoreAccessControl
NL_IgnoreAccessibility -> NL_IgnoreAccessControl
PrintAccessibility -> PrintAccess
PrintInternalAccessibilityKeyword -> PrintInternalAccessKeyword
SetterAccessibility -> SetterAccessLevel

setterAccessibility -> setterAccess
storedPropertyAccessibility -> storedPropertyAccess

-print-accessibility -> -print-access
2017-08-28 11:11:57 -07:00
Tony Allevato
a3db968057 Move derivesProtocolConformances from AST to Sema 2017-08-08 18:30:22 -07:00
Robert Widmann
e5918f70e8 [NFC] Refactor self type computation to return a Param
Remove a user of InOutType::get and flip a few users of
FunctionType::get to pass Params instead of naked input
types.
2017-07-23 21:36:16 -07:00
Robert Widmann
ac5594dabe Use a meaningful representation of parameter specifiers
In anticipation of future attributes, and perhaps the ability to
declare lvalues with specifiers other than 'let' and 'var', expand
the "isLet" bit into a more general "specifier" field.
2017-06-29 16:03:49 -07:00
Jordan Rose
c0ccdb1626 Change getBaseName to return DeclBaseName instead of Identifier (#9968)
This changes `getBaseName()` on `DeclName` to return a `DeclBaseName`
instead of an `Identifier`. All places that will continue to be
expecting an `Identifier` are changed to call `getBaseIdentifier` which
will later assert that the `DeclName` is actually backed by an
identifier and not a special name.

For transitional purposes, a conversion operator from `DeclBaseName` to
`Identifier` has been added that will be removed again once migration
to DeclBaseName has been completed in other parts of the compiler.

Unify approach to printing declaration names

Printing a declaration's name using `<<` and `getBaseName()` is be
independent of the return type of `getBaseName()` which will change in
the future from `Identifier` to `DeclBaseName`
2017-05-28 17:55:03 -07:00
Itai Ferber
e2318392be Add CodingKey and *codable derived conformance
* Allow CodingKey conformance to be automatically derived for enums
  which have no raw type (with no associated values) and which have
  a raw type of String or Int.
* Allow Encodable and Decodable conformance to be automatically derived
  for classes and structs with Encodable/Decodable properties
* Add initial unit tests for verifying derived conformance
2017-04-25 13:13:35 -07:00
Jordan Rose
e575d2d5ba [ClangImporter] Error structs from enums are not imported decls.
Enums with the ns_error_domain attribute represent codes for NSError,
which means Swift developers will expect to interact with them in
terms of Error. SE-0112 improved bridging for these enums to generate
a struct with the following form:

    struct MyError: Error {
      @objc enum Code: RawRepresentable {
        case outOfMemory
        case fileNotFound
      }
      var userInfo: [NSObject: AnyObject] { get }
      static var outOfMemory: Code { get }
      static var fileNotFound: Code { get }
    }

where MyError.Code corresponds to the original MyError enum defined in
Objective-C. Until recently, both the enum and the synthesized struct
were marked as having the original enum as their "Clang node", but
that leads to problems: the struct isn't really ObjC-compatible, and
the two decls have the same USR. (The latter had already been worked
around.)

This commit changes the struct to be merely considered a synthesized
"external definition", with no associated Clang node. This meant
auditing everywhere that's looking for a Clang node and seeing which
ones applied to external definitions in general.

There is one regression in quality here: the generated struct is no
longer printed as part of the Swift interface for a header file, since
it's not actually a decl with a corresponding Clang node. The previous
change to AST printing mitigates this a little by at least indicating
that the enum has become a nested "Code" type.
2017-04-24 09:57:41 -07:00
Slava Pestov
162b2d252e AST: Include gardening to minimize dependencies on Expr.h
A lot of files transitively include Expr.h, because it was
included from SILInstruction.h, SILLocation.h and SILDeclRef.h.

However in reality most of these files don't do anything
with Exprs, especially not anything in IRGen or the SILOptimizer.

Now we're down to 171 files in the frontend which depend on
Expr.h, which is still a lot but much better than before.
2017-03-12 22:26:56 -07:00
practicalswift
6d1ae2a39c [gardening] 2016 → 2017 2017-01-06 16:41:22 +01:00
Brian Gesiak
4108e1d9af [Sema] Mark VarDecl in capture lists
Fixes SR-2757.

Variables in capture lists are treated as 'let' constants, which can
result in misleading, incorrect diagnostics. Mark them as such in order
to produce better diagnostics, by adding an extra parameter to the
VarDecl initializer.

Alternatively, these variables could be marked as implicit, but that
results in other diagnostic problems: capture list variables that are
never used produce warnings, but these warnings aren't normally emitted for
implicit variables. Other assertions in the compiler also misfire when
these variables are treated as implicit.

Another alternative would be to walk up the AST and determine whether
the `VarDecl`, but there doesn't appear to be a way to do so.
2017-01-01 12:41:06 -05:00
Slava Pestov
1a991da16d AST: Assign interface types to ParamDecls
First, ensure all ParamDecls that are synthesized from scratch are given
both a contextual type and an interface type.

For ParamDecls written in source, add a new recordParamType() method to
GenericTypeResolver. This calls setType() or setInterfaceType() as
appropriate.

Interestingly enough a handful of diagnostics in the test suite have
improved. I'm not sure why, but I'll take it.

The ParamDecl::createUnboundSelf() method is now only used in the parser,
and no longer sets the type of the self parameter to the unbound generic
type. This was wrong anyway, since the type was always being overwritten.
This allows us to remove DeclContext::getSelfTypeOfContext().

Also, ensure that FuncDecl::getBodyResultTypeLoc() always has an interface
type for synthesized declarations, eliminating a mapTypeOutOfContext()
call when computing the function interface type in configureInterfaceType().

Finally, clean up the logic for resolving the DynamicSelfType. We now
get the interface or contextual type of 'Self' via the resolver, instead
of always getting the contextual type and patching it up inside
configureInterfaceType().
2016-12-04 00:02:21 -08:00
Slava Pestov
b4d11338ec AST: Push ValueDecl::{has,get,set}Type() down to VarDecl
After recent changes, this asserts on all decls that are not VarDecls,
so we can just enforce that statically now. Interestingly, this turns
up some dead code which would have asserted immediately if called.

Also, replace AnyFunctionRef::getType() with
AnyFunctionRef::getInterfaceType(), since the old
AnyFunctionRef::getType() would just assert when called on
a Decl.
2016-12-01 19:28:13 -08:00
Slava Pestov
0f7a455d7d AST: Don't call setType() on AbstractFunctionDecls and EnumElementDecls 2016-11-29 03:05:33 -07:00
Slava Pestov
f803d8f12c AST: Remove AbstractFunctionDecl::getBodyResultType()
This is made redundant by the existing getResultInterfaceType()
accessor.
2016-11-29 03:05:23 -07:00
practicalswift
797b80765f [gardening] Use the correct base URL (https://swift.org) in references to the Swift website
Remove all references to the old non-TLS enabled base URL (http://swift.org)
2016-11-20 17:36:03 +01:00
Huon Wilson
fa56e7928d [AST] Remove redundant GenericSignatures.
The GenericSignature is now canonically available through the
GenericEnvironment.
2016-11-11 14:57:04 -08: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
Doug Gregor
e1545a7d5a [Type checker/runtime] Move default implementation of Error._code into the runtime.
Rather than having Sema provide a default implementation of
Error._code when needed, introduce a runtime function to extract the
default code, so that we can provide a default implementation via a
protocol extension in the standard library.
2016-08-25 16:00:19 -07:00
Doug Gregor
6d2f11a305 [Type checker] Synthesize Error._code witnesses as 'final' within a class.
When synthesizing the witness for Error._code, synthesize it as
final. This isn't meant to be user-visible (and, therefore, isn't
meant to be user-overridable), so it's a minor efficiency
win. Moreover, we weren't making sure this member got synthesized in
in cross-module situations, leading to runtime crashes. Fixes
rdar://problem/27335637.
2016-08-01 21:27:51 -07:00
Jordan Rose
c70a5a5d67 Default access for many synthesized members to 'internal'.
More detail: some members are intended to have the same the access as
their containing types. This doesn't fly for SE-0025 'private', which
would limit the members to only being accessed from lexically within
the type decl, instead anywhere the type itself can be seen. Instead,
follow the rule for user-written members---internal by default---and
then raise the access level to 'public' if necessary. This affects:

- enum cases
- deinitializers
- protocol requirements
- generic parameters
- implicit initializers
- inherited initializers
- derived conformance members
- synthesized typealiases for associated types
2016-07-25 20:20:58 -07:00
Doug Gregor
1dcfd337e5 [Cleanup] Eliminate the notion of derived global declarations for DeclContexts.
These were only used for synthesized global operators, which have now
been eliminated.
2016-07-21 12:54:27 -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
Slava Pestov
112511cd1c Remember to set AbstractFunctionDecl's generic signature in a few places
I originally added this so that we would keep the signature around
even if type checking failed, and the function was given an
ErrorType.

Add a formal check to the AST verifier for this, and set the signature
in a few places where it wasn't being set.

Note that since we only serialize valid declarations, we don't have
to serialize a reference to the generic signature separately, but we
do have to remember to set it when deserializing, which wasn't being
done for destructors.
2016-05-28 22:30:40 -07:00
Joe Groff
5e2b20d05f SILGen: Fix crashes when conditionally looking up generic subscripts and properties via AnyObject.
The fix for methods to lower the dynamic method type from the substituted AST type of the expression also needed to be applied to the optional chaining, subscript, and property paths.

This also exposed a problem in the Clang importer, where imported subscript accessors would get the unbound generic context type as their Self parameter type instead of the type with the correct generic parameters. Fix this by renaming the all-too-convenient ParamDecl::createSelf factory to `createUnboundSelf`, and introduce a new `createSelf` that uses the bound generic type.

Fixes rdar://problem/26447758.
2016-05-24 19:18:37 -07:00
Slava Pestov
170992c39f AST: Add Throws flag and ThrowsLoc to AbstractFunctionDecl
The verifier now asserts that Throws, ThrowsLoc and isBodyThrowing()
match up.

Also, add /*Label=*/ comments where necessary to make the long argument
lists easier to read, and cleaned up some inconsistent naming conventions.

I caught a case where ClangImporter where we were passing in a loc as
StaticLoc instead of FuncLoc, but probably this didn't affect anything.
2016-05-21 12:51:50 -07:00
Jordan Rose
81905be8dd Rename _BridgedNSError._NSErrorDomain to _nsErrorDomain.
This isn't strictly necessary, since it's an implementation detail, but
it's consistent with the following changes.
2016-02-24 17:46:10 -08:00
Max Moiseev
61c837209b Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-04 16:13:39 -08:00
Doug Gregor
8336419844 Include completion source location information compound DeclNames.
When one spells a compound declaration name in the source (e.g.,
insertSubview(_:aboveSubview:), keep track of the locations of the
base name, parentheses, and argument labels.
2016-01-25 14:13:13 -08:00
practicalswift
71e00fefa1 [gardening] Fix typos: "word word" (two spaces) → "word word" (one space) 2016-01-24 21:27:16 +01:00
Slava Pestov
c75f443c83 Sema: Better fix for duplicate emission of accessors
When compiling a module with multiple FileUnits (eg, while running
swiftc without -whole-module-optimization), we emit all decls
in the ExternalDeclarations list for every FileUnit, leading to
duplicate symbols if any of those decls were public.

Joe's workaround skipped decls on ExternalDefinitions that were
already emitted in the current FileUnit, but that was not sufficient;
the right fix is to not put stuff on ExternalDeclarations at all,
if we're going to emit it as part of a decl inside our file.

In this case, the synthesized _code accessors for an ErrorType
conformance do not belong in ExternalDefinitions, because they're
part of an ExtensionDecl that is in the current FileUnit.

Finally add some tests for this stuff, because it appears our
existing coverage was insufficient.
2016-01-21 22:30:56 -08:00
Max Moiseev
08e1e4a043 Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-01-11 16:51:11 -08:00
Slava Pestov
c3dd77a50c Rename ASTContext::addedExternalDecl() to addExternalDecl() and improve some comments, NFC 2016-01-10 17:06:19 -08:00
Slava Pestov
9bdb7d377d Clean up handling of external declarations, NFC
This is the first in a series of patches that fixes some resilience-related
issues with synthesized accessors and materializeForSet.

Previously we maintained two lists of external declarations encountered while
type checking:

- ASTContext::ExternalDefinitions
- TypeChecker::implicitlyDefinedFunctions

The former contained the following:

- Imported nominal types from Clang, so that SILGen can emit witness tables
- Functions and variables with Clang decls, so that IRGen can instruct Clang
  to emit them
- Synthesized accessors

The latter contained synthesized functions for derived conformances.

Since the second list was not visible outside Sema, we relied on the Clang
importer to add the type that contained the declaration to the
ExternalDefinitions list. In practice, we only synthesized members of enums
in this manner.

Because of this, SILGenModule::emitExternalDefinitions() had special logic to
skip members of enums, since it would visit them when visiting the enum itself.

Instead, it appears that we can remove implicitlyDefinedFunctions completely,
changing usage sites to add the decl to ExternalDefinitions instead, and
simplify SILGenModule::emitExternalDefinition() a bit in the process.

Also, it looks like we never had Modules appear in ExternalDefinitions, so
assert if those come up instead of skipping them.
2016-01-10 17:05:31 -08:00
Max Moiseev
f51e708a8f Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-01-04 12:25:25 -08:00