diff --git a/src/main/java/spoon/support/reflect/code/CtCaseImpl.java b/src/main/java/spoon/support/reflect/code/CtCaseImpl.java index 164303bb187..85497765f6c 100644 --- a/src/main/java/spoon/support/reflect/code/CtCaseImpl.java +++ b/src/main/java/spoon/support/reflect/code/CtCaseImpl.java @@ -93,6 +93,7 @@ public > T addCaseExpression(CtExpression caseExpression) setCaseExpression(caseExpression); } getFactory().getEnvironment().getModelChangeListener().onObjectUpdate(this, CtRole.CASE, caseExpressions, this.caseExpressions); + caseExpression.setParent(this); this.caseExpressions.add(caseExpression); return (T) this; } diff --git a/src/test/java/spoon/test/model/SwitchCaseTest.java b/src/test/java/spoon/test/model/SwitchCaseTest.java index 4a232ba860e..7d3cac64099 100644 --- a/src/test/java/spoon/test/model/SwitchCaseTest.java +++ b/src/test/java/spoon/test/model/SwitchCaseTest.java @@ -112,6 +112,17 @@ public void testSwitchStatementOnAString() throws Exception { assertEquals(String.class.getName(), aCase.getCaseExpression().getType().getTypeDeclaration().getQualifiedName()); } } + @DisplayName("Parent is set") + @Test + public void testParentInCaseExpressions() { + // contract: for all expressions in a case, the parent is set. + Launcher launcher = new Launcher(); + launcher.getEnvironment().setComplianceLevel(14); + launcher.addInputResource(new VirtualFile("class A { { int x = switch(1) { case 1, 3 -> 0; default -> 1}; } }")); + launcher.buildModel(); + List> caseStatement = launcher.getModel().getElements(new TypeFilter<>(CtLiteral.class)); + assertTrue(caseStatement.stream().allMatch(CtLiteral::isParentInitialized)); + } }