Skip to content

Instantly share code, notes, and snippets.

@MasterDuke17
Created July 14, 2018 03:25
Show Gist options
  • Save MasterDuke17/573d960c76c917c95508be9ec64769a1 to your computer and use it in GitHub Desktop.
Save MasterDuke17/573d960c76c917c95508be9ec64769a1 to your computer and use it in GitHub Desktop.
package org.perl6.nqp.truffle.nodes.control;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.ControlFlowException;
import com.oracle.truffle.api.nodes.NodeInfo;
import com.oracle.truffle.api.nodes.LoopNode;
import com.oracle.truffle.api.nodes.RepeatingNode;
import org.perl6.nqp.truffle.nodes.NQPNode;
import org.perl6.nqp.dsl.Deserializer;
@NodeInfo(shortName = "while")
public final class NQPWhileNode extends NQPNode {
@Child private LoopNode whileNode;
public NQPWhileNode(NQPNode condNode, NQPNode bodyNode) {
whileNode = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(condNode, bodyNode));
}
@Override
public Object execute(VirtualFrame frame) {
whileNode.executeLoop(frame);
return null;
}
@Override
public void executeVoid(VirtualFrame frame) {
whileNode.executeLoop(frame);
}
private static class WhileRepeatingNode extends NQPNode implements RepeatingNode {
@Child private NQPNode condNode;
@Child private NQPNode bodyNode;
public WhileRepeatingNode(NQPNode condNode, NQPNode bodyNode) {
this.condNode = condNode;
this.bodyNode = bodyNode;
}
@Override
public boolean executeRepeating(VirtualFrame frame) {
if ((boolean) condNode.execute(frame)) {
try {
bodyNode.execute(frame);
} catch (ContinueException ex) {
// the body might throw a continue control-flow exception
// continue loop invocation
} catch (BreakException ex) {
// the body might throw a break control-flow exception
// break loop invocation by returning false
return false;
}
return true;
} else {
return false;
}
}
@Override
public void executeVoid(VirtualFrame frame) {}
}
// thrown by guest language continue statements
public final class ContinueException extends ControlFlowException {}
// thrown by guest language break statements
public final class BreakException extends ControlFlowException {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment