package cz.chovanecm.pascal.truffle.nodes.controlflow;

import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.LoopNode;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.NodeInfo;
import com.oracle.truffle.api.nodes.RepeatingNode;
import com.oracle.truffle.api.profiles.ConditionProfile;
import cz.chovanecm.pascal.truffle.PascalTypesGen;
import cz.chovanecm.pascal.truffle.nodes.ExpressionNode;
import cz.chovanecm.pascal.truffle.nodes.StatementNode;

/**
 * Created by martin on 1/27/17.
 */

/**
 * While node without any optimisation
 * (without Truffle.getRuntime().createLoopNode())
 */
@NodeInfo(shortName = "while")
public class WhileNode extends StatementNode {
    @Child
    private LoopNode loop;

    public WhileNode(ExpressionNode conditionNode, StatementNode loopNode) {

        loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(conditionNode, loopNode));

    }

    @Override
    public void execute(VirtualFrame frame) {
        loop.executeLoop(frame);
    }

    public static class WhileRepeatingNode extends Node implements RepeatingNode {
        private final ConditionProfile whileCondition;
        @Child
        private ExpressionNode conditionNode;
        @Child
        private StatementNode loopNode;

        public WhileRepeatingNode(ExpressionNode conditionNode, StatementNode loopNode) {
            this.conditionNode = conditionNode;
            this.loopNode = loopNode;
            whileCondition = ConditionProfile.createBinaryProfile();
        }

        @Override
        public boolean executeRepeating(VirtualFrame frame) {
            if (whileCondition.profile(PascalTypesGen.asBoolean(conditionNode.execute(frame)))) {
                loopNode.execute(frame);
                return true;
            } else {
                return false;
            }
        }
    }
}

@@ -327,65 +327,8 @@
 de;%0A
-import com.oracle.truffle.api.profiles.ConditionProfile;%0A
 impo
@@ -1119,63 +1119,8 @@
 e %7B%0A
-        private final ConditionProfile whileCondition;%0A
     
@@ -1122,32 +1122,32 @@
 %0A        @Child%0A
+
         private 
@@ -1412,77 +1412,8 @@
 de;%0A
-            whileCondition = ConditionProfile.createBinaryProfile();%0A
     
@@ -1518,31 +1518,8 @@
  if 
-(whileCondition.profile
 (Pas
@@ -1570,17 +1570,16 @@
 frame)))
-)
  %7B%0A     

Remove useless profiler in While