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 { public class Switch {
main(o) { main(o) {
return switch (o) { return switch (o) {
case Rec(Integer a, Integer b) -> { yield a + b; } case Rec(Integer a, Integer b) -> a + b;
case Rec(Integer a, Float b) -> { yield a + 10; } case Rec(Integer a, Float b) -> a + 10;
case Rec(Integer a, Rec(Integer b, Integer c)) -> { yield a + b + c; } case Rec(Integer a, Rec(Integer b, Integer c)) -> a + b + c;
case Integer i -> { yield i; } case Integer i -> i;
default -> { yield 0; } default -> 0;
}; };
} }
} }

View File

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

View File

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

View File

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