Commit Graph

37 Commits

Author SHA1 Message Date
Hamish Knight
fd5346fee3 [CS] Ensure DeclContext is switched for if/switch expressions
Similar to multi-statement closures, we need to
make sure we change the DeclContext of the
ConstraintSystem when solving a conjunction for an
if/switch expression. This is unfortunately needed
for cases within single-expression closures since
they can't switch the system's DeclContext (as
they're solved together with the rest of the system).
2025-02-17 12:02:16 +00:00
Hamish Knight
89a3390aa1 [Sema] Move SingleValueStmtUsageChecker into pre-checking
These diagnostics are better suited for pre-checking
since we ought to be emitting them even if there's
some other error with the expression.
2024-08-30 18:55:48 +01:00
Hamish Knight
4beaaf32ad [CS] Improve placeholder diagnostics slightly
Make sure `CouldNotInferPlaceholderType` can
produce a diagnostic for a `PlaceholderType`
locator element, and avoid emitting an extra
diagnostic for a placeholder type in an invalid
position.
2024-07-07 23:42:33 +01:00
Hamish Knight
94cf5620d5 [Sema] Catch invalid if/switch exprs in more places
Move out-of-place SingleValueStmtExpr checking into
`performSyntacticExprDiagnostics`, to ensure we
catch all expressions. Previously we did the walk
as a part of Decl-based MiscDiagnostics, but it
turns out that can miss expressions in property
initializers, subscript default arguments, and
custom attrs.

This does mean that we'll now no longer diagnose
out-of-place if/switch exprs if the expression
didn't type-check, but that's consistent with the
rest of MiscDiagnostics, and I don't think it will
be a major issue in practice. We probably ought to
consider moving this checking into PreCheckExpr,
but that would require first separating out
SequenceExpr folding, which has other consequences,
and so I'm leaving as future work for now.
2023-08-30 12:57:29 +01:00
Slava Pestov
1957bd6065 Sema: Reword diagnostics to say 'without a type annotation' instead of 'without more context' 2023-06-09 17:44:42 -04:00
Hamish Knight
3f7c3a2faf Handle #if for if/switch expressions
- Allow an if/switch expression to become an
implicit return of a function that has a `#if`
body with a single active element that is an `if`
or `switch`.
- Allow `#if` branches of an if/switch expression,
as long as there is a single active expression
element.

rdar://107487977
2023-04-12 14:54:22 +01:00
Luciano Almeida
1e4fa6a08d [Sema] Fix variable invalid optional chaining in if context diagnostic 2023-02-22 17:52:02 -03:00
Hamish Knight
a40f1abaff Introduce if/switch expressions
Introduce SingleValueStmtExpr, which allows the
embedding of a statement in an expression context.
This then allows us to parse and type-check `if`
and `switch` statements as expressions, gated
behind the `IfSwitchExpression` experimental
feature for now. In the future,
SingleValueStmtExpr could also be used for e.g
`do` expressions.

For now, only single expression branches are
supported for producing a value from an
`if`/`switch` expression, and each branch is
type-checked independently. A multi-statement
branch may only appear if it ends with a `throw`,
and it may not `break`, `continue`, or `return`.

The placement of `if`/`switch` expressions is also
currently limited by a syntactic use diagnostic.
Currently they're only allowed in bindings,
assignments, throws, and returns. But this could
be lifted in the future if desired.
2023-02-01 15:30:18 +00:00
Hamish Knight
457bd230d2 [test] Rename if_expr -> ternary_expr 2022-10-03 11:28:29 +01:00
Hamish Knight
bca941b152 [AST] NFC: Rename IfExpr -> TernaryExpr
This matches what we call it in SwiftSyntax, and
is just generally clearer.
2022-09-28 10:33:31 +01:00
Owen Voorhees
166555c34f [Diagnostics] Better diagnostic for integer used as a boolean condition 2020-02-03 21:20:41 -08:00
Pavel Yaskevich
51a02966f0 [Diagnostics] NFC: Adjust all of the improved if/ternary test-cases 2019-10-22 15:33:06 -07:00
Pavel Yaskevich
74a8ee177e [Diagnostics] Diagnose missing members via fixes
Try to fix constraint system in a way where member
reference is going to be defined in terms of its use,
which makes it seem like parameters match arguments
exactly. Such helps to produce solutions and diagnose
failures related to missing members precisely.

These changes would be further extended to diagnose use
of unavailable members and other structural member failures.

Resolves: rdar://problem/34583132
Resolves: rdar://problem/36989788
Resolved: rdar://problem/39586166
Resolves: rdar://problem/40537782
Resolves: rdar://problem/46211109
2019-01-09 17:29:49 -08:00
Doug Gregor
945c09b1cc [Type checker] Improve diagnostics when an optional value is not unwrapped.
When we determine that an optional value needs to be unwrapped to make
an expression type check, use notes to provide several different
Fix-It options (with descriptions) rather than always pushing users
toward '!'. Specifically, the errors + Fix-Its now looks like this:

    error: value of optional type 'X?' must be unwrapped to a value of
        type 'X'
      f(x)
        ^
    note: coalesce using '??' to provide a default when the optional
        value contains 'nil'
      f(x)
        ^
          ?? <#default value#>
    note: force-unwrap using '!' to abort execution if the optional
        value contains 'nil'
      f(x)
         ^
         !

Fixes rdar://problem/42081852.
2018-07-13 11:02:04 -07:00
Slava Pestov
e31bd92eee Sema: Fix crash in IfExpr diagnostics
Fixes <rdar://problem/39586166>.
2018-04-25 22:09:14 -07:00
Robert Widmann
26b53a5e63 Look through IUOs when converting the scrutiny of if-exprs
Previously this would cause strange diagnostics to be emitted when
values of type Bool! were the subject of if-expression conditions.

var isBoolean: Bool! = false
let conditional = isBoolean ? "Broken" : "Heart"
// ^ type 'Bool' is broken

Instead, look through IOUs before performing the member access to cover
our bases here.
2017-01-05 03:08:06 -07:00
Slava Pestov
8f96606cb2 Sema: Remove TupleToScalar conversion, which did nothing useful except crash
As far as I can tell there's no way to trigger this from valid code.
2017-01-03 23:00:07 -08:00
David Farler
b7d17b25ba Rename -parse flag to -typecheck
A parse-only option is needed for parse performance tracking and the
current option also includes semantic analysis.
2016-11-28 10:50:55 -08:00
Michael Gottesman
a047bb7564 Revert "Fix the build."
This reverts commit dc24c2bd34.

Turns out Chris fixed the build but when I was looking at the bots, his fix had
not been tested yet, so I thought the tree was still red and was trying to
revert to green.
2016-07-17 16:29:18 -07:00
Michael Gottesman
dc24c2bd34 Fix the build.
This reverts commit b4cba58330.
This reverts commit a602927c75.
This reverts commit 55fbe5a763.
2016-07-17 16:17:15 -07:00
Chris Lattner
55fbe5a763 Remove Boolean as a special, privileged type used by Sema, and instead
use the concrete Bool type.  This eliminates a bunch of complexity and
makes diagnostics more concrete.
2016-07-17 15:14:24 -07:00
Manav Gabhawala
7928140f79 [SE-0046] Implements consistent function parameter labels by discarding extraneous parameter names and adding _ where necessary 2016-04-06 20:21:58 -04:00
Maxim Moiseev
2c95bb6d51 BooleanType => Boolean 2015-12-10 14:56:32 -08:00
Chris Lattner
97e6a50148 Start using contextual information from function calls to diagnose issues in their
argument.  For now we start with some of the most simple cases: single argument 
calls.  This dramatically improves the QoI for error messages in argument lists,
typically turning a error+note combo into a single specific error message.

Some minor improvements coming (and also generalizing this to n-ary calls), but it 
is nice that all the infrastructure is starting to come together...



Swift SVN r30905
2015-08-01 04:37:52 +00:00
Chris Lattner
467cd07968 Two changes:
- Improve handling of if_expr in a couple of ways: teach constraint simplification
   about IfThen/IfElse and teach CSDiags about the case when the cond expr doesn't match
   BooleanType.  This is rarely necessary, but CSDiags is all about cornercases, and this
   does fix a problem in a testcase.
 - Be a bit more specific about the constraint failure kind (e.g. say subtype) and when
   we have a protocol conformance failure, emit a specific diagnostic about it, instead of
   just saying that the types aren't convertible.




Swift SVN r30650
2015-07-26 05:31:12 +00:00
Chris Lattner
77cd337336 make more check lines for diagnostics specific.
Swift SVN r30569
2015-07-24 05:46:21 +00:00
Chris Lattner
dd7c63448c fix <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
significantly improving the diagnostics for ?: mismatches.


Swift SVN r30117
2015-07-11 19:41:56 +00:00
Chris Lattner
e41c23801f A bunch of conflated changes:
- Fix TypeCheckExpr.cpp to be more careful when propagating sugar from an 
   argument to the result of the function.  We don't want to propagate parens,
   because they show up in diagnostics later.

 - Restructure FailureDiagnosis::diagnoseFailure() to strictly process the tree
   in depth first order.  Before it would only do this if contextual typing was
   unavailable, leading to unpredictable inconsistencies between diagnostics.

 - Always perform diagnoseContextualConversionError early, as part of the thing
   that calls the visitor, instead of in each visit method.  This may change in
   the future, but is a simplification for now.

 - Make the operator processing code handle the "candidate is an exact match"
   case by emitting a diagnostic indicating that the result type of the operator
   must not match expectations, instead of emitting the silly things like
   "binary operator '&' cannot be applied to two Int operands" which is obviously
   false.

These changes lead to minor improvements across the testsuite, and should make the
diagnostics more predictable for more complex real-world ones, but I haven't gone
through the radars yet.  

Major missing pieces:
 - CallExpr isn't using the same logic that the operators are.
 - When you have a near match (only one argument mismatches) we should specifically
   complain about that argument, instead of spewing an entire argument list.
 - The noescape function attr diagnostic is being emitted twice now.
 



Swift SVN r29733
2015-06-26 07:29:05 +00:00
Joe Pamer
0562411bb2 Improve support for diagnosing errors that result from contextual or conversion type mismatches. Doing so allows us to improve our diagnostics for a few important cases:
- Situations where the type of a return statement's result expression doesn't line up with the function's type annotation.
- Situations where the type of an initializer expression doesn't line up with its declaration's type pattern.
- Situations where we assume a conversion to a built-in protocol must take place, such as in if-statement conditionals.

(Addresses rdar://problem/19224776, rdar://problem/19422107, rdar://problem/19422156, rdar://problem/19547806 and lots of other dupes.)

Swift SVN r24853
2015-01-30 19:32:20 +00:00
Dmitri Hrybenko
3b04d1b013 tests: reorganize tests so that they actually use the target platform
Most tests were using %swift or similar substitutions, which did not
include the target triple and SDK.  The driver was defaulting to the
host OS.  Thus, we could not run the tests when the standard library was
not built for OS X.

Swift SVN r24504
2015-01-19 06:52:49 +00:00
Joe Pamer
2912159776 Improve diagnostics for expression typecheck errors
These changes make the following improvements to how we generate diagnostics for expression typecheck failure:
- Customizing a diagnostic for a specific expression kind is as easy as adding a new method to the FailureDiagnosis class,
  and does not require intimate knowledge of the constraint solver’s inner workings.
    - As part of this patch, I’ve introduced specialized diagnostics for call, binop, unop, subscript, assignment and inout
      expressions, but we can go pretty far with this.
    - This also opens up the possibility to customize diagnostics not just for the expression kind, but for the specific types
      involved as well.
- For the purpose of presenting accurate type info, partially-specialized subexpressions are individually re-typechecked
  free of any contextual types. This allows us to:
    - Properly surface subexpression errors.
    - Almost completely avoid any type variables in our diagnostics. In cases where they could not be eliminated, we now
      substitute in "_".
    - More accurately indicate the sources of errors.
- We do a much better job of diagnosing disjunction failures. (So no more nonsensical ‘UInt8’ error messages.)
- We now present reasonable error messages for overload resolution failures, informing the user of partially-matching
  parameter lists when possible.

At the very least, these changes address the following bugs:

<rdar://problem/15863738> More information needed in type-checking error messages
<rdar://problem/16306600> QoI: passing a 'let' value as an inout results in an unfriendly diagnostic
<rdar://problem/16449805> Wrong error for struct-to-protocol downcast
<rdar://problem/16699932> improve type checker diagnostic when passing Double to function taking a Float
<rdar://problem/16707914> fatal error: Can't unwrap Optional.None…Optional.swift, line 75 running Master-Detail Swift app built from template
<rdar://problem/16785829> Inout parameter fixit
<rdar://problem/16900438> We shouldn't leak the internal type placeholder
<rdar://problem/16909379> confusing type check diagnostics
<rdar://problem/16951521> Extra arguments to functions result in an unhelpful error
<rdar://problem/16971025> Two Terrible Diagnostics
<rdar://problem/17007804> $T2 in compiler error string
<rdar://problem/17027483> Terrible diagnostic
<rdar://problem/17083239> Mysterious error using find() with Foundation types
<rdar://problem/17149771> Diagnostic for closure with no inferred return value leaks type variables
<rdar://problem/17212371> Swift poorly-worded error message when overload resolution fails on return type
<rdar://problem/17236976> QoI: Swift error for incorrectly typed parameter is confusing/misleading
<rdar://problem/17304200> Wrong error for non-self-conforming protocols
<rdar://problem/17321369> better error message for inout protocols
<rdar://problem/17539380> Swift error seems wrong
<rdar://problem/17559593> Bogus locationless "treating a forced downcast to 'NSData' as optional will never produce 'nil'" warning
<rdar://problem/17567973> 32-bit error message is really far from the mark: error: missing argument for parameter 'withFont' in call
<rdar://problem/17671058> Wrong error message: "Missing argument for parameter 'completion' in call"
<rdar://problem/17704609> Float is not convertible to UInt8
<rdar://problem/17705424> Poor error reporting for passing Doubles to NSColor: extra argument 'red' in call
<rdar://problem/17743603> Swift compiler gives misleading error message in "NSLayoutConstraint.constraintsWithVisualFormat("x", options: 123, metrics: nil, views: views)"
<rdar://problem/17784167> application of operator to generic type results in odd diagnostic
<rdar://problem/17801696> Awful diagnostic trying to construct an Int when .Int is around
<rdar://problem/17863882> cannot convert the expression's type '()' to type 'Seq'
<rdar://problem/17865869> "has different argument names" diagnostic when parameter defaulted-ness differs
<rdar://problem/17937593> Unclear error message for empty array literal without type context
<rdar://problem/17943023> QoI: compiler displays wrong error when a float is provided to a Int16 parameter in init method
<rdar://problem/17951148> Improve error messages for expressions inside if statements by pre-evaluating outside the 'if'
<rdar://problem/18057815> Unhelpful Swift error message
<rdar://problem/18077468> Incorrect argument label for insertSubview(...)
<rdar://problem/18079213> 'T1' is not identical to 'T2' lacks directionality
<rdar://problem/18086470> Confusing Swift error message: error: 'T' is not convertible to 'MirrorDisposition'
<rdar://problem/18098995> QoI: Unhelpful compiler error when leaving off an & on an inout parameter
<rdar://problem/18104379> Terrible error message
<rdar://problem/18121897> unexpected low-level error on assignment to immutable value through array writeback
<rdar://problem/18123596> unexpected error on self. capture inside class method
<rdar://problem/18152074> QoI: Improve diagnostic for type mismatch in dictionary subscripting
<rdar://problem/18242160> There could be a better error message when using [] instead of [:]
<rdar://problem/18242812> 6A1021a : Type variable leaked
<rdar://problem/18331819> Unclear error message when trying to set an element of an array constant (Swift)
<rdar://problem/18414834> Bad diagnostics example
<rdar://problem/18422468> Calculation of constant value yields unexplainable error
<rdar://problem/18427217> Misleading error message makes debugging difficult
<rdar://problem/18439742> Misleading error: "cannot invoke" mentions completely unrelated types as arguments
<rdar://problem/18535804> Wrong compiler error from swift compiler
<rdar://problem/18567914> Xcode 6.1. GM, Swift, assignment from Int64 to NSNumber. Warning shown as problem with UInt8
<rdar://problem/18784027> Negating Int? Yields Float
<rdar://problem/17691565> attempt to modify a 'let' variable with ++ results in typecheck error about @lvalue Float
<rdar://problem/17164001> "++" on let value could give a better error message

Swift SVN r23782
2014-12-08 21:56:47 +00:00
Doug Gregor
5fc8ac7fd1 Require the 'override' keyword for initializers that override designated initializers.
Swift SVN r20490
2014-07-24 15:38:33 +00:00
Dmitri Hrybenko
d14f17beef Change 'getLogicValue()' into a property 'boolValue'; change
'getArrayBoundValue()' into a property 'arrayBoundValue'.

rdar://17156123


Swift SVN r20304
2014-07-22 12:08:10 +00:00
Dave Abrahams
cbcf9aba21 s/LogicValueType/BooleanType/
We're moving toward using that protocol for straight-up Bool types

Swift SVN r19884
2014-07-12 18:58:18 +00:00
Dave Abrahams
6d1095f44e Protocol names end in "Type," "ible," or "able"
Mechanically add "Type" to the end of any protocol names that don't end
in "Type," "ible," or "able."  Also, drop "Type" from the end of any
associated type names, except for those of the *LiteralConvertible
protocols.

There are obvious improvements to make in some of these names, which can
be handled with separate commits.

Fixes <rdar://problem/17165920> Protocols `Integer` etc should get
uglier names.

Swift SVN r19883
2014-07-12 17:29:57 +00:00
Ted Kremenek
fad874708e Adjust test cases.
Swift SVN r17964
2014-05-12 22:01:52 +00:00
Joe Groff
4c09ef61e3 Add conditional expressions.
Implement the syntax 'if x then y else z', which evaluates to 'y' if 'x' is true or 'z' if 'x' is false. 'x' must be a valid logic value, and 'y' and 'z' must be implicitly convertible to a common type.

Swift SVN r4407
2013-03-16 20:28:58 +00:00