@@ -840,23 +840,32 @@ private static ImStatementExpr inReturn(ImReturn parent, ImTupleExpr tupleExpr,
840840 "Cannot return tuple with " + flatExprs .size () + " element(s) from function expecting " + returnVars .size () + " element(s)" );
841841 }
842842
843- // 2) Assign per component, converting nulls to proper defaults of LHS type
843+ // 2) Capture every component before publishing any shared return slot. A later
844+ // component can call this function (or a sibling in its dispatch group) and write
845+ // the same slots, so assigning slots while components are still being evaluated
846+ // would corrupt the outer result.
847+ List <ImVar > staged = new ArrayList <>(returnVars .size ());
844848 for (int i = 0 ; i < returnVars .size (); i ++) {
845849 ImVar rv = returnVars .get (i );
846850 ImExpr rhs = flatExprs .get (i );
847851 rhs .setParent (null );
848852
849853 if (rhs instanceof ImNull ) {
850- // Use the *component target type* to build the correct default (0 for ints,
851- // (0,0) for tuple components if those ever occur, etc)
852- ImExpr defaultRhs = ImHelper .defaultValueForComplexType (rv .getType ());
853- stmts .add (JassIm .ImSet (parent .getTrace (), JassIm .ImVarAccess (rv ), defaultRhs ));
854- } else {
855- stmts .add (JassIm .ImSet (parent .getTrace (), JassIm .ImVarAccess (rv ), rhs ));
854+ rhs = ImHelper .defaultValueForComplexType (rv .getType ());
856855 }
856+ ImVar temp = JassIm .ImVar (rhs .attrTrace (), rv .getType (), "tuple_return" , false );
857+ f .getLocals ().add (temp );
858+ stmts .add (JassIm .ImSet (parent .getTrace (), JassIm .ImVarAccess (temp ), rhs ));
859+ staged .add (temp );
860+ }
861+
862+ // 3) Publish the complete value only after all potentially re-entrant evaluation.
863+ for (int i = 0 ; i < returnVars .size (); i ++) {
864+ stmts .add (JassIm .ImSet (parent .getTrace (), JassIm .ImVarAccess (returnVars .get (i )),
865+ JassIm .ImVarAccess (staged .get (i ))));
857866 }
858867
859- // 3 ) Return the first component temp
868+ // 4 ) Return the first component slot
860869 stmts .add (JassIm .ImReturn (parent .getTrace (), JassIm .ImVarAccess (returnVars .get (0 ))));
861870 return ImHelper .statementExprVoid (stmts );
862871 }
0 commit comments