ReadPreArgumentNode.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.methods.arguments;

  11. import com.oracle.truffle.api.frame.VirtualFrame;
  12. import com.oracle.truffle.api.source.SourceSection;
  13. import com.oracle.truffle.api.utilities.BranchProfile;
  14. import com.oracle.truffle.api.utilities.ValueProfile;
  15. import org.jruby.truffle.nodes.RubyNode;
  16. import org.jruby.truffle.runtime.RubyArguments;
  17. import org.jruby.truffle.runtime.RubyContext;
  18. import org.jruby.truffle.runtime.UndefinedPlaceholder;

  19. /**
  20.  * Read pre-optional argument.
  21.  */
  22. public class ReadPreArgumentNode extends RubyNode {

  23.     private final int index;

  24.     private final BranchProfile outOfRangeProfile = BranchProfile.create();
  25.     private final MissingArgumentBehaviour missingArgumentBehaviour;

  26.     private final ValueProfile argumentValueProfile = ValueProfile.createPrimitiveProfile();

  27.     public ReadPreArgumentNode(RubyContext context, SourceSection sourceSection, int index, MissingArgumentBehaviour missingArgumentBehaviour) {
  28.         super(context, sourceSection);
  29.         this.index = index;
  30.         this.missingArgumentBehaviour = missingArgumentBehaviour;
  31.     }

  32.     @Override
  33.     public Object execute(VirtualFrame frame) {
  34.         if (index >= RubyArguments.getUserArgumentsCount(frame.getArguments())) {
  35.             outOfRangeProfile.enter();

  36.             switch (missingArgumentBehaviour) {
  37.                 case RUNTIME_ERROR:
  38.                     break;

  39.                 case UNDEFINED:
  40.                     return UndefinedPlaceholder.INSTANCE;

  41.                 case NIL:
  42.                     return getContext().getCoreLibrary().getNilObject();
  43.             }
  44.         }

  45.         return argumentValueProfile.profile(RubyArguments.getUserArgument(frame.getArguments(), index));
  46.     }

  47. }