package org.mozartoz.truffle.nodes.control;

import org.mozartoz.truffle.nodes.OzNode;
import org.mozartoz.truffle.nodes.call.CallNode;
import org.mozartoz.truffle.nodes.call.CallableNode;
import org.mozartoz.truffle.runtime.OzProc;

import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.LoopNode;
import com.oracle.truffle.api.profiles.LoopConditionProfile;

public class ForNode extends OzNode {

	@Child OzNode fromNode;
	@Child OzNode toNode;
	@Child OzNode procNode;

	@Child CallableNode callNode = CallNode.create(null, null);
	private final LoopConditionProfile loopProfile = LoopConditionProfile.createCountingProfile();

	public ForNode(OzNode fromNode, OzNode toNode, OzNode procNode) {
		this.fromNode = fromNode;
		this.toNode = toNode;
		this.procNode = procNode;
	}

	@Override
	public Object execute(VirtualFrame frame) {
		long from = (long) fromNode.execute(frame);
		long to = (long) toNode.execute(frame);

		int count = 0;
		if (CompilerDirectives.inInterpreter()) {
			count = (int) Math.min(to - from + 1, Integer.MAX_VALUE);
		}

		try {
			loopProfile.profileCounted(count);
			for (long i = from; loopProfile.inject(i <= to); i++) {
				OzProc proc = (OzProc) procNode.execute(frame);
				callNode.executeCall(frame, proc, new Object[] { i });
			}
		} finally {
			LoopNode.reportLoopCount(this, count);
		}

		return unit;
	}

}

@@ -38,16 +38,61 @@
 ntrol;%0A%0A
+import org.mozartoz.truffle.nodes.DerefNode;%0A
 import o
@@ -121,24 +121,24 @@
 des.OzNode;%0A
-
 import org.m
@@ -593,16 +593,123 @@
 cNode;%0A%0A
+%09@Child DerefNode fromDerefNode = DerefNode.create();%0A%09@Child DerefNode toDerefNode = DerefNode.create();%0A%0A
 %09@Child 
@@ -1086,16 +1086,43 @@
  (long) 
+fromDerefNode.executeDeref(
 fromNode
@@ -1132,24 +1132,25 @@
 ecute(frame)
+)
 ;%0A%09%09long to 
@@ -1158,16 +1158,41 @@
  (long) 
+toDerefNode.executeDeref(
 toNode.e
@@ -1204,16 +1204,17 @@
 e(frame)
+)
 ;%0A%0A%09%09int

Add dereference on bounds of For nodes