Skip to content

Commit 83b4a8b

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 83b4a8b

File tree

7 files changed

+105
-26
lines changed

7 files changed

+105
-26
lines changed

lib/Sema/MiscDiagnostics.cpp

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

107107
bool IsExprStmt;
108+
// A flag to avoid rediagnosing the literal during the walk.
109+
bool ShouldDiagnoseTypeDefaultedCollections;
108110

109111
public:
110112
ASTContext &Ctx;
111113
const DeclContext *DC;
112114

113-
DiagnoseWalker(const DeclContext *DC, bool isExprStmt)
114-
: IsExprStmt(isExprStmt), Ctx(DC->getASTContext()), DC(DC) {}
115+
DiagnoseWalker(const DeclContext *DC, bool isExprStmt,
116+
bool shouldDiagnoseTypeDefaultedCollections)
117+
: IsExprStmt(isExprStmt), ShouldDiagnoseTypeDefaultedCollections(
118+
shouldDiagnoseTypeDefaultedCollections),
119+
Ctx(DC->getASTContext()), DC(DC) {}
115120

116121
std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override {
117122
return { false, P };
@@ -124,6 +129,19 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
124129
bool shouldWalkIntoTapExpression() override { return false; }
125130

126131
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
132+
133+
// When walked into a type defaulted collection expression, check if it
134+
// should be diagnosed.
135+
if (auto collection = dyn_cast<CollectionExpr>(E)) {
136+
if (collection->isTypeDefaulted() &&
137+
ShouldDiagnoseTypeDefaultedCollections) {
138+
// Only diagnose type defaulted collection if was not diagnosed
139+
// before.
140+
diagnoseTypeDefaultedCollectionExpr(
141+
const_cast<CollectionExpr *>(collection), Ctx, true);
142+
}
143+
}
144+
127145
// See through implicit conversions of the expression. We want to be able
128146
// to associate the parent of this expression with the ultimate callee.
129147
auto Base = E;
@@ -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 diagnoseAsWarning) {
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 (diagnoseAsWarning) {
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 (diagnoseAsWarning) {
467+
inFlight.limitBehavior(DiagnosticBehavior::Warning);
468+
}
440469
}
441470
}
442471

@@ -1308,18 +1337,21 @@ static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
13081337
}
13091338
};
13101339

1311-
DiagnoseWalker Walker(DC, isExprStmt);
1312-
const_cast<Expr *>(E)->walk(Walker);
1340+
bool shouldDiagnoseTypeDefaultedCollections = true;
13131341

1314-
// Diagnose uses of collection literals with defaulted types at the top
1315-
// level.
1316-
if (auto collection
1317-
= dyn_cast<CollectionExpr>(E->getSemanticsProvidingExpr())) {
1342+
if (auto collection =
1343+
dyn_cast<CollectionExpr>(E->getSemanticsProvidingExpr())) {
13181344
if (collection->isTypeDefaulted()) {
1319-
Walker.checkTypeDefaultedCollectionExpr(
1320-
const_cast<CollectionExpr *>(collection));
1345+
DiagnoseWalker::diagnoseTypeDefaultedCollectionExpr(
1346+
const_cast<CollectionExpr *>(collection), DC->getASTContext(), false);
1347+
// The expression was diagnosed, thus there is no need to diagnose it
1348+
// again.
1349+
shouldDiagnoseTypeDefaultedCollections = false;
13211350
}
13221351
}
1352+
1353+
DiagnoseWalker Walker(DC, isExprStmt, shouldDiagnoseTypeDefaultedCollections);
1354+
const_cast<Expr *>(E)->walk(Walker);
13231355
}
13241356

13251357

test/Constraints/array_literal.swift

Lines changed: 34 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,49 @@ 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 a8: (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 a9: 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+
func test<T>(_: [T]) {}
171+
172+
test([])
173+
// expected-warning@-1{{empty collection literal requires an explicit type}}
174+
test([1, nil, ""])
175+
// expected-warning@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
176+
177+
func test<T>() -> [T]? {
178+
[]
179+
}
180+
181+
_ = test() ?? []
182+
// expected-warning@-1{{empty collection literal requires an explicit type}}
183+
_ = ["Swift", 1, test([])]
184+
// expected-warning@-1 {{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
185+
// expected-warning@-2{{empty collection literal requires an explicit type}}
186+
187+
func f(_ b: Bool) {
188+
let _ = b ? [] : []
189+
// expected-warning@-1{{empty collection literal requires an explicit type}}
190+
}
158191
}
159192

160193
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/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)