CheckArityInstr.java

  1. package org.jruby.ir.instructions;

  2. import org.jruby.ir.IRVisitor;
  3. import org.jruby.ir.Operation;
  4. import org.jruby.ir.operands.Fixnum;
  5. import org.jruby.ir.operands.Operand;
  6. import org.jruby.ir.runtime.IRRuntimeHelpers;
  7. import org.jruby.ir.transformations.inlining.CloneInfo;
  8. import org.jruby.ir.transformations.inlining.InlineCloneInfo;
  9. import org.jruby.ir.transformations.inlining.SimpleCloneInfo;
  10. import org.jruby.runtime.ThreadContext;

  11. public class CheckArityInstr extends Instr implements FixedArityInstr {
  12.     public final int required;
  13.     public final int opt;
  14.     public final int rest;
  15.     public final boolean receivesKeywords;
  16.     public final int restKey;

  17.     public CheckArityInstr(int required, int opt, int rest, boolean receivesKeywords, int restKey) {
  18.         super(Operation.CHECK_ARITY);

  19.         this.required = required;
  20.         this.opt = opt;
  21.         this.rest = rest;
  22.         this.receivesKeywords = receivesKeywords;
  23.         this.restKey = restKey;
  24.     }

  25.     @Override
  26.     public Operand[] getOperands() {
  27.         return new Operand[] { new Fixnum(required), new Fixnum(opt), new Fixnum(rest) };
  28.     }

  29.     @Override
  30.     public String toString() {
  31.         return super.toString() + " req: " + required + ", opt: " + opt + ", *r: " + rest + ", kw: " + receivesKeywords + ", **r: " + restKey;
  32.     }

  33.     @Override
  34.     public Instr clone(CloneInfo info) {
  35.         if (info instanceof SimpleCloneInfo) return new CheckArityInstr(required, opt, rest, receivesKeywords, restKey);

  36.         InlineCloneInfo ii = (InlineCloneInfo) info;
  37.         if (ii.canMapArgsStatically()) { // we can error on bad arity or remove check_arity
  38.             int numArgs = ii.getArgsCount();

  39.             if (numArgs < required || (rest == -1 && numArgs > (required + opt))) {
  40.                 return new RaiseArgumentErrorInstr(required, opt, rest, rest);
  41.             }

  42.             return null;
  43.         }

  44.         return new CheckArgsArrayArityInstr(ii.getArgs(), required, opt, rest);
  45.     }

  46.     public void checkArity(ThreadContext context, Object[] args) {
  47.         IRRuntimeHelpers.checkArity(context, args, required, opt, rest, receivesKeywords, restKey);
  48.     }

  49.     @Override
  50.     public void visit(IRVisitor visitor) {
  51.         visitor.CheckArityInstr(this);
  52.     }
  53. }