Commit Graph

603 Commits

Author SHA1 Message Date
Slava Pestov
8cfe7377e3 Sema: Ban single-element tuple expressions
Fixes <rdar://problem/30384023>, <rdar://problem/41474370>,
and <https://bugs.swift.org/browse/SR-8109>.
2018-12-15 00:07:04 -05:00
Slava Pestov
6c012b2aec AST: Remove some unnecessary LazyResolver * parameters from ASTContext methods 2018-12-07 20:39:27 -05:00
Adrian Prantl
ff63eaea6f Remove \brief commands from doxygen comments.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.

Patch produced by

      for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
2018-12-04 15:45:04 -08: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
mzp
eff1b9eb63 use bool(...) to produce bool value 2018-09-11 10:57:22 +09:00
mzp
4d072543fb add space to fit with coding-style 2018-09-11 10:57:22 +09:00
mzp
f5ed8981b6 [Sema] Warn for a function value in string interpolation
Resolves https://bugs.swift.org/browse/SR-8464
2018-09-11 08:09:42 +09:00
Jordan Rose
5dace224a0 Merge pull request #18623 from dingobye/sr8453
[Sema] Warn for redundant access-level modifiers on setters or used in an extension.
2018-09-05 17:44:26 -07:00
Slava Pestov
45b2fe249e Sema: Remove some uses of TypeBase::getUnlabeledType() 2018-08-28 22:36:02 -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
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
Slava Pestov
f2ae23a2ab AST: Remove TupleType::getElementForScalarInit()
This is a legacy holdover from when tuple types had default
arguments, and also the constraint solver's matching of function
types pre-SE-0110.

Well, move the last live usage to CSDiag, where it can die a slow
painful death over time. The other usages were not doing anything.
2018-08-11 22:26:44 -07:00
Ding Ye
63e1937e44 Make it more comprehensive to warn when redundant access
modifier is used in an extension. In addition, add warnings
for access modifier redundancy on property setters; and
address comments from Jordan Rose.
2018-08-11 21:21:54 +10:00
Ding Ye
f34020bfd4 [Sema] Warn when redundant access-level modifier is added in an extension.
This patch adds warning for redundant access-level modifiers
used in an extension. It also refines the diagnostics of
access_control_ext_member_more issues, in case the fixit
could suggest redundant modifiers.

Resolves: SR-8453.
2018-08-10 14:33:16 +10:00
Doug Gregor
d07fa5ab69 Switch many callers of ClassDecl::getSuperclass() to ClassDecl::getSuperclassDecl().
ClassDecl::getSuperclass() produces a complete interface type describing the
superclass of a class, including any generic arguments (for a generic type).
Most callers only need the referenced ClassDecl, which is (now) cheaper
to compute: switch those callers over to ClassDecl::getSuperclassDecl().

Fixes an existing test for SR-5993.
2018-07-31 10:14:44 -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
e1da265873 Sema: Remove uses of AbstractFunctionDecl::getParameterLists() 2018-07-19 21:21:17 -07:00
Mark Lacey
28f759c8b0 Remove support for -swift-version 3 from the expression type checker.
This is the obvious stuff. There will probably be more fallout.
2018-07-06 16:10:08 -07:00
Hamish Knight
c66e68fb93 [Parse][Sema] Emit immediate deallocation warning on the '=' token for PBDs (#17700)
Pass through the location of the equal '=' token for pattern binding decl entries, and use this location for the immediate deallocation diagnostic. Previously, we were just diagnosing on the start of the initialiser expression.

Additionally, this commit moves the call to `diagnoseUnownedImmediateDeallocation` from `typeCheckBinding` to `typeCheckPatternBinding`. This not only gives us easier access to the PBD entry, but also avoids calling the diagnostic logic for statement conditions such as `if let x = <expr>`. We currently never diagnose on these anyway, as the 'weak' and 'unowned' keywords cannot be applied to such bindings.

Resolves [SR-7340](https://bugs.swift.org/browse/SR-7340).
2018-07-06 10:47:49 -07:00
Slava Pestov
2ec0842360 Sema: Tweak deprecated keypath write diagnostic to not use getLValueAccessKind()
This makes it less accurate, but who cares.
2018-07-05 23:49:57 -07:00
John McCall
34b0cbc11d Merge pull request #16237 from davezarzycki/metaprogram_ref_storage_types
[AST] NFC: Enable reference storage type meta-programming
2018-07-05 14:45:38 -04:00
Doug Gregor
80688d0176 [Type Checker] Remove the TypeChecker from most of the “override” checking.
A type checker instance isn’t needed for most of the “override” checking,
so remove the TypeChecker parameters and instead get the ASTContext or
DiagnosticEngine from whatever decl or type is available. Another step
toward reducing dependency on a TypeChecker instance.
2018-07-02 23:00:39 -07:00
Joe Groff
1f81d54812 Merge pull request #17642 from jckarter/no-unapplied-mutating-method-references
Sema: Diagnose completely unapplied references to mutating methods.
2018-06-30 10:02:17 -07:00
David Zarzycki
6dc2b7fda9 [Sema] NFC: Adopt reference storage type meta-programming macros 2018-06-30 06:44:33 -04:00
John McCall
9bee3cac5a Generalize storage implementations to support generalized accessors.
The storage kind has been replaced with three separate "impl kinds",
one for each of the basic access kinds (read, write, and read/write).
This makes it far easier to mix-and-match implementations of different
accessors, as well as subtleties like implementing both a setter
and an independent read/write operation.

AccessStrategy has become a bit more explicit about how exactly the
access should be implemented.  For example, the accessor-based kinds
now carry the exact accessor intended to be used.  Also, I've shifted
responsibilities slightly between AccessStrategy and AccessSemantics
so that AccessSemantics::Ordinary can be used except in the sorts of
semantic-bypasses that accessor synthesis wants.  This requires
knowing the correct DC of the access when computing the access strategy;
the upshot is that SILGenFunction now needs a DC.

Accessor synthesis has been reworked so that only the declarations are
built immediately; body synthesis can be safely delayed out of the main
decl-checking path.  This caused a large number of ramifications,
especially for lazy properties, and greatly inflated the size of this
patch.  That is... really regrettable.  The impetus for changing this
was necessity: I needed to rework accessor synthesis to end its reliance
on distinctions like Stored vs. StoredWithTrivialAccessors, and those
fixes were exposing serious re-entrancy problems, and fixing that... well.
Breaking the fixes apart at this point would be a serious endeavor.
2018-06-30 05:19:03 -04:00
Joe Groff
28fc7b0c80 Sema: Diagnose completely unapplied references to mutating methods.
The currying behavior of method references completely breaks in the face of `inout` semantics, even moreso with exclusivity enforcement, but we failed to diagnose these references in Swift 4 and previous versions. Raise a compatibility warning when these references are found in Swift 4 code, or error in Swift 5 and later. Simplify the partial application logic here slightly too now that standalone functions do not allow currying. Addresses rdar://problem/41361334 | SR-8074.
2018-06-29 21:04:42 -07:00
Mark Lacey
fea720f229 [MiscDiagnostics] Emit a deprecation warning for some writes through literal keypaths.
We incorrectly allowed some keypaths to be inferred as writable
keypaths in Swift 3/4 modes. This no longer happens when
-swift-version 5 is specified.

This warning is a limited attempt at providing some advanced notice of
code that will break, only in the cases where the keypath is a direct
argument to a keypath subscript write.

Fixes: rdar://problem/40068274
2018-06-25 23:03:06 -07:00
John McCall
9022b5152f Rename accessor kinds from IsGetter -> IsGet, etc.
Introduce some metaprogramming of accessors and generally prepare
for storing less-structured accessor lists.

NFC except for a change to the serialization format.
2018-06-14 17:08:55 -04:00
Slava Pestov
296ce3f312 AST: Remove hack-around for getInterfaceType() on ParamDecl returning InOutType
Most callers did not want the InOutType here, and checked
the ParamDecl's flags instead.
2018-06-13 15:38:52 -07:00
David Zarzycki
7a5d9680e1 [Sema] NFC: Reorder misc bits for better code gen
As a general rule, if one wants packs miscellaneous bits into what is
otherwise just a number, the low bits are preferable over the high bits,
at least on x86. On ppc64/ppc64le, the results are more of a wash. For
reference:

struct X {
    unsigned kind : 3;
    unsigned level : 29;
};

X example(X x, unsigned y) {
    x.level += y;
    return x;
}

bool example(X x) {
    return x.level > 1;
}

==== x86_64 with 'kind' first ====

_Z7example1Xj:
        leal    (%rdi,%rsi,8), %eax
        retq

_Z7example1X:
        cmpl    $15, %edi
        seta    %al
        retq

==== x86_64 with 'kind' last ====

_Z7example1Xj:
        leal    (%rsi,%rdi), %eax
        andl    $536870911, %eax        # imm = 0x1FFFFFFF
        andl    $-536870912, %edi       # imm = 0xE0000000
        orl     %edi, %eax
        retq

_Z7example1X:
        testl   $536870910, %edi        # imm = 0x1FFFFFFE
        setne   %al
        retq

==== PPC64 with 'kind' first ====

_Z7example1Xj:
        add 5, 5, 4
        rlwimi 5, 4, 0, 0, 2
        stw 5, 0(3)
        blr

_Z7example1X:
        rlwinm 3, 3, 0, 3, 30
        cntlzw  3, 3
        srwi 3, 3, 5
        xori 3, 3, 1
        blr

==== PPC64 with 'kind' last ====

_Z7example1Xj:
        slwi 5, 5, 3
        add 4, 5, 4
        stw 4, 0(3)
        blr

_Z7example1X:
        clrldi  3, 3, 32
        subfic 3, 3, 15
        rldicl 3, 3, 1, 63
        blr

==== PPC64LE with 'kind' first ====

_Z7example1Xj:
        slwi 4, 4, 3
        add 3, 4, 3
        blr

_Z7example1X:
        clrldi  3, 3, 32
        subfic 3, 3, 15
        rldicl 3, 3, 1, 63
        blr

==== PPC64LE with 'kind' last ====

_Z7example1Xj:
        add 4, 4, 3
        rlwimi 3, 4, 0, 3, 31
        blr

_Z7example1X:
        rlwinm 3, 3, 0, 3, 30
        cntlzw  3, 3
        srwi 3, 3, 5
        xori 3, 3, 1
        blr
2018-05-17 16:04:28 -04:00
Mark Lacey
08f80ec361 Properly handle subscripts when avoiding IUO-to-Any coercion warnings.
Ensure that we grab the decl from the subscript expression so that we
can check whether it returns an IUO.

Also add tests for subscripts and failable inits.
2018-05-07 18:10:57 -07:00
Mark Lacey
a61a6d536e Conditionalize warnings for IUO-to-Any coercion on Swift version.
These warnings are turning out to be pretty noisy for code that
declares IUOs (e.g. for @IBOutlets) and then passes them to
Objective-C APIs with parameters declared as _Nonnull id.

Since we bridge non-nil values successfully in most cases, and
previuosly written and correctly executing code is either not seeing
nil values passed in or are handling the nil (which is bridged as
NSNull), it seems like a nuisance to warn about these for existing
Swift versions.

We'll conditionalize the warning, and then users can deal with these
when moving to the new language version.

Fixes: rdar://problem/39886178
2018-05-07 15:49:56 -07:00
Doug Gregor
192234415d [AST] Store SubstitutionMaps in ConcreteDeclRef and Witness data structures.
Replace two prominent uses of SubstitutionList, in ConcreteDeclRef and
Witness, with SubstitutionMap. Deal with the myriad places where we
now have substitution maps and need substitution lists (or vice versa)
caused by this change.

Overall, removes ~50 explicit uses of SubstitutionList (of ~400).
2018-05-02 13:38:14 -07:00
Pavel Yaskevich
02b2aa7485 [MiscDiagnostics] Switch to use AnyFunctionType::getParams() instead of getInput() 2018-04-26 17:33:08 -07:00
David Zarzycki
9a8a9d44b9 Merge pull request #16058 from davezarzycki/qoi_formalize_ReferenceOwnership_diags
[Diag] QoI: Add ReferenceOwnership to DiagnosticArgumentKind
2018-04-20 11:02:48 -04:00
David Zarzycki
e326954bd0 [Diag] QoI: Add ReferenceOwnership to DiagnosticArgumentKind
By formalizing ReferenceOwnership as a diagnostic argument kind, we get
less boilerplate, better type safety, better output consistency, and
last but not least: future proofing.
2018-04-20 08:32:43 -04:00
Huon Wilson
fe00f53e48 [AST] Use flags instead of booleans for UnqualifiedLookup. 2018-04-09 10:58:49 +10:00
Hamish
4f8ad1afec [Sema] Revise #14875 in response to feedback
- Diagnose on the location of the '=' equals sign for assignments
- Use the variable decl as the location for the note
- Make AST node params 'const'
2018-04-02 23:05:33 +01:00
Hamish
92931b7434 Merge remote-tracking branch 'upstream/master' into warn-weak-insta-dealloc 2018-04-02 18:06:45 +01:00
Doug Gregor
b2b69e8abf Rename BoundNameAliasType to NameAliasType.
NameAliasType is dead! Long live NameAliasType!
2018-03-25 21:35:17 -07:00
Doug Gregor
c43f96a855 [AST] Remove now-unused NameAliasType. 2018-03-25 21:35:16 -07:00
Slava Pestov
6b899b625e Merge pull request #15435 from slavapestov/one-more-base-identifier
Sema: Change a getBaseIdentifier() to userFacingName()
2018-03-22 19:08:52 -07:00
Slava Pestov
7d9599a93d Sema: Change a getBaseIdentifier() to userFacingName() 2018-03-22 14:19:38 -07:00
Doug Gregor
253bd10bd3 Cope with BoundNameAliasType in more places that handle NameAliasType. 2018-03-21 23:49:33 -07:00
Mark Lacey
994c2d1acd Improve type join for function types.
It is still not completely general, but this moves things along a
little bit.
2018-03-21 11:51:54 -07:00
Slava Pestov
d118654fa8 Sema: Peephole for 'nil' literal of Optional type 2018-03-18 00:13:55 -07:00
Slava Pestov
615d068d63 Sema: Replace some uses of getBaseIdentifier() with userFacingName() 2018-03-14 22:26:58 -07:00
Hamish
48f08bdbc7 [Sema] Diagnose immediate deallocation of instances assigned to non-owning variables
When performing a binding/assignment to a weak or unowned variable/property from an initialiser call, emit a warning that the instance will be immediately deallocated.
2018-03-08 16:32:35 +00:00
Sho Ikeda
74ba135008 Merge pull request #15040 from ikesyo/gardening-not-empty
[gardening] Use `!empty()` over `size() > 0`
2018-03-08 18:47:12 +09:00
Huon Wilson
e307e54098 [AST] Explicitly track things marked __owned. 2018-03-08 12:36:24 +11:00