IfNode.java

  1. /*
  2.  * Copyright (c) 2013, 2014 Oracle and/or its affiliates. All rights reserved. This
  3.  * code is released under a tri EPL/GPL/LGPL license. You can use it,
  4.  * redistribute it and/or modify it under the terms of the:
  5.  *
  6.  * Eclipse Public License version 1.0
  7.  * GNU General Public License version 2
  8.  * GNU Lesser General Public License version 2.1
  9.  */
  10. package org.jruby.truffle.nodes.control;

  11. import com.oracle.truffle.api.frame.VirtualFrame;
  12. import com.oracle.truffle.api.source.SourceSection;
  13. import com.oracle.truffle.api.utilities.ConditionProfile;

  14. import org.jruby.truffle.nodes.RubyNode;
  15. import org.jruby.truffle.nodes.cast.BooleanCastNode;
  16. import org.jruby.truffle.runtime.RubyContext;

  17. /**
  18.  * Represents a Ruby {@code if} expression. Note that in this representation we always have an
  19.  * {@code else} part.
  20.  */
  21. public class IfNode extends RubyNode {

  22.     @Child protected BooleanCastNode condition;
  23.     @Child protected RubyNode thenBody;
  24.     @Child protected RubyNode elseBody;
  25.     private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile();

  26.     public IfNode(RubyContext context, SourceSection sourceSection, BooleanCastNode condition, RubyNode thenBody, RubyNode elseBody) {
  27.         super(context, sourceSection);

  28.         assert condition != null;
  29.         assert thenBody != null;
  30.         assert elseBody != null;

  31.         this.condition = condition;
  32.         this.thenBody = thenBody;
  33.         this.elseBody = elseBody;
  34.     }

  35.     @Override
  36.     public Object execute(VirtualFrame frame) {
  37.         if (conditionProfile.profile(condition.executeBoolean(frame))) {
  38.             return thenBody.execute(frame);
  39.         } else {
  40.             return elseBody.execute(frame);
  41.         }
  42.     }
  43. }