Child nodes in arrays

Often, it is necessary for a dynamic number of children to be present in a node (e.g. a block of code with multiple operations, or an array initializer in the guest language). This can be done with arrays, for which the code is fairly straightforward:

package com.wordpress.hextruffle.tests;

import com.oracle.truffle.api.CallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.TruffleRuntime;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.RootNode;

public class ChildrenNodesDemo {

	static class StringConcatenatorTestRootNode extends RootNode {

		@Children
		private final TestChildNode[] children;

		public StringConcatenatorTestRootNode(TestChildNode[] children) {
			super(null);
			this.children = children;
		}

		@Override
		public Object execute(VirtualFrame frame) {
			String sum = "";
			for (TestChildNode child : children) {
				sum += child.execute();
			}
			return sum;
		}
	}

	static class TestChildNode extends Node {
		private final String s;

		public TestChildNode(String s) {
			super(null);
			this.s = s;
		}

		public String execute() {
			return s;
		}
	}

	public static void main(String[] args) {
		TruffleRuntime runtime = Truffle.getRuntime();
	        TestChildNode firstChild = new TestChildNode("Hello");
	        TestChildNode secondChild = new TestChildNode(", ");
	        TestChildNode thirdChild = new TestChildNode("world");
	        TestChildNode forthChild = new TestChildNode("!");
	        StringConcatenatorTestRootNode root = new StringConcatenatorTestRootNode(new TestChildNode[]{firstChild,secondChild,thirdChild,forthChild});
	        CallTarget target = runtime.createCallTarget(root);
	        System.out.println(target.call());
	}
}

The important points to note here is that the array itself is final. Any changes to the array need to occur by changing the contents, and not by reassignment. The @Children annotation is also required for Truffle to properly handle the array, especially later on where nodes might be changing during runtime.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s