Commit Graph

937 Commits

Author SHA1 Message Date
Slava Pestov
89758758f0 Merge pull request #23672 from slavapestov/kill-argument-shuffle-expr
Kill ArgumentShuffleExpr
2019-03-31 11:20:30 -04:00
Slava Pestov
1467f554f5 AST: Remove ArgumentShuffleExpr 2019-03-31 01:36:19 -04:00
Slava Pestov
e212d4567f Sema: Collect varargs into an ArrayExpr and use DefaultArgumentExpr
Instead of building ArgumentShuffleExprs, lets just build a TupleExpr,
with explicit representation of collected varargs and default
arguments.

This isn't quite as elegant as it should be, because when re-typechecking,
SanitizeExpr needs to restore the 'old' parameter list by stripping out
the nodes inserted by type checking. However that hackery is all isolated
in one place and will go away soon.

Note that there's a minor change the generated SIL. Caller default
arguments (#file, #line, etc) are no longer delayed and are instead
evaluated in their usual argument position. I don't believe this actually
results in an observable change in behavior, but if it turns out to be
a problem, we can pretty easily change it back to the old behavior with a
bit of extra work.
2019-03-31 01:36:19 -04:00
Doug Gregor
a848d12665 Parse unknown attributes as "custom" attributes.
Parse custom attributes with the grammar:

```
'@' type-identifier expr-paren?
```
2019-03-29 23:10:36 -07:00
Slava Pestov
7c7f60a9a4 Merge pull request #23618 from slavapestov/array-expr-lowering
Convert ArrayExpr to not use callWitness() or generate a SemanticExpr.
2019-03-28 11:01:29 -04:00
Parker Schuh
d0779bd771 Convert ArrayExpr to not use callWitness() or generate a SemanticExpr. 2019-03-27 23:21:08 -04:00
Slava Pestov
e2c9c52c93 AST/Sema/SILGen: Implement tuple conversions
TupleShuffleExpr could not express the full range of tuple conversions that
were accepted by the constraint solver; in particular, while it could re-order
elements or introduce and eliminate labels, it could not convert the tuple
element types to their supertypes.

This was the source of the annoying "cannot express tuple conversion"
diagnostic.

Replace TupleShuffleExpr with DestructureTupleExpr, which evaluates a
source expression of tuple type and binds its elements to OpaqueValueExprs.

The DestructureTupleExpr's result expression can then produce an arbitrary
value written in terms of these OpaqueValueExprs, as long as each
OpaqueValueExpr is used exactly once.

This is sufficient to express conversions such as (Int, Float) => (Int?, Any),
as well as the various cases that were already supported, such as
(x: Int, y: Float) => (y: Float, x: Int).

https://bugs.swift.org/browse/SR-2672, rdar://problem/12340004
2019-03-27 18:12:05 -04:00
Slava Pestov
428c709491 AST: Remove argument list-specific parts of TupleShuffleExpr
Before extending TupleShuffleExpr to represent all tuple
conversions allowed by the constraint solver, remove the
parts of TupleShuffleExpr that are no longer needed; this is
support for default arguments, varargs, and scalar-to-tuple and
tuple-to-scalar conversions.
2019-03-21 02:18:41 -04:00
Slava Pestov
d470e9df4d AST: Split off ArgumentShuffleExpr from TupleShuffleExpr
Right now we use TupleShuffleExpr for two completely different things:

- Tuple conversions, where elements can be re-ordered and labels can be
  introduced/eliminated
- Complex argument lists, involving default arguments or varargs

The first case does not allow default arguments or varargs, and the
second case does not allow re-ordering or introduction/elimination
of labels. Furthermore, the first case has a representation limitation
that prevents us from expressing tuple conversions that change the
type of tuple elements.

For all these reasons, it is better if we use two separate Expr kinds
for these purposes. For now, just make an identical copy of
TupleShuffleExpr and call it ArgumentShuffleExpr. In CSApply, use
ArgumentShuffleExpr when forming the arguments to a call, and keep
using TupleShuffleExpr for tuple conversions. Each usage of
TupleShuffleExpr has been audited to see if it should instead look at
ArgumentShuffleExpr.

In sequent commits I plan on redesigning TupleShuffleExpr to correctly
represent all tuple conversions without any unnecessary baggage.

Longer term, we actually want to change the representation of CallExpr
to directly store an argument list; then instead of a single child
expression that must be a ParenExpr, TupleExpr or ArgumentShuffleExpr,
all CallExprs will have a uniform representation and ArgumentShuffleExpr
will go away altogether. This should reduce memory usage and radically
simplify parts of SILGen.
2019-03-21 02:18:41 -04:00
Parker Schuh
5160da6a2e FloatLiteralExpr now is lowered directly into SIL.
For context, String, Nil, Bool, and Int already behave this way.

Note: Swift can compile against 80 or 64 bit floats as the builtin
literal type. Thus, it was necessary to capture this bit somehow in the
FloatLiteralExpr. This was done as another Type field capturing this
info.
2019-03-01 09:01:30 -08:00
Joe Groff
bb67cf815c Merge pull request #21355 from technicated/tuple-keypaths-2
Tuple KeyPaths
2019-02-25 12:56:05 -08:00
technicated
bad2230ccd Private constructor for tuple element kind keypath in AST 2019-02-18 10:19:42 +01:00
Andrea Tomarelli
85df714f5b Fixed 'kind' check in KeyPathExpr::Component constructor 2019-02-18 09:04:43 +01:00
Andrea Tomarelli
6a462b131b Made a union in KeyPathExpr anonymous 2019-02-18 09:04:43 +01:00
Andrea Tomarelli
834ef2c253 Renamed fieldNumber to tupleIndex in AST & Sema 2019-02-18 09:04:42 +01:00
Andrea Tomarelli
ede47cafbd Partial AST & Sema implementation of TKP 2019-02-18 09:04:42 +01:00
Parker Schuh
b12fcb50db IntegerLiteralExpr now is lowered directly into SIL.
For context, String, Nil, and Bool already behave this way.

Note: Before it used to construct (call, ... (integer_literal)), and the
call would be made explicit / implicit based on if you did eg: Int(3) or
just 3. This however did not translate to the new world so this PR adds
a IsExplicitConversion bit to NumberLiteralExpr. Some side results of
all this are that some warnings changed a little and some instructions are
emitted in a different order.
2019-02-14 11:54:16 -08:00
Pavel Yaskevich
1d42e16ad2 [ConstraintSystem] Detect invalid implicit ref to initializer on non-const metatype
Situations like:

```swift
struct S {}
func foo(_ s: S.Type) {
  _ = s()
}
```

Used to be diagnosed in solution application phase, which means that
solver was allowed to formed an incorrect solution.
2019-02-07 00:17:07 -08:00
Pavel Yaskevich
9a1e92ec0a [AST] Add getDecl parameter to Expr::isTypeRerefence
So it could be extended to support not yet fully type-checked
AST when used by constraint system solver.
2019-02-05 18:09:51 -08:00
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