switch expressions: report bad result expression types

if they are not convertible to poly expression target type
This commit is contained in:
Anna.Kozlova
2018-11-21 18:51:47 +01:00
parent 2e30e0c457
commit a7eefcd5ae
3 changed files with 27 additions and 1 deletions
@@ -1437,6 +1437,25 @@ public class HighlightUtil extends HighlightUtilBase {
return null;
}
static Collection<HighlightInfo> checkSwitchExpressionReturnTypeCompatible(PsiSwitchExpression switchExpression) {
if (!PsiPolyExpressionUtil.isPolyExpression(switchExpression)) return null;
List<HighlightInfo> infos = new ArrayList<>();
PsiType switchExpressionType = switchExpression.getType();
if (switchExpressionType != null) {
for (PsiExpression expression : PsiUtil.getSwitchResultExpressions(switchExpression)) {
final PsiType expressionType = PsiResolveHelper.ourGraphGuard.doPreventingRecursion(expression, true, expression::getType);
if (expressionType != null && !switchExpressionType.isAssignableFrom(expressionType)) {
infos.add(HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
.range(expression)
.descriptionAndTooltip("Bad type in switch expression: " + expressionType.getCanonicalText() + " cannot be converted to " + switchExpressionType.getCanonicalText())
.create());
}
}
}
return infos;
}
private enum SelectorKind { INT, ENUM, STRING }
private static SelectorKind getSwitchSelectorKind(@NotNull PsiType type) {
@@ -1607,6 +1607,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
super.visitSwitchExpression(expression);
if (!myHolder.hasErrorResults()) myHolder.add(checkFeature(expression, Feature.SWITCH_EXPRESSION));
checkSwitchBlock(expression);
if (!myHolder.hasErrorResults()) myHolder.addAll(HighlightUtil.checkSwitchExpressionReturnTypeCompatible(expression));
}
private void checkSwitchBlock(PsiSwitchBlock switchBlock) {
@@ -26,9 +26,15 @@ no instance(s) of type variable(s) exist so that Object conforms to String">foo(
String s4 = foo(() -> switch (i) {default -> { break bar();}});
String s5 = foo(<error descr="Incompatible types. Required String but 'foo' was inferred to T:
no instance(s) of type variable(s) exist so that Integer conforms to String">() -> switch (i) {default -> { break 1;}}</error>);
String s6 = switch (i) {
case 1 -> <error descr="Bad type in switch expression: int cannot be converted to java.lang.String">2</error>;
default -> {
break <error descr="Bad type in switch expression: int cannot be converted to java.lang.String">1</error>;
}
};
Supplier<String> stringSupplier = switch (i) {
default -> {
break () -> <error descr="Bad return type in lambda expression: int cannot be converted to String">1</error>;
break () -> <error descr="Bad return type in lambda expression: int cannot be converted to String">1</error>;
}
};
}