55import java .util .ArrayList ;
66import java .util .Arrays ;
77import java .util .Deque ;
8+ import java .util .HashSet ;
89import java .util .LinkedHashSet ;
910import java .util .List ;
1011import java .util .Optional ;
2930import liquidjava .utils .constants .Types ;
3031
3132import org .apache .commons .lang3 .NotImplementedException ;
33+ import spoon .reflect .code .CaseKind ;
3234import spoon .reflect .code .CtArrayRead ;
3335import spoon .reflect .code .CtAbstractInvocation ;
36+ import spoon .reflect .code .CtAbstractSwitch ;
3437import spoon .reflect .code .CtArrayWrite ;
3538import spoon .reflect .code .CtAssignment ;
3639import spoon .reflect .code .CtBinaryOperator ;
3740import spoon .reflect .code .CtBlock ;
3841import spoon .reflect .code .CtBreak ;
42+ import spoon .reflect .code .CtCFlowBreak ;
43+ import spoon .reflect .code .CtCase ;
3944import spoon .reflect .code .CtCatchVariable ;
4045import spoon .reflect .code .CtConditional ;
4146import spoon .reflect .code .CtContinue ;
5762import spoon .reflect .code .CtNewArray ;
5863import spoon .reflect .code .CtNewClass ;
5964import spoon .reflect .code .CtOperatorAssignment ;
65+ import spoon .reflect .code .CtPattern ;
6066import spoon .reflect .code .CtReturn ;
6167import spoon .reflect .code .CtStatement ;
6268import spoon .reflect .code .CtSuperAccess ;
7177import spoon .reflect .code .CtVariableRead ;
7278import spoon .reflect .code .CtVariableWrite ;
7379import spoon .reflect .code .CtWhile ;
80+ import spoon .reflect .code .CtYieldStatement ;
7481import spoon .reflect .declaration .*;
7582import spoon .reflect .factory .Factory ;
7683import spoon .reflect .reference .CtFieldReference ;
@@ -575,6 +582,189 @@ public void visitCtIf(CtIf ifElement) {
575582 context .variablesFinishIfCombination ();
576583 }
577584
585+ @ Override
586+ public <S > void visitCtSwitch (CtSwitch <S > switchStatement ) {
587+ if (!visitSwitch (switchStatement ))
588+ super .visitCtSwitch (switchStatement );
589+ }
590+
591+ @ Override
592+ public <T , S > void visitCtSwitchExpression (CtSwitchExpression <T , S > switchExpression ) {
593+ if (!visitSwitch (switchExpression ))
594+ super .visitCtSwitchExpression (switchExpression );
595+ }
596+
597+ /**
598+ * Checks a switch as the chain of ifs that tests its labels in turn (see visitCtIf): each case is checked from the
599+ * state before the switch, knowing that the selector equals one of its labels, and the default case knowing that it
600+ * equals none of the others. A case that falls through goes on into the next one. The states of the cases that
601+ * reach the end of the switch are joined after it. Pattern and guarded cases are not modelled.
602+ *
603+ * @return whether the switch was checked, false when it has pattern or guarded cases
604+ */
605+ private boolean visitSwitch (CtAbstractSwitch <?> switchElement ) {
606+ List <CtCase <?>> cases = new ArrayList <>(switchElement .getCases ());
607+ if (cases .stream ().anyMatch (c -> c .getGuard () != null
608+ || c .getCaseExpressions ().stream ().anyMatch (label -> label instanceof CtPattern )))
609+ return false ;
610+ CtExpression <?> selector = switchElement .getSelector ();
611+ scan (selector );
612+ // the selector is evaluated once, so the cases compare its value then, not what its variables hold later
613+ String selectorName = GeneratedNames .of (GeneratedNames .SWITCH_SELECTOR , context .getCounter ());
614+ Predicate selectorRefs = getRefinement (selector ).substituteVariable (Keys .WILDCARD , selectorName );
615+ selectorRefs = snapshotMutableParameters (substituteAllVariablesForLastInstance (selectorRefs ), selector );
616+ context .addInstanceToContext (selectorName , selector .getType (), selectorRefs , selector );
617+
618+ // the cases with no statements share the statements of the next case, the default one is tested last
619+ List <CaseEntry > entries = new ArrayList <>();
620+ CaseEntry defaultEntry = null ;
621+ List <Predicate > labels = new ArrayList <>();
622+ boolean isDefault = false ;
623+ int start = 0 ;
624+ for (int i = 0 ; i < cases .size (); i ++) {
625+ CtCase <?> c = cases .get (i );
626+ for (CtExpression <?> label : c .getCaseExpressions ()) {
627+ scan (label );
628+ labels .add (getRefinement (label ));
629+ }
630+ isDefault |= c .getCaseExpressions ().isEmpty () || c .getIncludesDefault ();
631+ if (c .getStatements ().isEmpty () && i < cases .size () - 1 )
632+ continue ;
633+ CaseEntry entry = new CaseEntry (start , labels );
634+ if (isDefault )
635+ defaultEntry = entry ;
636+ else
637+ entries .add (entry );
638+ labels = new ArrayList <>();
639+ isDefault = false ;
640+ start = i + 1 ;
641+ }
642+ if (defaultEntry != null )
643+ entries .add (defaultEntry );
644+ visitCases (switchElement , cases , entries , 0 , selectorName , defaultEntry != null , new HashSet <>());
645+ return true ;
646+ }
647+
648+ /** A case to which the selector jumps when it equals one of {@code labels}, by their refinements */
649+ private record CaseEntry (int start , List <Predicate > labels ) {
650+ /** That the selector equals one of the labels, or null when a label has no known value */
651+ Predicate matches (String selectorName ) {
652+ Predicate matches = null ;
653+ for (Predicate label : labels ) {
654+ if (!label .getVariableNames ().contains (Keys .WILDCARD ))
655+ return null ;
656+ Predicate equals = label .substituteVariable (Keys .WILDCARD , selectorName );
657+ matches = matches == null ? equals : Predicate .createDisjunction (matches , equals );
658+ }
659+ return matches ;
660+ }
661+ }
662+
663+ /**
664+ * Checks the entries of a switch from {@code index} on, as an if that tests the one at {@code index} and checks the
665+ * others in its else, the last one being the default case if there is one
666+ *
667+ * @return whether the end of the switch can be reached from here
668+ */
669+ private boolean visitCases (CtAbstractSwitch <?> switchElement , List <CtCase <?>> cases , List <CaseEntry > entries ,
670+ int index , String selectorName , boolean hasDefault , Set <CtCase <?>> checked ) {
671+ if (index == entries .size ())
672+ return true ; // no label matches and there is no default case
673+ CaseEntry entry = entries .get (index );
674+ if (hasDefault && index == entries .size () - 1 )
675+ return visitCasesFrom (switchElement , cases , entry .start (), checked );
676+
677+ String pathVarName = GeneratedNames .of (GeneratedNames .CASE_CONDITION , context .getCounter ());
678+ // a label with no known value gives no information about which way the test went
679+ Predicate matches = entry .matches (selectorName );
680+ Predicate branchGuard = matches != null ? matches : Predicate .createVar (pathVarName );
681+ RefinedVariable pathVar = context .addInstanceToContext (pathVarName , factory .Type ().BOOLEAN_PRIMITIVE ,
682+ branchGuard , cases .get (entry .start ()));
683+ keepFreshValues (branchGuard );
684+ vcChecker .addPathVariable (pathVar );
685+
686+ context .variablesNewIfCombination ();
687+ context .variablesSetBeforeIf ();
688+ context .enterContext ();
689+
690+ context .enterContext ();
691+ boolean thenReaches = visitCasesFrom (switchElement , cases , entry .start (), checked );
692+ if (thenReaches )
693+ context .variablesSetThenIf ();
694+ context .exitContext ();
695+
696+ context .newRefinementToVariableInContext (pathVarName , branchGuard .negate ());
697+ context .enterContext ();
698+ boolean elseReaches = visitCases (switchElement , cases , entries , index + 1 , selectorName , hasDefault , checked );
699+ if (elseReaches )
700+ context .variablesSetElseIf ();
701+ context .exitContext ();
702+
703+ if (thenReaches == elseReaches ) {
704+ context .newRefinementToVariableInContext (pathVarName , matches != null ? matches : new Predicate ());
705+ vcChecker .removePathVariable (pathVar );
706+ } else {
707+ // keep the guard of the only branch that reaches the end of the switch
708+ context .newRefinementToVariableInContext (pathVarName , thenReaches ? branchGuard : branchGuard .negate ());
709+ }
710+ context .exitContext ();
711+ context .variablesCombineFromIf (branchGuard );
712+ context .variablesFinishIfCombination ();
713+ return thenReaches || elseReaches ;
714+ }
715+
716+ /**
717+ * Checks the statements of the case at {@code start}, and of the next cases while they fall through. The path
718+ * conditions they add are dropped after them.
719+ *
720+ * @return whether they reach the end of the switch
721+ */
722+ private boolean visitCasesFrom (CtAbstractSwitch <?> switchElement , List <CtCase <?>> cases , int start ,
723+ Set <CtCase <?>> checked ) {
724+ List <RefinedVariable > pathVariables = vcChecker .getPathVariables ();
725+ List <CtCFlowBreak > exits = new ArrayList <>();
726+ int end = start ;
727+ boolean completes ;
728+ while (true ) {
729+ CtCase <?> c = cases .get (end );
730+ if (!checked .add (c ))
731+ removeCheckMetadata (c , List .of ()); // checked again after falling through from another case
732+ for (CtStatement statement : c .getStatements ())
733+ scan (statement );
734+ exits .addAll (c .getElements (new TypeFilter <>(CtCFlowBreak .class )).stream ()
735+ .filter (jump -> leaves (jump , switchElement )).toList ());
736+ List <CtStatement > statements = c .getStatements ();
737+ completes = statements .isEmpty () || canCompleteNormally (statements .get (statements .size () - 1 ));
738+ if (!completes || c .getCaseKind () == CaseKind .ARROW || end == cases .size () - 1 )
739+ break ;
740+ end ++;
741+ }
742+ List <CtStatement > last = cases .get (end ).getStatements ();
743+ CtStatement lastExit = last .isEmpty () ? null : endingJump (last .get (last .size () - 1 ));
744+ // the states where a break or yield inside a statement leaves the switch are not followed: forget what these
745+ // cases change
746+ if (exits .stream ().anyMatch (jump -> jump != lastExit ))
747+ for (CtCase <?> c : cases .subList (start , end + 1 ))
748+ for (String name : changedIn (c , switchElement ))
749+ forgetChanges (name , new Predicate (), c );
750+ vcChecker .restorePathVariables (pathVariables );
751+ return completes || !exits .isEmpty ();
752+ }
753+
754+ /** Whether {@code jump} is a break or yield that leaves {@code switchElement} */
755+ private static boolean leaves (CtCFlowBreak jump , CtAbstractSwitch <?> switchElement ) {
756+ if (jump instanceof CtBreak breakStatement )
757+ return jumpTarget (breakStatement ) == switchElement ;
758+ return jump instanceof CtYieldStatement && jump .getParent (CtSwitchExpression .class ) == switchElement ;
759+ }
760+
761+ /** The jump that a statement ends with, as the last statement of its blocks */
762+ private static CtStatement endingJump (CtStatement statement ) {
763+ if (statement instanceof CtBlock <?> block )
764+ return block .getStatements ().isEmpty () ? null : endingJump (block .getLastStatement ());
765+ return statement instanceof CtCFlowBreak ? statement : null ;
766+ }
767+
578768 private Predicate snapshotMutableParameters (Predicate predicate , CtExpression <?> condition ) {
579769 // An unchanged parameter can keep its name; a later write must not change this guard's meaning.
580770 CtExecutable <?> executable = condition .getParent (CtExecutable .class );
@@ -651,7 +841,7 @@ boolean canCompleteNormally(CtStatement statement) {
651841 if (statement == null || isLeftByLabelledBreak (statement ))
652842 return true ;
653843 if (statement instanceof CtReturn <?> || statement instanceof CtThrow || statement instanceof CtBreak
654- || statement instanceof CtContinue )
844+ || statement instanceof CtContinue || statement instanceof CtYieldStatement )
655845 return false ;
656846 if (statement instanceof CtBlock <?> block ) {
657847 List <CtStatement > statements = block .getStatements ();
@@ -804,7 +994,11 @@ private static void removeCheckMetadata(CtLoop loop) {
804994 checkedBefore .addAll (forLoop .getForInit ());
805995 if (loop instanceof CtForEach forEach )
806996 checkedBefore .add (forEach .getExpression ());
807- for (CtElement element : loop .getElements ((CtElement e ) -> true )) {
997+ removeCheckMetadata (loop , checkedBefore );
998+ }
999+
1000+ private static void removeCheckMetadata (CtElement checked , List <CtElement > checkedBefore ) {
1001+ for (CtElement element : checked .getElements ((CtElement e ) -> true )) {
8081002 if (element instanceof CtTypeMember
8091003 || (element instanceof CtParameter <?> && element .getParent () instanceof CtTypeMember )
8101004 || checkedBefore .stream ().anyMatch (before -> element == before || element .hasParent (before )))
@@ -906,9 +1100,14 @@ void forgetChanges(String name, Predicate known, CtElement element) {
9061100 * if it calls any method or constructor (which may write them)
9071101 */
9081102 private Set <String > changedIn (CtLoop loop ) {
1103+ return changedIn (loop , loop .getBody ());
1104+ }
1105+
1106+ /** What {@code element} may change, but the variables declared in {@code scope}, which do not outlive it */
1107+ private Set <String > changedIn (CtElement element , CtElement scope ) {
9091108 List <CtVariableAccess <?>> changed = new ArrayList <>(
910- loop .getElements (new TypeFilter <CtVariableWrite <?>>(CtVariableWrite .class )));
911- List <CtAbstractInvocation <?>> calls = loop
1109+ element .getElements (new TypeFilter <CtVariableWrite <?>>(CtVariableWrite .class )));
1110+ List <CtAbstractInvocation <?>> calls = element
9121111 .getElements (new TypeFilter <CtAbstractInvocation <?>>(CtAbstractInvocation .class ));
9131112 Set <String > names = new LinkedHashSet <>();
9141113 for (CtAbstractInvocation <?> call : calls ) {
@@ -921,8 +1120,8 @@ else if (inv.getTarget() != null && AuxStateHandler.isCurrentReceiver(inv.getTar
9211120 }
9221121 for (CtVariableAccess <?> access : changed ) {
9231122 CtVariable <?> declaration = access .getVariable ().getDeclaration ();
924- if (declaration != null && declaration .hasParent (loop . getBody () ))
925- continue ; // declared in the body: a new variable on each iteration
1123+ if (declaration != null && declaration .hasParent (scope ))
1124+ continue ; // e.g. declared in a loop body: a new variable on each iteration
9261125 String name = access .getVariable ().getSimpleName ();
9271126 names .add (access instanceof CtFieldAccess <?> ? String .format (Formats .THIS , name ) : name );
9281127 }
0 commit comments