1 30 package org.jruby.runtime; 31 32 import java.io.Serializable ; 33 import java.util.HashMap ; 34 import java.util.Map ; 35 import org.jruby.Ruby; 36 import org.jruby.ast.AttrAssignNode; 37 import org.jruby.ast.CallNode; 38 import org.jruby.ast.Node; 39 import org.jruby.ast.types.IArityNode; 40 import org.jruby.runtime.builtin.IRubyObject; 41 42 45 public final class Arity implements Serializable { 46 private static final long serialVersionUID = 1L; 47 private static final Map arities = new HashMap (); 48 private final int value; 49 50 private Arity(int value) { 51 this.value = value; 52 } 53 54 public static Arity createArity(int value) { 55 Integer integerValue = new Integer (value); 56 Arity result; 57 synchronized (arities) { 58 result = (Arity) arities.get(integerValue); 59 if (result == null) { 60 result = new Arity(value); 61 arities.put(integerValue, result); 62 } 63 } 64 return result; 65 } 66 67 public static Arity fixed(int arity) { 68 assert arity >= 0; 69 return createArity(arity); 70 } 71 72 public static Arity optional() { 73 return createArity(-1); 74 } 75 76 public static Arity required(int minimum) { 77 assert minimum >= 0; 78 return createArity(-(1 + minimum)); 79 } 80 81 public static Arity noArguments() { 82 return createArity(0); 83 } 84 85 public static Arity singleArgument() { 86 return createArity(1); 87 } 88 89 public static Arity twoArguments() { 90 return createArity(2); 91 } 92 93 public static Arity procArityOf(Node node) { 94 if (node instanceof AttrAssignNode && node != null) { 95 node = ((AttrAssignNode) node).getArgsNode(); 96 } 97 if (node == null) { 98 return Arity.optional(); 99 } else if (node instanceof IArityNode) { 100 return ((IArityNode) node).getArity(); 101 } else if (node instanceof CallNode) { 102 return Arity.singleArgument(); 103 } 104 105 throw new Error ("unexpected type " + node.getClass() + " at " + node.getPosition()); 106 } 107 108 public int getValue() { 109 return value; 110 } 111 112 public void checkArity(Ruby runtime, IRubyObject[] args) { 113 if (isFixed()) { 114 if (args.length != required()) { 115 throw runtime.newArgumentError("wrong number of arguments(" + args.length + " for " + required() + ")"); 116 } 117 } else { 118 if (args.length < required()) { 119 throw runtime.newArgumentError("wrong number of arguments(" + args.length + " for " + required() + ")"); 120 } 121 } 122 } 123 124 public boolean isFixed() { 125 return value >= 0; 126 } 127 128 private int required() { 129 if (value < 0) { 130 return -(1 + value); 131 } 132 return value; 133 } 134 135 public boolean equals(Object other) { 136 return this == other; 137 } 138 139 public int hashCode() { 140 return value; 141 } 142 143 public String toString() { 144 if(isFixed()) { 145 return "Fixed" + required(); 146 } else { 147 return "Opt"; 148 } 149 } 150 } 151 | Popular Tags |