Allow single expressions in switch expression

This commit is contained in:
Daniel Holle 2023-08-17 13:26:30 +02:00
parent e69a367c33
commit 677c784b6d
4 changed files with 15 additions and 12 deletions

View File

@ -7,11 +7,11 @@ record Rec(Integer a, Object b) {}
public class Switch {
main(o) {
return switch (o) {
case Rec(Integer a, Integer b) -> { yield a + b; }
case Rec(Integer a, Float b) -> { yield a + 10; }
case Rec(Integer a, Rec(Integer b, Integer c)) -> { yield a + b + c; }
case Integer i -> { yield i; }
default -> { yield 0; }
case Rec(Integer a, Integer b) -> a + b;
case Rec(Integer a, Float b) -> a + 10;
case Rec(Integer a, Rec(Integer b, Integer c)) -> a + b + c;
case Integer i -> i;
default -> 0;
};
}
}

View File

@ -725,7 +725,7 @@ guardedPattern
// Java17
switchRuleOutcome
: block
| blockStatement*
| expression ';'
;
classType

View File

@ -408,12 +408,9 @@ public class StatementGenerator {
Block block;
if (Objects.isNull(outcome.block())) {
List<Statement> stmts = new ArrayList<>();
if (outcome.blockStatement().size() == 1) isSingleExpression = true;
outcome.blockStatement().stream().forEach((stmt) -> {
stmts.addAll(convert(stmt));
});
block = new Block(stmts, outcome.blockStatement(0).getStart());
stmts.add(new Yield(convert(outcome.expression()), outcome.expression().start));
isSingleExpression = true;
block = new Block(stmts, outcome.expression().getStart());
} else {
block = convert(outcome.block(), false);
}

View File

@ -1,4 +1,10 @@
package de.dhbwstuttgart.target.tree.expression;
import de.dhbwstuttgart.target.tree.type.TargetType;
public record TargetYield(TargetExpression expression) implements TargetExpression {
@Override
public TargetType type() {
return expression.type();
}
}