AndNode.java

  1. /*
  2.  * Copyright (c) 2013, 2015 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.nodes.cast.BooleanCastNodeFactory;
  17. import org.jruby.truffle.runtime.RubyContext;

  18. /**
  19.  * Represents a Ruby {@code and} or {@code &&} expression.
  20.  */
  21. public class AndNode extends RubyNode {

  22.     @Child protected RubyNode left;
  23.     @Child protected BooleanCastNode leftCast;
  24.     @Child protected RubyNode right;
  25.     private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile();

  26.     public AndNode(RubyContext context, SourceSection sourceSection, RubyNode left, RubyNode right) {
  27.         super(context, sourceSection);
  28.         this.left = left;
  29.         leftCast = BooleanCastNodeFactory.create(context, sourceSection, null);
  30.         this.right = right;
  31.     }

  32.     @Override
  33.     public Object execute(VirtualFrame frame) {
  34.         final Object leftValue = left.execute(frame);
  35.         if (conditionProfile.profile(leftCast.executeBoolean(frame, leftValue))) {
  36.             // Right expression evaluated and returned if left expression returns true.
  37.             return right.execute(frame);
  38.         } else {
  39.             return leftValue;
  40.         }
  41.     }
  42. }