Skip to content

Commit f4736d8

Browse files
emit diagnostics for same type coercion. Fixes SR-11295
1 parent 586327a commit f4736d8

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

include/swift/AST/DiagnosticsSema.def

+3-1
Original file line numberDiff line numberDiff line change
@@ -918,7 +918,9 @@ WARNING(isa_is_foreign_check,none,
918918
WARNING(conditional_downcast_coercion,none,
919919
"conditional cast from %0 to %1 always succeeds",
920920
(Type, Type))
921-
921+
WARNING(unecessary_same_type_coercion,none,
922+
"casting expression to %0 doesn't change the type",
923+
(Type))
922924
WARNING(forced_downcast_noop,none,
923925
"forced cast of %0 to same type has no effect", (Type))
924926

lib/Sema/CSApply.cpp

+9
Original file line numberDiff line numberDiff line change
@@ -3533,6 +3533,15 @@ namespace {
35333533
Expr *sub = expr->getSubExpr();
35343534

35353535
cs.setExprTypes(sub);
3536+
3537+
if (!SuppressDiagnostics) {
3538+
// If we are trying to perform coercion to the same type emit a warning.
3539+
if (cs.getType(sub)->isEqual(toType)) {
3540+
tc.diagnose(expr->getLoc(), diag::unecessary_same_type_coercion, toType)
3541+
.fixItRemove(SourceRange(expr->getLoc(),
3542+
expr->getCastTypeLoc().getSourceRange().End));
3543+
}
3544+
}
35363545

35373546
if (tc.convertToType(sub, toType, cs.DC))
35383547
return nullptr;

test/expr/cast/as_coerce.swift

+17
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,20 @@ _ = sr6022 as! AnyObject // expected-warning {{forced cast from '() -> Any' to '
135135
_ = sr6022 as? AnyObject // expected-warning {{conditional cast from '() -> Any' to 'AnyObject' always succeeds}}
136136
_ = sr6022_1 as! Any // expected-warning {{forced cast from '() -> ()' to 'Any' always succeeds; did you mean to use 'as'?}}
137137
_ = sr6022_1 as? Any // expected-warning {{conditional cast from '() -> ()' to 'Any' always succeeds}}
138+
139+
// SR-11295
140+
let a = "Hello"
141+
_ = a as String // expected-warning {{casting expression to 'String' doesn't change the type}} {{7-17=}}
142+
143+
let b = 1
144+
_ = b as Int // expected-warning {{casting expression to 'Int' doesn't change the type}} {{7-14=}}
145+
146+
typealias Type = String
147+
148+
let c: Type = "Hello Typealias"
149+
_ = c as String // expected-warning {{casting expression to 'String' doesn't change the type}} {{7-17=}}
150+
151+
let d = "Hello Typealias"
152+
_ = d as Type // expected-warning {{casting expression to 'Type' (aka 'String') doesn't change the type}} {{7-15=}}
153+
154+
_ = "Hello" as String // expected-warning {{casting expression to 'String' doesn't change the type}} {{13-23=}}

0 commit comments

Comments
 (0)