Skip to content

Commit bdcf5c9

Browse files
committed
Sema: Emit diagnostics when walking into collection literals with defaulted types
Resolves #60011 Gardening: clean up `checkTypeDefaultedCollectionExpr` function
1 parent 23e5143 commit bdcf5c9

File tree

9 files changed

+100
-30
lines changed

9 files changed

+100
-30
lines changed

lib/Sema/MiscDiagnostics.cpp

Lines changed: 47 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -105,13 +105,15 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
105105
SmallPtrSet<DeclRefExpr*, 4> AlreadyDiagnosedBitCasts;
106106

107107
bool IsExprStmt;
108+
bool HasReachedSemanticsProvidingExpr;
108109

109-
public:
110110
ASTContext &Ctx;
111111
const DeclContext *DC;
112112

113+
public:
113114
DiagnoseWalker(const DeclContext *DC, bool isExprStmt)
114-
: IsExprStmt(isExprStmt), Ctx(DC->getASTContext()), DC(DC) {}
115+
: IsExprStmt(isExprStmt), HasReachedSemanticsProvidingExpr(false),
116+
Ctx(DC->getASTContext()), DC(DC) {}
115117

116118
std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override {
117119
return { false, P };
@@ -124,6 +126,17 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
124126
bool shouldWalkIntoTapExpression() override { return false; }
125127

126128
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
129+
130+
if (auto collection = dyn_cast<CollectionExpr>(E)) {
131+
if (collection->isTypeDefaulted()) {
132+
// Diagnose type defaulted collection literals in subexpressions as
133+
// warnings to preserve source compatibility.
134+
diagnoseTypeDefaultedCollectionExpr(
135+
const_cast<CollectionExpr *>(collection), Ctx,
136+
/*downgradeToWarning=*/HasReachedSemanticsProvidingExpr);
137+
}
138+
}
139+
127140
// See through implicit conversions of the expression. We want to be able
128141
// to associate the parent of this expression with the ultimate callee.
129142
auto Base = E;
@@ -317,7 +330,12 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
317330
if (auto cast = dyn_cast<CheckedCastExpr>(E)) {
318331
checkCheckedCastExpr(cast);
319332
}
320-
333+
334+
if (!HasReachedSemanticsProvidingExpr &&
335+
E == E->getSemanticsProvidingExpr()) {
336+
HasReachedSemanticsProvidingExpr = true;
337+
}
338+
321339
return { true, E };
322340
}
323341

@@ -420,23 +438,34 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
420438
return false;
421439
}
422440

423-
/// We have a collection literal with a defaulted type, e.g. of [Any]. Emit
424-
/// an error if it was inferred to this type in an invalid context, which is
425-
/// one in which the parent expression is not itself a collection literal.
426-
void checkTypeDefaultedCollectionExpr(CollectionExpr *c) {
427-
// If the parent is a non-expression, or is not itself a literal, then
428-
// produce an error with a fixit to add the type as an explicit
429-
// annotation.
430-
if (c->getNumElements() == 0)
431-
Ctx.Diags.diagnose(c->getLoc(), diag::collection_literal_empty)
432-
.highlight(c->getSourceRange());
433-
else {
441+
/// Diagnose a collection literal with a defaulted type such as \c [Any].
442+
static void diagnoseTypeDefaultedCollectionExpr(CollectionExpr *c,
443+
ASTContext &ctx,
444+
bool downgradeToWarning) {
445+
// Produce a diagnostic with a fixit to add the defaulted type as an
446+
// explicit annotation.
447+
auto &diags = ctx.Diags;
448+
449+
if (c->getNumElements() == 0) {
450+
InFlightDiagnostic inFlight =
451+
diags.diagnose(c->getLoc(), diag::collection_literal_empty);
452+
inFlight.highlight(c->getSourceRange());
453+
454+
if (downgradeToWarning) {
455+
inFlight.limitBehavior(DiagnosticBehavior::Warning);
456+
}
457+
} else {
434458
assert(c->getType()->hasTypeRepr() &&
435459
"a defaulted type should always be printable");
436-
Ctx.Diags.diagnose(c->getLoc(), diag::collection_literal_heterogeneous,
437-
c->getType())
438-
.highlight(c->getSourceRange())
439-
.fixItInsertAfter(c->getEndLoc(), " as " + c->getType()->getString());
460+
InFlightDiagnostic inFlight = diags.diagnose(
461+
c->getLoc(), diag::collection_literal_heterogeneous, c->getType());
462+
inFlight.highlight(c->getSourceRange());
463+
inFlight.fixItInsertAfter(c->getEndLoc(),
464+
" as " + c->getType()->getString());
465+
466+
if (downgradeToWarning) {
467+
inFlight.limitBehavior(DiagnosticBehavior::Warning);
468+
}
440469
}
441470
}
442471

@@ -1310,16 +1339,6 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
13101339

13111340
DiagnoseWalker Walker(DC, isExprStmt);
13121341
const_cast<Expr *>(E)->walk(Walker);
1313-
1314-
// Diagnose uses of collection literals with defaulted types at the top
1315-
// level.
1316-
if (auto collection
1317-
= dyn_cast<CollectionExpr>(E->getSemanticsProvidingExpr())) {
1318-
if (collection->isTypeDefaulted()) {
1319-
Walker.checkTypeDefaultedCollectionExpr(
1320-
const_cast<CollectionExpr *>(collection));
1321-
}
1322-
}
13231342
}
13241343

13251344

test/Constraints/array_literal.swift

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// RUN: %target-typecheck-verify-swift
1+
// RUN: %target-typecheck-verify-swift -disable-availability-checking
22

33
struct IntList : ExpressibleByArrayLiteral {
44
typealias Element = Int
@@ -145,16 +145,48 @@ func defaultToAny(i: Int, s: String) {
145145
let _: [Any] = [1, "a", 3.5]
146146
let _: [Any] = [1, "a", [3.5, 3.7, 3.9]]
147147
let _: [Any] = [1, "a", [3.5, "b", 3]]
148+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
148149
let _: [Any] = [1, [2, [3]]]
150+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
149151

150152
let _: [Any?] = [1, "a", nil, 3.5]
151153
let _: [Any?] = [1, "a", nil, [3.5, 3.7, 3.9]]
152154
let _: [Any?] = [1, "a", nil, [3.5, "b", nil]]
155+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
153156
let _: [Any?] = [1, [2, [3]]]
157+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
154158
let _: [Any?] = [1, nil, [2, nil, [3]]]
159+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
155160

156161
let a6 = [B(), C()]
157162
let _: Int = a6 // expected-error{{value of type '[A]'}}
163+
164+
let a7: some Collection = [1, "Swift"]
165+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}} {{41-41= as [Any]}}
166+
let _: (any Sequence)? = [1, "Swift"]
167+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
168+
let _: any Sequence = [1, nil, "Swift"]
169+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
170+
let _ = [1, true, ([], 1)]
171+
// expected-error@-1 {{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
172+
// expected-warning@-2 {{empty collection literal requires an explicit type}}
173+
let _ = true ? [] : []
174+
// expected-warning@-1{{empty collection literal requires an explicit type}}
175+
let _ = (true, ([1, "Swift"]))
176+
//expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
177+
let _ = ([1, true])
178+
//expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
179+
180+
func f1<T>(_: [T]) {}
181+
182+
func f2<T>() -> [T]? {}
183+
184+
f1([])
185+
// expected-warning@-1{{empty collection literal requires an explicit type}}
186+
f1([1, nil, ""])
187+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
188+
_ = f2() ?? []
189+
// expected-warning@-1{{empty collection literal requires an explicit type}}
158190
}
159191

160192
func noInferAny(iob: inout B, ioc: inout C) {

test/Constraints/casts.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ func test_compatibility_coercions(_ arr: [Int], _ optArr: [Int]?, _ dict: [Strin
337337

338338
// The array can also be inferred to be [Any].
339339
_ = ([] ?? []) as Array // expected-warning {{left side of nil coalescing operator '??' has non-optional type '[Any]', so the right side is never used}}
340+
// expected-warning@-1{{empty collection literal requires an explicit type}}
340341

341342
// rdar://88334481 – Don't apply the compatibility logic for collection literals.
342343
typealias Magic<T> = T

test/Constraints/casts_swift6.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ func test_compatibility_coercions(_ arr: [Int], _ optArr: [Int]?, _ dict: [Strin
5757

5858
// The array can also be inferred to be [Any].
5959
_ = ([] ?? []) as Array // expected-warning {{left side of nil coalescing operator '??' has non-optional type '[Any]', so the right side is never used}}
60+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
6061

6162
// Cases from rdar://88334481
6263
typealias Magic<T> = T

test/Constraints/construction.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ SR_5245(s: SR_5245.S(f: [.e1, .e2]))
172172

173173
// rdar://problem/34670592 - Compiler crash on heterogeneous collection literal
174174
_ = Array([1, "hello"]) // Ok
175+
// expected-warning@-1 {{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
175176

176177
func init_via_non_const_metatype(_ s1: S1.Type) {
177178
_ = s1(i: 42) // expected-error {{initializing from a metatype value must reference 'init' explicitly}} {{9-9=.init}}

test/Constraints/dictionary_literal.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ func testDefaultExistentials() {
139139
"b": ["a", 2, 3.14159],
140140
"c": ["a": 2, "b": 3.5]]
141141
// expected-error@-3{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}}
142+
// expected-warning@-3{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
142143

143144
let d3 = ["b" : B(), "c" : C()]
144145
let _: Int = d3 // expected-error{{value of type '[String : A]'}}
@@ -193,4 +194,4 @@ f59215(["", ""]) //expected-error{{dictionary of type '[String : String]' cannot
193194
f59215(["", "", "", ""]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}}
194195
// expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} {{19-20=:}}
195196
f59215(["", "", "", ""]) //expected-error{{dictionary of type '[String : String]' cannot be used with array literal}}
196-
// expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} {{19-20=:}}
197+
// expected-note@-1{{did you mean to use a dictionary literal instead?}} {{11-12=:}} {{19-20=:}}

test/Constraints/subscript.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ extension Int {
104104
let _ = 1["1"] // expected-error {{ambiguous use of 'subscript(_:)'}}
105105

106106
let squares = [ 1, 2, 3 ].reduce([:]) { (dict, n) in
107+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
107108
var dict = dict
108109
dict[n] = n * n
109110
return dict

test/IDE/print_usrs_opaque_types.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,29 +9,34 @@
99
func testUnifyingGenericParams<T, U>(x: T) -> some Collection where T == U {
1010
// expected-warning@-1 {{same-type requirement makes generic parameters 'U' and 'T' equivalent}}
1111
return []
12+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
1213
}
1314

1415
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test0C22UnifyingGenericParams21xQrx_tSlRz7ElementQzRs_r0_lF
1516
func testUnifyingGenericParams2<T, U>(x: T) -> some Collection where T: Collection, U == T.Element {
1617
return []
18+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
1719
}
1820

1921
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test0C24ConcretizingGenericParam1xQrSi_tSiRszlF
2022
func testConcretizingGenericParam<T>(x: T) -> some Collection where T == Int {
2123
// expected-warning@-1 {{same-type requirement makes generic parameter 'T' non-generic}}
2224
return []
25+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
2326
}
2427

2528
struct GenericContext<T> {
2629
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test14GenericContextV0c8UnifyingD6Params1xQrx_tqd__RszlF
2730
func testUnifyingGenericParams<U>(x: T) -> some Collection where T == U {
2831
// expected-warning@-1 {{same-type requirement makes generic parameters 'U' and 'T' equivalent}}
2932
return []
33+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
3034
}
3135

3236
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test14GenericContextV0c8UnifyingD7Params21xQrx_tSlRz7ElementQzRsd__lF
3337
func testUnifyingGenericParams2<U>(x: T) -> some Collection where T: Collection, U == T.Element {
3438
return []
39+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
3540
}
3641

3742
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test14GenericContextVyQrxcqd__Rszluip
@@ -40,6 +45,7 @@ struct GenericContext<T> {
4045
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test14GenericContextVyQrxcqd__Rszluig
4146
get {
4247
return []
48+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
4349
}
4450
}
4551
}
@@ -48,6 +54,7 @@ extension GenericContext where T == Int {
4854
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test14GenericContextVAASiRszlE0c12ConcretizingD5Param1xQrSi_tF
4955
func testConcretizingGenericParam(x: T) -> some Collection {
5056
return []
57+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
5158
}
5259
}
5360

@@ -58,19 +65,22 @@ extension TooGenericTooContext where T == U {
5865
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test010TooGenericD7ContextVAAq_RszrlE0c8UnifyingE6Params1xQrx_tF
5966
func testUnifyingGenericParams(x: T) -> some Collection {
6067
return []
68+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
6169
}
6270
}
6371

6472
extension TooGenericTooContext where T: Collection, U == T.Element {
6573
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test010TooGenericD7ContextVAASlRz7ElementQzRs_rlE0c8UnifyingE7Params21xQrx_tF
6674
func testUnifyingGenericParams2(x: T) -> some Collection {
6775
return []
76+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
6877
}
6978
}
7079
extension TooGenericTooContext where T == Int {
7180
// CHECK: [[@LINE+1]]:{{[0-9]+}} s:14swift_ide_test010TooGenericD7ContextVAASiRszrlE0c12ConcretizingE5Param1xQrSi_tF
7281
func testConcretizingGenericParam(x: T) -> some Collection {
7382
return []
83+
// expected-warning@-1 {{empty collection literal requires an explicit type}}
7484
}
7585
}
7686

test/expr/cast/objc_coerce_array.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,13 @@ var x = 1
77
_ = [x] as [NSNumber]
88

99
_ = ["x":["y":"z","a":1]] as [String : [String : AnyObject]]
10+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[String : AnyObject]'; add explicit type annotation if this is intentiona}}
1011
_ = ["x":["z",1]] as [String : [AnyObject]]
12+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[AnyObject]'; add explicit type annotation if this is intentional}}
1113
_ = [["y":"z","a":1]] as [[String : AnyObject]]
14+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[String : AnyObject]'; add explicit type annotation if this is intentional}}
1215
_ = [["z",1]] as [[AnyObject]]
16+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[AnyObject]'; add explicit type annotation if this is intentional}}
1317

1418
var y: Any = 1
1519

0 commit comments

Comments
 (0)