Skip to content

Commit 3a6baaf

Browse files
committed
[Fixit] Provide fixit when converting expressions of type T to [T] or UnsafePointer<T>.
1 parent c994a3b commit 3a6baaf

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

lib/Sema/CSDiag.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3477,6 +3477,24 @@ bool FailureDiagnosis::diagnoseContextualConversionError() {
34773477
return true;
34783478
}
34793479

3480+
// When converting from T to [T] or UnsafePointer<T>, we can offer fixit to wrap
3481+
// the expr with brackets.
3482+
if (auto *contextDecl = contextualType->getAnyNominal()) {
3483+
if (contextDecl == CS->TC.Context.getArrayDecl() ||
3484+
contextDecl == CS->TC.Context.getUnsafePointerDecl()) {
3485+
SmallVector<Type, 4> scratch;
3486+
for (Type arg : contextualType->getAllGenericArgs(scratch)) {
3487+
if (arg->isEqual(exprType)) {
3488+
diagnose(expr->getLoc(), diagID, exprType, contextualType).
3489+
fixItInsert(expr->getStartLoc(), "[").fixItInsert(
3490+
Lexer::getLocForEndOfToken(CS->TC.Context.SourceMgr,
3491+
expr->getEndLoc()), "]");
3492+
return true;
3493+
}
3494+
}
3495+
}
3496+
}
3497+
34803498
// When complaining about conversion to a protocol type, complain about
34813499
// conformance instead of "conversion".
34823500
if (contextualType->is<ProtocolType>() ||

test/Sema/diag_type_conversion.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// RUN: %target-parse-verify-swift
2+
3+
func foo1(_ a: [Int]) {}
4+
func foo2(_ a : UnsafePointer<Int>) {}
5+
func foo3 () {
6+
foo1(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}} {{8-8=[}} {{9-9=]}}
7+
foo2(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafePointer<Int>'}} {{8-8=[}} {{9-9=]}}
8+
}

0 commit comments

Comments
 (0)