Skip to content

Commit 59348a1

Browse files
committed
Sema: Emit diagnostics when walking into collection literals with defaulted types
Resolves #60011 Tests: add verification for emitted fixit, a flag for no availability checking; add expected warnings Gardening: clean up diagnoseTypeDefaultedCollectionExpr function
1 parent 23e5143 commit 59348a1

File tree

8 files changed

+115
-32
lines changed

8 files changed

+115
-32
lines changed

lib/Sema/MiscDiagnostics.cpp

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

107107
bool IsExprStmt;
108+
bool ShouldDiagnoseTypeDefaultedCollectionAsWarning;
108109

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

113-
DiagnoseWalker(const DeclContext *DC, bool isExprStmt)
114-
: IsExprStmt(isExprStmt), Ctx(DC->getASTContext()), DC(DC) {}
113+
DiagnoseWalker(const DeclContext *DC, bool isExprStmt,
114+
bool shouldDiagnoseTypeDefaultedCollectionAsWarning)
115+
: IsExprStmt(isExprStmt),
116+
ShouldDiagnoseTypeDefaultedCollectionAsWarning(
117+
shouldDiagnoseTypeDefaultedCollectionAsWarning),
118+
Ctx(DC->getASTContext()), DC(DC) {}
119+
120+
public:
121+
static void walk(Expr *E, const DeclContext *DC, bool isExprStmt) {
122+
// Diagnose type defaulted collection literals in subexpressions as
123+
// warnings to preserve source compatibility.
124+
bool shouldDiagnoseTypeDefaultedCollectionAsWarning = true;
125+
126+
if (auto collection =
127+
dyn_cast<CollectionExpr>(E->getSemanticsProvidingExpr())) {
128+
if (collection->isTypeDefaulted()) {
129+
shouldDiagnoseTypeDefaultedCollectionAsWarning = false;
130+
}
131+
}
132+
133+
DiagnoseWalker Walker(DC, isExprStmt,
134+
shouldDiagnoseTypeDefaultedCollectionAsWarning);
135+
E->walk(Walker);
136+
}
115137

116138
std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override {
117139
return { false, P };
@@ -124,6 +146,24 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
124146
bool shouldWalkIntoTapExpression() override { return false; }
125147

126148
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
149+
150+
// When walked into a type defaulted collection expression, check if it
151+
// should be diagnosed.
152+
if (auto collection = dyn_cast<CollectionExpr>(E)) {
153+
if (collection->isTypeDefaulted()) {
154+
diagnoseTypeDefaultedCollectionExpr(
155+
const_cast<CollectionExpr *>(collection), Ctx,
156+
ShouldDiagnoseTypeDefaultedCollectionAsWarning);
157+
158+
// If an error was emitted, we diagnosed a top-level literal. Flip the
159+
// flag so that type defaulted collection literals in subexpressions
160+
// get diagnosed as warnings for source compatibility.
161+
if (!ShouldDiagnoseTypeDefaultedCollectionAsWarning) {
162+
ShouldDiagnoseTypeDefaultedCollectionAsWarning = true;
163+
}
164+
}
165+
}
166+
127167
// See through implicit conversions of the expression. We want to be able
128168
// to associate the parent of this expression with the ultimate callee.
129169
auto Base = E;
@@ -420,23 +460,34 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
420460
return false;
421461
}
422462

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 {
463+
/// Diagnose a collection literal with a defaulted type such as \c [Any].
464+
static void diagnoseTypeDefaultedCollectionExpr(CollectionExpr *c,
465+
ASTContext &ctx,
466+
bool diagnoseAsWarning) {
467+
// Produce a diagnostic with a fixit to add the defaulted type as an
468+
// explicit annotation.
469+
auto &diags = ctx.Diags;
470+
471+
if (c->getNumElements() == 0) {
472+
InFlightDiagnostic inFlight =
473+
diags.diagnose(c->getLoc(), diag::collection_literal_empty);
474+
inFlight.highlight(c->getSourceRange());
475+
476+
if (diagnoseAsWarning) {
477+
inFlight.limitBehavior(DiagnosticBehavior::Warning);
478+
}
479+
} else {
434480
assert(c->getType()->hasTypeRepr() &&
435481
"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());
482+
InFlightDiagnostic inFlight = diags.diagnose(
483+
c->getLoc(), diag::collection_literal_heterogeneous, c->getType());
484+
inFlight.highlight(c->getSourceRange());
485+
inFlight.fixItInsertAfter(c->getEndLoc(),
486+
" as " + c->getType()->getString());
487+
488+
if (diagnoseAsWarning) {
489+
inFlight.limitBehavior(DiagnosticBehavior::Warning);
490+
}
440491
}
441492
}
442493

@@ -1308,18 +1359,7 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
13081359
}
13091360
};
13101361

1311-
DiagnoseWalker Walker(DC, isExprStmt);
1312-
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-
}
1362+
DiagnoseWalker::walk(const_cast<Expr *>(E), DC, isExprStmt);
13231363
}
13241364

13251365

test/Constraints/array_literal.swift

Lines changed: 29 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,44 @@ 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+
176+
func f1<T>(_: [T]) {}
177+
178+
func f2<T>() -> [T]? {}
179+
180+
f1([])
181+
// expected-warning@-1{{empty collection literal requires an explicit type}}
182+
f1([1, nil, ""])
183+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
184+
_ = f2() ?? []
185+
// expected-warning@-1{{empty collection literal requires an explicit type}}
158186
}
159187

160188
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

0 commit comments

Comments
 (0)