Commit Graph

918 Commits

Author SHA1 Message Date
Pavel Yaskevich
1d8cee9cb4 [ConstraintSystem] Detect invalid initializer references early
Currently invalid initializer references are detected and
diagnosed in solution application phase, but that's too
late because solver wouldn't have required information while
attempting to determine the best solution, which might result
in viable solutions being ignored in favour of incorrect ones e.g.

```swift
protocol P {
  init(value: Int)
}

class C {
  init(value: Int, _: String = "") {}
}

func make<T: P & C>(type: T.Type) -> T {
  return T.init(value: 0)
}
```

In this example `init` on `C` would be preferred since it
comes from the concrete type, but reference itself is invalid
because it's an attempt to construct class object using
metatype value via non-required initalizer.

Situations like these should be recognized early and invalid
use like in case of `C.init` should be ranked lower or diagnosed
if that is the only possible solution.

Resolves: rdar://problem/47787705
2019-02-05 10:25:36 -08:00
Pavel Yaskevich
49c40d92f6 [AST] Augment getDepthMap with information about parent expressions
Which is very useful for the solver because otherwise it'd have to
compute and store this information twice.
2019-01-23 18:21:07 -08:00
Joe Groff
89979137fc Push ArchetypeType's API down to subclasses.
And clean up code that conditionally works only with certain kinds of archetype along the way.
2018-12-12 19:45:40 -08:00
BJ Homer
3ae807d4bf Make 'try?' flatten optional chaining like optional-chaining does.
If the sub-expression of the 'try?' is optional, the result will be the same level of optional-ness.
If the sub-expression is non-optional, the result is optional.

Thus, the following lines all end up with the same type of 'Int?'
 - let x = try? 3 as Int
 - let x = try? 3 as? Int
 - let x = try? 3 as Int?
2018-11-06 23:31:02 -07: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
John McCall
abdba1d3f4 Change the integer-literal type from Int2048 to IntLiteral.
Part of SR-290.
2018-10-31 23:14:58 -04:00
John McCall
2d70a03c34 [NFC] Improve the interfaces for integer widths and parsing integers 2018-10-31 12:45:52 -04:00
Jordan Rose
c22711a261 [AST] static_assert that Decls, Stmts, and Exprs don't need cleanup (#19667)
These types are all allocated on the ASTContext's BumpPtrAllocator,
and by default their destructors are never called. (ModuleDecl is the
exception; it registers its destructor with the ASTContext on
construction.)

No functionality change.
2018-10-02 10:42:42 -07:00
Joe Groff
93b5de61e7 Implement the final approved syntax for SE-227 identity key paths.
`\.self` is the final chosen syntax. Implement support for this syntax, and remove the stopgap builtin and `WritableKeyPath._identity` property that were in place before.
2018-09-19 11:45:13 -07:00
Mark Lacey
352e4a2de4 [ConstraintSystem] Infer empty closures as returning () more eagerly.
We previously allowed these closures to default to (), but be inferred
as other types as well, which means that we will find some expressions
to be ambiguous because we end up finding multiple viable solutions
where there is really only one reasonable solution.

Fixes: rdar://problem/42337247
2018-09-12 13:30:35 -07:00
Graydon Hoare
ffa1bf1979 [Stats] Expand and improve traceable-entity vocabulary. 2018-09-01 00:05:58 -07:00
John McCall
a30d91e3cb Implement vararg expansion well enough to support argument forwarding.
I needed this for materializeForSet remission, but it makes inherited
variadic initializers work, too.

I tried to make this a reasonable starting point for a real language
feature.  Here's what's still missing:

- syntax
- semantic restrictions to ensure that the expression isn't written in
  invalid places or arbitrarily converted
- SILGen support for expansions that aren't the only variadic argument

rdar://16331406
2018-08-22 06:46:08 -04:00
Slava Pestov
381483bd74 AST: Remove Expr's LValueAccessKind 2018-07-05 23:54:13 -07:00
Ben Cohen
2b04e9f105 Suppress a number of warnings in no-assert builds (#17721)
* Supress a number of warnings about things used only in asserts

* Re-use a couple of variables instead of supressing the warning
2018-07-04 07:15:14 -07: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
Brent Royal-Gordon
6323a5131c Extract helper for making integer literals
Several different places in the codebase synthesize IntegerLiteralExprs from computed unsigned variables; each one requires several lines of code and does things slightly differently. Write one central helper method to handle this.
2018-06-16 12:31:46 -07:00
Slava Pestov
69701b1b90 AST: Fix "statically derived metatype" check
A static reference to DynamicSelfType can only be written as an
implicit member expression where the contextual type is a
DynamicSelfType, ie, 'return .init(...)' in a static method
returning Self.

In this case, the base expression is not a statically-derived
metatype.
2018-05-29 22:51:25 -07:00
David Zarzycki
da20780485 Merge pull request #16695 from davezarzycki/nfc_move_isSelfExpr
[AST] NFC: Make 'isSelfExpr()' available for general use
2018-05-24 14:47:26 -04:00
swift-ci
81ce77d510 Merge pull request #16644 from ravikandhadai/LargeIntOverflowPR 2018-05-21 20:37:47 -07:00
Ravi Kandhadai
f1ff8a61a5 [Sema] Add Sema checks for detecting large integer literals that
overflow Builtin.Int2048 and add tests for checking the
correctness of the diagnostics.
2018-05-21 18:41:44 -07:00
David Zarzycki
6d52f434af [AST] NFC: Create abstract class for MemberRefExpr/SubscriptExpr
This consolidation includes two examples of where this useful. There are
probably more.
2018-05-19 12:33:35 -04:00
David Zarzycki
43a457b0a6 [AST] NFC: Make 'isSelfExpr()' available for general use
Also, generalize the stripping of implicit conversions.
2018-05-19 09:23:31 -04: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
Huon Wilson
b6d44f31da [AST] std::function -> llvm::function_ref for some non-escaping params. 2018-05-01 08:29:06 +10:00
Slava Pestov
f64aa9876c AST: Ban type variable types from being stored into Exprs 2018-04-27 22:51:16 -07:00
Hamish
92931b7434 Merge remote-tracking branch 'upstream/master' into warn-weak-insta-dealloc 2018-04-02 18:06:45 +01:00
Hamish
8f2790633f [Sema] Fix implementation of getValueProvidingExpr()
We should trying to find the value providing expr(s) from the semantic providing expr.
2018-03-07 19:52:05 +00:00
Sho Ikeda
26d650292f [gardening] Use empty() over size() == 0 2018-03-05 14:43:13 +09:00
Graydon Hoare
76b82accbc [Stats] Simplify FrontendStatsTracer uses and formatter-definitions. 2018-02-21 14:49:24 -08:00
Graydon Hoare
9334779f33 [Stats] Reduce layering violations in FrontendStatsTracer. 2018-01-30 01:54:07 -08:00
Argyrios Kyrtzidis
f7e897ec4a [AST] Make sure that if a TupleExpr is created with element names but not name locations, it is marked implicit as appropriate
Fixes a crash for SourceEntityWalker which assumed that a non-implicit TupleExpr has source locations for its name elements.

Fixes SR-6517, rdar://35830880
2018-01-11 12:57:03 -08:00
Mark Lacey
b6430d0644 IUO: Add ImplicitlyUnwrappedFunctionConversionExpr.
This expression node is only used when applying the results of
expression type checking. It initially appears above the function
reference that returns an optional that needs to be unwrapped, and
then when dealing with function application we remove this and insert
a node to force-unwrap the result of the function application.
2018-01-04 11:40:45 -08:00
David Zarzycki
9c33f05f97 [AST] NFC: Migrate GenericIdentTypeRepr to llvm::TrailingObjects 2017-12-30 10:12:26 -05:00
David Zarzycki
62795501d9 [AST] NFC: De-boilerplate "has ParenType sugar" 2017-12-29 11:37:20 -05:00
David Zarzycki
1040d18227 [AST] NFC: Tail allocate TupleShuffleExpr data 2017-12-21 08:52:13 -05:00
David Zarzycki
362d801472 [AST] NFC: Tail allocate CaptureListExpr entries 2017-12-20 09:35:15 -05:00
David Zarzycki
5a4e96fcc2 [AST] NFC: Tail allocate UnresolvedSpecializeExpr TypeLocs 2017-12-20 09:35:15 -05:00
David Zarzycki
dbb421ba95 [AST] NFC: Tail allocate ErasureExpr conformances 2017-12-20 09:35:15 -05:00
David Zarzycki
60d2f5586e [AST] QoI: Track DictionaryExpr commas and tail allocate CollectionExpr comma locs 2017-12-19 13:33:09 -05:00
David Zarzycki
c75912215e [AST] NFC: Tail allocate CollectionExpr elements 2017-12-19 13:33:09 -05:00
David Zarzycki
00542951d2 [AST] NFC: Repack misc TupleExpr bits 2017-12-19 13:33:09 -05:00
David Zarzycki
54ea315586 [Basic] NFC: Stop using transparent unions 2017-12-16 10:43:49 -05:00
Joe Groff
a67f9ca3e5 Sema: Require indexes in key path subscript components to be Hashable.
And save the conformance to be captured when we form the KeyPath object.
2017-09-15 09:59:51 -07:00
David Zarzycki
d4dbce452a Merge pull request #11837 2017-09-11 08:53:38 -04:00
John McCall
2d3d6addc0 Delay the validaton of storage accessors until finalization.
The base mutability of storage is part of the signature, so be sure
to compute that during validation.  Also, serialize it as part of
the storage declaration, and fix some places that synthesize
declarations to set it correctly.
2017-09-10 04:56:02 -04:00
David Zarzycki
14870179bd [AST] NFC: Consolidate shared code into DynamicLookupExpr 2017-09-09 12:44:44 -04:00
Robert Widmann
2823a6960f Properly interpolate negative AP literals
Integer and Floating literals are aware of their negation but
do not store the sign in the text of the value.  Retrieve the
sign bit and properly interpolate the text of the literal value
with it to distinguish negative and positive literals.
2017-08-01 09:48:53 -07:00
Robert Widmann
8cdddef2f8 Refactor Params to use flags
Also, begin to pass around base types instead of raw InOutType types.  Ideally, only Sema needs to deal with them, but this means that a bunch of callers need to unwrap any inouts that might still be lying around before forming these types.

Multiple parts of the compiler were slicing, dicing, or just dropping these flags.  Because I intend to use them for the new function type representation, I need them to be preserved all across the compiler.  As a first pass, this stubs in what will eventually be structural rules as asserts and tracks down all callers of consequence to conform to the new invariants.

This is temporary.
2017-07-19 09:49:32 -07:00
Slava Pestov
737174fe9f AST: Add a DeclContext field to ComponentIdentTypeRepr
Plumb this through and set it appropriately, but don't use it
for anything yet.
2017-07-18 22:10:33 -07:00
Joe Groff
963c58c4b5 Push subscript label allocation for KeyPathComponents into the root constructor.
A preemptive strike against memory management bugs in the future.
2017-07-11 10:25:56 -07:00