diff --git a/core/src/main/java/org/jruby/FiberScheduler.java b/core/src/main/java/org/jruby/FiberScheduler.java
index d2221193e84..1ae717c0b98 100644
--- a/core/src/main/java/org/jruby/FiberScheduler.java
+++ b/core/src/main/java/org/jruby/FiberScheduler.java
@@ -9,6 +9,7 @@
import java.nio.ByteBuffer;
import static org.jruby.api.Convert.asFixnum;
+import static org.jruby.api.Error.argumentError;
public class FiberScheduler {
// MRI: rb_fiber_scheduler_kernel_sleep
@@ -100,7 +101,7 @@ public static IRubyObject ioPWrite(ThreadContext context, IRubyObject scheduler,
// MRI: rb_fiber_scheduler_io_read_memory
public static IRubyObject ioReadMemory(ThreadContext context, IRubyObject scheduler, IRubyObject io, ByteBuffer base, int size, int length) {
- RubyIOBuffer buffer = RubyIOBuffer.newBuffer(context.runtime, base, size, RubyIOBuffer.LOCKED);
+ RubyIOBuffer buffer = RubyIOBuffer.newBuffer(context, base, size, RubyIOBuffer.LOCKED);
IRubyObject result = ioRead(context, scheduler, io, buffer, length, 0);
@@ -112,7 +113,7 @@ public static IRubyObject ioReadMemory(ThreadContext context, IRubyObject schedu
// MRI: rb_fiber_scheduler_io_pread_memory
public static IRubyObject ioPReadMemory(ThreadContext context, IRubyObject scheduler, IRubyObject io, ByteBuffer base, int from, int size, int length) {
- RubyIOBuffer buffer = RubyIOBuffer.newBuffer(context.runtime, base, size, RubyIOBuffer.LOCKED);
+ RubyIOBuffer buffer = RubyIOBuffer.newBuffer(context, base, size, RubyIOBuffer.LOCKED);
IRubyObject result = ioPRead(context, scheduler, io, buffer, from, length, 0);
@@ -124,7 +125,7 @@ public static IRubyObject ioPReadMemory(ThreadContext context, IRubyObject sched
// MRI: rb_fiber_scheduler_io_write_memory
public static IRubyObject ioWriteMemory(ThreadContext context, IRubyObject scheduler, IRubyObject io, ByteBuffer base, int size, int length) {
- RubyIOBuffer buffer = RubyIOBuffer.newBuffer(context.runtime, base, size, RubyIOBuffer.LOCKED | RubyIOBuffer.READONLY);
+ RubyIOBuffer buffer = RubyIOBuffer.newBuffer(context, base, size, RubyIOBuffer.LOCKED | RubyIOBuffer.READONLY);
IRubyObject result = ioWrite(context, scheduler, io, buffer, length, 0);
@@ -136,7 +137,7 @@ public static IRubyObject ioWriteMemory(ThreadContext context, IRubyObject sched
// MRI: p
public static IRubyObject ioPWriteMemory(ThreadContext context, IRubyObject scheduler, IRubyObject io, ByteBuffer base, int from, int size, int length) {
- RubyIOBuffer buffer = RubyIOBuffer.newBuffer(context.runtime, base, size, RubyIOBuffer.LOCKED | RubyIOBuffer.READONLY);
+ RubyIOBuffer buffer = RubyIOBuffer.newBuffer(context, base, size, RubyIOBuffer.LOCKED | RubyIOBuffer.READONLY);
IRubyObject result = ioPWrite(context, scheduler, io, buffer, from, length, 0);
@@ -157,21 +158,21 @@ public static IRubyObject addressResolve(ThreadContext context, IRubyObject sche
}
// MRI: verify_scheduler
- static void verifyInterface(IRubyObject scheduler) {
+ static void verifyInterface(ThreadContext context, IRubyObject scheduler) {
if (!scheduler.respondsTo("block")) {
- throw scheduler.getRuntime().newArgumentError("Scheduler must implement #block");
+ throw argumentError(context, "Scheduler must implement #block");
}
if (!scheduler.respondsTo("unblock")) {
- throw scheduler.getRuntime().newArgumentError("Scheduler must implement #unblock");
+ throw argumentError(context, "Scheduler must implement #unblock");
}
if (!scheduler.respondsTo("kernel_sleep")) {
- throw scheduler.getRuntime().newArgumentError("Scheduler must implement #kernel_sleep");
+ throw argumentError(context, "Scheduler must implement #kernel_sleep");
}
if (!scheduler.respondsTo("io_wait")) {
- throw scheduler.getRuntime().newArgumentError("Scheduler must implement #io_wait");
+ throw argumentError(context, "Scheduler must implement #io_wait");
}
}
diff --git a/core/src/main/java/org/jruby/RubyArithmeticSequence.java b/core/src/main/java/org/jruby/RubyArithmeticSequence.java
index 3f1cfc38f77..89e999a1225 100644
--- a/core/src/main/java/org/jruby/RubyArithmeticSequence.java
+++ b/core/src/main/java/org/jruby/RubyArithmeticSequence.java
@@ -53,6 +53,8 @@
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Convert.numericToLong;
+import static org.jruby.api.Create.newFixnum;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.runtime.Helpers.hashEnd;
import static org.jruby.runtime.Helpers.hashStart;
import static org.jruby.runtime.Helpers.murmurCombine;
@@ -186,42 +188,28 @@ public IRubyObject first(ThreadContext context, IRubyObject num) {
Ruby runtime = context.runtime;
IRubyObject b = begin, e = end, s = step;
RubyArray ary;
- long n;
- boolean x;
if (num == null) {
- if (b.isNil()) {
- return context.nil;
- }
+ if (b.isNil()) return context.nil;
if (!e.isNil()) {
IRubyObject zero = int2fix(runtime, 0);
CallSite op_cmp = sites(context).op_cmp;
CallSite op_gt = sites(context).op_gt;
CallSite op_lt = sites(context).op_lt;
int r = RubyComparable.cmpint(context, ((RubyNumeric)step).coerceCmp(context, op_cmp, zero), s, zero);
- if (r > 0 && RubyNumeric.numFuncall(context, b, op_gt, e).isTrue()) {
- return context.nil;
- }
-
- if (r < 0 && RubyNumeric.numFuncall(context, b, op_lt, e).isTrue()) {
- return context.nil;
- }
+ if (r > 0 && RubyNumeric.numFuncall(context, b, op_gt, e).isTrue()) return context.nil;
+ if (r < 0 && RubyNumeric.numFuncall(context, b, op_lt, e).isTrue()) return context.nil;
}
return b;
}
/* TODO: the following code should be extracted as arith_seq_take */
- n = numericToLong(context, num);
+ long n = numericToLong(context, num);
- if (n < 0) {
- throw runtime.newArgumentError("attempt to take negative size");
- }
+ if (n < 0) throw argumentError(context, "attempt to take negative size");
+ if (n == 0) return runtime.newEmptyArray();
- if (n == 0) {
- return runtime.newEmptyArray();
- }
-
- x = excludeEnd.isTrue();
+ boolean x = excludeEnd.isTrue();
if (b instanceof RubyFixnum && e.isNil() && s instanceof RubyFixnum) {
long i = fix2long(b);
@@ -255,7 +243,7 @@ public IRubyObject first(ThreadContext context, IRubyObject num) {
if (len < 0) len = 0;
ary = RubyArray.newArray(runtime, (n < len) ? n : len);
while (n > 0 && i < end) {
- ary.append(RubyFixnum.newFixnum(runtime, i));
+ ary.append(newFixnum(context, i));
if (i + unit < i) break;
i += unit;
--n;
@@ -465,32 +453,21 @@ public IRubyObject last(ThreadContext context) {
@JRubyMethod
public IRubyObject last(ThreadContext context, IRubyObject num) {
Ruby runtime = context.runtime;
- IRubyObject b = begin, e = end, s = step, len_1, len, last, nv;
+ IRubyObject b = begin, e = end, s = step, len_1, len;
RubyArray ary;
boolean last_is_adjusted;
- long n;
- if (e.isNil()) {
- throw runtime.newRangeError("cannot get the last element of endless arithmetic sequence");
- }
+ if (e.isNil()) throw runtime.newRangeError("cannot get the last element of endless arithmetic sequence");
len_1 = ((RubyNumeric)((RubyNumeric)e).op_minus(context, b)).idiv(context, s);
- if (Numeric.f_negative_p(context, len_1)) {
- if (num == null) {
- return context.nil;
- }
-
- return runtime.newEmptyArray();
- }
+ if (Numeric.f_negative_p(context, len_1)) return num == null ? context.nil : runtime.newEmptyArray();
- last = ((RubyNumeric)b).op_plus(context, Numeric.f_mul(context, s, len_1));
+ IRubyObject last = ((RubyNumeric)b).op_plus(context, Numeric.f_mul(context, s, len_1));
if ((last_is_adjusted = excludeEnd.isTrue()) && Helpers.rbEqual(context, last, e).isTrue()) {
last = ((RubyNumeric)last).op_minus(context, s);
}
- if (num == null) {
- return last;
- }
+ if (num == null) return last;
if (last_is_adjusted) {
len = len_1;
@@ -498,20 +475,16 @@ public IRubyObject last(ThreadContext context, IRubyObject num) {
len = ((RubyNumeric)len_1).op_plus(context, int2fix(runtime, 1));
}
- nv = num;
- if (!(nv instanceof RubyInteger)) {
- nv = num.convertToInteger();
- }
+ IRubyObject nv = num;
+ if (!(nv instanceof RubyInteger)) nv = num.convertToInteger();
CallSite op_gt = sites(context).op_gt;
if (RubyNumeric.numFuncall(context, nv, op_gt, len).isTrue()) {
nv = len;
}
- n = numericToLong(context, nv);
- if (n < 0) {
- throw runtime.newArgumentError("negative array size");
- }
+ long n = numericToLong(context, nv);
+ if (n < 0) throw argumentError(context, "negative array size");
ary = RubyArray.newArray(runtime, n);
b = ((RubyNumeric)last).op_minus(context, Numeric.f_mul(context, s, nv));
@@ -582,9 +555,10 @@ public IRubyObject size(ThreadContext context) {
}
/**
- * A size method suitable for lambda method reference implementation of {@link SizeFn#size(ThreadContext, IRubyObject, IRubyObject[])}
+ * A size method suitable for lambda method reference implementation of
+ * {@link RubyEnumerator.SizeFn#size(ThreadContext, IRubyObject, IRubyObject[])}
*
- * @see SizeFn#size(ThreadContext, IRubyObject, IRubyObject[])
+ * @see RubyEnumerator.SizeFn#size(ThreadContext, IRubyObject, IRubyObject[])
*/
private static IRubyObject size(ThreadContext context, RubyArithmeticSequence self, IRubyObject[] args) {
return self.size(context);
@@ -597,7 +571,7 @@ private static FiberSites fiberSites(ThreadContext context) {
@JRubyMethod(name = "each_cons")
public IRubyObject each_cons(ThreadContext context, IRubyObject arg, final Block block) {
int size = (int) numericToLong(context, arg);
- if (size <= 0) throw context.runtime.newArgumentError("invalid size");
+ if (size <= 0) throw argumentError(context, "invalid size");
return block.isGiven() ? RubyEnumerable.each_consCommon(context, this, size, block) :
enumeratorize(context.runtime, this, "each_cons", arg);
}
@@ -605,7 +579,7 @@ public IRubyObject each_cons(ThreadContext context, IRubyObject arg, final Block
@JRubyMethod(name = "each_slice")
public IRubyObject each_slice(ThreadContext context, IRubyObject arg, final Block block) {
int size = (int) numericToLong(context, arg);
- if (size <= 0) throw context.runtime.newArgumentError("invalid size");
+ if (size <= 0) throw argumentError(context, "invalid size");
return block.isGiven() ? RubyEnumerable.each_sliceCommon(context, this, size, block) :
enumeratorizeWithSize(context, this, "each_slice", new IRubyObject[]{arg}, RubyArithmeticSequence::size);
diff --git a/core/src/main/java/org/jruby/RubyArray.java b/core/src/main/java/org/jruby/RubyArray.java
index ae5d6d8776c..4f0f6410689 100644
--- a/core/src/main/java/org/jruby/RubyArray.java
+++ b/core/src/main/java/org/jruby/RubyArray.java
@@ -94,6 +94,8 @@
import static org.jruby.RubyEnumerator.enumeratorizeWithSize;
import static org.jruby.RubyEnumerator.enumWithSize;
import static org.jruby.api.Convert.*;
+import static org.jruby.api.Create.newFixnum;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.Helpers.addBufferLength;
import static org.jruby.runtime.Helpers.arrayOf;
@@ -103,8 +105,6 @@
import static org.jruby.runtime.Helpers.validateBufferLength;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.util.Inspector.*;
-import static org.jruby.util.RubyStringBuilder.str;
-import static org.jruby.util.RubyStringBuilder.types;
/**
* The implementation of the built-in class Array in Ruby.
@@ -601,7 +601,7 @@ private RubyArray makeSharedFirst(ThreadContext context, IRubyObject num, boolea
if (n > realLength) {
n = realLength;
} else if (n < 0) {
- throw context.runtime.newArgumentError("negative array size");
+ throw argumentError(context, "negative array size");
}
return makeShared(last ? begin + realLength - n : begin, n, klass);
@@ -686,7 +686,6 @@ public IRubyObject initialize(ThreadContext context, IRubyObject arg0, IRubyObje
protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) {
unpack();
- Ruby runtime = context.runtime;
if (arg1 == null && !(arg0 instanceof RubyFixnum)) {
IRubyObject val = arg0.checkArrayType();
@@ -697,8 +696,8 @@ protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0,
}
long len = numericToLong(context, arg0);
- if (len < 0) throw runtime.newArgumentError("negative array size");
- int ilen = validateBufferLength(runtime, len);
+ if (len < 0) throw argumentError(context, "negative array size");
+ int ilen = validateBufferLength(context.runtime, len);
modify();
@@ -709,7 +708,7 @@ protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0,
if (block.isGiven()) {
if (arg1 != null) {
- runtime.getWarnings().warn(ID.BLOCK_BEATS_DEFAULT_VALUE, "block supersedes default value argument");
+ context.runtime.getWarnings().warn(ID.BLOCK_BEATS_DEFAULT_VALUE, "block supersedes default value argument");
}
if (block.getSignature() == Signature.NO_ARGUMENTS) {
@@ -720,7 +719,7 @@ protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0,
}
} else {
for (int i = 0; i < ilen; i++) {
- storeInternal(i, block.yield(context, RubyFixnum.newFixnum(runtime, i)));
+ storeInternal(i, block.yield(context, newFixnum(context, i)));
realLength = i + 1;
}
}
@@ -728,12 +727,12 @@ protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0,
} else {
try {
if (arg1 == null) {
- Helpers.fillNil(values, begin, begin + ilen, runtime);
+ Helpers.fillNil(values, begin, begin + ilen, context.runtime);
} else {
Arrays.fill(values, begin, begin + ilen, arg1);
}
} catch (ArrayIndexOutOfBoundsException ex) {
- throw concurrentModification(runtime, ex);
+ throw concurrentModification(context.runtime, ex);
}
realLength = ilen;
}
@@ -1884,7 +1883,7 @@ public IRubyObject first(IRubyObject arg0) {
if (n > realLength) {
n = realLength;
} else if (n < 0) {
- throw context.runtime.newArgumentError("negative array size (or size too big)");
+ throw argumentError(context, "negative array size (or size too big)");
} else if (n == 1) {
return newArray(context.runtime, eltOk(0));
} else if (n == 2) {
@@ -1991,8 +1990,7 @@ public IRubyObject eachSlice(ThreadContext context, int size, Block block) {
@JRubyMethod
public IRubyObject each_slice(ThreadContext context, IRubyObject arg, Block block) {
final int size = RubyNumeric.num2int(arg);
- final Ruby runtime = context.runtime;
- if (size <= 0) throw runtime.newArgumentError("invalid slice size");
+ if (size <= 0) throw argumentError(context, "invalid slice size");
return block.isGiven() ? eachSlice(context, size, block) : enumeratorizeWithSize(context, this, "each_slice", arg, arg);
}
@@ -2105,7 +2103,7 @@ private static void strJoin(RubyString result, RubyString val, boolean[] first)
private void recursiveJoin(final ThreadContext context, final IRubyObject outValue,
final RubyString sep, final RubyString result, final RubyArray ary, final boolean[] first) {
- if (ary == this) throw context.runtime.newArgumentError("recursive array join");
+ if (ary == this) throw argumentError(context, "recursive array join");
first[0] = false;
@@ -2219,7 +2217,7 @@ public IRubyObject to_h(ThreadContext context, Block block) {
RubyArray ary = (RubyArray)key_value_pair;
if (ary.getLength() != 2) {
- throw runtime.newArgumentError("wrong array length at " + i + " (expected 2, was " + ary.getLength() + ")");
+ throw argumentError(context, "wrong array length at " + i + " (expected 2, was " + ary.getLength() + ")");
}
if (useSmallHash) {
@@ -2407,12 +2405,10 @@ public IRubyObject fill(ThreadContext context, IRubyObject arg1, IRubyObject arg
@JRubyMethod
public IRubyObject fill(ThreadContext context, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3, Block block) {
- if (block.isGiven()) {
- throw context.runtime.newArgumentError(3, 2);
- } else {
- int beg;
- return fillCommon(context, beg = fillBegin(arg2), fillLen(context, beg, arg3), arg1);
- }
+ if (block.isGiven()) throw context.runtime.newArgumentError(3, 2);
+
+ int beg = fillBegin(arg2);
+ return fillCommon(context, beg, fillLen(context, beg, arg3), arg1);
}
private int fillBegin(IRubyObject arg) {
@@ -2444,7 +2440,7 @@ protected IRubyObject fillCommon(ThreadContext context, int beg, long len, IRuby
if (len < 0) return this;
- if (len > Integer.MAX_VALUE - beg) throw context.runtime.newArgumentError("argument too big");
+ if (len > Integer.MAX_VALUE - beg) throw argumentError(context, "argument too big");
int end = (int)(beg + len);
if (end > realLength) {
@@ -2470,7 +2466,7 @@ protected IRubyObject fillCommon(ThreadContext context, int beg, long len, Block
if (len < 0) return this;
- if (len > Integer.MAX_VALUE - beg) throw context.runtime.newArgumentError("argument too big");
+ if (len > Integer.MAX_VALUE - beg) throw argumentError(context, "argument too big");
int end = (int)(beg + len);
if (end > realLength) {
@@ -3362,9 +3358,7 @@ protected boolean flatten(ThreadContext context, final int level, final RubyArra
result.append(elt);
} else { // nested array element
if (memo != null) {
- if (memo.get(tmp) != null) {
- throw runtime.newArgumentError("tried to flatten recursive array");
- }
+ if (memo.get(tmp) != null) throw argumentError(context, "tried to flatten recursive array");
memo.put(ary, NEVER);
}
stack.push(ary);
@@ -3531,11 +3525,8 @@ public IRubyObject op_times(ThreadContext context, IRubyObject times) {
long len = numericToLong(context, times);
Ruby runtime = context.runtime;
if (len == 0) return RubyArray.newEmptyArray(runtime);
- if (len < 0) throw runtime.newArgumentError("negative argument");
-
- if (Long.MAX_VALUE / len < realLength) {
- throw runtime.newArgumentError("argument too big");
- }
+ if (len < 0) throw argumentError(context, "negative argument");
+ if (Long.MAX_VALUE / len < realLength) throw argumentError(context, "argument too big");
len *= realLength;
@@ -4087,7 +4078,7 @@ public IRubyObject sort_by_bang(ThreadContext context, Block block) {
@JRubyMethod(name = "take")
public IRubyObject take(ThreadContext context, IRubyObject n) {
long len = numericToLong(context, n);
- if (len < 0) throw context.runtime.newArgumentError("attempt to take negative size");
+ if (len < 0) throw argumentError(context, "attempt to take negative size");
return subseq(0, len);
}
@@ -4113,7 +4104,7 @@ public IRubyObject take_while(ThreadContext context, Block block) {
@JRubyMethod(name = "drop")
public IRubyObject drop(ThreadContext context, IRubyObject n) {
long pos = numericToLong(context, n);
- if (pos < 0) throw context.runtime.newArgumentError("attempt to drop negative size");
+ if (pos < 0) throw argumentError(context, "attempt to drop negative size");
IRubyObject result = subseq(pos, realLength);
return result.isNil() ? context.runtime.newEmptyArray() : result;
@@ -4663,7 +4654,7 @@ private IRubyObject sampleCommon(ThreadContext context, IRubyObject sample, IRub
int n = RubyNumeric.num2int(sample);
try {
- if (n < 0) throw runtime.newArgumentError("negative sample number");
+ if (n < 0) throw argumentError(context, "negative sample number");
if (n > realLength) n = realLength;
long[] rnds = new long[SORTED_THRESHOLD];
@@ -5775,7 +5766,7 @@ protected static class State {
}
public IRubyObject call(ThreadContext context, State state, IRubyObject obj, boolean recur) {
- if (recur) throw context.runtime.newArgumentError("recursive array join");
+ if (recur) throw argumentError(context, "recursive array join");
state.ary.joinAny(context, state.sep, 0, state.result, state.first);
@@ -5978,7 +5969,7 @@ public IRubyObject shuffle(ThreadContext context, IRubyObject[] args) {
case 1:
return shuffle(context, args[0]);
default:
- throw context.runtime.newArgumentError(args.length, 0, 0);
+ throw argumentError(context, args.length, 0, 0);
}
}
@@ -5990,7 +5981,7 @@ public IRubyObject shuffle_bang(ThreadContext context, IRubyObject[] args) {
case 1:
return shuffle_bang(context, args[0]);
default:
- throw context.runtime.newArgumentError(args.length, 0, 0);
+ throw argumentError(context, args.length, 0, 0);
}
}
@@ -6004,7 +5995,7 @@ public IRubyObject sample(ThreadContext context, IRubyObject[] args) {
case 2:
return sample(context, args[0], args[1]);
default:
- throw context.runtime.newArgumentError(args.length, 0, 1);
+ throw argumentError(context, args.length, 0, 1);
}
}
diff --git a/core/src/main/java/org/jruby/RubyBasicObject.java b/core/src/main/java/org/jruby/RubyBasicObject.java
index d5c1b5cc880..03e5a0120fb 100644
--- a/core/src/main/java/org/jruby/RubyBasicObject.java
+++ b/core/src/main/java/org/jruby/RubyBasicObject.java
@@ -68,6 +68,7 @@
import static org.jruby.anno.FrameField.*;
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.castAsModule;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.ir.runtime.IRRuntimeHelpers.dupIfKeywordRestAtCallsite;
import static org.jruby.runtime.Helpers.invokeChecked;
@@ -955,7 +956,7 @@ private RubyBasicObject rbCloneInternal(ThreadContext context, IRubyObject freez
// MRI: immutable_obj_clone
if (isSpecialObject()) {
final Ruby runtime = context.runtime;
- if (freeze == runtime.getFalse()) throw runtime.newArgumentError(str(runtime, "can't unfreeze ", types(runtime, getType())));
+ if (freeze == runtime.getFalse()) throw argumentError(context, str(runtime, "can't unfreeze ", types(runtime, getType())));
return this;
}
@@ -1678,11 +1679,9 @@ public static IRubyObject method_missing(ThreadContext context, IRubyObject recv
Visibility lastVis = context.getLastVisibility();
CallType lastCallType = context.getLastCallType();
- if (args.length == 0 || !(args[0] instanceof RubySymbol)) {
- throw context.runtime.newArgumentError("no id given");
- }
+ if (args.length == 0 || !(args[0] instanceof RubySymbol sym)) throw argumentError(context, "no id given");
- return RubyKernel.methodMissingDirect(context, recv, (RubySymbol)args[0], lastVis, lastCallType, args);
+ return RubyKernel.methodMissingDirect(context, recv, sym, lastVis, lastCallType, args);
}
@JRubyMethod(name = "__send__", omit = true, keywords = true)
diff --git a/core/src/main/java/org/jruby/RubyBignum.java b/core/src/main/java/org/jruby/RubyBignum.java
index c0f2790beff..8838a007d4d 100644
--- a/core/src/main/java/org/jruby/RubyBignum.java
+++ b/core/src/main/java/org/jruby/RubyBignum.java
@@ -53,6 +53,7 @@
import static org.jruby.RubyFixnum.zero;
import static org.jruby.api.Convert.*;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
/**
@@ -345,8 +346,8 @@ public RubyArray digits(ThreadContext context, IRubyObject base) {
BigInteger bigBase = base instanceof RubyBignum ?
((RubyBignum) base).value : long2big(((RubyFixnum) base).value);
- if (bigBase.signum() == -1) throw context.runtime.newArgumentError("negative radix");
- if (bigBase.compareTo(BigInteger.valueOf(2)) == -1) throw context.runtime.newArgumentError("invalid radix: " + bigBase);
+ if (bigBase.signum() == -1) throw argumentError(context, "negative radix");
+ if (bigBase.compareTo(BigInteger.valueOf(2)) == -1) throw argumentError(context, "invalid radix: " + bigBase);
if (self.signum() == 0) {
return RubyArray.newArray(context.runtime, zero(context.runtime));
@@ -397,14 +398,11 @@ public RubyString to_s(IRubyObject arg0) {
@Override
public IRubyObject coerce(IRubyObject other) {
final Ruby runtime = getRuntime();
- if (other instanceof RubyFixnum) {
- return runtime.newArray(newBignum(runtime, ((RubyFixnum) other).value), this);
- }
- if (other instanceof RubyBignum) {
- return runtime.newArray(newBignum(runtime, ((RubyBignum) other).value), this);
- }
+ ThreadContext context = runtime.getCurrentContext();
+ if (other instanceof RubyFixnum fix) return runtime.newArray(newBignum(runtime, fix.value), this);
+ if (other instanceof RubyBignum big) return runtime.newArray(newBignum(runtime, big.value), this);
- return RubyArray.newArray(runtime, RubyKernel.new_float(runtime, other), RubyKernel.new_float(runtime, this));
+ return RubyArray.newArray(runtime, RubyKernel.new_float(context, other), RubyKernel.new_float(context, this));
}
/** rb_big_uminus
@@ -420,15 +418,10 @@ public IRubyObject op_uminus(ThreadContext context) {
*/
@Override
public IRubyObject op_plus(ThreadContext context, IRubyObject other) {
- if (other instanceof RubyFixnum) {
- return op_plus(context, ((RubyFixnum) other).value);
- }
- if (other instanceof RubyBignum) {
- return op_plus(context, ((RubyBignum) other).value);
- }
- if (other instanceof RubyFloat) {
- return addFloat((RubyFloat) other);
- }
+ if (other instanceof RubyFixnum fix) return op_plus(context, fix.value);
+ if (other instanceof RubyBignum big) return op_plus(context, big.value);
+ if (other instanceof RubyFloat flote) return addFloat(flote);
+
return addOther(context, other);
}
diff --git a/core/src/main/java/org/jruby/RubyClass.java b/core/src/main/java/org/jruby/RubyClass.java
index cf48eae4106..8366d99a573 100644
--- a/core/src/main/java/org/jruby/RubyClass.java
+++ b/core/src/main/java/org/jruby/RubyClass.java
@@ -724,7 +724,6 @@ private static boolean checkFuncallRespondTo(ThreadContext context, RubyClass kl
* MRI: check_funcall_respond_to
*/
private static boolean checkFuncallRespondTo(ThreadContext context, RubyClass klass, IRubyObject recv, RespondToCallSite respondToSite) {
- final Ruby runtime = context.runtime;
DynamicMethod me = respondToSite.retrieveCache(klass).method;
// NOTE: isBuiltin here would be NOEX_BASIC in MRI, a flag only added to respond_to?, method_missing, and
@@ -733,13 +732,11 @@ private static boolean checkFuncallRespondTo(ThreadContext context, RubyClass kl
int required = me.getSignature().required();
- if (required > 2) throw runtime.newArgumentError("respond_to? must accept 1 or 2 arguments (requires " + required + ")");
+ if (required > 2) throw argumentError(context, "respond_to? must accept 1 or 2 arguments (requires " + required + ")");
- if (required == 1) {
- return respondToSite.respondsTo(context, recv, recv);
- } else {
- return respondToSite.respondsTo(context, recv, recv, true);
- }
+ return required == 1 ?
+ respondToSite.respondsTo(context, recv, recv) :
+ respondToSite.respondsTo(context, recv, recv, true);
}
// MRI: check_funcall_callable
diff --git a/core/src/main/java/org/jruby/RubyClassPathVariable.java b/core/src/main/java/org/jruby/RubyClassPathVariable.java
index 8aea623ed43..043139e000e 100644
--- a/core/src/main/java/org/jruby/RubyClassPathVariable.java
+++ b/core/src/main/java/org/jruby/RubyClassPathVariable.java
@@ -40,6 +40,7 @@
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
/**
* @author Ola Bini
@@ -79,7 +80,7 @@ public IRubyObject append(ThreadContext context, IRubyObject obj) {
}
context.runtime.getJRubyClassLoader().addURL(url);
} catch (MalformedURLException mue) {
- throw context.runtime.newArgumentError(mue.getLocalizedMessage());
+ throw argumentError(context, mue.getLocalizedMessage());
}
}
return this;
diff --git a/core/src/main/java/org/jruby/RubyComparable.java b/core/src/main/java/org/jruby/RubyComparable.java
index 6333476802f..9a8e26a4080 100644
--- a/core/src/main/java/org/jruby/RubyComparable.java
+++ b/core/src/main/java/org/jruby/RubyComparable.java
@@ -94,18 +94,19 @@ public static int cmpAndCmpint(ThreadContext context, CallSite op_cmp, CallSite
return cmpint(context, op_gt, op_lt, cmpResult, a, b);
}
+ @Deprecated
+ public static IRubyObject cmperr(IRubyObject recv, IRubyObject other) {
+ return cmperr(recv.getRuntime().getCurrentContext(), recv, other);
+ }
+
/** rb_cmperr
*
*/
- public static IRubyObject cmperr(IRubyObject recv, IRubyObject other) {
- IRubyObject target;
- if (other.isImmediate() || !(other.isNil() || other.isTrue() || other == recv.getRuntime().getFalse())) {
- target = other.inspect();
- } else {
- target = other.getType();
- }
+ public static IRubyObject cmperr(ThreadContext context, IRubyObject recv, IRubyObject other) {
+ IRubyObject target = other.isImmediate() || !(other.isNil() || other.isTrue() || other == context.fals) ?
+ other.inspect() : other.getType();
- throw recv.getRuntime().newArgumentError("comparison of " + recv.getType() + " with " + target + " failed");
+ throw argumentError(context, "comparison of " + recv.getType() + " with " + target + " failed");
}
/** rb_invcmp
@@ -164,7 +165,7 @@ private static IRubyObject callCmpMethod(final ThreadContext context, final IRub
public static RubyBoolean op_gt(ThreadContext context, IRubyObject recv, IRubyObject other) {
var result = sites(context).op_cmp.call(context, recv, recv, other);
- if (result.isNil()) cmperr(recv, other);
+ if (result.isNil()) cmperr(context, recv, other);
return asBoolean(context, cmpint(context, result, recv, other) > 0);
}
@@ -176,7 +177,7 @@ public static RubyBoolean op_gt(ThreadContext context, IRubyObject recv, IRubyOb
public static RubyBoolean op_ge(ThreadContext context, IRubyObject recv, IRubyObject other) {
var result = sites(context).op_cmp.call(context, recv, recv, other);
- if (result.isNil()) cmperr(recv, other);
+ if (result.isNil()) cmperr(context, recv, other);
return asBoolean(context, cmpint(context, result, recv, other) >= 0);
}
@@ -192,7 +193,7 @@ public static RubyBoolean op_lt(ThreadContext context, IRubyObject recv, IRubyOb
public static RubyBoolean op_lt(ThreadContext context, CallSite cmp, IRubyObject recv, IRubyObject other) {
var result = cmp.call(context, recv, recv, other);
- if (result.isNil()) cmperr(recv, other);
+ if (result.isNil()) cmperr(context, recv, other);
return asBoolean(context, cmpint(context, result, recv, other) < 0);
}
@@ -204,7 +205,7 @@ public static RubyBoolean op_lt(ThreadContext context, CallSite cmp, IRubyObject
public static RubyBoolean op_le(ThreadContext context, IRubyObject recv, IRubyObject other) {
var result = sites(context).op_cmp.call(context, recv, recv, other);
- if (result.isNil()) cmperr(recv, other);
+ if (result.isNil()) cmperr(context, recv, other);
return asBoolean(context, cmpint(context, result, recv, other) <= 0);
}
@@ -236,7 +237,7 @@ public static IRubyObject clamp(ThreadContext context, IRubyObject recv, IRubyOb
CallSite op_cmp = sites.op_cmp;
if (!min.isNil() && !max.isNil() && cmpAndCmpint(context, op_cmp, op_gt, op_lt, min, max) > 0) {
- throw context.runtime.newArgumentError("min argument must be smaller than max argument");
+ throw argumentError(context, "min argument must be smaller than max argument");
}
if (!min.isNil()) {
diff --git a/core/src/main/java/org/jruby/RubyComplex.java b/core/src/main/java/org/jruby/RubyComplex.java
index 452c427e21e..2aa36154e42 100644
--- a/core/src/main/java/org/jruby/RubyComplex.java
+++ b/core/src/main/java/org/jruby/RubyComplex.java
@@ -53,6 +53,7 @@
import java.util.function.BiFunction;
import static org.jruby.api.Convert.asBoolean;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.Helpers.invokedynamic;
import static org.jruby.runtime.invokedynamic.MethodNames.HASH;
@@ -452,21 +453,15 @@ public static IRubyObject convert(ThreadContext context, IRubyObject recv, IRuby
*/
@JRubyMethod(name = "convert", meta = true, visibility = Visibility.PRIVATE)
public static IRubyObject convert(ThreadContext context, IRubyObject recv, IRubyObject a1, IRubyObject a2) {
- Ruby runtime = context.runtime;
-
- IRubyObject maybeKwargs = ArgsUtil.getOptionsArg(runtime, a2, false);
-
- if (maybeKwargs.isNil()) {
- return convertCommon(context, recv, a1, a2, true);
- }
+ IRubyObject maybeKwargs = ArgsUtil.getOptionsArg(context.runtime, a2, false);
+ if (maybeKwargs.isNil()) return convertCommon(context, recv, a1, a2, true);
IRubyObject exception = ArgsUtil.extractKeywordArg(context, "exception", (RubyHash) maybeKwargs);
if (exception instanceof RubyBoolean) {
- if (a1 instanceof RubyComplex) return a1;
- return convertCommon(context, recv, a1, null, exception.isTrue());
+ return a1 instanceof RubyComplex ? a1 : convertCommon(context, recv, a1, null, exception.isTrue());
}
- throw runtime.newArgumentError("`Complex': expected true or false as exception: " + exception);
+ throw argumentError(context, "`Complex': expected true or false as exception: " + exception);
}
/** nucomp_s_convert
@@ -487,7 +482,7 @@ public static IRubyObject convert(ThreadContext context, IRubyObject recv, IRuby
return convertCommon(context, recv, a1, a2, exception.isTrue());
}
- throw runtime.newArgumentError("`Complex': expected true or false as exception: " + exception);
+ throw argumentError(context, "`Complex': expected true or false as exception: " + exception);
}
// MRI: nucomp_s_convert
@@ -1308,13 +1303,13 @@ private static IRubyObject str_to_c_strict(ThreadContext context, RubyString str
if (str.hasNul()) {
if (!raise) return context.nil;
- throw context.runtime.newArgumentError("string contains null byte");
+ throw argumentError(context, "string contains null byte");
}
IRubyObject[] ary = str_to_c_internal(context, str);
if (ary[0] == context.nil || ary[1].convertToString().getByteList().length() > 0) {
if (raise) {
- throw context.runtime.newArgumentError(str(context.runtime, "invalid value for convert(): ", str.callMethod(context, "inspect")));
+ throw argumentError(context, str(context.runtime, "invalid value for convert(): ", str.callMethod(context, "inspect")));
}
return context.nil;
diff --git a/core/src/main/java/org/jruby/RubyConverter.java b/core/src/main/java/org/jruby/RubyConverter.java
index 1457e1f6785..215376de748 100644
--- a/core/src/main/java/org/jruby/RubyConverter.java
+++ b/core/src/main/java/org/jruby/RubyConverter.java
@@ -60,6 +60,7 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.Visibility.PRIVATE;
@@ -309,28 +310,16 @@ public IRubyObject primitive_convert(ThreadContext context, IRubyObject[] args)
}
while (true) {
- if (outputByteOffsetObj.isNil()) {
- outputByteoffset = outBytes.getRealSize();
- }
-
- if (outputByteoffset < 0) {
- throw runtime.newArgumentError("negative output offset");
- }
-
- if (outBytes.getRealSize() < outputByteoffset) {
- throw runtime.newArgumentError("output offset too big");
- }
+ if (outputByteOffsetObj.isNil()) outputByteoffset = outBytes.getRealSize();
- if (outputBytesize < 0) {
- throw runtime.newArgumentError("negative bytesize");
- }
+ if (outputByteoffset < 0) throw argumentError(context, "negative output offset");
+ if (outBytes.getRealSize() < outputByteoffset) throw argumentError(context, "output offset too big");
+ if (outputBytesize < 0) throw argumentError(context, "negative bytesize");
long outputByteEnd = outputByteoffset + outputBytesize;
- if (outputByteEnd > Integer.MAX_VALUE) {
- // overflow check
- throw runtime.newArgumentError("output offset + bytesize too big");
- }
+ // overflow check
+ if (outputByteEnd > Integer.MAX_VALUE) throw argumentError(context, "output offset + bytesize too big");
outBytes.ensure((int)outputByteEnd);
@@ -348,7 +337,7 @@ public IRubyObject primitive_convert(ThreadContext context, IRubyObject[] args)
if (outputBytesizeObj.isNil() && res == EConvResult.DestinationBufferFull) {
if (Integer.MAX_VALUE / 2 < outputBytesize) {
- throw runtime.newArgumentError("too long conversion result");
+ throw argumentError(context, "too long conversion result");
}
outputBytesize *= 2;
outputByteOffsetObj = context.nil;
@@ -389,7 +378,7 @@ public IRubyObject convert(ThreadContext context, IRubyObject srcBuffer) {
}
if (retStr.equals(EConvResult.Finished.symbolicName())) {
- throw context.runtime.newArgumentError("converter already finished");
+ throw argumentError(context, "converter already finished");
}
if (!retStr.equals(EConvResult.SourceBufferEmpty.symbolicName())) {
@@ -573,7 +562,6 @@ public void call(byte[] source, byte[] destination, int depth) {
// econv_insert_output
@JRubyMethod
public IRubyObject insert_output(ThreadContext context, IRubyObject string) {
- Ruby runtime = context.runtime;
byte[] insertEnc;
int ret;
@@ -583,15 +571,13 @@ public IRubyObject insert_output(ThreadContext context, IRubyObject string) {
string = EncodingUtils.rbStrEncode(
context,
string,
- runtime.getEncodingService().findEncodingObject(insertEnc),
+ context.runtime.getEncodingService().findEncodingObject(insertEnc),
0,
context.nil);
ByteList stringBL = ((RubyString)string).getByteList();
ret = ec.insertOutput(stringBL.getUnsafeBytes(), stringBL.getBegin(), stringBL.getRealSize(), insertEnc);
- if (ret == -1) {
- throw runtime.newArgumentError("too big string");
- }
+ if (ret == -1) throw argumentError(context, "too big string");
return context.nil;
}
diff --git a/core/src/main/java/org/jruby/RubyDir.java b/core/src/main/java/org/jruby/RubyDir.java
index 122d155170c..deae0c4f856 100644
--- a/core/src/main/java/org/jruby/RubyDir.java
+++ b/core/src/main/java/org/jruby/RubyDir.java
@@ -243,7 +243,7 @@ private static void globOptions(ThreadContext context, IRubyObject[] args, Strin
if (rets[1] != null) {
if (!(rets[1] instanceof RubyBoolean)) {
- throw context.runtime.newArgumentError(str(runtime, "expected true or false as sort:", rets[1]));
+ throw argumentError(context, str(runtime, "expected true or false as sort:", rets[1]));
}
options.sort = !runtime.getFalse().equals(rets[1]); // weirdly only explicit false is honored for sort.
}
@@ -299,7 +299,7 @@ private static ByteList globArgumentAsByteList(ThreadContext context, IRubyObjec
if (!(arg instanceof RubyString)) {
str = RubyFile.get_path(context, arg);
} else if (StringSupport.strNullCheck(arg)[0] == null) {
- throw context.runtime.newArgumentError("nul-separated glob pattern is deprecated");
+ throw argumentError(context, "nul-separated glob pattern is deprecated");
} else {
str = (RubyString) arg;
// FIXME: It is possible this can just be EncodingUtils.strCompatAndValid() but the spec says specifically it must be ascii compat which is more constrained than that method.
@@ -433,54 +433,52 @@ private static void checkDirIsTwoSlashesOnWindows(Ruby runtime, String path) {
/** Changes the current directory to path
*/
@JRubyMethod(meta = true)
public static IRubyObject chdir(ThreadContext context, IRubyObject recv, IRubyObject _path, Block block) {
- Ruby runtime = context.runtime;
-
- RubyString path = StringSupport.checkEmbeddedNulls(runtime, RubyFile.get_path(context, _path));
+ RubyString path = StringSupport.checkEmbeddedNulls(context.runtime, RubyFile.get_path(context, _path));
- return chdirCommon(context, block, runtime, path);
+ return chdirCommon(context, block, path);
}
/** Changes the current directory to path
*/
@JRubyMethod(meta = true)
public static IRubyObject chdir(ThreadContext context, IRubyObject recv, Block block) {
- Ruby runtime = context.runtime;
RubyHash env = context.runtime.getENV();
if (env.op_aref(context, newString(context, "LOG_DIR")).isNil() &&
env.op_aref(context, newString(context, "HOME")).isNil()){
- throw runtime.newArgumentError("HOME/LOGDIR not set");
+ throw argumentError(context, "HOME/LOGDIR not set");
}
RubyString path = getHomeDirectoryPath(context);
- return chdirCommon(context, block, runtime, path);
+ return chdirCommon(context, block, path);
}
- private static IRubyObject chdirCommon(ThreadContext context, Block block, Ruby runtime, RubyString path) {
+ private static IRubyObject chdirCommon(ThreadContext context, Block block, RubyString path) {
+ Ruby runtime = context.runtime;
String adjustedPath = RubyFile.adjustRootPathOnWindows(runtime, path.asJavaString(), null);
checkDirIsTwoSlashesOnWindows(runtime, adjustedPath);
adjustedPath = getExistingDir(runtime, adjustedPath).canonicalPath();
- if (context.runtime.getChdirThread() != null && context.getThread() != context.runtime.getChdirThread()) {
+ if (runtime.getChdirThread() != null && context.getThread() != runtime.getChdirThread()) {
throw runtime.newRuntimeError("conflicting chdir during another chdir block");
}
- if(!block.isGiven() && context.runtime.getChdirThread() != null) {
+ if(!block.isGiven() && runtime.getChdirThread() != null) {
context.runtime.getWarnings().warn("conflicting chdir during another chdir block");
}
IRubyObject result;
if (block.isGiven()) {
- context.runtime.setChdirThread(context.getThread());
+ runtime.setChdirThread(context.getThread());
final String oldCwd = runtime.getCurrentDirectory();
runtime.setCurrentDirectory(adjustedPath);
try {
result = block.yield(context, path);
} finally {
- context.runtime.setChdirThread(null);
+ runtime.setChdirThread(null);
getExistingDir(runtime, oldCwd); // needed in case the block deleted the oldCwd
runtime.setCurrentDirectory(oldCwd);
}
@@ -1140,7 +1138,7 @@ public static IRubyObject getHomeDirectoryPath(ThreadContext context, String use
}
}
- throw runtime.newArgumentError("user " + user + " doesn't exist");
+ throw argumentError(context, "user " + user + " doesn't exist");
}
private static RubyString newFilesystemString(Ruby runtime, String home) {
diff --git a/core/src/main/java/org/jruby/RubyEnumerable.java b/core/src/main/java/org/jruby/RubyEnumerable.java
index 1861d8aaf52..c4d9f8f0da9 100644
--- a/core/src/main/java/org/jruby/RubyEnumerable.java
+++ b/core/src/main/java/org/jruby/RubyEnumerable.java
@@ -69,6 +69,7 @@
import static org.jruby.RubyObject.equalInternal;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Convert.numericToLong;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.Helpers.arrayOf;
import static org.jruby.runtime.Helpers.invokedynamic;
@@ -266,17 +267,16 @@ private static IRubyObject cycleSize(ThreadContext context, IRubyObject self, IR
@JRubyMethod(name = "take")
public static IRubyObject take(ThreadContext context, IRubyObject self, IRubyObject n, Block block) {
- final Ruby runtime = context.runtime;
final long len = numericToLong(context, n);
- if (len < 0) throw runtime.newArgumentError("attempt to take negative size");
- if (len == 0) return runtime.newEmptyArray();
+ if (len < 0) throw argumentError(context, "attempt to take negative size");
+ if (len == 0) return context.runtime.newEmptyArray();
- final RubyArray result = runtime.newArray();
+ final RubyArray result = context.runtime.newArray();
try {
// Atomic ?
- each(context, eachSite(context), self, new JavaInternalBlockBody(runtime, Signature.OPTIONAL) {
+ each(context, eachSite(context), self, new JavaInternalBlockBody(context.runtime, Signature.OPTIONAL) {
long i = len; // Atomic ?
@Override
public IRubyObject yield(ThreadContext context1, IRubyObject[] args) {
@@ -327,7 +327,7 @@ public static IRubyObject drop(ThreadContext context, IRubyObject self, IRubyObj
final Ruby runtime = context.runtime;
final long len = numericToLong(context, n);
- if (len < 0) throw runtime.newArgumentError("attempt to drop negative size");
+ if (len < 0) throw argumentError(context, "attempt to drop negative size");
final RubyArray result = runtime.newArray();
@@ -411,7 +411,7 @@ public static IRubyObject first(ThreadContext context, IRubyObject self, final I
final long firstCount = numericToLong(context, num);
if (firstCount == 0) return runtime.newEmptyArray();
- if (firstCount < 0) throw runtime.newArgumentError("attempt to take negative size");
+ if (firstCount < 0) throw argumentError(context, "attempt to take negative size");
final RubyArray result = RubyArray.newArray(runtime, firstCount);
try {
@@ -1072,7 +1072,7 @@ public static IRubyObject injectCommon(final ThreadContext context, IRubyObject
@JRubyMethod(name = {"inject", "reduce"})
public static IRubyObject inject(ThreadContext context, IRubyObject self, final Block block) {
- if (!block.isGiven()) throw context.runtime.newArgumentError("wrong number of arguments (given 0, expected 1..2)");
+ if (!block.isGiven()) throw argumentError(context, "wrong number of arguments (given 0, expected 1..2)");
return injectCommon(context, self, null, block);
}
@@ -1251,7 +1251,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) {
@JRubyMethod(name = "each_slice")
public static IRubyObject each_slice(ThreadContext context, IRubyObject self, IRubyObject arg, final Block block) {
int size = (int) numericToLong(context, arg);
- if (size <= 0) throw context.runtime.newArgumentError("invalid size");
+ if (size <= 0) throw argumentError(context, "invalid size");
return block.isGiven() ? each_sliceCommon(context, self, size, block) :
enumeratorizeWithSize(context, self, "each_slice", new IRubyObject[]{arg}, RubyEnumerable::eachSliceSize);
@@ -1259,7 +1259,7 @@ public static IRubyObject each_slice(ThreadContext context, IRubyObject self, IR
static IRubyObject each_sliceCommon(ThreadContext context, IRubyObject self, final int size, final Block block) {
final Ruby runtime = context.runtime;
- if (size <= 0) throw runtime.newArgumentError("invalid slice size");
+ if (size <= 0) throw argumentError(context, "invalid slice size");
final SingleObject result = new SingleObject<>(runtime.newArray(size));
@@ -1286,7 +1286,7 @@ private static IRubyObject eachSliceSize(ThreadContext context, IRubyObject self
assert args != null && args.length > 0 && args[0] instanceof RubyNumeric; // #each_slice ensures arg[0] is numeric
long sliceSize = ((RubyNumeric) args[0]).getLongValue();
if (sliceSize <= 0) {
- throw runtime.newArgumentError("invalid slice size");
+ throw argumentError(context, "invalid slice size");
}
IRubyObject size = RubyEnumerable.size(context, self, args);
@@ -1301,7 +1301,7 @@ private static IRubyObject eachSliceSize(ThreadContext context, IRubyObject self
@JRubyMethod(name = "each_cons")
public static IRubyObject each_cons(ThreadContext context, IRubyObject self, IRubyObject arg, final Block block) {
int size = (int) numericToLong(context, arg);
- if (size <= 0) throw context.runtime.newArgumentError("invalid size");
+ if (size <= 0) throw argumentError(context, "invalid size");
return block.isGiven() ? each_consCommon(context, self, size, block) : enumeratorizeWithSize(context, self, "each_cons", new IRubyObject[] { arg }, (SizeFn) RubyEnumerable::eachConsSize);
}
@@ -1328,7 +1328,7 @@ private static IRubyObject eachConsSize(ThreadContext context, IRubyObject self,
assert args != null && args.length > 0 && args[0] instanceof RubyNumeric; // #each_cons ensures arg[0] is numeric
long consSize = ((RubyNumeric) args[0]).getLongValue();
if (consSize <= 0) {
- throw runtime.newArgumentError("invalid size");
+ throw argumentError(context, "invalid size");
}
IRubyObject size = ((SizeFn) RubyEnumerable::size).size(context, self, args);
@@ -1717,7 +1717,7 @@ public static IRubyObject all_p(ThreadContext context, IRubyObject self, IRubyOb
case 1:
return all_p(context, self, args[0], block);
default:
- throw context.runtime.newArgumentError(args.length, 0, 1);
+ throw argumentError(context, args.length, 0, 1);
}
}
@@ -1807,7 +1807,7 @@ public static IRubyObject any_p(ThreadContext context, IRubyObject self, IRubyOb
case 1:
return any_pCommon(context, eachSite(context), self, args[0], block);
default:
- throw context.runtime.newArgumentError(args.length, 0, 1);
+ throw argumentError(context, args.length, 0, 1);
}
}
@@ -2364,11 +2364,12 @@ public IRubyObject call(ThreadContext context, IRubyObject[] largs, Block blk) {
}
private void callImpl(final Ruby runtime, IRubyObject value) {
+ ThreadContext context = runtime.getCurrentContext();
IRubyObject ary = TypeConverter.checkArrayType(runtime, value);
- if (ary.isNil()) throw typeError(runtime.getCurrentContext(), "wrong element type ", value, " (expected array)");
+ if (ary.isNil()) throw typeError(context, "wrong element type ", value, " (expected array)");
final RubyArray array = (RubyArray) ary;
if (array.size() != 2) {
- throw runtime.newArgumentError("element has wrong array length (expected 2, was " + array.size() + ")");
+ throw argumentError(context, "element has wrong array length (expected 2, was " + array.size() + ")");
}
result.fastASetCheckString(runtime, array.eltOk(0), array.eltOk(1));
}
diff --git a/core/src/main/java/org/jruby/RubyEnumerator.java b/core/src/main/java/org/jruby/RubyEnumerator.java
index 406df97e9ac..32992461d0f 100644
--- a/core/src/main/java/org/jruby/RubyEnumerator.java
+++ b/core/src/main/java/org/jruby/RubyEnumerator.java
@@ -47,6 +47,7 @@
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Convert.numericToLong;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.Helpers.arrayOf;
import static org.jruby.runtime.ThreadContext.CALL_KEYWORD;
@@ -419,7 +420,7 @@ public IRubyObject each_entry(ThreadContext context, final IRubyObject[] args, f
@JRubyMethod(name = "each_slice")
public IRubyObject each_slice(ThreadContext context, IRubyObject arg, final Block block) {
int size = (int) numericToLong(context, arg);
- if (size <= 0) throw context.runtime.newArgumentError("invalid size");
+ if (size <= 0) throw argumentError(context, "invalid size");
return block.isGiven() ? RubyEnumerable.each_sliceCommon(context, this, size, block) :
enumeratorize(context.runtime, getType(), this, "each_slice", arg);
@@ -428,7 +429,7 @@ public IRubyObject each_slice(ThreadContext context, IRubyObject arg, final Bloc
@JRubyMethod(name = "each_cons")
public IRubyObject each_cons(ThreadContext context, IRubyObject arg, final Block block) {
int size = (int) numericToLong(context, arg);
- if (size <= 0) throw context.runtime.newArgumentError("invalid size");
+ if (size <= 0) throw argumentError(context, "invalid size");
return block.isGiven() ? RubyEnumerable.each_consCommon(context, this, size, block) :
enumeratorize(context.runtime, getType(), this, "each_cons", arg);
}
@@ -571,24 +572,15 @@ private static JavaSites.FiberSites sites(ThreadContext context) {
public static IRubyObject produce(ThreadContext context, IRubyObject recv, IRubyObject[] args, final Block block) {
int argc = Arity.checkArgumentCount(context, args, 0, 1);
- IRubyObject init;
-
- if (!block.isGiven()) throw context.runtime.newArgumentError("no block given");
-
- if (argc == 0) {
- init = null;
- } else {
- init = args[0];
- }
+ if (!block.isGiven()) throw argumentError(context, "no block given");
+ IRubyObject init = argc == 0 ? null : args[0];
RubyProducer producer = RubyProducer.newProducer(context, init, block);
return enumeratorizeWithSize(context, producer, "each", RubyProducer::size);
}
@Deprecated
public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block) {
- Ruby runtime = context.runtime;
-
IRubyObject size = Arity.checkArgumentCount(context, args, 0, 1) == 1 ? args[0] : null;
return initializeWithSize(context, size, block);
diff --git a/core/src/main/java/org/jruby/RubyFile.java b/core/src/main/java/org/jruby/RubyFile.java
index 1ad149bc5e5..65e249c35cf 100644
--- a/core/src/main/java/org/jruby/RubyFile.java
+++ b/core/src/main/java/org/jruby/RubyFile.java
@@ -84,6 +84,7 @@
import static org.jruby.api.Convert.*;
import static org.jruby.api.Create.newFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.runtime.ThreadContext.hasKeywords;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.util.StringSupport.*;
@@ -696,17 +697,15 @@ public static String dirname(ThreadContext context, final String filename) {
}
public static String dirname(ThreadContext context, final String filename, int level) {
- if (level < 0) {
- throw context.runtime.newArgumentError("negative level: " + level);
- }
+ if (level < 0) throw argumentError(context, "negative level: " + level);
+
final RubyClass File = context.runtime.getFile();
IRubyObject sep = File.getConstant("SEPARATOR");
final String separator; final char separatorChar;
if (sep instanceof RubyString && ((RubyString) sep).size() == 1) {
separatorChar = ((RubyString) sep).getByteList().charAt(0);
separator = (separatorChar == '/') ? "/" : String.valueOf(separatorChar);
- }
- else {
+ } else {
separator = sep.toString();
separatorChar = separator.isEmpty() ? '\0' : separator.charAt(0);
}
@@ -1268,7 +1267,7 @@ public static IRubyObject umask(ThreadContext context, IRubyObject recv, IRubyOb
int newMask = (int) args[0].convertToInteger().getLongValue();
oldMask = PosixShim.umask(context.runtime.getPosix(), newMask);
} else {
- throw context.runtime.newArgumentError("wrong number of arguments");
+ throw argumentError(context, "wrong number of arguments");
}
return asFixnum(context, oldMask);
@@ -2171,7 +2170,7 @@ public static String expandUserPath(ThreadContext context, String path, final bo
path = RubyDir.getHomeDirectoryPath(context, checkHome(context)).toString();
if (raiseOnRelativePath && !isAbsolutePath(path)) {
- throw context.runtime.newArgumentError("non-absolute home");
+ throw argumentError(context, "non-absolute home");
}
} else {
// No directory delimeter. Rest of string is username
@@ -2184,7 +2183,7 @@ public static String expandUserPath(ThreadContext context, String path, final bo
path = RubyDir.getHomeDirectoryPath(context, checkHome(context)).toString() + path.substring(1);
if (raiseOnRelativePath && !isAbsolutePath(path)) {
- throw context.runtime.newArgumentError("non-absolute home");
+ throw argumentError(context, "non-absolute home");
}
} else if (userEnd > 1){
// '~user/...' as path to expand
@@ -2192,14 +2191,14 @@ public static String expandUserPath(ThreadContext context, String path, final bo
IRubyObject dir = RubyDir.getHomeDirectoryPath(context, user);
if (dir.isNil()) {
- throw context.runtime.newArgumentError("user " + user + " does not exist");
+ throw argumentError(context, "user " + user + " does not exist");
}
path = dir + (pathLength == userEnd ? "" : path.substring(userEnd));
// getpwd (or /etc/passwd fallback) returns a home which is not absolute!!! [mecha-unlikely]
if (raiseOnRelativePath && !isAbsolutePath(path)) {
- throw context.runtime.newArgumentError("non-absolute home of " + user);
+ throw argumentError(context, "non-absolute home of " + user);
}
}
}
@@ -2378,7 +2377,7 @@ private static boolean joinImpl(final StringBuilder buffer, final String separat
element = arg.convertToString().toString();
} else if (arg instanceof RubyArray) {
if (context.runtime.isInspecting(arg)) {
- throw context.runtime.newArgumentError("recursive array");
+ throw argumentError(context, "recursive array");
} else {
element = joinImplInspecting(separator, context, recv, args, ((RubyArray) arg)).toString();
}
@@ -2519,7 +2518,7 @@ public static IRubyObject dirname(ThreadContext context, IRubyObject recv, IRuby
case 2:
return dirname(context, recv, args[0], args[1]);
default:
- throw context.runtime.newArgumentError(args.length, 1, 2);
+ throw argumentError(context, args.length, 1, 2);
}
}
@@ -2531,7 +2530,7 @@ public static IRubyObject expand_path(ThreadContext context, IRubyObject recv, I
case 2:
return expand_path(context, recv, args[0], args[1]);
default:
- throw context.runtime.newArgumentError(args.length, 1, 2);
+ throw argumentError(context, args.length, 1, 2);
}
}
@@ -2543,7 +2542,7 @@ private static RubyString expandPathInternal(ThreadContext context, IRubyObject[
case 2:
return expandPathInternal(context, args[0], args[1], expandUser, canonicalize);
default:
- throw context.runtime.newArgumentError(args.length, 1, 2);
+ throw argumentError(context, args.length, 1, 2);
}
}
@@ -2555,7 +2554,7 @@ public static IRubyObject absolute_path(ThreadContext context, IRubyObject recv,
case 2:
absolute_path(context, recv, args[0], args[1]);
default:
- throw context.runtime.newArgumentError(args.length, 1, 2);
+ throw argumentError(context, args.length, 1, 2);
}
}
@@ -2567,7 +2566,7 @@ public static IRubyObject realdirpath(ThreadContext context, IRubyObject recv, I
case 2:
realdirpath(context, recv, args[0], args[1]);
default:
- throw context.runtime.newArgumentError(args.length, 1, 2);
+ throw argumentError(context, args.length, 1, 2);
}
}
@@ -2588,7 +2587,7 @@ public static IRubyObject fnmatch(ThreadContext context, IRubyObject recv, IRuby
case 3:
return fnmatch(context, recv, args[0], args[1], args[2]);
default:
- throw context.runtime.newArgumentError(args.length, 2, 3);
+ throw argumentError(context, args.length, 2, 3);
}
}
}
diff --git a/core/src/main/java/org/jruby/RubyFixnum.java b/core/src/main/java/org/jruby/RubyFixnum.java
index 1ebf41736da..bfa0f1771da 100644
--- a/core/src/main/java/org/jruby/RubyFixnum.java
+++ b/core/src/main/java/org/jruby/RubyFixnum.java
@@ -60,6 +60,7 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.util.Numeric.f_odd_p;
@@ -374,29 +375,24 @@ public IRubyObject truncate(ThreadContext context, IRubyObject arg) {
@Override
public RubyArray digits(ThreadContext context, IRubyObject base) {
long value = getLongValue();
-
if (value < 0) throw context.runtime.newMathDomainError("out of domain");
base = base.convertToInteger();
-
if (base instanceof RubyBignum) return RubyArray.newArray(context.runtime, newFixnum(context.runtime, value));
long longBase = ((RubyFixnum) base).value;
- if (longBase < 0) throw context.runtime.newArgumentError("negative radix");
- if (longBase < 2) throw context.runtime.newArgumentError("invalid radix: " + longBase);
-
- if (value == 0) {
- return RubyArray.newArray(context.runtime, zero(context.runtime));
- } else {
- RubyArray res = RubyArray.newArray(context.runtime, 0);
+ if (longBase < 0) throw argumentError(context, "negative radix");
+ if (longBase < 2) throw argumentError(context, "invalid radix: " + longBase);
- while (value > 0) {
- res.append(newFixnum(context.runtime, value % longBase));
- value /= longBase;
- }
+ if (value == 0) return RubyArray.newArray(context.runtime, zero(context.runtime));
- return res;
+ RubyArray res = RubyArray.newArray(context.runtime, 0);
+ while (value > 0) {
+ res.append(newFixnum(context.runtime, value % longBase));
+ value /= longBase;
}
+
+ return res;
}
diff --git a/core/src/main/java/org/jruby/RubyFloat.java b/core/src/main/java/org/jruby/RubyFloat.java
index 8c0fb9748e3..2b0273616db 100644
--- a/core/src/main/java/org/jruby/RubyFloat.java
+++ b/core/src/main/java/org/jruby/RubyFloat.java
@@ -63,6 +63,7 @@
import org.jruby.util.Sprintf;
import static org.jruby.api.Convert.asBoolean;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.util.Numeric.f_abs;
import static org.jruby.util.Numeric.f_add;
@@ -301,7 +302,7 @@ public IRubyObject to_s() {
@Override
public IRubyObject coerce(IRubyObject other) {
final Ruby runtime = metaClass.runtime;
- return runtime.newArray(RubyKernel.new_float(runtime, other), this);
+ return runtime.newArray(RubyKernel.new_float(runtime.getCurrentContext(), other), this);
}
/** flo_uminus
@@ -1059,7 +1060,7 @@ private static double doRound(ThreadContext context, RoundingMode roundingMode,
case HALF_EVEN:
return roundHalfEven(number, scale);
}
- throw context.runtime.newArgumentError("invalid rounding mode: " + roundingMode);
+ throw argumentError(context, "invalid rounding mode: " + roundingMode);
}
private static double roundHalfUp(double x, double s) {
diff --git a/core/src/main/java/org/jruby/RubyHash.java b/core/src/main/java/org/jruby/RubyHash.java
index 29fc0a62455..15587d4b150 100644
--- a/core/src/main/java/org/jruby/RubyHash.java
+++ b/core/src/main/java/org/jruby/RubyHash.java
@@ -81,6 +81,7 @@
import static org.jruby.RubyEnumerator.SizeFn;
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.Visibility.PRIVATE;
import static org.jruby.util.Inspector.*;
@@ -173,11 +174,11 @@ public static IRubyObject create(ThreadContext context, IRubyObject recv, IRubyO
IRubyObject key;
IRubyObject val = nil;
if (v == nil) {
- throw runtime.newArgumentError("wrong element type " + e.getMetaClass() + " at " + i + " (expected array)");
+ throw argumentError(context, "wrong element type " + e.getMetaClass() + " at " + i + " (expected array)");
}
switch (((RubyArray) v).getLength()) {
default:
- throw runtime.newArgumentError("invalid number of elements (" + ((RubyArray) v).getLength() + " for 1..2)");
+ throw argumentError(context, "invalid number of elements (" + ((RubyArray) v).getLength() + " for 1..2)");
case 2:
val = ((RubyArray) v).entry(1);
case 1:
@@ -189,9 +190,7 @@ public static IRubyObject create(ThreadContext context, IRubyObject recv, IRubyO
}
}
- if ((args.length & 1) != 0) {
- throw runtime.newArgumentError("odd number of arguments for Hash");
- }
+ if ((args.length & 1) != 0) throw argumentError(context, "odd number of arguments for Hash");
RubyHash hash = (RubyHash) ((RubyClass) recv).allocate();
for (int i=0; i < args.length; i+=2) hash.fastASetCheckString(runtime, args[i], args[i+1]);
@@ -1123,7 +1122,7 @@ protected RubyHash to_h_block(ThreadContext context, Block block) {
RubyArray ary = (RubyArray) keyValue;
if (ary.getLength() != 2) {
- throw context.runtime.newArgumentError("element has wrong array length " + "(expected 2, was " + ary.getLength() + ")");
+ throw argumentError(context, "element has wrong array length " + "(expected 2, was " + ary.getLength() + ")");
}
result.fastASet(ary.eltInternal(0), ary.eltInternal(1));
diff --git a/core/src/main/java/org/jruby/RubyIO.java b/core/src/main/java/org/jruby/RubyIO.java
index debfe8244af..3314516d50b 100644
--- a/core/src/main/java/org/jruby/RubyIO.java
+++ b/core/src/main/java/org/jruby/RubyIO.java
@@ -110,8 +110,8 @@
import static org.jruby.RubyEnumerator.enumeratorize;
import static org.jruby.anno.FrameField.LASTLINE;
import static org.jruby.api.Convert.*;
-import static org.jruby.api.Create.newFixnum;
-import static org.jruby.api.Create.newString;
+import static org.jruby.api.Create.*;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.ThreadContext.*;
import static org.jruby.runtime.Visibility.*;
@@ -442,12 +442,11 @@ public Channel getChannel() {
// io_reopen
protected RubyIO reopenIO(ThreadContext context, RubyIO nfile) {
- Ruby runtime = context.runtime;
OpenFile fptr, orig;
ChannelFD fd, fd2;
long pos = 0;
- nfile = TypeConverter.ioGetIO(runtime, nfile);
+ nfile = TypeConverter.ioGetIO(context.runtime, nfile);
fptr = getOpenFileChecked();
orig = nfile.getOpenFileChecked();
@@ -456,9 +455,12 @@ protected RubyIO reopenIO(ThreadContext context, RubyIO nfile) {
if ((fptr.stdio_file == System.in && !orig.isReadable()) ||
(fptr.stdio_file == System.out && !orig.isWritable()) ||
(fptr.stdio_file == System.err && !orig.isWritable())) {
- throw runtime.newArgumentError(fptr.PREP_STDIO_NAME() + " can't change access mode from \"" + fptr.getModeAsString(runtime) + "\" to \"" + orig.getModeAsString(runtime) + "\"");
+ throw argumentError(context, fptr.PREP_STDIO_NAME() + " can't change access mode from \"" +
+ fptr.getModeAsString(context) + "\" to \"" + orig.getModeAsString(context) + "\"");
}
}
+
+ Ruby runtime = context.runtime;
// FIXME: three lock acquires...trying to reduce risk of deadlock, but not sure it's possible.
boolean locked = fptr.lock();
@@ -638,7 +640,8 @@ public IRubyObject reopen(ThreadContext context, IRubyObject[] args) {
if (fptr.IS_PREP_STDIO() &&
((fptr.getMode() & OpenFile.READWRITE) & (fmode_p[0] & OpenFile.READWRITE)) !=
(fptr.getMode() & OpenFile.READWRITE)) {
- throw runtime.newArgumentError(fptr.PREP_STDIO_NAME() + " can't change access mode from \"" + fptr.getModeAsString(runtime) + "\" to \"" + OpenFile.getStringFromMode(fmode_p[0]));
+ throw argumentError(context, fptr.PREP_STDIO_NAME() + " can't change access mode from \"" +
+ fptr.getModeAsString(context) + "\" to \"" + OpenFile.getStringFromMode(fmode_p[0]));
}
fptr.setMode(fmode_p[0]);
fptr.encs = convconfig;
@@ -952,17 +955,13 @@ private IRubyObject initializeCommon(ThreadContext context, ChannelFD fd, IRubyO
int ofmode;
int[] oflags_p = {ModeFlags.RDONLY};
- if(opt != null && !opt.isNil() && !(opt instanceof RubyHash) && !(sites(context).respond_to_to_hash.respondsTo(context, opt, opt))) {
- throw runtime.newArgumentError("last argument must be a hash!");
+ if (opt != null && !opt.isNil() && !(opt instanceof RubyHash) && !(sites(context).respond_to_to_hash.respondsTo(context, opt, opt))) {
+ throw argumentError(context, "last argument must be a hash!");
}
- if (opt != null && !opt.isNil()) {
- opt = opt.convertToHash();
- }
+ if (opt != null && !opt.isNil()) opt = opt.convertToHash();
- if (!fd.ch.isOpen()) {
- throw runtime.newErrnoEBADFError();
- }
+ if (!fd.ch.isOpen()) throw runtime.newErrnoEBADFError();
IRubyObject vperm = asFixnum(context, 0);
API.ModeAndPermission pm = new API.ModeAndPermission(vmodeArg, vperm);
@@ -1116,13 +1115,13 @@ public IRubyObject set_encoding_by_bom(ThreadContext context) {
fptr = getOpenFile();
if (!fptr.isBinmode()) {
- throw context.runtime.newArgumentError("ASCII incompatible encoding needs binmode");
+ throw argumentError(context, "ASCII incompatible encoding needs binmode");
}
if (getEnc2() != null) {
- throw context.runtime.newArgumentError("encoding conversion is set");
+ throw argumentError(context, "encoding conversion is set");
} else if (getEnc() != null && getEnc() != ASCIIEncoding.INSTANCE) {
- throw context.runtime.newArgumentError("encoding is set to " + getEnc() + " already");
+ throw argumentError(context, "encoding is set to " + getEnc() + " already");
}
if (EncodingUtils.ioSetEncodingByBOM(context, this) == null) return context.nil;
@@ -1250,7 +1249,7 @@ else if (!(intmode = checkToInteger(context, vmode)).isNil())
oflags = asInt(context, (RubyInteger) intmode);
else {
vmode = vmode.convertToString();
- oflags = OpenFile.ioModestrOflags(runtime, vmode.toString());
+ oflags = OpenFile.ioModestrOflags(context, vmode.toString());
}
int perm = (vperm.isNil()) ? 0666 : RubyNumeric.num2int(vperm);
@@ -2652,7 +2651,7 @@ public IRubyObject getline(ThreadContext context, RubyIO self, IRubyObject rs, i
@Override
public RubyIO getline(ThreadContext context, RubyIO self, IRubyObject rs, int limit, boolean chomp, Block block) {
if (limit == 0) {
- throw context.runtime.newArgumentError("invalid limit: 0 for foreach");
+ throw argumentError(context, "invalid limit: 0 for foreach");
}
IRubyObject line;
@@ -3272,12 +3271,9 @@ IRubyObject getPartial(ThreadContext context, IRubyObject[] args, boolean nonblo
private IRubyObject getPartialCommon(ThreadContext context, Ruby runtime, IRubyObject length, IRubyObject str, boolean nonblock, boolean noException) {
OpenFile fptr;
final int len;
- if ( ( len = RubyNumeric.num2int(length) ) < 0 ) {
- throw runtime.newArgumentError("negative length " + len + " given");
- }
+ if ( ( len = RubyNumeric.num2int(length) ) < 0 ) throw argumentError(context, "negative length " + len + " given");
str = EncodingUtils.setStrBuf(runtime, str, len);
-
fptr = getOpenFileChecked();
final boolean locked = fptr.lock();
@@ -3313,7 +3309,7 @@ private IRubyObject getPartialCommon(ThreadContext context, Ruby runtime, IRubyO
if (!nonblock && fptr.waitReadable(context))
continue again;
if (nonblock && (e == Errno.EWOULDBLOCK || e == Errno.EAGAIN)) {
- if (noException) return runtime.newSymbol("wait_readable");
+ if (noException) return newSymbol(context, "wait_readable");
throw runtime.newErrnoEAGAINReadableError("read would block");
}
return nonblockEOF(runtime, noException);
@@ -3484,7 +3480,7 @@ public IRubyObject read(ThreadContext context, IRubyObject length, IRubyObject m
protected void checkLength(ThreadContext context, int len) {
if (len < 0) {
- throw context.runtime.newArgumentError("negative length " + len + " given");
+ throw argumentError(context, "negative length " + len + " given");
}
}
@@ -3651,7 +3647,6 @@ public IRubyObject each_codepoint(ThreadContext context, Block block) {
// rb_io_each_codepoint
private IRubyObject eachCodePointCommon(ThreadContext context, Block block, String methodName) {
- Ruby runtime = context.runtime;
OpenFile fptr;
Encoding enc;
int c;
@@ -3679,25 +3674,23 @@ private IRubyObject eachCodePointCommon(ThreadContext context, Block block, Stri
if (!StringSupport.MBCLEN_NEEDMORE_P(r))
break;
if (fptr.cbuf.len == fptr.cbuf.capa) {
- throw runtime.newIOError("too long character");
+ throw context.runtime.newIOError("too long character");
}
}
if (fptr.moreChar(context) == OpenFile.MORE_CHAR_FINISHED) {
fptr.clearReadConversion();
if (!StringSupport.MBCLEN_CHARFOUND_P(r)) {
- enc = fptr.encs.enc;
- throw runtime.newArgumentError("invalid byte sequence in " + enc);
+ throw argumentError(context, "invalid byte sequence in " + fptr.encs.enc);
}
return this;
}
}
if (StringSupport.MBCLEN_INVALID_P(r)) {
- enc = fptr.encs.enc;
- throw runtime.newArgumentError("invalid byte sequence in " + enc);
+ throw argumentError(context, "invalid byte sequence in " + fptr.encs.enc);
}
n = StringSupport.MBCLEN_CHARFOUND_LEN(r);
if (fptr.encs.enc != null) {
- c = StringSupport.codePoint(runtime, fptr.encs.enc, fptr.cbuf.ptr, fptr.cbuf.off, fptr.cbuf.off + fptr.cbuf.len);
+ c = StringSupport.codePoint(context, fptr.encs.enc, fptr.cbuf.ptr, fptr.cbuf.off, fptr.cbuf.off + fptr.cbuf.len);
}
else {
c = fptr.cbuf.ptr[fptr.cbuf.off] & 0xFF;
@@ -3708,33 +3701,33 @@ private IRubyObject eachCodePointCommon(ThreadContext context, Block block, Stri
}
}
fptr.NEED_NEWLINE_DECORATOR_ON_READ_CHECK();
- enc = fptr.inputEncoding(runtime);
+ enc = fptr.inputEncoding(context.runtime);
while (fptr.fillbuf(context) >= 0) {
r = StringSupport.preciseLength(enc, fptr.rbuf.ptr, fptr.rbuf.off, fptr.rbuf.off + fptr.rbuf.len);
if (StringSupport.MBCLEN_CHARFOUND_P(r) &&
(n = StringSupport.MBCLEN_CHARFOUND_LEN(r)) <= fptr.rbuf.len) {
- c = StringSupport.codePoint(runtime, enc, fptr.rbuf.ptr, fptr.rbuf.off, fptr.rbuf.off + fptr.rbuf.len);
+ c = StringSupport.codePoint(context, enc, fptr.rbuf.ptr, fptr.rbuf.off, fptr.rbuf.off + fptr.rbuf.len);
fptr.rbuf.off += n;
fptr.rbuf.len -= n;
block.yield(context, asFixnum(context, c & 0xFFFFFFFF));
} else if (StringSupport.MBCLEN_INVALID_P(r)) {
- throw runtime.newArgumentError("invalid byte sequence in " + enc);
+ throw argumentError(context, "invalid byte sequence in " + enc);
} else if (StringSupport.MBCLEN_NEEDMORE_P(r)) {
byte[] cbuf = new byte[8];
int p = 0;
int more = StringSupport.MBCLEN_NEEDMORE_LEN(r);
- if (more > cbuf.length) throw runtime.newArgumentError("invalid byte sequence in " + enc);
+ if (more > cbuf.length) throw argumentError(context, "invalid byte sequence in " + enc);
more += n = fptr.rbuf.len;
- if (more > cbuf.length) throw runtime.newArgumentError("invalid byte sequence in " + enc);
+ if (more > cbuf.length) throw argumentError(context, "invalid byte sequence in " + enc);
while ((n = fptr.readBufferedData(cbuf, p, more)) > 0) {
p += n;
if ((more -= n) <= 0) break;
- if (fptr.fillbuf(context) < 0) throw runtime.newArgumentError("invalid byte sequence in " + enc);
+ if (fptr.fillbuf(context) < 0) throw argumentError(context, "invalid byte sequence in " + enc);
if ((n = fptr.rbuf.len) > more) n = more;
}
r = enc.length(cbuf, 0, p);
- if (!StringSupport.MBCLEN_CHARFOUND_P(r)) throw runtime.newArgumentError("invalid byte sequence in " + enc);
+ if (!StringSupport.MBCLEN_CHARFOUND_P(r)) throw argumentError(context, "invalid byte sequence in " + enc);
c = enc.mbcToCode(cbuf, 0, p);
block.yield(context, asFixnum(context, c));
} else {
@@ -3991,7 +3984,7 @@ public static IRubyObject select(ThreadContext context, IRubyObject recv, IRubyO
throw e; // won't happen
}
final double t = _timeout.convertToFloat().getDoubleValue();
- if ( t < 0 ) throw context.runtime.newArgumentError("negative timeout");
+ if ( t < 0 ) throw argumentError(context, "negative timeout");
timeout = (long) (t * 1000); // ms
}
@@ -4053,7 +4046,7 @@ public IRubyObject wait(ThreadContext context, IRubyObject[] argv) {
ops |= SelectionKey.OP_ACCEPT | SelectionKey.OP_READ | SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE;
break;
default:
- throw context.runtime.newArgumentError("unsupported mode: " + sym);
+ throw argumentError(context, "unsupported mode: " + sym);
}
} else if (argv[1] instanceof RubyFixnum) {
RubyFixnum fix = (RubyFixnum) argv[1];
@@ -4064,7 +4057,7 @@ public IRubyObject wait(ThreadContext context, IRubyObject[] argv) {
ops |= SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE;
}
} else {
- throw context.runtime.newArgumentError("unsupported mode: " + argv[1].getType());
+ throw argumentError(context, "unsupported mode: " + argv[1].getType());
}
} else {
ops |= SelectionKey.OP_ACCEPT | SelectionKey.OP_READ;
@@ -4101,7 +4094,7 @@ private static long prepareTimeout(ThreadContext context, IRubyObject[] argv) {
}
else {
tv = (long)(RubyTime.convertTimeInterval(context, timeout) * 1000);
- if (tv < 0) throw context.runtime.newArgumentError("time interval must be positive");
+ if (tv < 0) throw argumentError(context, "time interval must be positive");
}
return tv;
}
@@ -4252,9 +4245,9 @@ private static RubyIO ioOpenGeneric(ThreadContext context, IRubyObject recv, IRu
if ((recv == runtime.getIO()) && (cmd = PopenExecutor.checkPipeCommand(context, filename)) != context.nil) {
runtime.getWarnings().warn("IO process creation with a leading '|' is deprecated and will be removed in Ruby 4.0; use IO.popen instead");
if (PopenExecutor.nativePopenAvailable(runtime)) {
- return (RubyIO) PopenExecutor.pipeOpen(context, cmd, OpenFile.ioOflagsModestr(runtime, oflags), fmode, convconfig);
+ return (RubyIO) PopenExecutor.pipeOpen(context, cmd, OpenFile.ioOflagsModestr(context, oflags), fmode, convconfig);
} else {
- throw runtime.newArgumentError("pipe open is not supported without native subprocess logic");
+ throw argumentError(context, "pipe open is not supported without native subprocess logic");
}
}
return (RubyIO) ((RubyFile) runtime.getFile().allocate()).fileOpenGeneric(context, filename, oflags, fmode, convconfig, perm);
@@ -4712,7 +4705,7 @@ public static IRubyObject pipe(ThreadContext context, IRubyObject klass, IRubyOb
fptr2 = w.getOpenFileChecked();
fptr2.setSync(true);
- EncodingUtils.extractBinmode(runtime, opt, fmode_p);
+ EncodingUtils.extractBinmode(context, opt, fmode_p);
if (EncodingUtils.DEFAULT_TEXTMODE != 0) {
if ((fptr.getMode() & OpenFile.TEXTMODE) != 0 && (fmode_p[0] & OpenFile.BINMODE) != 0) {
@@ -4812,7 +4805,7 @@ private static RubyFixnum copyStreamCommon(ThreadContext context, IRubyObject ar
try {
if (arg1 == runtime.getArgsFile() || !(arg1 instanceof RubyFile || arg1 instanceof RubyString || arg1.respondsTo("to_path"))) {
if (offset != null) {
- throw Error.argumentError(context, "cannot specify src_offset for non-IO");
+ throw argumentError(context, "cannot specify src_offset for non-IO");
}
if (sites.respond_to_readpartial.respondsTo(context, arg1, arg1, true)) {
@@ -5179,10 +5172,10 @@ public static IRubyObject wait(ThreadContext context, IRubyObject _io, IRubyObje
ops |= SelectionKey.OP_ACCEPT | SelectionKey.OP_READ | SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE;
break;
default:
- throw context.runtime.newArgumentError("unsupported mode: " + sym);
+ throw argumentError(context, "unsupported mode: " + sym);
}
} else {
- throw context.runtime.newArgumentError("unsupported mode: " + argv[1].getType());
+ throw argumentError(context, "unsupported mode: " + argv[1].getType());
}
} else {
ops |= SelectionKey.OP_ACCEPT | SelectionKey.OP_READ;
@@ -5377,12 +5370,12 @@ static void checkValidSpawnOptions(ThreadContext context, RubyHash opts) {
for (Object opt : opts.directKeySet()) {
if (opt instanceof RubySymbol) {
if (!ALL_SPAWN_OPTIONS.contains(((RubySymbol) opt).idString())) {
- throw context.runtime.newArgumentError("wrong exec option symbol: " + opt);
+ throw argumentError(context, "wrong exec option symbol: " + opt);
}
}
else if (opt instanceof RubyString) {
if (!ALL_SPAWN_OPTIONS.contains(((RubyString) opt).toString())) {
- throw context.runtime.newArgumentError("wrong exec option: " + opt);
+ throw argumentError(context, "wrong exec option: " + opt);
}
}
}
@@ -5867,7 +5860,7 @@ public IRubyObject write_nonblock(ThreadContext context, IRubyObject[] argv) {
case 2:
return write_nonblock(context, argv[0], argv[1]);
default:
- throw context.runtime.newArgumentError(argv.length, 1, 2);
+ throw argumentError(context, argv.length, 1, 2);
}
}
@@ -5921,7 +5914,7 @@ public static IRubyObject pipe(ThreadContext context, IRubyObject klass, IRubyOb
case 3:
return pipe(context, klass, argv[0], argv[1], argv[2], block);
default:
- throw context.runtime.newArgumentError(argv.length, 0, 3);
+ throw argumentError(context, argv.length, 0, 3);
}
}
diff --git a/core/src/main/java/org/jruby/RubyIOBuffer.java b/core/src/main/java/org/jruby/RubyIOBuffer.java
index e8608d595e1..db38d2d5e72 100644
--- a/core/src/main/java/org/jruby/RubyIOBuffer.java
+++ b/core/src/main/java/org/jruby/RubyIOBuffer.java
@@ -27,8 +27,8 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
-import static org.jruby.api.Create.newFixnum;
-import static org.jruby.api.Create.newString;
+import static org.jruby.api.Create.*;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
public class RubyIOBuffer extends RubyObject {
@@ -80,6 +80,12 @@ public static RubyClass createIOBufferClass(Ruby runtime) {
@JRubyConstant
public static final int NETWORK_ENDIAN = BIG_ENDIAN;
+ public static RubyIOBuffer newBuffer(ThreadContext context, ByteBuffer base, int size, int flags) {
+ if (base == null) return newBuffer(context.runtime, size, flags);
+
+ return new RubyIOBuffer(context.runtime, context.runtime.getIOBuffer(), base, size, flags);
+ }
+
public static RubyIOBuffer newBuffer(Ruby runtime, ByteBuffer base, int size, int flags) {
if (base == null) return newBuffer(runtime, size, flags);
@@ -94,7 +100,7 @@ public static RubyIOBuffer newBuffer(ThreadContext context, RubyString string, i
ByteList bytes = string.getByteList();
int size = bytes.realSize();
- return newBuffer(context.runtime, ByteBuffer.wrap(bytes.unsafeBytes(), bytes.begin(), size), size, flags);
+ return newBuffer(context, ByteBuffer.wrap(bytes.unsafeBytes(), bytes.begin(), size), size, flags);
}
public RubyIOBuffer(Ruby runtime, RubyClass metaClass) {
@@ -137,15 +143,13 @@ public static IRubyObject rbFor(ThreadContext context, IRubyObject self, IRubyOb
@JRubyMethod(meta = true)
public static IRubyObject string(ThreadContext context, IRubyObject self, IRubyObject _length, Block block) {
- Ruby runtime = context.runtime;
-
int size = _length.convertToInteger().getIntValue();
- if (size < 0) throw runtime.newArgumentError("negative string size (or size too big)");
- RubyString string = RubyString.newString(runtime, new byte[size]);
+ if (size < 0) throw argumentError(context, "negative string size (or size too big)");
+ RubyString string = RubyString.newString(context.runtime, new byte[size]);
ByteList bytes = string.getByteList();
ByteBuffer wrap = ByteBuffer.wrap(bytes.unsafeBytes(), bytes.begin(), size);
- RubyIOBuffer buffer = newBuffer(context.runtime, wrap, size, 0);
+ RubyIOBuffer buffer = newBuffer(context, wrap, size, 0);
block.yieldSpecific(context, buffer);
@@ -201,22 +205,14 @@ private static int getSizeForMap(ThreadContext context, RubyFile file, IRubyObje
}
private static int getSizeFromFile(ThreadContext context, RubyFile _file) {
- int size;
long file_size = _file.getSize(context);
+ if (file_size < 0) throw argumentError(context, "Invalid negative file size!");
- // Compiler can confirm that we handled file_size < 0 case:
- if (file_size < 0) {
- throw context.runtime.newArgumentError("Invalid negative file size!");
- }
// Here, we assume that file_size is positive:
- else if (file_size > Integer.MAX_VALUE) {
- throw context.runtime.newArgumentError("File larger than address space!");
- }
- else {
- // This conversion should be safe:
- size = (int) file_size;
- }
- return size;
+ if (file_size > Integer.MAX_VALUE) throw argumentError(context, "File larger than address space!");
+
+ // This conversion should be safe:
+ return (int) file_size;
}
@JRubyMethod(name = "map", required = 1, optional = 3, meta = true)
@@ -676,10 +672,7 @@ public IRubyObject slice(ThreadContext context) {
@JRubyMethod(name = "slice")
public IRubyObject slice(ThreadContext context, IRubyObject _offset) {
int offset = RubyNumeric.num2int(_offset);
-
- if (offset < 0) {
- throw context.runtime.newArgumentError("Offset can't be negative!");
- }
+ if (offset < 0) throw argumentError(context, "Offset can't be negative!");
return slice(context, offset, size - offset);
}
@@ -687,16 +680,10 @@ public IRubyObject slice(ThreadContext context, IRubyObject _offset) {
@JRubyMethod(name = "slice")
public IRubyObject slice(ThreadContext context, IRubyObject _offset, IRubyObject _length) {
int offset = RubyNumeric.num2int(_offset);
+ if (offset < 0) throw argumentError(context, "Offset can't be negative!");
- if (offset < 0) {
- throw context.runtime.newArgumentError("Offset can't be negative!");
- }
-
int length = RubyNumeric.num2int(_length);
-
- if (length < 0) {
- throw context.runtime.newArgumentError("Length can't be negative!");
- }
+ if (length < 0) throw argumentError(context, "Length can't be negative!");
return slice(context, offset, length);
}
@@ -711,14 +698,12 @@ public IRubyObject slice(ThreadContext context, int offset, int length) {
ByteBuffer slice = base.slice();
base.clear();
- return newBuffer(context.runtime, slice, length, flags);
+ return newBuffer(context, slice, length, flags);
}
// MRI: io_buffer_validate_range
private void validateRange(ThreadContext context, int offset, int length) {
- if (offset + length > size) {
- throw context.runtime.newArgumentError("Specified offset+length is bigger than the buffer size!");
- }
+ if (offset + length > size) throw argumentError(context, "Specified offset+length is bigger than the buffer size!");
}
@JRubyMethod(name = "<=>")
@@ -788,14 +773,9 @@ public IRubyObject clear(ThreadContext context, IRubyObject _value, IRubyObject
// MRI: rb_io_buffer_clear
private IRubyObject clear(ThreadContext context, int value, int offset, int length) {
ByteBuffer buffer = getBufferForWriting(context);
+ if (offset + length > size) throw argumentError(context, "The given offset + length out of bounds!");
- if (offset + length > size) {
- throw context.runtime.newArgumentError("The given offset + length out of bounds!");
- }
-
- if (buffer.hasArray()) {
- Arrays.fill(buffer.array(), offset, offset + length, (byte) value);
- }
+ if (buffer.hasArray()) Arrays.fill(buffer.array(), offset, offset + length, (byte) value);
return this;
}
@@ -1018,16 +998,16 @@ private static void writeDouble(ThreadContext context, ByteBuffer buffer, int of
buffer.putDouble(offset, Double.longBitsToDouble(Long.reverseBytes(Double.doubleToLongBits(value))));
}
- private static IRubyObject wrap(Ruby runtime, long value) {
- return RubyFixnum.newFixnum(runtime, value);
+ private static IRubyObject wrap(ThreadContext context, long value) {
+ return newFixnum(context, value);
}
- private static IRubyObject wrap(Ruby runtime, BigInteger value) {
- return RubyBignum.newBignum(runtime, value);
+ private static IRubyObject wrap(ThreadContext context, BigInteger value) {
+ return RubyBignum.newBignum(context.runtime, value);
}
- private static IRubyObject wrap(Ruby runtime, double value) {
- return RubyFloat.newFloat(runtime, value);
+ private static IRubyObject wrap(ThreadContext context, double value) {
+ return newFloat(context, value);
}
private static long unwrapLong(IRubyObject value) {
@@ -1054,74 +1034,66 @@ public IRubyObject get_value(ThreadContext context, IRubyObject type, IRubyObjec
}
private static IRubyObject getValue(ThreadContext context, ByteBuffer buffer, int size, DataType dataType, int offset) {
- Ruby runtime = context.runtime;
-
// TODO: validate size
switch (dataType) {
case S8:
- return wrap(runtime, readByte(context, buffer, offset));
+ return wrap(context, readByte(context, buffer, offset));
case U8:
- return wrap(runtime, readUnsignedByte(context, buffer, offset));
+ return wrap(context, readUnsignedByte(context, buffer, offset));
case u16:
- return wrap(runtime, readUnsignedShort(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
+ return wrap(context, readUnsignedShort(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
case U16:
- return wrap(runtime, readUnsignedShort(context, buffer, offset, ByteOrder.BIG_ENDIAN));
+ return wrap(context, readUnsignedShort(context, buffer, offset, ByteOrder.BIG_ENDIAN));
case s16:
- return wrap(runtime, readShort(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
+ return wrap(context, readShort(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
case S16:
- return wrap(runtime, readShort(context, buffer, offset, ByteOrder.BIG_ENDIAN));
+ return wrap(context, readShort(context, buffer, offset, ByteOrder.BIG_ENDIAN));
case u32:
- return wrap(runtime, readUnsignedInt(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
+ return wrap(context, readUnsignedInt(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
case U32:
- return wrap(runtime, readUnsignedInt(context, buffer, offset, ByteOrder.BIG_ENDIAN));
+ return wrap(context, readUnsignedInt(context, buffer, offset, ByteOrder.BIG_ENDIAN));
case s32:
- return wrap(runtime, readInt(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
+ return wrap(context, readInt(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
case S32:
- return wrap(runtime, readInt(context, buffer, offset, ByteOrder.BIG_ENDIAN));
+ return wrap(context, readInt(context, buffer, offset, ByteOrder.BIG_ENDIAN));
case u64:
- return wrap(runtime, readUnsignedLong(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
+ return wrap(context, readUnsignedLong(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
case U64:
- return wrap(runtime, readUnsignedLong(context, buffer, offset, ByteOrder.BIG_ENDIAN));
+ return wrap(context, readUnsignedLong(context, buffer, offset, ByteOrder.BIG_ENDIAN));
case s64:
- return wrap(runtime, readLong(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
+ return wrap(context, readLong(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
case S64:
- return wrap(runtime, readLong(context, buffer, offset, ByteOrder.BIG_ENDIAN));
+ return wrap(context, readLong(context, buffer, offset, ByteOrder.BIG_ENDIAN));
case f32:
- return wrap(runtime, readFloat(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
+ return wrap(context, readFloat(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
case F32:
- return wrap(runtime, readFloat(context, buffer, offset, ByteOrder.BIG_ENDIAN));
+ return wrap(context, readFloat(context, buffer, offset, ByteOrder.BIG_ENDIAN));
case f64:
- return wrap(runtime, readDouble(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
+ return wrap(context, readDouble(context, buffer, offset, ByteOrder.LITTLE_ENDIAN));
case F64:
- return wrap(runtime, readDouble(context, buffer, offset, ByteOrder.BIG_ENDIAN));
+ return wrap(context, readDouble(context, buffer, offset, ByteOrder.BIG_ENDIAN));
}
- throw runtime.newArgumentError("Unknown data_type: " + dataType); // should never happen
+ throw argumentError(context, "Unknown data_type: " + dataType); // should never happen
}
@JRubyMethod(name = "get_values")
public IRubyObject get_values(ThreadContext context, IRubyObject dataTypes, IRubyObject _offset) {
- Ruby runtime = context.runtime;
-
int offset = RubyNumeric.num2int(_offset);
-
int size = this.size;
-
ByteBuffer buffer = getBufferForReading(context);
- if (!(dataTypes instanceof RubyArray)) {
- throw runtime.newArgumentError("Argument data_types should be an array!");
+ if (!(dataTypes instanceof RubyArray dataTypesArray)) {
+ throw argumentError(context, "Argument data_types should be an array!");
}
- RubyArray> dataTypesArray = (RubyArray>) dataTypes;
int dataTypesSize = dataTypesArray.size();
- RubyArray values = RubyArray.newArray(runtime, dataTypesSize);
+ RubyArray values = RubyArray.newArray(context.runtime, dataTypesSize);
for (long i = 0; i < dataTypesSize; i++) {
IRubyObject type = dataTypesArray.eltOk(i);
DataType dataType = getDataType(type);
-
IRubyObject value = getValue(context, buffer, size, dataType, offset);
offset += dataType.type.size();
@@ -1254,7 +1226,7 @@ private IRubyObject eachByte(ThreadContext context, ByteBuffer buffer, int offse
Ruby runtime = context.runtime;
for (int i = 0 ; i < count; i++) {
- IRubyObject value = wrap(runtime, readByte(context, buffer, offset + i));
+ IRubyObject value = wrap(context, readByte(context, buffer, offset + i));
block.yieldSpecific(context, value);
}
@@ -1321,7 +1293,7 @@ private static void setValue(ThreadContext context, ByteBuffer buffer, int size,
return;
}
- throw context.runtime.newArgumentError("Unknown data_type: " + dataType); // should never happen
+ throw argumentError(context, "Unknown data_type: " + dataType); // should never happen
}
@JRubyMethod(name = "set_value")
@@ -1339,26 +1311,20 @@ public IRubyObject set_value(ThreadContext context, IRubyObject _dataType, IRuby
@JRubyMethod(name = "set_values")
public IRubyObject set_values(ThreadContext context, IRubyObject _dataTypes, IRubyObject _offset, IRubyObject _values) {
- Ruby runtime = context.runtime;
-
int offset = RubyNumeric.num2int(_offset);
-
int size = this.size;
-
ByteBuffer buffer = getBufferForWriting(context);
- if (!(_dataTypes instanceof RubyArray)) {
- throw runtime.newArgumentError("Argument data_types should be an array!");
+ if (!(_dataTypes instanceof RubyArray dataTypes)) {
+ throw argumentError(context, "Argument data_types should be an array!");
}
- RubyArray> dataTypes = (RubyArray>) _dataTypes;
- if (!(_values instanceof RubyArray)) {
- throw runtime.newArgumentError("Argument values should be an array!");
+ if (!(_values instanceof RubyArray values)) {
+ throw argumentError(context, "Argument values should be an array!");
}
- RubyArray> values = (RubyArray>) _values;
if (dataTypes.size() != values.size()) {
- throw runtime.newArgumentError("Argument data_types and values should have the same length!");
+ throw argumentError(context, "Argument data_types and values should have the same length!");
}
int dataTypesSize = dataTypes.size();
@@ -1366,7 +1332,6 @@ public IRubyObject set_values(ThreadContext context, IRubyObject _dataTypes, IRu
for (long i = 0; i < dataTypesSize; i++) {
IRubyObject type = dataTypes.eltOk(i);
DataType dataType = getDataType(type);
-
IRubyObject value = values.eltOk(i);
setValue(context, buffer, size, dataType, offset, value);
@@ -1374,7 +1339,7 @@ public IRubyObject set_values(ThreadContext context, IRubyObject _dataTypes, IRu
offset += dataType.type.size();
}
- return RubyFixnum.newFixnum(runtime, offset);
+ return newFixnum(context, offset);
}
@JRubyMethod(name = "copy")
@@ -1433,7 +1398,7 @@ public IRubyObject copy(ThreadContext context, IRubyObject source, IRubyObject _
public IRubyObject copy(ThreadContext context, RubyIOBuffer source, int offset, int length, int sourceOffset) {
if (sourceOffset > length) {
- throw context.runtime.newArgumentError("The given source offset is bigger than the source itself!");
+ throw argumentError(context, "The given source offset is bigger than the source itself!");
}
ByteBuffer sourceBuffer = source.getBufferForReading(context);
@@ -1446,7 +1411,7 @@ public IRubyObject copy(ThreadContext context, RubyIOBuffer source, int offset,
// MRI: io_buffer_copy_from
public IRubyObject copy(ThreadContext context, RubyString source, int offset, int length, int sourceOffset) {
if (sourceOffset > length) {
- throw context.runtime.newArgumentError("The given source offset is bigger than the source itself!");
+ throw argumentError(context, "The given source offset is bigger than the source itself!");
}
bufferCopy(context, offset, source.getByteList(), sourceOffset, source.size(), length);
@@ -1969,7 +1934,7 @@ private static IRubyObject preadInternal(ThreadContext context, RubyIO io, ByteB
private int extractLength(ThreadContext context, IRubyObject _length, int offset) {
if (!_length.isNil()) {
if (RubyNumeric.negativeInt(context, _length)) {
- throw context.runtime.newArgumentError("Length can't be negative!");
+ throw argumentError(context, "Length can't be negative!");
}
return RubyNumeric.num2int(_length);
@@ -1980,7 +1945,7 @@ private int extractLength(ThreadContext context, IRubyObject _length, int offset
private int defaultLength(ThreadContext context, int offset) {
if (offset > size) {
- throw context.runtime.newArgumentError("The given offset is bigger than the buffer size!");
+ throw argumentError(context, "The given offset is bigger than the buffer size!");
}
// Note that the "length" is computed by the size the offset.
@@ -1990,7 +1955,7 @@ private int defaultLength(ThreadContext context, int offset) {
// MRI: offset parts of io_buffer_extract_length_offset and io_buffer_extract_offset
private static int extractOffset(ThreadContext context, IRubyObject _offset) {
if (RubyNumeric.negativeInt(context, _offset)) {
- throw context.runtime.newArgumentError("Offset can't be negative!");
+ throw argumentError(context, "Offset can't be negative!");
}
return RubyNumeric.num2int(_offset);
@@ -1998,7 +1963,7 @@ private static int extractOffset(ThreadContext context, IRubyObject _offset) {
private static int extractSize(ThreadContext context, IRubyObject _size) {
if (RubyNumeric.negativeInt(context, _size)) {
- throw context.runtime.newArgumentError("Size can't be negative!");
+ throw argumentError(context, "Size can't be negative!");
}
return RubyNumeric.num2int(_size);
diff --git a/core/src/main/java/org/jruby/RubyInteger.java b/core/src/main/java/org/jruby/RubyInteger.java
index e0f19f681aa..31b78c54bfd 100644
--- a/core/src/main/java/org/jruby/RubyInteger.java
+++ b/core/src/main/java/org/jruby/RubyInteger.java
@@ -62,6 +62,7 @@
import static org.jruby.RubyEnumerator.SizeFn;
import static org.jruby.RubyEnumerator.enumeratorizeWithSize;
import static org.jruby.api.Convert.*;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.util.Numeric.f_gcd;
import static org.jruby.util.Numeric.f_lcm;
@@ -654,7 +655,7 @@ private static long doRound(ThreadContext context, RoundingMode roundingMode, lo
case HALF_EVEN:
return int_round_half_even(n, f);
}
- throw context.runtime.newArgumentError("invalid rounding mode: " + roundingMode);
+ throw argumentError(context, "invalid rounding mode: " + roundingMode);
}
private static boolean doRoundCheck(ThreadContext context, RoundingMode roundingMode, RubyInteger num, RubyNumeric n, IRubyObject f) {
@@ -666,7 +667,7 @@ private static boolean doRoundCheck(ThreadContext context, RoundingMode rounding
case HALF_EVEN:
return int_half_p_half_even(context, num, n, f);
}
- throw context.runtime.newArgumentError("invalid rounding mode: " + roundingMode);
+ throw argumentError(context, "invalid rounding mode: " + roundingMode);
}
protected boolean int_round_zero_p(ThreadContext context, int ndigits) {
@@ -674,12 +675,9 @@ protected boolean int_round_zero_p(ThreadContext context, int ndigits) {
return (-0.415241 * ndigits - 0.125 > bytes);
}
- protected static long int_round_half_even(long x, long y)
- {
+ protected static long int_round_half_even(long x, long y) {
long z = +(x + y / 2) / y;
- if ((z * y - x) * 2 == y) {
- z &= ~1;
- }
+ if ((z * y - x) * 2 == y) z &= ~1;
return z * y;
}
@@ -988,16 +986,12 @@ public IRubyObject op_aref(ThreadContext context, IRubyObject index) {
if (beg.isNil()) {
if (!negativeInt(context, end)) {
- if (!isExclusive) {
- end = ((RubyInteger) end).op_plus(context, asFixnum(context, 1));
- }
+ if (!isExclusive) end = ((RubyInteger) end).op_plus(context, asFixnum(context, 1));
RubyInteger mask = generateMask(context, end);
- if (((RubyInteger) op_and(context, mask)).isZero()) {
- return asFixnum(context, 0);
- } else {
- throw context.runtime.newArgumentError("The beginless range for Integer#[] results in infinity");
- }
+ if (((RubyInteger) op_and(context, mask)).isZero()) return asFixnum(context, 0);
+
+ throw argumentError(context, "The beginless range for Integer#[] results in infinity");
} else {
return asFixnum(context, 0);
}
diff --git a/core/src/main/java/org/jruby/RubyKernel.java b/core/src/main/java/org/jruby/RubyKernel.java
index c460e65e7f5..4768c7a7d8f 100644
--- a/core/src/main/java/org/jruby/RubyKernel.java
+++ b/core/src/main/java/org/jruby/RubyKernel.java
@@ -111,7 +111,8 @@
import static org.jruby.anno.FrameField.VISIBILITY;
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
-import static org.jruby.api.Create.newString;
+import static org.jruby.api.Create.*;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.ir.runtime.IRRuntimeHelpers.dupIfKeywordRestAtCallsite;
import static org.jruby.runtime.ThreadContext.hasKeywords;
@@ -179,7 +180,7 @@ static void recacheBuiltinMethods(Ruby runtime, RubyModule kernelModule) {
@JRubyMethod(module = true, visibility = PRIVATE)
public static IRubyObject at_exit(ThreadContext context, IRubyObject recv, Block block) {
- if (!block.isGiven()) throw context.runtime.newArgumentError("called without a block");
+ if (!block.isGiven()) throw argumentError(context, "called without a block");
return context.runtime.pushExitBlock(context.runtime.newProc(Block.Type.PROC, block));
}
@@ -188,11 +189,8 @@ public static IRubyObject at_exit(ThreadContext context, IRubyObject recv, Block
public static IRubyObject autoload_p(ThreadContext context, final IRubyObject recv, IRubyObject symbol) {
RubyModule module = IRRuntimeHelpers.getCurrentClassBase(context, recv);
- if (module == null || module.isNil()) {
- return context.nil;
- }
-
- return module.autoload_p(context, symbol);
+ return module == null || module.isNil() ?
+ context.nil : module.autoload_p(context, symbol);
}
@JRubyMethod(required = 2, module = true, visibility = PRIVATE, reads = {SCOPE})
@@ -208,11 +206,9 @@ public static IRubyObject method_missing(ThreadContext context, IRubyObject recv
Visibility lastVis = context.getLastVisibility();
CallType lastCallType = context.getLastCallType();
- if (args.length == 0 || !(args[0] instanceof RubySymbol)) {
- throw context.runtime.newArgumentError("no id given");
- }
+ if (args.length == 0 || !(args[0] instanceof RubySymbol sym)) throw argumentError(context, "no id given");
- return methodMissingDirect(context, recv, (RubySymbol) args[0], lastVis, lastCallType, args);
+ return methodMissingDirect(context, recv, sym, lastVis, lastCallType, args);
}
protected static IRubyObject methodMissingDirect(ThreadContext context, IRubyObject recv, RubySymbol symbol, Visibility lastVis, CallType lastCallType, IRubyObject[] args) {
@@ -258,7 +254,6 @@ private static String getMethodMissingFormat(Visibility visibility, CallType cal
@JRubyMethod(name = "open", required = 1, optional = 3, checkArity = false, module = true, visibility = PRIVATE, keywords = true)
public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
- Ruby runtime = context.runtime;
boolean redirect = false;
int callInfo = ThreadContext.resetCallInfo(context);
boolean keywords = hasKeywords(callInfo);
@@ -275,12 +270,12 @@ public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObj
} else {
IRubyObject cmd = PopenExecutor.checkPipeCommand(context, tmp);
if (cmd != context.nil) {
- if (PopenExecutor.nativePopenAvailable(runtime)) {
+ if (PopenExecutor.nativePopenAvailable(context.runtime)) {
args[0] = cmd;
- return PopenExecutor.popen(context, args, runtime.getIO(), block);
- } else {
- throw runtime.newArgumentError("pipe open is not supported without native subprocess logic");
+ return PopenExecutor.popen(context, args, context.runtime.getIO(), block);
}
+
+ throw argumentError(context, "pipe open is not supported without native subprocess logic");
}
}
}
@@ -302,7 +297,7 @@ public static IRubyObject open(ThreadContext context, IRubyObject recv, IRubyObj
// We had to save callInfo from original call because kwargs needs to still pass through to IO#open
context.callInfo = callInfo;
- return RubyIO.open(context, runtime.getFile(), args, block);
+ return RubyIO.open(context, context.runtime.getFile(), args, block);
}
@JRubyMethod(module = true, visibility = PRIVATE)
@@ -397,39 +392,45 @@ public static IRubyObject new_float(ThreadContext context, IRubyObject recv, IRu
}
private static boolean checkExceptionOpt(ThreadContext context, RubyClass rubyClass, IRubyObject opts) {
- boolean exception = true;
-
IRubyObject maybeOpts = ArgsUtil.getOptionsArg(context.runtime, opts, false);
+ if (maybeOpts.isNil()) return true;
- if (!maybeOpts.isNil()) {
- IRubyObject exObj = ArgsUtil.extractKeywordArg(context, opts, "exception");
+ IRubyObject exObj = ArgsUtil.extractKeywordArg(context, opts, "exception");
- if (exObj != context.tru && exObj != context.fals) {
- throw context.runtime.newArgumentError("'" + rubyClass.getName() + "': expected true or false as exception: " + exObj);
- }
- exception = exObj.isTrue();
+ if (exObj != context.tru && exObj != context.fals) {
+ throw argumentError(context, "'" + rubyClass.getName() + "': expected true or false as exception: " + exObj);
}
- return exception;
+ return exObj.isTrue();
}
+ @Deprecated(since = "10.0", forRemoval = true)
public static RubyFloat new_float(IRubyObject recv, IRubyObject object) {
return (RubyFloat) new_float(recv.getRuntime().getCurrentContext(), object, true);
}
private static final ByteList ZEROx = new ByteList(new byte[] { '0','x' }, false);
+ @Deprecated(since = "10.0", forRemoval = true)
public static RubyFloat new_float(final Ruby runtime, IRubyObject object) {
return (RubyFloat) new_float(runtime.getCurrentContext(), object, true);
}
+ public static RubyFloat new_float(ThreadContext context, IRubyObject object) {
+ return (RubyFloat) new_float(context, object, true);
+ }
+
private static BigInteger SIXTEEN = BigInteger.valueOf(16L);
private static BigInteger MINUS_ONE = BigInteger.valueOf(-1L);
- private static RaiseException floatError(Ruby runtime, ByteList string) {
- throw runtime.newArgumentError(str(runtime, "invalid value for Float(): ", runtime.newString(string)));
+ private static RaiseException floatError(ThreadContext context, ByteList string) {
+ throw argumentError(context, str(context.runtime, "invalid value for Float(): ", newString(context, string)));
}
+ @Deprecated(since = "10.0", forRemoval = true)
+ public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str) {
+ return parseHexidecimalExponentString2(runtime.getCurrentContext(), str);
+ }
/**
* Parse hexidecimal exponential notation:
* ...
@@ -439,10 +440,11 @@ private static RaiseException floatError(Ruby runtime, ByteList string) {
* @param str the bytelist to be parsed
* @return the result.
*/
- public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str) {
+
+ public static double parseHexidecimalExponentString2(ThreadContext context, ByteList str) {
byte[] bytes = str.unsafeBytes();
int length = str.length();
- if (length <= 2) throw floatError(runtime, str);
+ if (length <= 2) throw floatError(context, str);
int sign = 1;
int letter;
int i = str.begin();
@@ -457,9 +459,9 @@ public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str)
// Skip '0x'
letter = bytes[i++];
- if (letter != '0') throw floatError(runtime, str);
+ if (letter != '0') throw floatError(context, str);
letter = bytes[i++];
- if (letter != 'x') throw floatError(runtime, str);
+ if (letter != 'x') throw floatError(context, str);
int exponent = 0;
int explicitExponent = 0;
@@ -468,7 +470,7 @@ public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str)
boolean explicitExponentFound = false;
BigInteger value = BigInteger.valueOf(0L);
- if (i == length || bytes[i] == '_' || bytes[i] == 'p' || bytes[i] == 'P') throw floatError(runtime, str);
+ if (i == length || bytes[i] == '_' || bytes[i] == 'p' || bytes[i] == 'P') throw floatError(context, str);
for(; i < length && !explicitExponentFound; i++) {
letter = bytes[i];
@@ -478,7 +480,7 @@ public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str)
continue;
case 'p': // Explicit exponent "1.23(p)1a"
case 'P':
- if (bytes[i-1] == '_' || i == length - 1) throw floatError(runtime, str);
+ if (bytes[i-1] == '_' || i == length - 1) throw floatError(context, str);
explicitExponentFound = true;
continue;
case '_':
@@ -487,7 +489,7 @@ public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str)
// base 16 value representing main pieces of number
int digit = Character.digit(letter, 16);
- if (Character.forDigit(digit, 16) == 0) throw floatError(runtime, str);
+ if (Character.forDigit(digit, 16) == 0) throw floatError(context, str);
value = value.multiply(SIXTEEN).add(BigInteger.valueOf(digit));
if (periodFound) exponent++;
@@ -500,17 +502,17 @@ public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str)
} else if (bytes[i] == '+') {
i++;
} else if (bytes[i] == '_') {
- throw floatError(runtime, str);
+ throw floatError(context, str);
}
for (; i < length; i++) { // base 10 value representing base 2 exponent
letter = bytes[i];
if (letter == '_') {
- if (i == length - 1) throw floatError(runtime, str);
+ if (i == length - 1) throw floatError(context, str);
continue;
}
int digit = Character.digit(letter, 10);
- if (Character.forDigit(digit, 10) == 0) throw floatError(runtime, str);
+ if (Character.forDigit(digit, 10) == 0) throw floatError(context, str);
explicitExponent = explicitExponent * 10 + digit;
}
}
@@ -523,23 +525,18 @@ public static double parseHexidecimalExponentString2(Ruby runtime, ByteList str)
public static IRubyObject new_float(ThreadContext context, IRubyObject object, boolean exception) {
Ruby runtime = context.runtime;
- if (object instanceof RubyInteger){
- return new_float(runtime, (RubyInteger) object);
- }
- if (object instanceof RubyFloat) {
- return object;
- }
- if (object instanceof RubyString) {
- RubyString str = (RubyString) object;
+ if (object instanceof RubyInteger)return new_float(context, (RubyInteger) object);
+ if (object instanceof RubyFloat) return object;
+ if (object instanceof RubyString str) {
ByteList bytes = str.getByteList();
- if (bytes.getRealSize() == 0){ // rb_cstr_to_dbl case
- if (!exception) return runtime.getNil();
- throw runtime.newArgumentError("invalid value for Float(): " + object.inspect());
+ if (bytes.isEmpty()) { // rb_cstr_to_dbl case
+ if (!exception) return context.nil;
+ throw argumentError(context, "invalid value for Float(): " + object.inspect());
}
if (bytes.startsWith(ZEROx)) { // startsWith("0x")
if (bytes.indexOf('p') != -1 || bytes.indexOf('P') != -1) {
- return runtime.newFloat(parseHexidecimalExponentString2(runtime, bytes));
+ return newFloat(context, parseHexidecimalExponentString2(context, bytes));
}
IRubyObject inum = ConvertBytes.byteListToInum(runtime, bytes, 16, true, exception);
if (!exception && inum.isNil()) return inum;
@@ -559,16 +556,15 @@ public static IRubyObject new_float(ThreadContext context, IRubyObject object, b
if (exception) throw re;
}
- if (!exception) return runtime.getNil();
+ if (!exception) return context.nil;
return TypeConverter.handleUncoercibleObject(runtime, object, runtime.getFloat(), true);
}
- static RubyFloat new_float(final Ruby runtime, RubyInteger num) {
- if (num instanceof RubyBignum) {
- return RubyFloat.newFloat(runtime, RubyBignum.big2dbl((RubyBignum) num));
- }
- return RubyFloat.newFloat(runtime, num.getDoubleValue());
+ static RubyFloat new_float(ThreadContext context, RubyInteger num) {
+ return num instanceof RubyBignum ?
+ newFloat(context, RubyBignum.big2dbl((RubyBignum) num)) :
+ newFloat(context, num.getDoubleValue());
}
@JRubyMethod(name = "Hash", required = 1, module = true, visibility = PRIVATE)
@@ -992,9 +988,7 @@ public static RubyBoolean blockGiven(ThreadContext context, IRubyObject recv, Bl
@JRubyMethod(name = {"sprintf", "format"}, required = 1, rest = true, checkArity = false, module = true, visibility = PRIVATE)
public static IRubyObject sprintf(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
- if (args.length == 0) {
- throw context.runtime.newArgumentError("sprintf must have at least one argument");
- }
+ if (args.length == 0) throw argumentError(context, "sprintf must have at least one argument");
RubyString str = RubyString.stringValue(args[0]);
@@ -1015,36 +1009,24 @@ public static IRubyObject sprintf(IRubyObject recv, IRubyObject[] args) {
return sprintf(recv.getRuntime().getCurrentContext(), recv, args);
}
public static IRubyObject raise(ThreadContext context, IRubyObject self, IRubyObject arg0) {
- final Ruby runtime = context.runtime;
-
// semi extract_raise_opts :
- IRubyObject cause;
- if (arg0 instanceof RubyHash) {
- RubyHash opt = (RubyHash) arg0;
- RubySymbol key;
- if (!opt.isEmpty() && (opt.has_key_p(context, runtime.newSymbol("cause")) == runtime.getTrue())) {
- throw runtime.newArgumentError("only cause is given with no arguments");
- }
+ if (arg0 instanceof RubyHash opt && !opt.isEmpty() &&
+ opt.has_key_p(context, newSymbol(context, "cause")) == context.tru) {
+ throw argumentError(context, "only cause is given with no arguments");
}
- cause = context.getErrorInfo(); // returns nil for no error-info
+ IRubyObject cause = context.getErrorInfo(); // returns nil for no error-info
maybeRaiseJavaException(context, arg0);
- RaiseException raise;
- if (arg0 instanceof RubyString) {
- raise = ((RubyException) runtime.getRuntimeError().newInstance(context, arg0)).toThrowable();
- } else {
- raise = convertToException(context, arg0, null).toThrowable();
- }
+ RaiseException raise = arg0 instanceof RubyString ?
+ ((RubyException) context.runtime.getRuntimeError().newInstance(context, arg0)).toThrowable() :
+ convertToException(context, arg0, null).toThrowable();
- if (runtime.isDebug()) {
- printExceptionSummary(runtime, raise.getException());
- }
+ var exception = raise.getException();
- if (raise.getException().getCause() == null && cause != raise.getException()) {
- raise.getException().setCause(cause);
- }
+ if (context.runtime.isDebug()) printExceptionSummary(context, exception);
+ if (exception.getCause() == null && cause != exception) exception.setCause(cause);
throw raise;
}
@@ -1063,11 +1045,11 @@ public static IRubyObject raise(ThreadContext context, IRubyObject recv, IRubyOb
if (last instanceof RubyHash) {
RubyHash opt = (RubyHash) last;
RubySymbol key;
- if (!opt.isEmpty() && (opt.has_key_p(context, key = runtime.newSymbol("cause")) == runtime.getTrue())) {
+ if (!opt.isEmpty() && (opt.has_key_p(context, key = newSymbol(context, "cause")) == context.tru)) {
cause = opt.delete(context, key, Block.NULL_BLOCK);
forceCause = true;
if (opt.isEmpty() && --argc == 0) { // more opts will be passed along
- throw runtime.newArgumentError("only cause is given with no arguments");
+ throw argumentError(context, "only cause is given with no arguments");
}
}
}
@@ -1108,13 +1090,9 @@ public static IRubyObject raise(ThreadContext context, IRubyObject recv, IRubyOb
break;
}
- if (runtime.isDebug()) {
- printExceptionSummary(runtime, raise.getException());
- }
-
- if (forceCause || argc > 0 && raise.getException().getCause() == null && cause != raise.getException()) {
- raise.getException().setCause(cause);
- }
+ var exception = raise.getException();
+ if (runtime.isDebug()) printExceptionSummary(context, exception);
+ if (forceCause || argc > 0 && exception.getCause() == null && cause != exception) exception.setCause(cause);
throw raise;
}
@@ -1160,16 +1138,16 @@ private static RubyException convertToException(ThreadContext context, IRubyObje
return (RubyException) exception;
}
- private static void printExceptionSummary(Ruby runtime, RubyException rEx) {
+ private static void printExceptionSummary(ThreadContext context, RubyException rEx) {
RubyStackTraceElement[] elements = rEx.getBacktraceElements();
RubyStackTraceElement firstElement = elements.length > 0 ? elements[0] :
new RubyStackTraceElement("", "", "(empty)", 0, false);
String msg = String.format("Exception '%s' at %s:%s - %s\n",
rEx.getMetaClass(),
firstElement.getFileName(), firstElement.getLineNumber(),
- TypeConverter.convertToType(rEx, runtime.getString(), "to_s"));
+ TypeConverter.convertToType(rEx, context.runtime.getString(), "to_s"));
- runtime.getErrorStream().print(msg);
+ context.runtime.getErrorStream().print(msg);
}
/**
@@ -1388,12 +1366,8 @@ static R withLevelAndLength(ThreadContext context, IRubyObject level, IRubyO
lev = defaultLevel;
}
- if (lev < 0) {
- throw context.runtime.newArgumentError("negative level (" + lev + ')');
- }
- if (len < 0) {
- throw context.runtime.newArgumentError("negative size (" + len + ')');
- }
+ if (lev < 0) throw argumentError(context, "negative level (" + lev + ')');
+ if (len < 0) throw argumentError(context, "negative size (" + len + ')');
return func.apply(context, lev, len);
}
@@ -1501,17 +1475,13 @@ public static IRubyObject warn(ThreadContext context, IRubyObject recv, IRubyObj
IRubyObject[] ret = ArgsUtil.extractKeywordArgs(context, (RubyHash) opts, "uplevel", "category");
if (ret[0] != null) {
explicitUplevel = true;
- if ((uplevel = RubyNumeric.num2int(ret[0])) < 0) {
- throw context.runtime.newArgumentError("negative level (" + uplevel + ")");
- }
+ uplevel = RubyNumeric.num2int(ret[0]);
+ if (uplevel < 0) throw argumentError(context, "negative level (" + uplevel + ")");
}
if (ret[1] != null) {
- if (ret[1].isNil()) {
- category = ret[1];
- } else {
- category = TypeConverter.convertToType(ret[1], context.runtime.getSymbol(), "to_sym");
- }
+ category = ret[1].isNil() ?
+ context.nil : TypeConverter.convertToType(ret[1], context.runtime.getSymbol(), "to_sym");
}
}
}
@@ -1660,15 +1630,9 @@ public static RubyProc proc(ThreadContext context, IRubyObject recv, Block block
@JRubyMethod(module = true, visibility = PRIVATE)
public static RubyProc lambda(ThreadContext context, IRubyObject recv, Block block) {
// existing procs remain procs vs becoming lambdas.
- Block.Type type = block.type;
+ if (block.type == Block.Type.PROC) throw argumentError(context, "the lambda method requires a literal block");
- if (type == Block.Type.PROC) {
- throw context.runtime.newArgumentError("the lambda method requires a literal block");
- } else {
- type = Block.Type.LAMBDA;
- }
-
- return context.runtime.newProc(type, block);
+ return context.runtime.newProc(Block.Type.LAMBDA, block);
}
@Deprecated
@@ -1823,7 +1787,7 @@ private static int getTestCommand(ThreadContext context, IRubyObject arg0) {
case '>': case '-':
break;
default:
- throw context.runtime.newArgumentError("unknown command ?" + (char) cmd);
+ throw argumentError(context, "unknown command ?" + (char) cmd);
}
return cmd;
}
@@ -2179,9 +2143,7 @@ public static IRubyObject singleton_class(IRubyObject recv) {
@JRubyMethod(rest = true, keywords = true, reads = SCOPE)
public static IRubyObject public_send(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) {
- if (args.length == 0) {
- throw context.runtime.newArgumentError("no method name given");
- }
+ if (args.length == 0) throw argumentError(context, "no method name given");
String name = RubySymbol.idStringFromObject(context, args[0]);
@@ -2573,7 +2535,7 @@ public static IRubyObject rand(ThreadContext context, IRubyObject recv, IRubyObj
case 1:
return RubyRandom.randKernel(context, recv, args[0]);
default:
- throw context.runtime.newArgumentError(args.length, 0, 1);
+ throw argumentError(context, args.length, 0, 1);
}
}
@@ -2601,7 +2563,7 @@ public static IRubyObject sleep(ThreadContext context, IRubyObject recv, IRubyOb
case 1:
return sleep(context, recv, args[0]);
default:
- throw context.runtime.newArgumentError(args.length, 0, 1);
+ throw argumentError(context, args.length, 0, 1);
}
}
@@ -2613,7 +2575,7 @@ public static IRubyObject test(ThreadContext context, IRubyObject recv, IRubyObj
case 3:
return test(context, recv, args[0], args[1], args[2]);
default:
- throw context.runtime.newArgumentError(args.length, 2, 3);
+ throw argumentError(context, args.length, 2, 3);
}
}
}
diff --git a/core/src/main/java/org/jruby/RubyMath.java b/core/src/main/java/org/jruby/RubyMath.java
index 7f6dd6c5757..61a9b50aba7 100644
--- a/core/src/main/java/org/jruby/RubyMath.java
+++ b/core/src/main/java/org/jruby/RubyMath.java
@@ -38,6 +38,8 @@
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
+import static org.jruby.api.Create.newFloat;
+
@JRubyModule(name="Math")
public class RubyMath {
/** Create the Math module and add it to the Ruby runtime.
@@ -635,7 +637,7 @@ public static RubyFloat erfc(ThreadContext context, IRubyObject recv, IRubyObjec
@JRubyMethod(name = "gamma", module = true, visibility = Visibility.PRIVATE)
public static RubyFloat gamma(ThreadContext context, IRubyObject recv, IRubyObject x) {
- double value = RubyKernel.new_float(context.runtime, x).value;
+ double value = RubyKernel.new_float(context, x).value;
double result = nemes_gamma(value);
/* note nemes_gamma can return Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY
* when value is an integer less than 1.
@@ -653,12 +655,10 @@ public static RubyFloat gamma(ThreadContext context, IRubyObject recv, IRubyObje
}
}
- if (Double.isNaN(value)) {
- return RubyFloat.newFloat(context.runtime, Double.NaN);
- }
+ if (Double.isNaN(value)) return newFloat(context, Double.NaN);
domainCheck(recv, result, "gamma");
- return RubyFloat.newFloat(context.runtime, result);
+ return newFloat(context, result);
}
@@ -674,14 +674,14 @@ public static RubyFloat gamma(ThreadContext context, IRubyObject recv, IRubyObje
@JRubyMethod(name = "lgamma", module = true, visibility = Visibility.PRIVATE)
public static RubyArray lgamma(ThreadContext context, IRubyObject recv, IRubyObject x) {
- double value = RubyKernel.new_float(context.runtime, x).value;
+ double value = RubyKernel.new_float(context, x).value;
// JRUBY-4653: Could this error checking done more elegantly?
if (value < 0 && Double.isInfinite(value)) throw context.runtime.newMathDomainError("lgamma");
NemesLogGamma l = new NemesLogGamma(value);
return RubyArray.newArray(context.runtime,
- RubyFloat.newFloat(context.runtime, l.value), RubyInteger.int2fix(context.runtime, (int) l.sign));
+ newFloat(context, l.value), RubyInteger.int2fix(context.runtime, (int) l.sign));
}
public static double nemes_gamma(double x) {
diff --git a/core/src/main/java/org/jruby/RubyNumeric.java b/core/src/main/java/org/jruby/RubyNumeric.java
index e0022ff845a..59fe74247d9 100644
--- a/core/src/main/java/org/jruby/RubyNumeric.java
+++ b/core/src/main/java/org/jruby/RubyNumeric.java
@@ -62,6 +62,7 @@
import static org.jruby.RubyEnumerator.enumeratorizeWithSize;
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.util.Numeric.f_abs;
import static org.jruby.util.Numeric.f_arg;
@@ -135,7 +136,7 @@ public static RoundingMode getRoundingMode(ThreadContext context, IRubyObject op
}
}
- throw context.runtime.newArgumentError("invalid rounding mode: " + halfArg);
+ throw argumentError(context, "invalid rounding mode: " + halfArg);
}
// The implementations of these are all bonus (see above)
@@ -653,37 +654,26 @@ protected final IRubyObject coerceCmp(ThreadContext context, CallSite site, IRub
@Deprecated // no longer used
protected final IRubyObject coerceRelOp(ThreadContext context, String method, IRubyObject other) {
RubyArray ary = doCoerce(context, other, false);
- if (ary == null) {
- return RubyComparable.cmperr(this, other);
- }
- return unwrapCoerced(context, method, other, ary);
+ return ary == null ? RubyComparable.cmperr(context, this, other) : unwrapCoerced(context, method, other, ary);
}
protected final IRubyObject coerceRelOp(ThreadContext context, CallSite site, IRubyObject other) {
RubyArray ary = doCoerce(context, other, false);
- if (ary == null) {
- return RubyComparable.cmperr(this, other);
- }
- return unwrapCoerced(context, site, other, ary);
+ return ary == null ? RubyComparable.cmperr(context, this, other) : unwrapCoerced(context, site, other, ary);
}
private IRubyObject unwrapCoerced(ThreadContext context, String method, IRubyObject other, RubyArray ary) {
IRubyObject result = (ary.eltInternal(0)).callMethod(context, method, ary.eltInternal(1));
- if (result == context.nil) {
- return RubyComparable.cmperr(this, other);
- }
- return result;
+
+ return result == context.nil ? RubyComparable.cmperr(context,this, other) : result;
}
private IRubyObject unwrapCoerced(ThreadContext context, CallSite site, IRubyObject other, RubyArray ary) {
IRubyObject car = ary.eltInternal(0);
IRubyObject result = site.call(context, car, car, ary.eltInternal(1));
- if (result == context.nil) {
- return RubyComparable.cmperr(this, other);
- }
- return result;
+ return result == context.nil ? RubyComparable.cmperr(context, this, other) : result;
}
public RubyNumeric asNumeric() {
@@ -728,10 +718,11 @@ public IRubyObject initialize_copy(IRubyObject arg) {
@JRubyMethod(name = "coerce")
public IRubyObject coerce(IRubyObject other) {
final Ruby runtime = metaClass.runtime;
+ ThreadContext context = runtime.getCurrentContext();
if (metaClass == other.getMetaClass()) return runtime.newArray(other, this);
- IRubyObject cdr = RubyKernel.new_float(runtime, this);
- IRubyObject car = RubyKernel.new_float(runtime, other);
+ IRubyObject cdr = RubyKernel.new_float(context, this);
+ IRubyObject car = RubyKernel.new_float(context, other);
return runtime.newArray(car, cdr);
}
@@ -1596,9 +1587,7 @@ public boolean isPositive() {
protected static IRubyObject compareWithZero(ThreadContext context, IRubyObject num, JavaSites.CheckedSites site) {
IRubyObject zero = RubyFixnum.zero(context.runtime);
IRubyObject r = getMetaClass(num).finvokeChecked(context, num, site, zero);
- if (r == null) {
- RubyComparable.cmperr(num, zero);
- }
+ if (r == null) RubyComparable.cmperr(context, num, zero);
return r;
}
diff --git a/core/src/main/java/org/jruby/RubyObject.java b/core/src/main/java/org/jruby/RubyObject.java
index cb2b16efe86..88fea50f599 100644
--- a/core/src/main/java/org/jruby/RubyObject.java
+++ b/core/src/main/java/org/jruby/RubyObject.java
@@ -221,6 +221,7 @@ public ClassIndex getNativeClassIndex() {
* Simple helper to print any objects.
* @deprecated no longer used - uses Java's System.out
*/
+ @Deprecated
public static void puts(Object obj) {
System.out.println(obj.toString());
}
diff --git a/core/src/main/java/org/jruby/RubyString.java b/core/src/main/java/org/jruby/RubyString.java
index c507385da63..0bec4c8e8d4 100644
--- a/core/src/main/java/org/jruby/RubyString.java
+++ b/core/src/main/java/org/jruby/RubyString.java
@@ -95,6 +95,7 @@
import static org.jruby.RubyEnumerator.enumeratorizeWithSize;
import static org.jruby.anno.FrameField.BACKREF;
import static org.jruby.api.Convert.*;
+import static org.jruby.api.Create.newFixnum;
import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.Visibility.PRIVATE;
@@ -2623,7 +2624,7 @@ public static RubyString inspect(final Ruby runtime, ByteList byteList) {
(c == '#' &&
p < end &&
MBCLEN_CHARFOUND_P(StringSupport.preciseLength(enc, bytes, p, end)) &&
- ((cc = codePoint(runtime, enc, bytes, p, end)) == '$' ||
+ ((cc = codePoint(runtime.getCurrentContext(), enc, bytes, p, end)) == '$' ||
cc == '@' || cc == '{')
)
)) {
@@ -4680,7 +4681,7 @@ private RubyArray splitCommon(ThreadContext context, IRubyObject pat, int lim) {
Object splitPattern = determineSplitPattern(context, pat);
if (splitPattern == context.nil) { // AWK SPLIT
- result = awkSplit(context.runtime, limit, lim);
+ result = awkSplit(context, limit, lim);
} else if (splitPattern instanceof ByteList bytelist) { // OPTIMIZED STRING SPLIT
// no need to check for broken strings because both have to be 7 bit to be at this point.
switch (bytelist.realSize()) {
@@ -4717,7 +4718,7 @@ private RubyArray splitCommon(ThreadContext context, IRubyObject pat, int lim) {
c = len == StringSupport.preciseLength(spatEnc, bytes, p, p + len) ? spatEnc.mbcToCode(bytes, p, p + len) : -1;
}
if (c == ' ') {
- result = awkSplit(runtime, limit, lim);
+ result = awkSplit(context, limit, lim);
} else {
result = stringSplit(context, splitString, limit, lim);
}
@@ -4825,8 +4826,8 @@ private RubyArray regexSplit(ThreadContext context, RubyRegexp pattern, boolean
}
// MRI: rb_str_split_m, when split_type = awk
- private RubyArray awkSplit(final Ruby runtime, boolean limit, int lim) {
- RubyArray result = runtime.newArray();
+ private RubyArray awkSplit(final ThreadContext context, boolean limit, int lim) {
+ RubyArray result = context.runtime.newArray();
byte[]bytes = value.getUnsafeBytes();
int p = value.getBegin();
@@ -4844,7 +4845,7 @@ private RubyArray awkSplit(final Ruby runtime, boolean limit, int lim) {
if (singlebyte) {
c = bytes[p++] & 0xff;
} else {
- c = StringSupport.codePoint(runtime, enc, bytes, p, end);
+ c = StringSupport.codePoint(context, enc, bytes, p, end);
p += StringSupport.length(enc, bytes, p, end);
}
@@ -4860,7 +4861,7 @@ private RubyArray awkSplit(final Ruby runtime, boolean limit, int lim) {
} else {
// MRI uses rb_isspace
if (ASCII.isSpace(c)) {
- result.append(makeSharedString(runtime, b, e - b));
+ result.append(makeSharedString(context.runtime, b, e - b));
skip = true;
b = p - ptr;
if (limit) i++;
@@ -4870,7 +4871,7 @@ private RubyArray awkSplit(final Ruby runtime, boolean limit, int lim) {
}
}
- if (len > 0 && (limit || len > b || lim < 0)) result.append(makeSharedString(runtime, b, len - b));
+ if (len > 0 && (limit || len > b || lim < 0)) result.append(makeSharedString(context.runtime, b, len - b));
return result;
}
@@ -5805,11 +5806,10 @@ private IRubyObject singleByteLStrip(ThreadContext context, byte[] bytes, int s,
}
private IRubyObject multiByteLStrip(ThreadContext context, Encoding enc, byte[]bytes, int s, int end) {
- final Ruby runtime = context.runtime;
int p = s;
while (p < end) {
- int c = codePoint(runtime, enc, bytes, p, end);
+ int c = codePoint(context, enc, bytes, p, end);
if (!ASCII.isSpace(c) && c != 0) break;
p += codeLength(enc, c);
}
@@ -5866,7 +5866,6 @@ private IRubyObject singleByteRStrip(ThreadContext context) {
// In 1.9 we strip any combination of \0 and \s
private IRubyObject multiByteRStrip(ThreadContext context) {
- final Ruby runtime = context.runtime;
byte[] bytes = value.getUnsafeBytes();
int start = value.getBegin();
int end = start + value.getRealSize();
@@ -5874,7 +5873,7 @@ private IRubyObject multiByteRStrip(ThreadContext context) {
int endp = end;
int prev;
while ((prev = enc.prevCharHead(bytes, start, endp, end)) != -1) {
- int point = codePoint(runtime, enc, bytes, prev, end);
+ int point = codePoint(context, enc, bytes, prev, end);
if (point != 0 && !ASCII.isSpace(point)) break;
endp = prev;
}
@@ -5928,7 +5927,7 @@ public IRubyObject count(ThreadContext context, IRubyObject arg) {
int n = 0;
int[] len_p = {0};
- int c = EncodingUtils.encCodepointLength(runtime, countBytes, begin, begin + size, len_p, enc);
+ int c = EncodingUtils.encCodepointLength(context, countBytes, begin, begin + size, len_p, enc);
final byte[] bytes = value.unsafeBytes();
int i = value.begin();
@@ -6390,7 +6389,6 @@ else if (!wantarray) {
// MRI: rb_str_enumerate_codepoints
private IRubyObject enumerateCodepoints(ThreadContext context, String name, Block block, boolean wantarray) {
- Ruby runtime = context.runtime;
RubyString str = this;
byte[] ptrBytes;
int ptr, end;
@@ -6400,7 +6398,7 @@ private IRubyObject enumerateCodepoints(ThreadContext context, String name, Bloc
if (block.isGiven()) {
if (wantarray) {
- runtime.getWarnings().warning(ID.BLOCK_DEPRECATED, "passing a block to String#" + name + " is deprecated");
+ context.runtime.getWarnings().warning(ID.BLOCK_DEPRECATED, "passing a block to String#" + name + " is deprecated");
wantarray = false;
}
}
@@ -6415,13 +6413,13 @@ else if (!wantarray) {
end = ptr + strByteList.getRealSize();
enc = EncodingUtils.getEncoding(strByteList);
- RubyArray ary = wantarray ? RubyArray.newArray(runtime, str.strLength(strByteList, enc)) : null;
+ RubyArray ary = wantarray ? RubyArray.newArray(context.runtime, str.strLength(strByteList, enc)) : null;
while (ptr < end) {
- int c = codePoint(runtime, enc, ptrBytes, ptr, end);
+ int c = codePoint(context, enc, ptrBytes, ptr, end);
int n = codeLength(enc, c);
- if (wantarray) ary.append(RubyFixnum.newFixnum(runtime, c));
- else block.yield(context, RubyFixnum.newFixnum(runtime, c));
+ if (wantarray) ary.append(newFixnum(context, c));
+ else block.yield(context, newFixnum(context, c));
ptr += n;
}
@@ -6834,6 +6832,7 @@ public RubyString chill() {
* @param value The new java.lang.String this RubyString should encapsulate
* @deprecated
*/
+ @Deprecated
public void setValue(CharSequence value) {
view(ByteList.plain(value), false);
}
diff --git a/core/src/main/java/org/jruby/RubySymbol.java b/core/src/main/java/org/jruby/RubySymbol.java
index 3e2aeabda43..85409b5cb92 100644
--- a/core/src/main/java/org/jruby/RubySymbol.java
+++ b/core/src/main/java/org/jruby/RubySymbol.java
@@ -79,6 +79,7 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
+import static org.jruby.api.Create.newString;
import static org.jruby.api.Error.typeError;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.RubyStringBuilder.ids;
@@ -460,21 +461,22 @@ public IRubyObject inspect() {
return inspect(metaClass.runtime);
}
- @JRubyMethod(name = "inspect")
- public IRubyObject inspect(ThreadContext context) {
- return inspect(context.runtime);
+ @Deprecated
+ final RubyString inspect(final Ruby runtime) {
+ return (RubyString) inspect(runtime.getCurrentContext());
}
- final RubyString inspect(final Ruby runtime) {
+ @JRubyMethod(name = "inspect")
+ public IRubyObject inspect(ThreadContext context) {
// TODO: 1.9 rb_enc_symname_p
- Encoding resenc = runtime.getDefaultInternalEncoding();
- if (resenc == null) resenc = runtime.getDefaultExternalEncoding();
+ Encoding resenc = context.runtime.getDefaultInternalEncoding();
+ if (resenc == null) resenc = context.runtime.getDefaultExternalEncoding();
- RubyString str = RubyString.newString(runtime, getBytes());
+ RubyString str = newString(context, getBytes());
- if (!(isPrintable(runtime) && (resenc.equals(getBytes().getEncoding()) || str.isAsciiOnly()) &&
+ if (!(isPrintable(context) && (resenc.equals(getBytes().getEncoding()) || str.isAsciiOnly()) &&
isSymbolName(symbol))) {
- str = str.inspect(runtime);
+ str = str.inspect(context.runtime);
}
ByteList result = new ByteList(str.getByteList().getRealSize() + 1);
@@ -482,7 +484,7 @@ final RubyString inspect(final Ruby runtime) {
result.append((byte)':');
result.append(str.getByteList());
- return RubyString.newString(runtime, result);
+ return newString(context, result);
}
@Override
@@ -842,7 +844,7 @@ private static boolean isSpecialGlobalName(String s) {
return true;
}
- private boolean isPrintable(final Ruby runtime) {
+ private boolean isPrintable(ThreadContext context) {
ByteList symbolBytes = getBytes();
int p = symbolBytes.getBegin();
int end = p + symbolBytes.getRealSize();
@@ -850,7 +852,7 @@ private boolean isPrintable(final Ruby runtime) {
Encoding enc = symbolBytes.getEncoding();
while (p < end) {
- int c = codePoint(runtime, enc, bytes, p, end);
+ int c = codePoint(context, enc, bytes, p, end);
if (!enc.isPrint(c)) return false;
diff --git a/core/src/main/java/org/jruby/RubyThread.java b/core/src/main/java/org/jruby/RubyThread.java
index b6fd281e2a4..e50f0075b84 100644
--- a/core/src/main/java/org/jruby/RubyThread.java
+++ b/core/src/main/java/org/jruby/RubyThread.java
@@ -2610,13 +2610,13 @@ public static IRubyObject uninterruptible(ThreadContext context, Sta
*
* MRI: rb_fiber_scheduler_set
*/
- public IRubyObject setFiberScheduler(IRubyObject scheduler) {
+ public IRubyObject setFiberScheduler(ThreadContext context, IRubyObject scheduler) {
// VM_ASSERT(ruby_thread_has_gvl_p());
Objects.requireNonNull(scheduler);
if (scheduler != null && !scheduler.isNil()) {
- FiberScheduler.verifyInterface(scheduler);
+ FiberScheduler.verifyInterface(context, scheduler);
}
if (!this.scheduler.isNil()) {
diff --git a/core/src/main/java/org/jruby/RubyTime.java b/core/src/main/java/org/jruby/RubyTime.java
index 7d9068a459a..67e1ad5100d 100644
--- a/core/src/main/java/org/jruby/RubyTime.java
+++ b/core/src/main/java/org/jruby/RubyTime.java
@@ -1049,6 +1049,7 @@ public RubyInteger sec(ThreadContext context) {
return asFixnum(context, dt.getSecondOfMinute());
}
+ @Deprecated(since = "10.0", forRemoval = true)
public RubyInteger sec() {
return sec(getCurrentContext());
}
@@ -1058,7 +1059,7 @@ public RubyInteger min(ThreadContext context) {
return asFixnum(context, dt.getMinuteOfHour());
}
- @Deprecated
+ @Deprecated(since = "10.0", forRemoval = true)
public RubyInteger min() {
return min(getCurrentContext());
}
@@ -1068,7 +1069,7 @@ public RubyInteger hour(ThreadContext context) {
return asFixnum(context, dt.getHourOfDay());
}
- @Deprecated
+ @Deprecated(since = "10.0", forRemoval = true)
public RubyInteger hour() {
return hour(getCurrentContext());
}
@@ -1078,7 +1079,7 @@ public RubyInteger mday(ThreadContext context) {
return asFixnum(context, dt.getDayOfMonth());
}
- @Deprecated
+ @Deprecated(since = "10.0", forRemoval = true)
public RubyInteger mday() {
return mday(getCurrentContext());
}
@@ -1088,6 +1089,7 @@ public RubyInteger month(ThreadContext context) {
return asFixnum(context, dt.getMonthOfYear());
}
+ @Deprecated(since = "10.0", forRemoval = true)
public RubyInteger month() {
return month(getCurrentContext());
}
@@ -1097,7 +1099,7 @@ public RubyInteger year(ThreadContext context) {
return asFixnum(context, dt.getYear());
}
- @Deprecated
+ @Deprecated(since = "10.0", forRemoval = true)
public RubyInteger year() {
return year(getCurrentContext());
}
@@ -1107,7 +1109,7 @@ public RubyInteger wday(ThreadContext context) {
return asFixnum(context, (dt.getDayOfWeek() % 7));
}
- @Deprecated
+ @Deprecated(since = "10.0", forRemoval = true)
public RubyInteger wday() {
return wday(getCurrentContext());
}
@@ -1117,6 +1119,7 @@ public RubyInteger yday(ThreadContext context) {
return asFixnum(context, dt.getDayOfYear());
}
+ @Deprecated(since = "10.0", forRemoval = true)
public RubyInteger yday() {
return yday(getCurrentContext());
}
diff --git a/core/src/main/java/org/jruby/api/Error.java b/core/src/main/java/org/jruby/api/Error.java
index f84cd63d59d..93cb6a18c96 100644
--- a/core/src/main/java/org/jruby/api/Error.java
+++ b/core/src/main/java/org/jruby/api/Error.java
@@ -25,7 +25,7 @@ public class Error {
* @return the created exception
*/
public static ArgumentError argumentError(ThreadContext context, String message) {
- return (ArgumentError) context.runtime.newArgumentError(message);
+ return (ArgumentError) context.runtime.newRaiseException(context.runtime.getArgumentError(), message);
}
/**
diff --git a/core/src/main/java/org/jruby/api/MRI.java b/core/src/main/java/org/jruby/api/MRI.java
index 19c7f6fda06..d4096a9f1f9 100644
--- a/core/src/main/java/org/jruby/api/MRI.java
+++ b/core/src/main/java/org/jruby/api/MRI.java
@@ -211,7 +211,7 @@ public static int rb_enc_mbcput(ThreadContext context, int c, byte[] buf, int p,
}
public static int rb_enc_codepoint_len(ThreadContext context, byte[] pBytes, int p, int e, int[] len_p, Encoding enc) {
- return EncodingUtils.encCodepointLength(context.runtime, pBytes, p, e, len_p, enc);
+ return EncodingUtils.encCodepointLength(context, pBytes, p, e, len_p, enc);
}
public static RubyString rb_str_escape(ThreadContext context, RubyString str) {
diff --git a/core/src/main/java/org/jruby/ext/bigdecimal/RubyBigDecimal.java b/core/src/main/java/org/jruby/ext/bigdecimal/RubyBigDecimal.java
index be53360861c..16932a5cb44 100644
--- a/core/src/main/java/org/jruby/ext/bigdecimal/RubyBigDecimal.java
+++ b/core/src/main/java/org/jruby/ext/bigdecimal/RubyBigDecimal.java
@@ -60,8 +60,8 @@
import org.jruby.util.StringSupport;
import static org.jruby.api.Convert.*;
-import static org.jruby.api.Create.newFixnum;
-import static org.jruby.api.Create.newString;
+import static org.jruby.api.Create.*;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
/**
@@ -332,7 +332,7 @@ public static IRubyObject limit(ThreadContext context, IRubyObject recv, IRubyOb
IRubyObject old = limit(context, recv);
if (arg == context.nil) return old;
- if (Convert.castAsFixnum(context, arg).getLongValue() < 0) throw context.runtime.newArgumentError("argument must be positive");
+ if (Convert.castAsFixnum(context, arg).getLongValue() < 0) throw argumentError(context, "argument must be positive");
((RubyModule) recv).setInternalModuleVariable("vpPrecLimit", arg);
@@ -372,8 +372,6 @@ private static IRubyObject modeExecute(final ThreadContext context, final RubyMo
@JRubyMethod(required = 1, optional = 1, checkArity = false, meta = true)
public static IRubyObject mode(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
- Ruby runtime = context.runtime;
-
// FIXME: I doubt any of the constants referenced in this method
// are ever redefined -- should compare to the known values, rather
// than do an expensive constant lookup.
@@ -386,7 +384,7 @@ public static IRubyObject mode(ThreadContext context, IRubyObject recv, IRubyObj
if ((mode & EXCEPTION_ALL) != 0) {
if (value.isNil()) return c.searchInternalModuleVariable("vpExceptionMode");
- if (!(value instanceof RubyBoolean)) throw context.runtime.newArgumentError("second argument must be true or false");
+ if (!(value instanceof RubyBoolean)) throw argumentError(context, "second argument must be true or false");
long newExceptionMode = c.searchInternalModuleVariable("vpExceptionMode").convertToInteger().getLongValue();
@@ -408,15 +406,13 @@ public static IRubyObject mode(ThreadContext context, IRubyObject recv, IRubyObj
newExceptionMode = enable ? newExceptionMode | EXCEPTION_ZERODIVIDE : newExceptionMode & ~(EXCEPTION_ZERODIVIDE);
}
- RubyFixnum fixnumMode = RubyFixnum.newFixnum(runtime, newExceptionMode);
+ RubyFixnum fixnumMode = newFixnum(context, newExceptionMode);
c.setInternalModuleVariable("vpExceptionMode", fixnumMode);
return fixnumMode;
}
if (mode == ROUND_MODE) {
- if (value == context.nil) {
- return c.searchInternalModuleVariable("vpRoundingMode");
- }
+ if (value == context.nil) return c.searchInternalModuleVariable("vpRoundingMode");
RoundingMode javaRoundingMode = javaRoundingModeFromRubyRoundingMode(context, value);
RubyFixnum roundingMode = newFixnum(context, rubyRoundingModeFromJavaRoundingMode(context, javaRoundingMode));
@@ -429,33 +425,33 @@ public static IRubyObject mode(ThreadContext context, IRubyObject recv, IRubyObj
}
// The Fixnum cast should be fine because these are internal variables and user code cannot change them.
- private static long bigDecimalVar(Ruby runtime, String variableName) {
- return ((RubyFixnum) runtime.getClass("BigDecimal").searchInternalModuleVariable(variableName)).getLongValue();
+ private static long bigDecimalVar(ThreadContext context, String variableName) {
+ return ((RubyFixnum) context.runtime.getClass("BigDecimal").searchInternalModuleVariable(variableName)).getLongValue();
}
- private static RoundingMode getRoundingMode(Ruby runtime) {
- IRubyObject mode = runtime.getClass("BigDecimal").searchInternalModuleVariable("vpRoundingMode");
- return javaRoundingModeFromRubyRoundingMode(runtime.getCurrentContext(), mode);
+ private static RoundingMode getRoundingMode(ThreadContext context) {
+ IRubyObject mode = context.runtime.getClass("BigDecimal").searchInternalModuleVariable("vpRoundingMode");
+ return javaRoundingModeFromRubyRoundingMode(context, mode);
}
- private static boolean isNaNExceptionMode(Ruby runtime) {
- return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_NaN) != 0;
+ private static boolean isNaNExceptionMode(ThreadContext context) {
+ return (bigDecimalVar(context, "vpExceptionMode") & EXCEPTION_NaN) != 0;
}
- private static boolean isInfinityExceptionMode(Ruby runtime) {
- return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_INFINITY) != 0;
+ private static boolean isInfinityExceptionMode(ThreadContext context) {
+ return (bigDecimalVar(context, "vpExceptionMode") & EXCEPTION_INFINITY) != 0;
}
- private static boolean isOverflowExceptionMode(Ruby runtime) {
- return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_OVERFLOW) != 0;
+ private static boolean isOverflowExceptionMode(ThreadContext context) {
+ return (bigDecimalVar(context, "vpExceptionMode") & EXCEPTION_OVERFLOW) != 0;
}
- private static boolean isUnderflowExceptionMode(Ruby runtime) {
- return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_UNDERFLOW) != 0;
+ private static boolean isUnderflowExceptionMode(ThreadContext context) {
+ return (bigDecimalVar(context, "vpExceptionMode") & EXCEPTION_UNDERFLOW) != 0;
}
- private static boolean isZeroDivideExceptionMode(Ruby runtime) {
- return (bigDecimalVar(runtime, "vpExceptionMode") & EXCEPTION_ZERODIVIDE) != 0;
+ private static boolean isZeroDivideExceptionMode(ThreadContext context) {
+ return (bigDecimalVar(context, "vpExceptionMode") & EXCEPTION_ZERODIVIDE) != 0;
}
private static RubyBigDecimal cannotBeCoerced(ThreadContext context, IRubyObject value, boolean must) {
@@ -498,7 +494,7 @@ private RubyBigDecimal getVpValueWithPrec(ThreadContext context, IRubyObject val
throw context.runtime.newFloatDomainError("NaN");
}
- MathContext mathContext = new MathContext(RubyFloat.DIG + 1, getRoundingMode(context.runtime));
+ MathContext mathContext = new MathContext(RubyFloat.DIG + 1, getRoundingMode(context));
// uses value.toString to prevent a precision error
// e.g. new BigDecimal(64.4) -> 64.400000000000005684341886080801486968994140625
// new BigDecimal("64.4") -> 64.4
@@ -516,11 +512,11 @@ private static RubyBigDecimal getVpValue(ThreadContext context, IRubyObject valu
case BIGDECIMAL:
return (RubyBigDecimal) value;
case FIXNUM:
- return newInstance(context.runtime, context.runtime.getClass("BigDecimal"), (RubyFixnum) value, MathContext.UNLIMITED);
+ return newInstance(context, context.runtime.getClass("BigDecimal"), (RubyFixnum) value, MathContext.UNLIMITED);
case BIGNUM:
- return newInstance(context.runtime, context.runtime.getClass("BigDecimal"), (RubyBignum) value, MathContext.UNLIMITED);
+ return newInstance(context, context.runtime.getClass("BigDecimal"), (RubyBignum) value, MathContext.UNLIMITED);
case FLOAT:
- return newInstance(context.runtime, context.runtime.getClass("BigDecimal"), (RubyFloat) value, new MathContext(RubyFloat.DIG));
+ return newInstance(context, context.runtime.getClass("BigDecimal"), (RubyFloat) value, new MathContext(RubyFloat.DIG));
case RATIONAL:
return newInstance(context, context.runtime.getClass("BigDecimal"), (RubyRational) value, new MathContext(RubyFloat.DIG));
}
@@ -536,14 +532,14 @@ private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyBi
return new RubyBigDecimal(runtime, (RubyClass) recv, arg.value, arg.zeroSign, arg.infinitySign, arg.isNaN);
}
- private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyFixnum arg, MathContext mathContext) {
+ private static RubyBigDecimal newInstance(ThreadContext context, IRubyObject recv, RubyFixnum arg, MathContext mathContext) {
final long value = arg.getLongValue();
- if (value == 0) return getZero(runtime, 1);
- return new RubyBigDecimal(runtime, (RubyClass) recv, new BigDecimal(value, mathContext));
+ if (value == 0) return getZero(context, 1);
+ return new RubyBigDecimal(context.runtime, (RubyClass) recv, new BigDecimal(value, mathContext));
}
private static RubyBigDecimal newInstance(ThreadContext context, IRubyObject recv, RubyRational arg, MathContext mathContext) {
- if (arg.getNumerator().isZero()) return getZero(context.runtime, 1);
+ if (arg.getNumerator().isZero()) return getZero(context, 1);
BigDecimal num = toBigDecimal(context, arg.getNumerator());
BigDecimal den = toBigDecimal(context, arg.getDenominator());
@@ -557,27 +553,27 @@ private static RubyBigDecimal newInstance(ThreadContext context, IRubyObject rec
return new RubyBigDecimal(context.runtime, (RubyClass) recv, value);
}
- private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyFloat arg, MathContext mathContext) {
+ private static RubyBigDecimal newInstance(ThreadContext context, IRubyObject recv, RubyFloat arg, MathContext mathContext) {
// precision can be no more than float digits
- if (mathContext.getPrecision() > RubyFloat.DIG + 1) throw runtime.newArgumentError("precision too large");
+ if (mathContext.getPrecision() > RubyFloat.DIG + 1) throw argumentError(context, "precision too large");
- RubyBigDecimal res = newFloatSpecialCases(runtime, arg);
+ RubyBigDecimal res = newFloatSpecialCases(context, arg);
if (res != null) return res;
- return new RubyBigDecimal(runtime, (RubyClass) recv, new BigDecimal(arg.toString(), mathContext));
+ return new RubyBigDecimal(context.runtime, (RubyClass) recv, new BigDecimal(arg.toString(), mathContext));
}
- private static RubyBigDecimal newFloatSpecialCases(Ruby runtime, RubyFloat val) {
- if (val.isNaN()) return getNaN(runtime);
- if (val.isInfinite()) return getInfinity(runtime, val.getDoubleValue() == Double.POSITIVE_INFINITY ? 1 : -1);
- if (val.isZero()) return getZero(runtime, Double.doubleToLongBits(val.getDoubleValue()) == NEGATIVE_ZERO_LONG_BITS ? -1 : 1);
+ private static RubyBigDecimal newFloatSpecialCases(ThreadContext context, RubyFloat val) {
+ if (val.isNaN()) return getNaN(context);
+ if (val.isInfinite()) return getInfinity(context, val.getDoubleValue() == Double.POSITIVE_INFINITY ? 1 : -1);
+ if (val.isZero()) return getZero(context, Double.doubleToLongBits(val.getDoubleValue()) == NEGATIVE_ZERO_LONG_BITS ? -1 : 1);
return null;
}
- private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyBignum arg, MathContext mathContext) {
+ private static RubyBigDecimal newInstance(ThreadContext context, IRubyObject recv, RubyBignum arg, MathContext mathContext) {
final BigInteger value = arg.getBigIntegerValue();
- if (value.equals(BigInteger.ZERO)) return getZero(runtime, 1);
- return new RubyBigDecimal(runtime, (RubyClass) recv, new BigDecimal(value, mathContext));
+ if (value.equals(BigInteger.ZERO)) return getZero(context, 1);
+ return new RubyBigDecimal(context.runtime, (RubyClass) recv, new BigDecimal(value, mathContext));
}
private static IRubyObject newInstance(ThreadContext context, RubyClass recv, RubyString arg, MathContext mathContext, boolean strict, boolean exception) {
@@ -589,7 +585,7 @@ private static IRubyObject newInstance(ThreadContext context, RubyClass recv, Ru
if (e == 0) {
switch (str[0]) {
case '0':
- return getZero(context.runtime, 1);
+ return getZero(context, 1);
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return new RubyBigDecimal(context.runtime, recv, BigDecimal.valueOf(str[0] - '0'));
@@ -606,17 +602,17 @@ private static IRubyObject newInstance(ThreadContext context, RubyClass recv, Ru
if (!strict) return context.nil;
throw invalidArgumentError(context, arg);
case 'N' :
- if ( contentEquals("NaN", str, s, e) ) return getNaN(context.runtime);
+ if ( contentEquals("NaN", str, s, e) ) return getNaN(context);
break;
case 'I' :
- if ( contentEquals("Infinity", str, s, e) ) return getInfinity(context.runtime, 1);
+ if ( contentEquals("Infinity", str, s, e) ) return getInfinity(context, 1);
break;
case '-' :
- if ( contentEquals("-Infinity", str, s, e) ) return getInfinity(context.runtime, -1);
+ if ( contentEquals("-Infinity", str, s, e) ) return getInfinity(context, -1);
sign = -1;
break;
case '+' :
- if ( contentEquals("+Infinity", str, s, e) ) return getInfinity(context.runtime, +1);
+ if ( contentEquals("+Infinity", str, s, e) ) return getInfinity(context, +1);
break;
}
@@ -721,43 +717,37 @@ private static IRubyObject newInstance(ThreadContext context, RubyClass recv, Ru
else if (isExponentOutOfRange(str, exp + 1, e)) {
// Handle infinity (Integer.MIN_VALUE + 1) < expValue < Integer.MAX_VALUE
// checking the sign of exponent part.
- if (isZeroBase(str, s, exp) || str[exp + 1] == '-') return getZero(context.runtime, sign);
- return getInfinity(context.runtime, sign);
+ if (isZeroBase(str, s, exp) || str[exp + 1] == '-') return getZero(context, sign);
+ return getInfinity(context, sign);
}
- }
- else if ( lastSign > s ) {
+ } else if ( lastSign > s ) {
e = lastSign - 1; // ignored tail junk e.g. "5-6" -> "-6"
}
BigDecimal decimal;
try {
decimal = new BigDecimal(str, s, e - s + 1, mathContext);
- }
- catch (ArithmeticException ex) {
- return checkOverUnderFlow(context.runtime, ex, false, strict, exception);
- }
- catch (NumberFormatException ex) {
+ } catch (ArithmeticException ex) {
+ return checkOverUnderFlow(context, ex, false, strict, exception);
+ } catch (NumberFormatException ex) {
return handleInvalidArgument(context, arg, strict, exception);
}
// MRI behavior: -0 and +0 are two different things
- if (decimal.signum() == 0) return getZero(context.runtime, sign);
+ if (decimal.signum() == 0) return getZero(context, sign);
return new RubyBigDecimal(context.runtime, recv, decimal);
}
private static IRubyObject handleInvalidArgument(ThreadContext context, RubyString arg, boolean strict, boolean exception) {
- if (!strict) {
- return getZero(context.runtime, 1);
- }
- if (!exception) {
- return context.nil;
- }
+ if (!strict) return getZero(context, 1);
+ if (!exception) return context.nil;
+
throw invalidArgumentError(context, arg);
}
private static RaiseException invalidArgumentError(ThreadContext context, RubyString arg) {
- return context.runtime.newArgumentError("invalid value for BigDecimal(): \"" + arg + "\"");
+ return argumentError(context, "invalid value for BigDecimal(): \"" + arg + "\"");
}
private static boolean contentEquals(final String str1, final char[] str2, final int s2, final int e2) {
@@ -826,9 +816,9 @@ public static IRubyObject new_(ThreadContext context, IRubyObject recv, IRubyObj
}
private static IRubyObject handleMissingPrecision(ThreadContext context, String name, boolean strict, boolean exception) {
- if (!strict) return getZero(context.runtime, 1);
+ if (!strict) return getZero(context, 1);
if (!exception) return context.nil;
- throw context.runtime.newArgumentError("can't omit precision for a " + name + ".");
+ throw argumentError(context, "can't omit precision for a " + name + ".");
}
// Left for arjdbc (being phased out from 61.3 forward and newer points of newer arjdbc versions)
@@ -844,28 +834,28 @@ public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, I
case RATIONAL:
return handleMissingPrecision(context, "Rational", strict, exception);
case FLOAT:
- RubyBigDecimal res = newFloatSpecialCases(context.runtime, (RubyFloat) arg);
+ RubyBigDecimal res = newFloatSpecialCases(context, (RubyFloat) arg);
if (res != null) return res;
return handleMissingPrecision(context, "Float", strict, exception);
case FIXNUM:
- return newInstance(context.runtime, recv, (RubyFixnum) arg, MathContext.UNLIMITED);
+ return newInstance(context, recv, (RubyFixnum) arg, MathContext.UNLIMITED);
case BIGNUM:
- return newInstance(context.runtime, recv, (RubyBignum) arg, MathContext.UNLIMITED);
+ return newInstance(context, recv, (RubyBignum) arg, MathContext.UNLIMITED);
case BIGDECIMAL:
return arg;
case COMPLEX:
RubyComplex c = (RubyComplex) arg;
if (!((RubyNumeric)c.image()).isZero()) {
- throw context.runtime.newArgumentError("Unable to make a BigDecimal from non-zero imaginary number");
+ throw argumentError(context, "Unable to make a BigDecimal from non-zero imaginary number");
}
}
IRubyObject maybeString = arg.checkStringType();
if (maybeString.isNil()) {
- if (!strict) return getZero(context.runtime, 1);
+ if (!strict) return getZero(context, 1);
if (!exception) return context.nil;
- throw context.runtime.newTypeError("no implicit conversion of " + arg.inspect() + "into to String");
+ throw typeError(context, "no implicit conversion of " + arg.inspect() + "into to String");
}
return newInstance(context, (RubyClass) recv, maybeString.convertToString(), MathContext.UNLIMITED, strict, exception);
}
@@ -882,12 +872,12 @@ public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, I
int digits = (int) mathArg.convertToInteger().getLongValue();
if (digits < 0) {
- if (!strict) return getZero(context.runtime, 1);
+ if (!strict) return getZero(context, 1);
if (!exception) return context.nil;
- throw context.runtime.newArgumentError("argument must be positive");
+ throw argumentError(context, "argument must be positive");
}
- MathContext mathContext = new MathContext(digits, getRoundingMode(context.runtime));
+ MathContext mathContext = new MathContext(digits, getRoundingMode(context));
switch (((RubyBasicObject) arg).getNativeClassIndex()) {
case RATIONAL:
@@ -897,17 +887,17 @@ public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, I
}
return newInstance(context, recv, (RubyRational) arg, mathContext);
case FLOAT:
- RubyBigDecimal res = newFloatSpecialCases(context.runtime, (RubyFloat) arg);
+ RubyBigDecimal res = newFloatSpecialCases(context, (RubyFloat) arg);
if (res != null) return res;
// mri uses SIZE_MAX
if (digits == Integer.MAX_VALUE) {
return handleMissingPrecision(context, "Float", strict, exception);
}
- return newInstance(context.runtime, recv, (RubyFloat) arg, mathContext);
+ return newInstance(context, recv, (RubyFloat) arg, mathContext);
case FIXNUM:
- return newInstance(context.runtime, recv, (RubyFixnum) arg, mathContext);
+ return newInstance(context, recv, (RubyFixnum) arg, mathContext);
case BIGNUM:
- return newInstance(context.runtime, recv, (RubyBignum) arg, mathContext);
+ return newInstance(context, recv, (RubyBignum) arg, mathContext);
case BIGDECIMAL:
// mri uses SIZE_MAX
if (digits == Integer.MAX_VALUE) {
@@ -917,7 +907,7 @@ public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, I
case COMPLEX:
RubyComplex c = (RubyComplex) arg;
if (!((RubyNumeric)c.image()).isZero()) {
- throw context.runtime.newArgumentError("Unable to make a BigDecimal from non-zero imaginary number");
+ throw argumentError(context, "Unable to make a BigDecimal from non-zero imaginary number");
}
return newInstance(context, recv, c.real(), mathArg, strict, exception);
}
@@ -932,54 +922,52 @@ public static IRubyObject newInstance(ThreadContext context, IRubyObject recv, I
return newInstance(context, (RubyClass) recv, (RubyString) maybeString, MathContext.UNLIMITED, strict, exception);
}
- private static RubyBigDecimal getZero(final Ruby runtime, final int sign) {
+ private static RubyBigDecimal getZero(ThreadContext context, final int sign) {
String constantName = sign < 0 ? "NEGATIVE_ZERO" : "POSITIVE_ZERO";
- return (RubyBigDecimal)runtime.getClass("BigDecimal").getConstant(constantName);
+ return (RubyBigDecimal) context.runtime.getClass("BigDecimal").getConstant(constantName);
}
- private static RubyBigDecimal getNaN(final Ruby runtime) {
- if ( isNaNExceptionMode(runtime) ) {
- throw newNaNFloatDomainError(runtime);
- }
- return (RubyBigDecimal)runtime.getClass("BigDecimal").getConstant("NAN");
+ private static RubyBigDecimal getNaN(ThreadContext context) {
+ if ( isNaNExceptionMode(context) ) throw newNaNFloatDomainError(context);
+
+ return (RubyBigDecimal) context.runtime.getClass("BigDecimal").getConstant("NAN");
}
- private static RaiseException newNaNFloatDomainError(final Ruby runtime) {
- return runtime.newFloatDomainError("Computation results to 'NaN'(Not a Number)");
+ private static RaiseException newNaNFloatDomainError(ThreadContext context) {
+ return context.runtime.newFloatDomainError("Computation results to 'NaN'(Not a Number)");
}
private enum InfinityErrorMsgType {To, In}
- private static RubyBigDecimal getInfinity(final Ruby runtime, final int sign) {
- return getInfinity(runtime, sign, InfinityErrorMsgType.To);
+ private static RubyBigDecimal getInfinity(ThreadContext context, final int sign) {
+ return getInfinity(context, sign, InfinityErrorMsgType.To);
}
- private static RubyBigDecimal getInfinity(final Ruby runtime, final int sign, final InfinityErrorMsgType type) {
- if ( isInfinityExceptionMode(runtime) ) {
- throw newInfinityFloatDomainError(runtime, sign, type);
- }
+ private static RubyBigDecimal getInfinity(ThreadContext context, final int sign, final InfinityErrorMsgType type) {
+ if (isInfinityExceptionMode(context)) throw newInfinityFloatDomainError(context, sign, type);
+
String constantName = sign < 0 ? "NEGATIVE_INFINITY" : "INFINITY";
- return (RubyBigDecimal)runtime.getClass("BigDecimal").getConstant(constantName);
+ return (RubyBigDecimal) context.runtime.getClass("BigDecimal").getConstant(constantName);
}
- private static RaiseException newInfinityFloatDomainError(final Ruby runtime, final int sign) {
- return newInfinityFloatDomainError(runtime, sign, InfinityErrorMsgType.To);
+ private static RaiseException newInfinityFloatDomainError(ThreadContext context, final int sign) {
+ return newInfinityFloatDomainError(context, sign, InfinityErrorMsgType.To);
}
- private static RaiseException newInfinityFloatDomainError(final Ruby runtime, final int sign, final InfinityErrorMsgType type) {
+ private static RaiseException newInfinityFloatDomainError(ThreadContext context, final int sign, final InfinityErrorMsgType type) {
if (type == InfinityErrorMsgType.To) {
- return runtime.newFloatDomainError("Computation results to " + (sign < 0 ? "'-Infinity'" : "'Infinity'"));
+ return context.runtime.newFloatDomainError("Computation results to " + (sign < 0 ? "'-Infinity'" : "'Infinity'"));
} else {
- return runtime.newFloatDomainError("Computation results in " + (sign < 0 ? "'-Infinity'" : "'Infinity'"));
+ return context.runtime.newFloatDomainError("Computation results in " + (sign < 0 ? "'-Infinity'" : "'Infinity'"));
}
}
- private RubyBigDecimal setResult() {
- return setResult(0);
+ private RubyBigDecimal setResult(ThreadContext context) {
+ return setResult(context, 0);
}
- private RubyBigDecimal setResult(int prec) {
- if (prec == 0) prec = getPrecLimit(getRuntime());
+ private RubyBigDecimal setResult(ThreadContext context, int prec) {
+ if (prec == 0) prec = getPrecLimit(context);
int exponent;
if (prec > 0 && this.value.scale() > (prec - (exponent = getExponent()))) {
this.value = this.value.setScale(prec - exponent, RoundingMode.HALF_UP);
@@ -1028,17 +1016,17 @@ public IRubyObject op_mod(ThreadContext context, IRubyObject other) {
RubyBigDecimal val = getVpValueWithPrec(context, other, false);
if (val == null) return callCoerced(context, sites(context).op_mod, other, true);
- if (isNaN() || val.isNaN() || isInfinity() && val.isInfinity()) return getNaN(context.runtime);
+ if (isNaN() || val.isNaN() || isInfinity() && val.isInfinity()) return getNaN(context);
if (val.isZero()) throw context.runtime.newZeroDivisionError();
- if (isInfinity()) return getNaN(context.runtime);
+ if (isInfinity()) return getNaN(context);
if (val.isInfinity()) return this;
- if (isZero()) return getZero(context.runtime, value.signum());
+ if (isZero()) return getZero(context, value.signum());
// Java and MRI definitions of modulo are different.
BigDecimal modulo = value.remainder(val.value);
if (modulo.signum() * val.value.signum() < 0) modulo = modulo.add(val.value);
- return new RubyBigDecimal(context.runtime, modulo).setResult();
+ return new RubyBigDecimal(context.runtime, modulo).setResult(context);
}
@Override
@@ -1048,25 +1036,25 @@ public IRubyObject remainder(ThreadContext context, IRubyObject arg) {
}
private IRubyObject remainderInternal(ThreadContext context, RubyBigDecimal val, IRubyObject arg) {
- if (isInfinity() || isNaN()) return getNaN(context.runtime);
+ if (isInfinity() || isNaN()) return getNaN(context);
if (val == null) return callCoerced(context, sites(context).remainder, arg, true);
if (val.isInfinity()) return this;
- if (val.isNaN() || val.isZero()) return getNaN(context.runtime);
+ if (val.isNaN() || val.isZero()) return getNaN(context);
// Java and MRI definitions of remainder are the same.
- return new RubyBigDecimal(context.runtime, value.remainder(val.value)).setResult();
+ return new RubyBigDecimal(context.runtime, value.remainder(val.value)).setResult(context);
}
@JRubyMethod(name = "*")
public IRubyObject op_mul(ThreadContext context, IRubyObject arg) {
RubyBigDecimal val = getVpValueWithPrec(context, arg, false);
if (val == null) return callCoerced(context, sites(context).op_times, arg, true);
- return multImpl(context.runtime, val);
+ return multImpl(context, val);
}
@JRubyMethod(name = "mult")
public IRubyObject mult2(ThreadContext context, IRubyObject b, IRubyObject n) {
- final int mx = getPrecisionInt(context.runtime, n);
+ final int mx = getPrecisionInt(context, n);
if (mx == 0) return op_mul(context, b);
RubyBigDecimal val = getVpValueWithPrec(context, b, false);
@@ -1074,79 +1062,78 @@ public IRubyObject mult2(ThreadContext context, IRubyObject b, IRubyObject n) {
return callCoerced(context, sites(context).op_times, b, true);
}
- return multImpl(context.runtime, val).setResult(mx);
+ return multImpl(context, val).setResult(context, mx);
}
- private RubyBigDecimal multImpl(final Ruby runtime, RubyBigDecimal val) {
- if ( isNaN() || val.isNaN() ) return getNaN(runtime);
+ private RubyBigDecimal multImpl(ThreadContext context, RubyBigDecimal val) {
+ if ( isNaN() || val.isNaN() ) return getNaN(context);
if ( isZero() || val.isZero() ) {
- if ((isInfinity() && val.isZero()) || (isZero() && val.isInfinity())) return getNaN(runtime);
+ if ((isInfinity() && val.isZero()) || (isZero() && val.isInfinity())) return getNaN(context);
int sign1 = isZero()? zeroSign : value.signum();
int sign2 = val.isZero() ? val.zeroSign : val.value.signum();
- return getZero(runtime, sign1 * sign2);
+ return getZero(context, sign1 * sign2);
}
if ( isInfinity() || val.isInfinity() ) {
int sign1 = isInfinity() ? infinitySign : value.signum();
int sign2 = val.isInfinity() ? val.infinitySign : val.value.signum();
- return getInfinity(runtime, sign1 * sign2);
+ return getInfinity(context, sign1 * sign2);
}
int mx = value.precision() + val.value.precision();
- MathContext mathContext = new MathContext(mx, getRoundingMode(runtime));
+ MathContext mathContext = new MathContext(mx, getRoundingMode(context));
BigDecimal result;
try {
result = value.multiply(val.value, mathContext);
}
catch (ArithmeticException ex) {
- return (RubyBigDecimal) checkOverUnderFlow(runtime, ex, false, true, true);
+ return (RubyBigDecimal) checkOverUnderFlow(context, ex, false, true, true);
}
- return new RubyBigDecimal(runtime, result).setResult();
+ return new RubyBigDecimal(context.runtime, result).setResult(context);
}
- private static IRubyObject checkOverUnderFlow(final Ruby runtime, final ArithmeticException ex, boolean nullDefault, boolean strict, boolean exception) {
+ private static IRubyObject checkOverUnderFlow(ThreadContext context, final ArithmeticException ex,
+ boolean nullDefault, boolean strict, boolean exception) {
String message = ex.getMessage();
if (message == null) message = "";
message = message.toLowerCase(Locale.ENGLISH);
if (message.contains("underflow")) {
- if (isUnderflowExceptionMode(runtime)) {
- return handleFloatDomainError(runtime, message, strict, exception);
- }
- return getZero(runtime, 1);
+ return isUnderflowExceptionMode(context) ?
+ handleFloatDomainError(context, message, strict, exception) :
+ getZero(context, 1);
}
if (message.contains("overflow")) {
- if (isOverflowExceptionMode(runtime)) {
- return handleFloatDomainError(runtime, message, strict, exception);
- }
- return getInfinity(runtime, 1); // TODO sign?
+ return isOverflowExceptionMode(context) ?
+ handleFloatDomainError(context, message, strict, exception) :
+ getInfinity(context, 1); // TODO sign?
}
- if (nullDefault) return null;
- return handleFloatDomainError(runtime, message, strict, exception);
+
+ return nullDefault ? null : handleFloatDomainError(context, message, strict, exception);
}
- private static IRubyObject handleFloatDomainError(Ruby runtime, String message, boolean strict, boolean exception) {
- if (!strict) return getZero(runtime, 1);
- if (!exception) return runtime.getNil();
- throw runtime.newFloatDomainError(message);
+ private static IRubyObject handleFloatDomainError(ThreadContext context, String message, boolean strict, boolean exception) {
+ if (!strict) return getZero(context, 1);
+ if (!exception) return context.nil;
+ throw context.runtime.newFloatDomainError(message);
}
// Calculate appropriate zero or infinity depending on exponent...
private RubyBigDecimal newPowOfInfinity(ThreadContext context, RubyNumeric exp) {
if (Numeric.f_negative_p(context, exp)) {
- if (infinitySign >= 0) return getZero(context.runtime, 0);
+ if (infinitySign >= 0) return getZero(context, 0);
// (-Infinity) ** (-even_integer) -> +0 AND (-Infinity) ** (-odd_integer) -> -0
- if (Numeric.f_integer_p(context, exp)) return getZero(context.runtime, isEven(exp) ? 1 : -1);
+ if (Numeric.f_integer_p(context, exp)) return getZero(context, isEven(exp) ? 1 : -1);
- return getZero(context.runtime, -1); // (-Infinity) ** (-non_integer) -> -0
+ return getZero(context, -1); // (-Infinity) ** (-non_integer) -> -0
}
- if (infinitySign >= 0) return getInfinity(context.runtime, 1);
+ if (infinitySign >= 0) return getInfinity(context, 1);
- if (Numeric.f_integer_p(context, exp)) return getInfinity(context.runtime, isEven(exp) ? 1 : -1);
+ if (Numeric.f_integer_p(context, exp)) return getInfinity(context, isEven(exp) ? 1 : -1);
throw context.runtime.newMathDomainError("a non-integral exponent for a negative base");
}
@@ -1155,25 +1142,25 @@ private RubyBigDecimal newPowOfInfinity(ThreadContext context, RubyNumeric exp)
private RubyBigDecimal newPowOfZero(ThreadContext context, RubyNumeric exp) {
if (Numeric.f_negative_p(context, exp)) {
/* (+0) ** (-num) -> Infinity */
- if (zeroSign >= 0) return getInfinity(context.runtime, 1);
+ if (zeroSign >= 0) return getInfinity(context, 1);
// (-0) ** (-even_integer) -> +Infinity AND (-0) ** (-odd_integer) -> -Infinity
- if (Numeric.f_integer_p(context, exp)) return getInfinity(context.runtime, isEven(exp) ? 1 : -1);
+ if (Numeric.f_integer_p(context, exp)) return getInfinity(context, isEven(exp) ? 1 : -1);
- return getInfinity(context.runtime, -1); // (-0) ** (-non_integer) -> Infinity
+ return getInfinity(context, -1); // (-0) ** (-non_integer) -> Infinity
}
- if (Numeric.f_zero_p(context, exp)) return new RubyBigDecimal(context.runtime, BigDecimal.ONE);
-
- return getZero(context.runtime, 1);
+ return Numeric.f_zero_p(context, exp) ?
+ new RubyBigDecimal(context.runtime, BigDecimal.ONE) :
+ getZero(context, 1);
}
- private static IRubyObject vpPrecLimit(final Ruby runtime) {
- return runtime.getClass("BigDecimal").searchInternalModuleVariable("vpPrecLimit");
+ private static IRubyObject vpPrecLimit(ThreadContext context) {
+ return context.runtime.getClass("BigDecimal").searchInternalModuleVariable("vpPrecLimit");
}
- private static int getPrecLimit(final Ruby runtime) {
- return RubyNumeric.fix2int(vpPrecLimit(runtime));
+ private static int getPrecLimit(ThreadContext context) {
+ return RubyNumeric.fix2int(vpPrecLimit(context));
}
@JRubyMethod(name = "**")
@@ -1188,17 +1175,15 @@ public IRubyObject op_power(ThreadContext context, IRubyObject exp) {
@JRubyMethod(name = "power")
public IRubyObject op_power(ThreadContext context, IRubyObject exp, IRubyObject prec) {
- final Ruby runtime = context.runtime;
-
- if (isNaN()) return getNaN(runtime);
+ if (isNaN()) return getNaN(context);
if (!(exp instanceof RubyNumeric)) throw typeError(context, exp, "scalar Numeric");
if (exp instanceof RubyBignum || exp instanceof RubyFixnum) {
} else if (exp instanceof RubyFloat) {
double d = ((RubyFloat) exp).getValue();
if (d == Math.round(d)) {
- exp = RubyNumeric.fixable(runtime, d) ?
- RubyFixnum.newFixnum(runtime, (long) d) : RubyBignum.newBignorm(runtime, d);
+ exp = RubyNumeric.fixable(context.runtime, d) ?
+ newFixnum(context, (long) d) : RubyBignum.newBignorm(context.runtime, d);
}
} else if (exp instanceof RubyRational) {
if (Numeric.f_zero_p(context, Numeric.f_numerator(context, exp))) {
@@ -1207,7 +1192,7 @@ public IRubyObject op_power(ThreadContext context, IRubyObject exp, IRubyObject
exp = Numeric.f_numerator(context, exp);
}
} else if (exp instanceof RubyBigDecimal) {
- IRubyObject zero = RubyNumeric.int2fix(runtime, 0);
+ IRubyObject zero = RubyNumeric.int2fix(context.runtime, 0);
IRubyObject rounded = ((RubyBigDecimal)exp).round(context, new IRubyObject[]{zero});
if (((RubyBigDecimal)exp).eql_p(context, rounded).isTrue()) {
exp = ((RubyBigDecimal)exp).to_int();
@@ -1236,22 +1221,22 @@ public IRubyObject op_power(ThreadContext context, IRubyObject exp, IRubyObject
} else if (exp instanceof RubyBignum) {
BigDecimal absValue = value.abs();
if (absValue.equals(BigDecimal.ONE)) {
- return new RubyBigDecimal(runtime, BigDecimal.ONE, 0, 1) ;
+ return new RubyBigDecimal(context.runtime, BigDecimal.ONE, 0, 1) ;
} else if (absValue.compareTo(BigDecimal.ONE) == -1) {
if (Numeric.f_negative_p(context, exp)) {
- return getInfinity(runtime, (isEven((RubyBignum)exp) ? 1 : -1 ) * value.signum());
+ return getInfinity(context, (isEven((RubyBignum)exp) ? 1 : -1 ) * value.signum());
} else if (Numeric.f_negative_p(context, this) && isEven((RubyBignum)exp)) {
- return getZero(runtime, -1);
+ return getZero(context, -1);
} else {
- return getZero(runtime, 1);
+ return getZero(context, 1);
}
} else {
if (!Numeric.f_negative_p(context, exp)) {
- return getInfinity(runtime, (isEven((RubyBignum)exp) ? 1 : -1 ) * value.signum());
+ return getInfinity(context, (isEven((RubyBignum)exp) ? 1 : -1 ) * value.signum());
} else if(value.signum() == -1 && isEven((RubyBignum)exp)) {
- return getZero(runtime, -1);
+ return getZero(context, -1);
} else {
- return getZero(runtime, 1);
+ return getZero(context, 1);
}
}
} else if ( ! ( exp instanceof RubyInteger ) ) {
@@ -1260,17 +1245,15 @@ public IRubyObject op_power(ThreadContext context, IRubyObject exp, IRubyObject
BigDecimal expVal = BigDecimal.valueOf( ((RubyNumeric) exp).getDoubleValue() );
BigDecimal[] divAndRem = expVal.divideAndRemainder(BigDecimal.ONE);
times = divAndRem[0].intValueExact(); rem = divAndRem[1].doubleValue();
- }
- else {
+ } else {
times = RubyNumeric.fix2int(exp); rem = 0;
}
BigDecimal pow;
if ( times < 0 ) {
- if (isZero()) return getInfinity(context.runtime, value.signum());
+ if (isZero()) return getInfinity(context, value.signum());
pow = powNegative(times);
- }
- else {
+ } else {
pow = value.pow(times);
}
@@ -1280,11 +1263,9 @@ public IRubyObject op_power(ThreadContext context, IRubyObject exp, IRubyObject
pow = pow.multiply( BigDecimal.valueOf(remPow) );
}
- if (!prec.isNil()) {
- pow = pow.setScale(nx, getRoundingMode(context.runtime));
- }
+ if (!prec.isNil()) pow = pow.setScale(nx, getRoundingMode(context));
- return new RubyBigDecimal(runtime, pow);
+ return new RubyBigDecimal(context.runtime, pow);
}
// mri bigdecimal_power_by_bigdecimal
@@ -1316,7 +1297,7 @@ private BigDecimal powNegative(final int times) {
@JRubyMethod(name = "+")
public IRubyObject op_plus(ThreadContext context, IRubyObject b) {
- return addInternal(context, getVpValueWithPrec(context, b, false), b, vpPrecLimit(context.runtime));
+ return addInternal(context, getVpValueWithPrec(context, b, false), b, vpPrecLimit(context));
}
@JRubyMethod(name = "add")
@@ -1325,7 +1306,6 @@ public IRubyObject add2(ThreadContext context, IRubyObject b, IRubyObject digits
}
private IRubyObject addInternal(ThreadContext context, RubyBigDecimal val, IRubyObject b, IRubyObject digits) {
- final Ruby runtime = context.runtime;
int prec = getPositiveInt(context, digits);
if (val == null) {
// TODO:
@@ -1336,46 +1316,39 @@ private IRubyObject addInternal(ThreadContext context, RubyBigDecimal val, IRuby
// We'll use ours for now, thus providing an ability to add Floats.
RubyBigDecimal ret = (RubyBigDecimal) callCoerced(context, sites(context).op_plus, b, true);
if (ret != null) {
- ret.setResult(prec);
+ ret.setResult(context, prec);
}
return ret;
}
RubyBigDecimal res = addSpecialCases(context, val);
if ( res != null ) return res;
- MathContext mathContext = new MathContext(prec, getRoundingMode(runtime));
- return new RubyBigDecimal(runtime, value.add(val.value, mathContext)).setResult(prec);
+ MathContext mathContext = new MathContext(prec, getRoundingMode(context));
+ return new RubyBigDecimal(context.runtime, value.add(val.value, mathContext)).setResult(context, prec);
}
private static int getPositiveInt(ThreadContext context, IRubyObject arg) {
int value = Convert.castAsFixnum(context, arg).getIntValue();
- if (value < 0) throw context.runtime.newArgumentError("argument must be positive");
+ if (value < 0) throw argumentError(context, "argument must be positive");
return value;
}
private RubyBigDecimal addSpecialCases(ThreadContext context, RubyBigDecimal val) {
- if (isNaN() || val.isNaN) {
- return getNaN(context.runtime);
- }
+ if (isNaN() || val.isNaN) return getNaN(context);
+
if (isZero()) {
- if (val.isZero()) {
- return getZero(context.runtime, zeroSign == val.zeroSign ? zeroSign : 1);
- }
- if (val.isInfinity()) {
- return getInfinity(context.runtime, val.infinitySign);
- }
+ if (val.isZero()) return getZero(context, zeroSign == val.zeroSign ? zeroSign : 1);
+ if (val.isInfinity()) return getInfinity(context, val.infinitySign);
return new RubyBigDecimal(context.runtime, val.value);
}
int sign = infinitySign * val.infinitySign;
- if (sign > 0) return getInfinity(context.runtime, infinitySign);
- if (sign < 0) return getNaN(context.runtime);
+ if (sign > 0) return getInfinity(context, infinitySign);
+ if (sign < 0) return getNaN(context);
if (sign == 0) {
sign = infinitySign + val.infinitySign;
- if (sign != 0) {
- return getInfinity(context.runtime, sign);
- }
+ if (sign != 0) return getInfinity(context, sign);
}
return null;
}
@@ -1389,9 +1362,9 @@ public IRubyObject op_uplus() {
@Override
@JRubyMethod(name = "-@")
public IRubyObject op_uminus(ThreadContext context) {
- if (isNaN()) return getNaN(context.runtime);
- if (isInfinity()) return getInfinity(context.runtime, -infinitySign);
- if (isZero()) return getZero(context.runtime, -zeroSign);
+ if (isNaN()) return getNaN(context);
+ if (isInfinity()) return getInfinity(context, -infinitySign);
+ if (isZero()) return getZero(context, -zeroSign);
return new RubyBigDecimal(context.runtime, value.negate());
}
@@ -1407,36 +1380,29 @@ public IRubyObject sub2(ThreadContext context, IRubyObject b, IRubyObject n) {
}
private IRubyObject subInternal(ThreadContext context, RubyBigDecimal val, IRubyObject b, int prec) {
- if (val == null) return ((RubyBigDecimal)callCoerced(context, sites(context).op_minus, b, true)).setResult(prec);
+ if (val == null) return ((RubyBigDecimal)callCoerced(context, sites(context).op_minus, b, true)).setResult(context, prec);
RubyBigDecimal res = subSpecialCases(context, val);
- return res != null ? res : new RubyBigDecimal(context.runtime, value.subtract(val.value)).setResult(prec);
+ return res != null ? res : new RubyBigDecimal(context.runtime, value.subtract(val.value)).setResult(context, prec);
}
private RubyBigDecimal subSpecialCases(ThreadContext context, RubyBigDecimal val) {
- if (isNaN() || val.isNaN()) {
- return getNaN(context.runtime);
- }
+ if (isNaN() || val.isNaN()) return getNaN(context);
+
if (isZero()) {
- if (val.isZero()) return getZero(context.runtime, zeroSign * val.zeroSign);
- if (val.isInfinity()) return getInfinity(context.runtime, val.infinitySign * -1);
+ if (val.isZero()) return getZero(context, zeroSign * val.zeroSign);
+ if (val.isInfinity()) return getInfinity(context, val.infinitySign * -1);
return new RubyBigDecimal(context.runtime, val.value.negate());
}
int sign = infinitySign * val.infinitySign;
- if (sign > 0) return getNaN(context.runtime);
- if (sign < 0) return getInfinity(context.runtime, infinitySign);
+ if (sign > 0) return getNaN(context);
+ if (sign < 0) return getInfinity(context, infinitySign);
if (sign == 0) {
- if (isInfinity()) {
- return this;
- }
- if (val.isInfinity()) {
- return getInfinity(context.runtime, val.infinitySign * -1);
- }
+ if (isInfinity()) return this;
+ if (val.isInfinity()) return getInfinity(context, val.infinitySign * -1);
sign = infinitySign + val.infinitySign;
- if (sign != 0) {
- return getInfinity(context.runtime, sign);
- }
+ if (sign != 0) return getInfinity(context, sign);
}
return null;
}
@@ -1447,7 +1413,7 @@ public IRubyObject op_divide(ThreadContext context, IRubyObject other) {
RubyBigDecimal val = getVpValueWithPrec(context, other, false);
if (val == null) return callCoerced(context, sites(context).op_quo, other, true);
- if (isNaN() || val.isNaN()) return getNaN(context.runtime);
+ if (isNaN() || val.isNaN()) return getNaN(context);
RubyBigDecimal div = divSpecialCases(context, val);
if (div != null) return div;
@@ -1473,7 +1439,6 @@ public IRubyObject op_quo(ThreadContext context, IRubyObject object, IRubyObject
}
private RubyBigDecimal quoImpl(ThreadContext context, RubyBigDecimal that) {
- Ruby runtime = context.runtime;
int mx = this.getPrecisionScale()[0];
int mxb = that.getPrecisionScale()[0];
if (mx < mxb) mx = mxb;
@@ -1482,14 +1447,14 @@ private RubyBigDecimal quoImpl(ThreadContext context, RubyBigDecimal that) {
mx = VP_DOUBLE_FIG * 2;
}
- final int limit = getPrecLimit(runtime);
+ final int limit = getPrecLimit(context);
if (limit > 0 && limit < mx) mx = limit;
mx = (mx + 8) / BASE_FIG * BASE_FIG;
- RoundingMode mode = getRoundingMode(runtime);
+ RoundingMode mode = getRoundingMode(context);
MathContext mathContext = new MathContext(mx * 2, mode);
BigDecimal ret = divide(this.value, that.value, mathContext).setScale(mx, mode);
- return new RubyBigDecimal(context.runtime, ret).setResult(limit);
+ return new RubyBigDecimal(context.runtime, ret).setResult(context, limit);
}
// NOTE: base on Android's
@@ -1536,15 +1501,15 @@ private static RubyBigDecimal div2Impl(ThreadContext context, RubyNumeric a, Rub
RubyBigDecimal thiz = getVpValue(context, a, true);
RubyBigDecimal that = getVpValue(context, b, true);
- if (thiz.isNaN() || that.isNaN()) return getNaN(context.runtime);
+ if (thiz.isNaN() || that.isNaN()) return getNaN(context);
RubyBigDecimal div = thiz.divSpecialCases(context, that);
if (div != null) return div;
int mx = thiz.value.precision() + that.value.precision() + 2;
- MathContext mathContext = new MathContext((mx * 2 + 2) * BASE_FIG, getRoundingMode(context.runtime));
- return new RubyBigDecimal(context.runtime, thiz.value.divide(that.value, mathContext)).setResult(ix);
+ MathContext mathContext = new MathContext((mx * 2 + 2) * BASE_FIG, getRoundingMode(context));
+ return new RubyBigDecimal(context.runtime, thiz.value.divide(that.value, mathContext)).setResult(context, ix);
}
// mri : BigDecimal_div3
@@ -1554,25 +1519,24 @@ public IRubyObject op_div(ThreadContext context, IRubyObject other) {
}
private RubyInteger idiv(ThreadContext context, RubyRational val) {
- if (isNaN()) throw newNaNFloatDomainError(context.runtime);
+ if (isNaN()) throw newNaNFloatDomainError(context);
if (isInfinity()) { // NOTE: MRI is inconsistent with div(other, d) impl
- throw newInfinityFloatDomainError(context.runtime, infinitySign);
+ throw newInfinityFloatDomainError(context, infinitySign);
}
if (val.isZero()) throw context.runtime.newZeroDivisionError();
BigDecimal result = this.value.multiply(toBigDecimal(context, val.getDenominator()))
.divideToIntegralValue(toBigDecimal(context, val.getNumerator()));
- return toInteger(context.runtime, result);
+ return toInteger(context, result);
}
private static final BigDecimal MAX_FIX = BigDecimal.valueOf(RubyFixnum.MAX);
private static final BigDecimal MIN_FIX = BigDecimal.valueOf(RubyFixnum.MIN);
- private static RubyInteger toInteger(final Ruby runtime, final BigDecimal result) {
- if (result.compareTo(MAX_FIX) <= 0 && result.compareTo(MIN_FIX) >= 0) {
- return RubyFixnum.newFixnum(runtime, result.longValue());
- }
- return RubyBignum.newBignum(runtime, result.toBigInteger());
+ private static RubyInteger toInteger(ThreadContext context, final BigDecimal result) {
+ return result.compareTo(MAX_FIX) <= 0 && result.compareTo(MIN_FIX) >= 0 ?
+ newFixnum(context, result.longValue()) :
+ RubyBignum.newBignum(context.runtime, result.toBigInteger());
}
// mri : BigDecimal_div2
@@ -1582,15 +1546,15 @@ public IRubyObject op_div(ThreadContext context, IRubyObject other, IRubyObject
if (digits.isNil()) {
if (val == null) return callCoerced(context, sites(context).div, other, true);
- if (isNaN() || val.isNaN()) throw newNaNFloatDomainError(context.runtime);
+ if (isNaN() || val.isNaN()) throw newNaNFloatDomainError(context);
if (isInfinity()) { // NOTE: MRI is inconsistent with div(other, d) impl
- if (val.isInfinity()) throw newNaNFloatDomainError(context.runtime);
- throw newInfinityFloatDomainError(context.runtime, infinitySign);
+ if (val.isInfinity()) throw newNaNFloatDomainError(context);
+ throw newInfinityFloatDomainError(context, infinitySign);
}
if (val.isZero()) throw context.runtime.newZeroDivisionError();
if (val.isInfinity()) return RubyFixnum.zero(context.runtime);
- return toInteger(context.runtime, this.value.divideToIntegralValue(val.value));
+ return toInteger(context, this.value.divideToIntegralValue(val.value));
}
final int scale = RubyNumeric.fix2int(digits);
@@ -1599,43 +1563,38 @@ public IRubyObject op_div(ThreadContext context, IRubyObject other, IRubyObject
if (scale == 0) return op_divide(context, other);
val = getVpValue(context, other, true);
- if (isNaN() || val.isNaN()) return getNaN(context.runtime);
+ if (isNaN() || val.isNaN()) return getNaN(context);
RubyBigDecimal div = divSpecialCases(context, val);
if (div != null) return div;
- MathContext mathContext = new MathContext(scale, getRoundingMode(context.runtime));
- return new RubyBigDecimal(context.runtime, value.divide(val.value, mathContext)).setResult(scale);
+ MathContext mathContext = new MathContext(scale, getRoundingMode(context));
+ return new RubyBigDecimal(context.runtime, value.divide(val.value, mathContext)).setResult(context, scale);
}
private RubyBigDecimal divSpecialCases(ThreadContext context, RubyBigDecimal val) {
if (isInfinity()) {
- if (val.isInfinity()) return getNaN(context.runtime);
- return getInfinity(context.runtime, infinitySign * val.value.signum());
+ return val.isInfinity() ? getNaN(context) : getInfinity(context, infinitySign * val.value.signum());
}
- if (val.isInfinity()) return getZero(context.runtime, value.signum() * val.infinitySign);
+ if (val.isInfinity()) return getZero(context, value.signum() * val.infinitySign);
if (val.isZero()) {
- if (isZero()) return getNaN(context.runtime);
- if (isZeroDivideExceptionMode(context.runtime)) {
- throw context.runtime.newFloatDomainError("Divide by zero");
- }
+ if (isZero()) return getNaN(context);
+ if (isZeroDivideExceptionMode(context)) throw context.runtime.newFloatDomainError("Divide by zero");
+
int sign1 = isInfinity() ? infinitySign : value.signum();
- return getInfinity(context.runtime, sign1 * val.zeroSign, InfinityErrorMsgType.In);
+ return getInfinity(context, sign1 * val.zeroSign, InfinityErrorMsgType.In);
}
- if (isZero()) return getZero(context.runtime, zeroSign * val.value.signum());
+ if (isZero()) return getZero(context, zeroSign * val.value.signum());
return null;
}
private IRubyObject cmp(ThreadContext context, final IRubyObject arg, final char op) {
final int e;
- RubyBigDecimal rb;
- if (arg instanceof RubyRational) {
- rb = getVpValueWithPrec(context, arg, false);
- } else {
- rb = getVpValue(context, arg, false);
- }
+ RubyBigDecimal rb = arg instanceof RubyRational ?
+ getVpValueWithPrec(context, arg, false) : getVpValue(context, arg, false);
+
if (rb == null) {
String id = "!=";
switch (op) {
@@ -1658,7 +1617,7 @@ private IRubyObject cmp(ThreadContext context, final IRubyObject arg, final char
IRubyObject cmp = callCoerced(context, id, arg);
if (cmp == context.nil) { // arg.coerce failed
- throw context.runtime.newArgumentError("comparison of BigDecimal with "+ errMessageType(context, arg) +" failed");
+ throw argumentError(context, "comparison of BigDecimal with "+ errMessageType(context, arg) +" failed");
}
return cmp;
}
@@ -1722,12 +1681,17 @@ public IRubyObject op_ge(ThreadContext context, IRubyObject arg) {
return cmp(context, arg, 'G');
}
- @JRubyMethod
+ @Deprecated(since = "10.0", forRemoval = true)
public IRubyObject abs() {
- if (isNaN()) return getNaN(getRuntime());
- if (isInfinity()) return getInfinity(getRuntime(), 1);
+ return abs(getCurrentContext());
+ }
+
+ @JRubyMethod
+ public IRubyObject abs(ThreadContext context) {
+ if (isNaN()) return getNaN(context);
+ if (isInfinity()) return getInfinity(context, 1);
- return new RubyBigDecimal(getRuntime(), value.abs()).setResult();
+ return new RubyBigDecimal(context.runtime, value.abs()).setResult(context);
}
@JRubyMethod
@@ -1806,14 +1770,16 @@ public IRubyObject divmod(ThreadContext context, IRubyObject other) {
RubyBigDecimal val = getVpValueWithPrec(context, other, false);
if (val == null) return callCoerced(context, sites(context).divmod, other, true);
- if (isNaN() || val.isNaN() || isInfinity() && val.isInfinity()) return RubyArray.newArray(runtime, getNaN(runtime), getNaN(runtime));
+ if (isNaN() || val.isNaN() || isInfinity() && val.isInfinity()) {
+ return RubyArray.newArray(runtime, getNaN(context), getNaN(context));
+ }
if (val.isZero()) throw runtime.newZeroDivisionError();
if (isInfinity()) {
int sign = (infinitySign == val.value.signum()) ? 1 : -1;
- return RubyArray.newArray(runtime, getInfinity(runtime, sign), getNaN(runtime));
+ return RubyArray.newArray(runtime, getInfinity(context, sign), getNaN(context));
}
- if (val.isInfinity()) return RubyArray.newArray(runtime, getZero(runtime, val.value.signum()), this);
- if (isZero()) return RubyArray.newArray(runtime, getZero(runtime, value.signum()), getZero(runtime, value.signum()));
+ if (val.isInfinity()) return RubyArray.newArray(runtime, getZero(context, val.value.signum()), this);
+ if (isZero()) return RubyArray.newArray(runtime, getZero(context, value.signum()), getZero(context, value.signum()));
// Java and MRI definitions of divmod are different.
BigDecimal[] divmod = value.divideAndRemainder(val.value);
@@ -1850,8 +1816,8 @@ public IRubyObject finite_p() {
}
private RubyBigDecimal floorNaNInfinityCheck(ThreadContext context) {
- if (isNaN()) throw newNaNFloatDomainError(context.runtime);
- if (isInfinity()) throw newInfinityFloatDomainError(context.runtime, infinitySign);
+ if (isNaN()) throw newNaNFloatDomainError(context);
+ if (isInfinity()) throw newInfinityFloatDomainError(context, infinitySign);
return null;
}
@@ -1869,18 +1835,17 @@ public IRubyObject floor(ThreadContext context) {
@JRubyMethod
public IRubyObject floor(ThreadContext context, IRubyObject arg) {
RubyBigDecimal res = floorNaNInfinityCheck(context);
- if (res != null) return res;
- return floorImpl(context, RubyNumeric.fix2int(arg));
+ return res != null ? res : floorImpl(context, RubyNumeric.fix2int(arg));
}
@JRubyMethod
public IRubyObject frac(ThreadContext context) {
- if (isNaN()) return getNaN(context.runtime);
- if (isInfinity()) return getInfinity(context.runtime, infinitySign);
+ if (isNaN()) return getNaN(context);
+ if (isInfinity()) return getInfinity(context, infinitySign);
- if (value.scale() > 0 && value.precision() < value.scale()) return new RubyBigDecimal(context.runtime, value);
-
- return new RubyBigDecimal(context.runtime, value.subtract(((RubyBigDecimal)fix()).value));
+ return value.scale() > 0 && value.precision() < value.scale() ?
+ new RubyBigDecimal(context.runtime, value) :
+ new RubyBigDecimal(context.runtime, value.subtract(((RubyBigDecimal)fix()).value));
}
@JRubyMethod(name = "infinite?")
@@ -1991,27 +1956,24 @@ public IRubyObject precs(ThreadContext context) {
public IRubyObject round(ThreadContext context, IRubyObject[] args) {
int argc = Arity.checkArgumentCount(context, args, 0, 2);
- Ruby runtime = context.runtime;
-
// Special treatment for BigDecimal::NAN and BigDecimal::INFINITY
//
// If round is called without any argument, we should raise a
// FloatDomainError. Otherwise, we don't have to call round ;
// we can simply return the number itself.
if (isNaN()) {
- if (argc == 0) {
- throw newNaNFloatDomainError(runtime);
- }
- return getNaN(runtime);
+ if (argc == 0) throw newNaNFloatDomainError(context);
+
+ return getNaN(context);
}
if (isInfinity()) {
if (argc == 0) {
- throw newInfinityFloatDomainError(runtime, infinitySign);
+ throw newInfinityFloatDomainError(context, infinitySign);
}
- return getInfinity(runtime, infinitySign);
+ return getInfinity(context, infinitySign);
}
- RoundingMode mode = getRoundingMode(runtime);
+ RoundingMode mode = getRoundingMode(context);
int scale = 0;
boolean roundToInt = false;
@@ -2021,7 +1983,7 @@ public IRubyObject round(ThreadContext context, IRubyObject[] args) {
scale = num2int(args[0]);
break;
case 1:
- if (ArgsUtil.getOptionsArg(runtime, args[0]) == context.nil) {
+ if (ArgsUtil.getOptionsArg(context.runtime, args[0]) == context.nil) {
scale = num2int(args[0]);
if (scale < 1) {
roundToInt = true;
@@ -2044,12 +2006,12 @@ public IRubyObject round(ThreadContext context, IRubyObject[] args) {
// ...round to that digit
BigDecimal rounded = normalized.setScale(0, mode);
// ...and shift the result back to the left (multiply by 10**(abs(scale)))
- bigDecimal = new RubyBigDecimal(runtime, rounded.movePointLeft(scale));
+ bigDecimal = new RubyBigDecimal(context.runtime, rounded.movePointLeft(scale));
} else {
- bigDecimal = new RubyBigDecimal(runtime, value.setScale(scale, mode));
+ bigDecimal = new RubyBigDecimal(context.runtime, value.setScale(scale, mode));
}
- return roundToInt ? bigDecimal.to_int(runtime) : bigDecimal;
+ return roundToInt ? bigDecimal.to_int(context.runtime) : bigDecimal;
}
public IRubyObject round(ThreadContext context, IRubyObject scale, IRubyObject mode) {
@@ -2072,17 +2034,17 @@ private static int rubyRoundingModeFromJavaRoundingMode(ThreadContext context, R
} else if (mode.equals(RoundingMode.HALF_EVEN)) {
return ROUND_HALF_EVEN;
} else {
- throw context.runtime.newArgumentError("invalid rounding mode");
+ throw argumentError(context, "invalid rounding mode");
}
}
//this relies on the Ruby rounding enumerations == Java ones, which they (currently) all are
private static RoundingMode javaRoundingModeFromRubyRoundingMode(ThreadContext context, IRubyObject arg) {
- if (arg == context.nil) return getRoundingMode(context.runtime);
+ if (arg == context.nil) return getRoundingMode(context);
IRubyObject opts = ArgsUtil.getOptionsArg(context.runtime, arg);
if (opts != context.nil) {
arg = ArgsUtil.extractKeywordArg(context, (RubyHash) opts, "half");
- if (arg == null || arg == context.nil) return getRoundingMode(context.runtime);
+ if (arg == null || arg == context.nil) return getRoundingMode(context);
String roundingMode;
if (arg instanceof RubySymbol) {
roundingMode = arg.asJavaString();
@@ -2097,7 +2059,7 @@ private static RoundingMode javaRoundingModeFromRubyRoundingMode(ThreadContext c
case "even" :
return RoundingMode.HALF_EVEN;
default :
- throw context.runtime.newArgumentError("invalid rounding mode (" + roundingMode + ")");
+ throw argumentError(context, "invalid rounding mode (" + roundingMode + ")");
}
}
if (arg instanceof RubySymbol) {
@@ -2123,7 +2085,7 @@ private static RoundingMode javaRoundingModeFromRubyRoundingMode(ThreadContext c
case "floor" :
return RoundingMode.FLOOR;
default :
- throw context.runtime.newArgumentError("invalid rounding mode (" + roundingMode + ")");
+ throw argumentError(context, "invalid rounding mode (" + roundingMode + ")");
}
} else {
int ordinal = num2int(arg);
@@ -2143,7 +2105,7 @@ private static RoundingMode javaRoundingModeFromRubyRoundingMode(ThreadContext c
case ROUND_HALF_EVEN :
return RoundingMode.HALF_EVEN;
default :
- throw context.runtime.newArgumentError("invalid rounding mode");
+ throw argumentError(context, "invalid rounding mode");
}
}
}
@@ -2198,53 +2160,66 @@ private int getExponent() {
return val.precision() - val.scale();
}
- @JRubyMethod
+ @Deprecated(since = "10.0", forRemoval = true)
public IRubyObject sqrt(IRubyObject arg) {
- Ruby runtime = getRuntime();
- if (isNaN()) throw runtime.newFloatDomainError("sqrt of 'NaN'(Not a Number)");
- if ((isInfinity() && infinitySign < 0) || value.signum() < 0) throw runtime.newFloatDomainError("sqrt of negative value");
- if (isInfinity() && infinitySign > 0) return getInfinity(runtime, 1);
+ return sqrt(getCurrentContext(), arg);
+ }
- int n = RubyNumeric.num2int(precision(runtime.getCurrentContext())) * (getPrecisionInt(runtime, arg) + 1);
+ @JRubyMethod
+ public IRubyObject sqrt(ThreadContext context, IRubyObject arg) {
+ if (isNaN()) throw context.runtime.newFloatDomainError("sqrt of 'NaN'(Not a Number)");
+ if ((isInfinity() && infinitySign < 0) || value.signum() < 0) {
+ throw context.runtime.newFloatDomainError("sqrt of negative value");
+ }
+ if (isInfinity() && infinitySign > 0) return getInfinity(context, 1);
- return new RubyBigDecimal(runtime, bigSqrt(value, new MathContext(n, RoundingMode.HALF_UP))).setResult();
+ int n = RubyNumeric.num2int(precision(context)) * (getPrecisionInt(context, arg) + 1);
+
+ return new RubyBigDecimal(context.runtime, bigSqrt(value, new MathContext(n, RoundingMode.HALF_UP))).setResult(context);
}
// MRI: GetPrecisionInt(VALUE v)
- private static int getPrecisionInt(final Ruby runtime, final IRubyObject v) {
+ private static int getPrecisionInt(ThreadContext context, final IRubyObject v) {
int n = RubyNumeric.num2int(v);
- if (n < 0) throw runtime.newArgumentError("negative precision");
+ if (n < 0) throw argumentError(context, "negative precision");
return n;
}
+ @Deprecated(since = "10.0", forRemoval = true)
+ public IRubyObject to_f() {
+ return toFloat(getCurrentContext(), true);
+ }
+
@JRubyMethod
- public IRubyObject to_f() { return toFloat(getRuntime(), true); }
+ public IRubyObject to_f(ThreadContext context) {
+ return toFloat(context, true);
+ }
- private RubyFloat toFloat(final Ruby runtime, final boolean checkFlow) {
- if (isNaN()) return RubyFloat.newFloat(runtime, Double.NaN);
- if (isInfinity()) return RubyFloat.newFloat(runtime, infinitySign < 0 ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY);
- if (isZero()) return RubyFloat.newFloat(runtime, zeroSign < 0 ? -0.0 : 0.0);
+ private RubyFloat toFloat(ThreadContext context, final boolean checkFlow) {
+ if (isNaN()) return newFloat(context, Double.NaN);
+ if (isInfinity()) return newFloat(context, infinitySign < 0 ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY);
+ if (isZero()) return newFloat(context, zeroSign < 0 ? -0.0 : 0.0);
int exponent = getExponent();
if (exponent > RubyFloat.MAX_10_EXP + VP_DOUBLE_FIG) {
- if (checkFlow && isOverflowExceptionMode(runtime)) {
- throw runtime.newFloatDomainError("BigDecimal to Float conversion");
+ if (checkFlow && isOverflowExceptionMode(context)) {
+ throw context.runtime.newFloatDomainError("BigDecimal to Float conversion");
}
- return RubyFloat.newFloat(getRuntime(), value.signum() > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY);
+ return newFloat(context, value.signum() > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY);
}
if (exponent < RubyFloat.MIN_10_EXP - VP_DOUBLE_FIG) {
- if (checkFlow && isUnderflowExceptionMode(runtime)) {
- throw runtime.newFloatDomainError("BigDecimal to Float conversion");
+ if (checkFlow && isUnderflowExceptionMode(context)) {
+ throw context.runtime.newFloatDomainError("BigDecimal to Float conversion");
}
- return RubyFloat.newFloat(getRuntime(), 0);
+ return newFloat(context, 0);
}
- return RubyFloat.newFloat(runtime, SafeDoubleParser.doubleValue(value));
+ return newFloat(context, SafeDoubleParser.doubleValue(value));
}
@Override
public RubyFloat convertToFloat() {
- return toFloat(getRuntime(), false);
+ return toFloat(getRuntime().getCurrentContext(), false);
}
public final IRubyObject to_int() {
@@ -2449,9 +2424,9 @@ private RubyString toStringImpl(final Ruby runtime, String arg) {
@Override
public String toString() {
- if ( isNaN() ) return "NaN";
- if ( isInfinity() ) return infinityString(infinitySign);
- if ( isZero() ) return zeroSign < 0 ? "-0.0" : "0.0";
+ if (isNaN()) return "NaN";
+ if (isInfinity()) return infinityString(infinitySign);
+ if (isZero()) return zeroSign < 0 ? "-0.0" : "0.0";
return engineeringValue(null).toString();
}
@@ -2462,33 +2437,35 @@ public IRubyObject to_s(IRubyObject[] args) {
}
// Note: #fix has only no-arg form, but truncate allows optional parameter.
+ @Deprecated(since = "10.0", forRemoval = true)
+ public IRubyObject fix() {
+ return fix(getCurrentContext());
+ }
@JRubyMethod
- public IRubyObject fix() {
- return truncateInternal(getRuntime(), 0);
+ public IRubyObject fix(ThreadContext context) {
+ return truncateInternal(context, 0);
}
- private RubyBigDecimal truncateInternal(final Ruby runtime, int arg) {
- if (isNaN()) return getNaN(runtime);
- if (isInfinity()) return getInfinity(runtime, infinitySign);
+ private RubyBigDecimal truncateInternal(ThreadContext context, int arg) {
+ if (isNaN()) return getNaN(context);
+ if (isInfinity()) return getInfinity(context, infinitySign);
int precision = value.precision() - value.scale() + arg;
- if (precision > 0) {
- return new RubyBigDecimal(runtime, value.round(new MathContext(precision, RoundingMode.DOWN)));
- }
-
- return getZero(runtime, this.zeroSign);
+ return precision > 0 ?
+ new RubyBigDecimal(context.runtime, value.round(new MathContext(precision, RoundingMode.DOWN))) :
+ getZero(context, this.zeroSign);
}
@JRubyMethod
public IRubyObject truncate(ThreadContext context) {
- return truncateInternal(context.runtime, 0).to_int(context.runtime);
+ return truncateInternal(context, 0).to_int(context.runtime);
}
@JRubyMethod
public IRubyObject truncate(ThreadContext context, IRubyObject arg) {
- return truncateInternal(context.runtime, RubyNumeric.fix2int(arg));
+ return truncateInternal(context, RubyNumeric.fix2int(arg));
}
@Override
diff --git a/core/src/main/java/org/jruby/ext/date/RubyDate.java b/core/src/main/java/org/jruby/ext/date/RubyDate.java
index dd951cddb57..6ec61626dec 100644
--- a/core/src/main/java/org/jruby/ext/date/RubyDate.java
+++ b/core/src/main/java/org/jruby/ext/date/RubyDate.java
@@ -62,6 +62,7 @@
import static org.jruby.api.Convert.*;
import static org.jruby.api.Create.newFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.ext.date.DateUtils.*;
import static org.jruby.util.Numeric.*;
@@ -243,39 +244,35 @@ private void initialize(final ThreadContext context, IRubyObject arg, IRubyObjec
private RubyFixnum DAY_MS_CACHE;
private long initMillis(final ThreadContext context, IRubyObject ajd) {
- final Ruby runtime = context.runtime;
// cannot use DateTimeUtils.fromJulianDay since we need to keep ajd as a Rational for precision
// millis, @sub_millis = ((ajd - UNIX_EPOCH_IN_AJD) * 86400000).divmod(1)
IRubyObject val;
- if (ajd instanceof RubyFixnum) {
- val = ((RubyFixnum) ajd).op_minus(context, 4881175 / 2);
+ if (ajd instanceof RubyFixnum fix) {
+ val = fix.op_minus(context, 4881175 / 2);
val = ((RubyFixnum) val).op_mul(context, DAY_MS);
- val = ((RubyInteger) val).op_plus(context, RubyFixnum.newFixnum(runtime, DAY_MS / 2)); // missing 1/2
- }
- else {
- RubyRational _UNIX_EPOCH_IN_AJD = RubyRational.newRational(runtime, -4881175, 2); // -(1970-01-01)
+ val = ((RubyInteger) val).op_plus(context, newFixnum(context, DAY_MS / 2)); // missing 1/2
+ } else {
+ RubyRational _UNIX_EPOCH_IN_AJD = RubyRational.newRational(context.runtime, -4881175, 2); // -(1970-01-01)
val = _UNIX_EPOCH_IN_AJD.op_plus(context, ajd);
val = DAY_MS(context).op_mul(context, val);
}
- if (val instanceof RubyFixnum) {
- return ((RubyFixnum) val).getLongValue();
- }
+ if (val instanceof RubyFixnum fix) return fix.getLongValue();
// fallback
val = ((RubyNumeric) val).divmod(context, RubyFixnum.one(context.runtime));
IRubyObject millis = ((RubyArray) val).eltInternal(0);
- if (!(millis instanceof RubyFixnum)) { // > java.lang.Long::MAX_VALUE
- throw runtime.newArgumentError("Date out of range: millis=" + millis + " (" + millis.getMetaClass() + ")");
+ if (!(millis instanceof RubyFixnum ms)) { // > java.lang.Long::MAX_VALUE
+ throw argumentError(context, "Date out of range: millis=" + millis + " (" + millis.getMetaClass() + ")");
}
IRubyObject subMillis = ((RubyArray) val).eltInternal(1);
this.subMillisNum = ((RubyNumeric) subMillis).numerator(context).convertToInteger().getLongValue();
this.subMillisDen = ((RubyNumeric) subMillis).denominator(context).convertToInteger().getLongValue();
- return ((RubyFixnum) millis).getLongValue();
+ return ms.getLongValue();
}
private RubyFixnum DAY_MS(final ThreadContext context) {
@@ -1511,14 +1508,13 @@ public static Chronology getChronology(ThreadContext context, final long sg, fin
if (off == 0) {
if (sg == ITALY) return CHRONO_ITALY_UTC;
zone = DateTimeZone.UTC;
- }
- else {
+ } else {
try {
zone = DateTimeZone.forOffsetMillis(off * 1000); // off in seconds
} // NOTE: JODA only allows 'valid': -23:59:59.999 to +23:59:59.999
catch (IllegalArgumentException ex) { // while MRI handles 25/24 fine
debug(context, "invalid offset", ex);
- throw context.runtime.newArgumentError("invalid offset: " + off);
+ throw argumentError(context, "invalid offset: " + off);
}
}
return getChronology(context, sg, zone);
diff --git a/core/src/main/java/org/jruby/ext/fiber/ThreadFiber.java b/core/src/main/java/org/jruby/ext/fiber/ThreadFiber.java
index 8e17e55305a..8cd4e0abb95 100644
--- a/core/src/main/java/org/jruby/ext/fiber/ThreadFiber.java
+++ b/core/src/main/java/org/jruby/ext/fiber/ThreadFiber.java
@@ -39,8 +39,7 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.castAsHash;
-import static org.jruby.api.Error.frozenError;
-import static org.jruby.api.Error.typeError;
+import static org.jruby.api.Error.*;
public class ThreadFiber extends RubyObject implements ExecutionContext {
@@ -116,7 +115,7 @@ public static void initRootFiber(ThreadContext context, RubyThread currentThread
public IRubyObject initialize(ThreadContext context, Block block) {
Ruby runtime = context.runtime;
- if (!block.isGiven()) throw runtime.newArgumentError("tried to create Proc object without block");
+ if (!block.isGiven()) throw argumentError(context, "tried to create Proc object without block");
inheritFiberStorage(context);
@@ -124,18 +123,16 @@ public IRubyObject initialize(ThreadContext context, Block block) {
FiberData currentFiberData = context.getFiber().data;
- thread = createThread(runtime, data, currentFiberData.queue, block);
+ thread = createThread(context, data, currentFiberData.queue, block);
return context.nil;
}
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject _opts, Block block) {
- Ruby runtime = context.runtime;
-
- if (!block.isGiven()) throw runtime.newArgumentError("tried to create Proc object without block");
+ if (!block.isGiven()) throw argumentError(context, "tried to create Proc object without block");
- IRubyObject opts = ArgsUtil.getOptionsArg(runtime, _opts);
+ IRubyObject opts = ArgsUtil.getOptionsArg(context.runtime, _opts);
boolean blocking = false;
@@ -160,11 +157,11 @@ public IRubyObject initialize(ThreadContext context, IRubyObject _opts, Block bl
}
}
- data = new FiberData(new FiberQueue(runtime), context.getFiberCurrentThread(), this, blocking);
+ data = new FiberData(new FiberQueue(context.runtime), context.getFiberCurrentThread(), this, blocking);
FiberData currentFiberData = context.getFiber().data;
- thread = createThread(runtime, data, currentFiberData.queue, block);
+ thread = createThread(context, data, currentFiberData.queue, block);
return context.nil;
}
@@ -506,7 +503,7 @@ final boolean alive() {
return true;
}
- static RubyThread createThread(final Ruby runtime, final FiberData data, final FiberQueue queue, final Block block) {
+ static RubyThread createThread(ThreadContext context, final FiberData data, final FiberQueue queue, final Block block) {
final AtomicReference fiberThread = new AtomicReference();
// retry with GC once
@@ -514,11 +511,11 @@ static RubyThread createThread(final Ruby runtime, final FiberData data, final F
while (!retried) {
try {
- FIBER_LAUNCHER.accept(runtime, () -> {
- ThreadContext context = runtime.getCurrentContext();
- context.setFiber(data.fiber.get());
- context.useRecursionGuardsFrom(data.parent.getContext());
- RubyThread rubyThread = context.getThread();
+ FIBER_LAUNCHER.accept(context.runtime, () -> {
+ ThreadContext ctxt = context.runtime.getCurrentContext();
+ ctxt.setFiber(data.fiber.get());
+ ctxt.useRecursionGuardsFrom(data.parent.getContext());
+ RubyThread rubyThread = ctxt.getThread();
fiberThread.set(rubyThread);
rubyThread.setFiberCurrentThread(data.parent);
@@ -527,15 +524,15 @@ static RubyThread createThread(final Ruby runtime, final FiberData data, final F
thread.setName("Fiber thread for block at: " + block.getBody().getFile() + ":" + block.getBody().getLine());
try {
- FiberRequest init = data.queue.pop(context);
+ FiberRequest init = data.queue.pop(ctxt);
try {
FiberRequest result;
if (init == NEVER) {
- result = new FiberRequest(block.yieldSpecific(context), RequestType.DATA);
+ result = new FiberRequest(block.yieldSpecific(ctxt), RequestType.DATA);
} else {
- result = new FiberRequest(block.yieldArray(context, init.data, null), RequestType.DATA);
+ result = new FiberRequest(block.yieldArray(ctxt, init.data, null), RequestType.DATA);
}
// Clear ThreadFiber's thread since we're on the way out and need to appear non-alive?
@@ -544,37 +541,37 @@ static RubyThread createThread(final Ruby runtime, final FiberData data, final F
ThreadFiber tf = data.fiber.get();
if (tf != null) tf.thread = null;
- data.prev.data.queue.push(context, result);
+ data.prev.data.queue.push(ctxt, result);
} finally {
// Ensure we do everything for shutdown now
data.queue.shutdown();
- runtime.getThreadService().unregisterCurrentThread(context);
+ context.runtime.getThreadService().unregisterCurrentThread(ctxt);
ThreadFiber tf = data.fiber.get();
if (tf != null) tf.thread = null;
}
} catch (JumpException.FlowControlException fce) {
if (data.prev != null) {
- data.prev.thread.raise(fce.buildException(runtime).getException());
+ data.prev.thread.raise(fce.buildException(context.runtime).getException());
}
} catch (IRBreakJump bj) {
// This is one of the rare cases where IR flow-control jumps
// leaks into the runtime impl.
if (data.prev != null) {
- data.prev.thread.raise(((RaiseException) IRException.BREAK_LocalJumpError.getException(runtime)).getException());
+ data.prev.thread.raise(((RaiseException) IRException.BREAK_LocalJumpError.getException(context.runtime)).getException());
}
} catch (IRReturnJump rj) {
// This is one of the rare cases where IR flow-control jumps
// leaks into the runtime impl.
if (data.prev != null) {
- data.prev.thread.raise(((RaiseException) IRException.RETURN_LocalJumpError.getException(runtime)).getException());
+ data.prev.thread.raise(((RaiseException) IRException.RETURN_LocalJumpError.getException(context.runtime)).getException());
}
} catch (RaiseException re) {
if (data.prev != null) {
- data.prev.data.queue.push(context, new FiberRequest(re.getException(), RequestType.RAISE));
+ data.prev.data.queue.push(ctxt, new FiberRequest(re.getException(), RequestType.RAISE));
}
} catch (Throwable t) {
if (data.prev != null) {
- data.prev.thread.raise(JavaUtil.convertJavaToUsableRubyObject(runtime, t));
+ data.prev.thread.raise(JavaUtil.convertJavaToUsableRubyObject(context.runtime, t));
}
} finally {
thread.setName(oldName);
@@ -771,7 +768,7 @@ public IRubyObject storage(ThreadContext context) {
private void checkSameFiber(ThreadContext context) {
if (context.getFiber() != this) {
- throw context.runtime.newArgumentError("Fiber storage can only be accessed from the Fiber it belongs to");
+ throw argumentError(context, "Fiber storage can only be accessed from the Fiber it belongs to");
}
}
@@ -833,7 +830,7 @@ public static IRubyObject current_scheduler(ThreadContext context, IRubyObject s
// MRI: rb_fiber_set_scheduler
@JRubyMethod(name = "set_scheduler", meta = true)
public static IRubyObject set_scheduler(ThreadContext context, IRubyObject self, IRubyObject scheduler) {
- return context.getFiberCurrentThread().setFiberScheduler(scheduler);
+ return context.getFiberCurrentThread().setFiberScheduler(context, scheduler);
}
}
diff --git a/core/src/main/java/org/jruby/ext/jruby/JRubyExecutionContextLocal.java b/core/src/main/java/org/jruby/ext/jruby/JRubyExecutionContextLocal.java
index 8f83129bd7d..0ce0caf803d 100644
--- a/core/src/main/java/org/jruby/ext/jruby/JRubyExecutionContextLocal.java
+++ b/core/src/main/java/org/jruby/ext/jruby/JRubyExecutionContextLocal.java
@@ -39,6 +39,8 @@
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
+import static org.jruby.api.Error.argumentError;
+
public abstract class JRubyExecutionContextLocal extends RubyObject {
private IRubyObject default_value;
private RubyProc default_proc;
@@ -52,9 +54,8 @@ public JRubyExecutionContextLocal(Ruby runtime, RubyClass type) {
@JRubyMethod(name = "initialize", optional = 1, checkArity = false, visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block) {
if (block.isGiven()) {
- if (args.length != 0) {
- throw context.runtime.newArgumentError("wrong number of arguments");
- }
+ if (args.length != 0) throw argumentError(context, "wrong number of arguments");
+
default_proc = block.getProcObject();
if (default_proc == null) {
default_proc = RubyProc.newProc(context.runtime, block, block.type == Block.Type.LAMBDA ? block.type : Block.Type.PROC);
@@ -63,7 +64,7 @@ public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block b
if (args.length == 1) {
default_value = args[0];
} else if (args.length != 0) {
- throw context.runtime.newArgumentError("wrong number of arguments");
+ throw argumentError(context, "wrong number of arguments");
}
}
return context.nil;
diff --git a/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java b/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java
index ec46d0b0988..00e04440a01 100644
--- a/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java
+++ b/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java
@@ -51,6 +51,7 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.util.URLUtil.getPath;
/**
@@ -215,10 +216,13 @@ public static IRubyObject set_meta_class(ThreadContext context, IRubyObject recv
@JRubyMethod(module = true, name = { "load_ext" })
public static IRubyObject load_ext(ThreadContext context, IRubyObject recv, IRubyObject klass) {
if (klass instanceof RubySymbol) {
- switch(((RubySymbol) klass).asJavaString()) {
- case "string" : CoreExt.loadStringExtensions(context.runtime); return context.tru;
- default : throw context.runtime.newArgumentError(':' + ((RubySymbol) klass).asJavaString());
- }
+ return switch (klass.asJavaString()) {
+ case "string" -> {
+ CoreExt.loadStringExtensions(context.runtime);
+ yield context.tru;
+ }
+ default -> throw argumentError(context, ':' + klass.asJavaString());
+ };
}
return loadExtension(context.runtime, klass.convertToString().toString()) ? context.tru : context.fals;
}
diff --git a/core/src/main/java/org/jruby/ext/pathname/RubyPathname.java b/core/src/main/java/org/jruby/ext/pathname/RubyPathname.java
index c2c2aea20d6..eed5e07b1a8 100644
--- a/core/src/main/java/org/jruby/ext/pathname/RubyPathname.java
+++ b/core/src/main/java/org/jruby/ext/pathname/RubyPathname.java
@@ -32,6 +32,7 @@
import static org.jruby.anno.FrameField.BACKREF;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import org.jruby.*;
import org.jruby.anno.JRubyClass;
@@ -160,16 +161,12 @@ public static RubyPathname newInstance(ThreadContext context, IRubyObject path)
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject path) {
- if (path.respondsTo("to_path")) {
- path = path.callMethod(context, "to_path");
- }
+ if (path.respondsTo("to_path")) path = path.callMethod(context, "to_path");
RubyString str = path.convertToString();
- if (str.getByteList().indexOf('\0') != -1) {
- throw context.runtime.newArgumentError("pathname contains null byte");
- }
+ if (str.getByteList().indexOf('\0') != -1) throw argumentError(context, "pathname contains null byte");
- this.setPath((RubyString) str.dup());
+ setPath((RubyString) str.dup());
return this;
}
diff --git a/core/src/main/java/org/jruby/ext/ripper/RubyRipper.java b/core/src/main/java/org/jruby/ext/ripper/RubyRipper.java
index c5b83d7b4a9..23badcb35f3 100644
--- a/core/src/main/java/org/jruby/ext/ripper/RubyRipper.java
+++ b/core/src/main/java/org/jruby/ext/ripper/RubyRipper.java
@@ -51,6 +51,7 @@
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newFixnum;
import static org.jruby.api.Create.newSymbol;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.lexer.LexingCommon.*;
public class RubyRipper extends RubyObject {
@@ -300,11 +301,9 @@ public IRubyObject initialize(ThreadContext context, IRubyObject src,IRubyObject
@JRubyMethod
public IRubyObject column(ThreadContext context) {
- if (!parser.hasStarted()) throw context.runtime.newArgumentError("method called for uninitialized object");
+ if (!parser.hasStarted()) throw argumentError(context, "method called for uninitialized object");
- if (!parseStarted) return context.nil;
-
- return asFixnum(context, parser.getColumn());
+ return !parseStarted ? context.nil : asFixnum(context, parser.getColumn());
}
@JRubyMethod
@@ -328,11 +327,9 @@ public IRubyObject filename(ThreadContext context) {
@JRubyMethod
public IRubyObject lineno(ThreadContext context) {
- if (!parser.hasStarted()) throw context.runtime.newArgumentError("method called for uninitialized object");
+ if (!parser.hasStarted()) throw argumentError(context, "method called for uninitialized object");
- if (!parseStarted) return context.nil;
-
- return asFixnum(context, parser.getLineno());
+ return !parseStarted ? context.nil : asFixnum(context, parser.getLineno());
}
@JRubyMethod
diff --git a/core/src/main/java/org/jruby/ext/set/RubySet.java b/core/src/main/java/org/jruby/ext/set/RubySet.java
index c764dbfbc46..9ca660335f8 100644
--- a/core/src/main/java/org/jruby/ext/set/RubySet.java
+++ b/core/src/main/java/org/jruby/ext/set/RubySet.java
@@ -52,6 +52,7 @@
import static org.jruby.RubyEnumerator.enumeratorizeWithSize;
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
+import static org.jruby.api.Error.argumentError;
/**
* Native implementation of Ruby's Set (set.rb replacement).
@@ -120,12 +121,16 @@ private RubySet(Ruby runtime, RubyHash hash) {
// since MRI uses Hash.new(false) we'll (initially) strive for maximum compatibility
// ... this is important with Rails using Sprockets at its marshalling Set instances
+ final void allocHash(final ThreadContext context) {
+ setHash(new RubyHash(context.runtime, context.fals));
+ }
+
final void allocHash(final Ruby runtime) {
setHash(new RubyHash(runtime, runtime.getFalse()));
}
- final void allocHash(final Ruby runtime, final int size) {
- setHash(new RubyHash(runtime, runtime.getFalse(), size));
+ final void allocHash(final ThreadContext context, final int size) {
+ setHash(new RubyHash(context.runtime, context.fals, size));
}
final void setHash(final RubyHash hash) {
@@ -172,7 +177,7 @@ private static RubySet newSet(final ThreadContext context, final RubyClass metaC
}
final RubySet initSet(final ThreadContext context, final IRubyObject[] elements, final int off, final int len) {
- allocHash(context.runtime, Math.max(4, len));
+ allocHash(context, Math.max(4, len));
for ( int i = off; i < len; i++ ) {
invokeAdd(context, elements[i]);
}
@@ -198,7 +203,7 @@ public IRubyObject initialize(ThreadContext context, Block block) {
if ( block.isGiven() && context.runtime.isVerbose() ) {
context.runtime.getWarnings().warning(IRubyWarnings.ID.BLOCK_UNUSED, "given block not used");
}
- allocHash(context.runtime);
+ allocHash(context);
return this;
}
@@ -213,7 +218,7 @@ public IRubyObject initialize(ThreadContext context, IRubyObject enume, Block bl
return initWithEnum(context, enume, block);
}
- allocHash(context.runtime);
+ allocHash(context);
return sites(context).merge.call(context, this, this, enume); // TODO site-cache
}
@@ -226,34 +231,28 @@ protected IRubyObject initialize(ThreadContext context, IRubyObject[] args, Bloc
}
private IRubyObject initWithEnum(final ThreadContext context, final IRubyObject enume, final Block block) {
- if ( enume instanceof RubyArray ) {
- RubyArray ary = (RubyArray) enume;
- allocHash(context.runtime, ary.size());
+ if (enume instanceof RubyArray ary) {
+ allocHash(context, ary.size());
for ( int i = 0; i < ary.size(); i++ ) {
invokeAdd(context, block.yield(context, ary.eltInternal(i)));
}
return ary; // done
- }
-
- if ( enume instanceof RubySet ) {
- RubySet set = (RubySet) enume;
- allocHash(context.runtime, set.size());
+ } else if (enume instanceof RubySet set) {
+ allocHash(context, set.size());
for ( IRubyObject elem : set.elementsOrdered() ) {
invokeAdd(context, block.yield(context, elem));
}
return set; // done
- }
-
- final Ruby runtime = context.runtime;
-
- allocHash(runtime);
+ } else {
+ allocHash(context);
- // set.rb do_with_enum :
- return doWithEnum(context, enume, new EachBody(runtime) {
- IRubyObject yieldImpl(ThreadContext context, IRubyObject val) {
- return invokeAdd(context, block.yield(context, val));
- }
- });
+ // set.rb do_with_enum :
+ return doWithEnum(context, enume, new EachBody(context) {
+ IRubyObject yieldImpl(ThreadContext context, IRubyObject val) {
+ return invokeAdd(context, block.yield(context, val));
+ }
+ });
+ }
}
// set.rb do_with_enum (block is required)
@@ -266,7 +265,7 @@ private static IRubyObject doWithEnum(final ThreadContext context, final IRubyOb
return sites.each.call(context, enume, enume, new Block(blockImpl));
}
- throw context.runtime.newArgumentError("value must be enumerable");
+ throw argumentError(context, "value must be enumerable");
}
// YAML doesn't have proper treatment for Set serialization, it dumps it just like
@@ -287,8 +286,8 @@ IRubyObject invokeAdd(final ThreadContext context, final IRubyObject val) {
private static abstract class EachBody extends JavaInternalBlockBody {
- EachBody(final Ruby runtime) {
- super(runtime, Signature.ONE_ARGUMENT);
+ EachBody(final ThreadContext context) {
+ super(context.runtime, Signature.ONE_ARGUMENT);
}
@Override
@@ -347,7 +346,7 @@ public IRubyObject empty_p(ThreadContext context) {
@JRubyMethod(name = "clear")
public IRubyObject rb_clear(ThreadContext context) {
- modifyCheck(context.runtime);
+ modifyCheck(context);
clearImpl();
return this;
@@ -362,18 +361,16 @@ protected void clearImpl() {
*/
@JRubyMethod
public RubySet replace(final ThreadContext context, IRubyObject enume) {
- if ( enume instanceof RubySet ) {
- modifyCheck(context.runtime);
+ if (enume instanceof RubySet) {
+ modifyCheck(context);
clearImpl();
addImplSet(context, (RubySet) enume);
- }
- else {
- final Ruby runtime = context.runtime;
+ } else {
// do_with_enum(enum) # make sure enum is enumerable before calling clear :
- if ( ! enume.getMetaClass().hasModuleInHierarchy(runtime.getEnumerable()) ) {
+ if (!enume.getMetaClass().hasModuleInHierarchy(context.runtime.getEnumerable())) {
// NOTE: likely no need to do this but due MRI compat (do_with_enum) :
- if ( ! enume.respondsTo("each_entry") ) {
- throw runtime.newArgumentError("value must be enumerable");
+ if (!enume.respondsTo("each_entry")) {
+ throw argumentError(context, "value must be enumerable");
}
}
clearImpl();
@@ -408,20 +405,17 @@ public RubySet to_set(final ThreadContext context, final Block block) {
public RubySet to_set(final ThreadContext context, final IRubyObject[] args, final Block block) {
if ( args.length == 0 ) return to_set(context, block);
- final Ruby runtime = context.runtime;
-
- IRubyObject klass = args[0]; final RubyClass Set = runtime.getClass("Set");
+ IRubyObject klass = args[0];
+ final RubyClass Set = context.runtime.getClass("Set");
- if ( klass == Set && args.length == 1 & ! block.isGiven() ) {
- return this;
- }
+ if (klass == Set && args.length == 1 && !block.isGiven()) return this;
final IRubyObject[] rest;
- if ( klass instanceof RubyClass ) {
+ if (klass instanceof RubyClass) {
rest = ArraySupport.newCopy(args, 1, args.length - 1);
- }
- else {
- klass = Set; rest = args;
+ } else {
+ klass = Set;
+ rest = args;
}
RubySet set = new RubySet(context.runtime, (RubyClass) klass);
@@ -446,15 +440,14 @@ public RubySet flatten_merge(final ThreadContext context, IRubyObject set) {
return this;
}
- private void flattenMerge(final ThreadContext context, final IRubyObject set, final IdentityHashMap seen) {
- if ( set instanceof RubySet ) {
- for ( IRubyObject e : ((RubySet) set).elementsOrdered() ) {
+ private void flattenMerge(final ThreadContext context, final IRubyObject setArg, final IdentityHashMap seen) {
+ if (setArg instanceof RubySet set) {
+ for (IRubyObject e: set.elementsOrdered()) {
addFlattened(context, seen, e);
}
- }
- else {
- sites(context).each.call(context, set, set, new Block(
- new EachBody(context.runtime) {
+ } else {
+ sites(context).each.call(context, setArg, setArg, new Block(
+ new EachBody(context) {
IRubyObject yieldImpl(ThreadContext context, IRubyObject e) {
addFlattened(context, seen, e); return context.nil;
}
@@ -464,15 +457,13 @@ IRubyObject yieldImpl(ThreadContext context, IRubyObject e) {
}
private void addFlattened(final ThreadContext context, final IdentityHashMap seen, IRubyObject e) {
- if ( e instanceof RubySet ) {
- if ( seen.containsKey(e) ) {
- throw context.runtime.newArgumentError("tried to flatten recursive Set");
- }
+ if (e instanceof RubySet) {
+ if (seen.containsKey(e)) throw argumentError(context, "tried to flatten recursive Set");
+
seen.put(e, null);
flattenMerge(context, e, seen);
seen.remove(e);
- }
- else {
+ } else {
add(context, e); // self.add(e)
}
}
@@ -506,79 +497,58 @@ final boolean containsImpl(IRubyObject obj) {
}
private boolean allElementsIncluded(final RubySet set) {
- for ( IRubyObject o : set.elements() ) { // set.all? { |o| include?(o) }
- if ( ! containsImpl(o) ) return false;
+ for (IRubyObject o : set.elements()) { // set.all? { |o| include?(o) }
+ if (!containsImpl(o)) return false;
}
return true;
}
// Returns true if the set is a superset of the given set.
@JRubyMethod(name = "superset?", alias = { ">=" })
- public IRubyObject superset_p(final ThreadContext context, IRubyObject set) {
- if ( set instanceof RubySet ) {
- if ( getMetaClass().isInstance(set) ) {
- return this.hash.op_ge(context, ((RubySet) set).hash);
- }
- // size >= set.size && set.all? { |o| include?(o) }
- return asBoolean(context,
- size() >= ((RubySet) set).size() && allElementsIncluded((RubySet) set)
- );
- }
- throw context.runtime.newArgumentError("value must be a set");
+ public IRubyObject superset_p(final ThreadContext context, IRubyObject setArg) {
+ if (!(setArg instanceof RubySet set)) throw argumentError(context, "value must be a set");
+ if (getMetaClass().isInstance(set)) return hash.op_ge(context, set.hash);
+
+ // size >= set.size && set.all? { |o| include?(o) }
+ return asBoolean(context, size() >= set.size() && allElementsIncluded(set));
}
// Returns true if the set is a proper superset of the given set.
@JRubyMethod(name = "proper_superset?", alias = { ">" })
- public IRubyObject proper_superset_p(final ThreadContext context, IRubyObject set) {
- if ( set instanceof RubySet ) {
- if ( getMetaClass().isInstance(set) ) {
- return this.hash.op_gt(context, ((RubySet) set).hash);
- }
- // size >= set.size && set.all? { |o| include?(o) }
- return asBoolean(context,
- size() > ((RubySet) set).size() && allElementsIncluded((RubySet) set)
- );
- }
- throw context.runtime.newArgumentError("value must be a set");
+ public IRubyObject proper_superset_p(final ThreadContext context, IRubyObject setArg) {
+ if (!(setArg instanceof RubySet set)) throw argumentError(context, "value must be a set");
+ if (getMetaClass().isInstance(set)) return hash.op_gt(context, set.hash);
+
+ // size >= set.size && set.all? { |o| include?(o) }
+ return asBoolean(context, size() > set.size() && allElementsIncluded(set));
}
@JRubyMethod(name = "subset?", alias = { "<=" })
- public IRubyObject subset_p(final ThreadContext context, IRubyObject set) {
- if ( set instanceof RubySet ) {
- if ( getMetaClass().isInstance(set) ) {
- return this.hash.op_le(context, ((RubySet) set).hash);
- }
- // size >= set.size && set.all? { |o| include?(o) }
- return asBoolean(context,
- size() <= ((RubySet) set).size() && allElementsIncluded((RubySet) set)
- );
- }
- throw context.runtime.newArgumentError("value must be a set");
+ public IRubyObject subset_p(final ThreadContext context, IRubyObject setArg) {
+ if (!(setArg instanceof RubySet set)) throw argumentError(context, "value must be a set");
+ if (getMetaClass().isInstance(set)) return this.hash.op_le(context, set.hash);
+
+ // size >= set.size && set.all? { |o| include?(o) }
+ return asBoolean(context, size() <= set.size() && allElementsIncluded(set));
}
@JRubyMethod(name = "proper_subset?", alias = { "<" })
- public IRubyObject proper_subset_p(final ThreadContext context, IRubyObject set) {
- if ( set instanceof RubySet ) {
- if ( getMetaClass().isInstance(set) ) {
- return this.hash.op_lt(context, ((RubySet) set).hash);
- }
- // size >= set.size && set.all? { |o| include?(o) }
- return asBoolean(context,
- size() < ((RubySet) set).size() && allElementsIncluded((RubySet) set)
- );
- }
- throw context.runtime.newArgumentError("value must be a set");
+ public IRubyObject proper_subset_p(final ThreadContext context, IRubyObject setArg) {
+ if (!(setArg instanceof RubySet set)) throw argumentError(context, "value must be a set");
+ if (getMetaClass().isInstance(set)) return this.hash.op_lt(context, set.hash);
+
+ // size >= set.size && set.all? { |o| include?(o) }
+ return asBoolean(context, size() < set.size() && allElementsIncluded(set));
}
/**
* Returns true if the set and the given set have at least one element in common.
*/
@JRubyMethod(name = "intersect?")
- public IRubyObject intersect_p(final ThreadContext context, IRubyObject set) {
- if ( set instanceof RubySet ) {
- return asBoolean(context, intersect((RubySet) set) );
- }
- throw context.runtime.newArgumentError("value must be a set");
+ public IRubyObject intersect_p(final ThreadContext context, IRubyObject setArg) {
+ if (!(setArg instanceof RubySet set)) throw argumentError(context, "value must be a set");
+
+ return asBoolean(context, intersect(set));
}
public boolean intersect(final RubySet set) {
@@ -587,8 +557,7 @@ public boolean intersect(final RubySet set) {
for ( IRubyObject o : elementsOrdered() ) {
if ( set.containsImpl(o) ) return true;
}
- }
- else {
+ } else {
// set.any? { |o| include?(o) }
for ( IRubyObject o : set.elementsOrdered() ) {
if ( containsImpl(o) ) return true;
@@ -602,18 +571,15 @@ public boolean intersect(final RubySet set) {
* This method is the opposite of +intersect?+.
*/
@JRubyMethod(name = "disjoint?")
- public IRubyObject disjoint_p(final ThreadContext context, IRubyObject set) {
- if ( set instanceof RubySet ) {
- return asBoolean(context, ! intersect((RubySet) set) );
- }
- throw context.runtime.newArgumentError("value must be a set");
+ public IRubyObject disjoint_p(final ThreadContext context, IRubyObject setArg) {
+ if (!(setArg instanceof RubySet set)) throw argumentError(context, "value must be a set");
+
+ return asBoolean(context, !intersect(set));
}
@JRubyMethod
public IRubyObject each(final ThreadContext context, Block block) {
- if ( ! block.isGiven() ) {
- return enumeratorizeWithSize(context, this, "each", RubySet::size);
- }
+ if (!block.isGiven()) return enumeratorizeWithSize(context, this, "each", RubySet::size);
for (IRubyObject elem : elementsOrdered()) block.yield(context, elem);
return this;
@@ -633,13 +599,18 @@ private static IRubyObject size(ThreadContext context, RubySet recv, IRubyObject
*/
@JRubyMethod(name = "add", alias = "<<")
public RubySet add(final ThreadContext context, IRubyObject obj) {
- modifyCheck(context.runtime);
- addImpl(context.runtime, obj);
+ modifyCheck(context);
+ addImpl(context, obj);
return this;
}
+ @Deprecated
protected void addImpl(final Ruby runtime, final IRubyObject obj) {
- hash.fastASetCheckString(runtime, obj, runtime.getTrue()); // @hash[obj] = true
+ addImpl(runtime.getCurrentContext(), obj);
+ }
+
+ protected void addImpl(final ThreadContext context, final IRubyObject obj) {
+ hash.fastASetCheckString(context.runtime, obj, context.tru); // @hash[obj] = true
}
protected void addImplSet(final ThreadContext context, final RubySet set) {
@@ -659,7 +630,7 @@ public IRubyObject add_p(final ThreadContext context, IRubyObject obj) {
@JRubyMethod
public IRubyObject delete(final ThreadContext context, IRubyObject obj) {
- modifyCheck(context.runtime);
+ modifyCheck(context);
deleteImpl(obj);
return this;
}
@@ -713,13 +684,11 @@ public IRubyObject keep_if(final ThreadContext context, Block block) {
@JRubyMethod(name = "collect!", alias = "map!")
public IRubyObject collect_bang(final ThreadContext context, Block block) {
- if ( ! block.isGiven() ) {
- return enumeratorizeWithSize(context, this, "collect!", RubySet::size);
- }
+ if (!block.isGiven()) return enumeratorizeWithSize(context, this, "collect!", RubySet::size);
final RubyArray elems = to_a(context); clearImpl();
for ( int i=0; i it = elementsOrdered().iterator();
- while ( it.hasNext() ) {
+ for(Iterator it = elementsOrdered().iterator(); it.hasNext(); ) {
IRubyObject elem = it.next();
- if ( block.yield(context, elem).isTrue() ) deleteImplIterator(elem, it); // it.remove
+ if (block.yield(context, elem).isTrue()) deleteImplIterator(elem, it); // it.remove
}
return size == size() ? context.nil : this;
}
@@ -761,23 +727,18 @@ public IRubyObject select_bang(final ThreadContext context, Block block) {
*/
@JRubyMethod(name = "merge")
public RubySet rb_merge(final ThreadContext context, IRubyObject enume) {
- final Ruby runtime = context.runtime;
-
- if ( enume instanceof RubySet ) {
- modifyCheck(runtime);
- addImplSet(context, (RubySet) enume);
- }
- else if ( enume instanceof RubyArray ) {
- modifyCheck(runtime);
- RubyArray ary = (RubyArray) enume;
+ if ( enume instanceof RubySet set) {
+ modifyCheck(context);
+ addImplSet(context, set);
+ } else if (enume instanceof RubyArray ary) {
+ modifyCheck(context);
for ( int i = 0; i < ary.size(); i++ ) {
- addImpl(runtime, ary.eltInternal(i));
+ addImpl(context, ary.eltInternal(i));
}
- }
- else { // do_with_enum(enum) { |o| add(o) }
- doWithEnum(context, enume, new EachBody(runtime) {
+ } else { // do_with_enum(enum) { |o| add(o) }
+ doWithEnum(context, enume, new EachBody(context) {
IRubyObject yieldImpl(ThreadContext context, IRubyObject val) {
- addImpl(context.runtime, val); return context.nil;
+ addImpl(context, val); return context.nil;
}
});
}
@@ -790,23 +751,18 @@ IRubyObject yieldImpl(ThreadContext context, IRubyObject val) {
*/
@JRubyMethod(name = "subtract")
public IRubyObject subtract(final ThreadContext context, IRubyObject enume) {
- final Ruby runtime = context.runtime;
-
- if ( enume instanceof RubySet ) {
- modifyCheck(runtime);
- for ( IRubyObject elem : ((RubySet) enume).elementsOrdered() ) {
+ if (enume instanceof RubySet set) {
+ modifyCheck(context);
+ for (IRubyObject elem : set.elementsOrdered()) {
deleteImpl(elem);
}
- }
- else if ( enume instanceof RubyArray ) {
- modifyCheck(runtime);
- RubyArray ary = (RubyArray) enume;
+ } else if (enume instanceof RubyArray ary) {
+ modifyCheck(context);
for ( int i = 0; i < ary.size(); i++ ) {
deleteImpl(ary.eltInternal(i));
}
- }
- else { // do_with_enum(enum) { |o| delete(o) }
- doWithEnum(context, enume, new EachBody(runtime) {
+ } else { // do_with_enum(enum) { |o| delete(o) }
+ doWithEnum(context, enume, new EachBody(context) {
IRubyObject yieldImpl(ThreadContext context, IRubyObject val) {
deleteImpl(val); return context.nil;
}
@@ -837,29 +793,24 @@ public IRubyObject op_diff(final ThreadContext context, IRubyObject enume) {
*/
@JRubyMethod(name = "&", alias = { "intersection" })
public IRubyObject op_and(final ThreadContext context, IRubyObject enume) {
- final Ruby runtime = context.runtime;
-
- final RubySet newSet = new RubySet(runtime, getMetaClass());
- if ( enume instanceof RubySet ) {
- newSet.allocHash(runtime, ((RubySet) enume).size());
- for ( IRubyObject obj : ((RubySet) enume).elementsOrdered() ) {
- if ( containsImpl(obj) ) newSet.addImpl(runtime, obj);
+ final RubySet newSet = new RubySet(context.runtime, getMetaClass());
+ if (enume instanceof RubySet set) {
+ newSet.allocHash(context, set.size());
+ for ( IRubyObject obj : set.elementsOrdered() ) {
+ if (containsImpl(obj)) newSet.addImpl(context, obj);
}
- }
- else if ( enume instanceof RubyArray ) {
- RubyArray ary = (RubyArray) enume;
- newSet.allocHash(runtime, ary.size());
+ } else if (enume instanceof RubyArray ary) {
+ newSet.allocHash(context, ary.size());
for ( int i = 0; i < ary.size(); i++ ) {
final IRubyObject obj = ary.eltInternal(i);
- if ( containsImpl(obj) ) newSet.addImpl(runtime, obj);
+ if (containsImpl(obj)) newSet.addImpl(context, obj);
}
- }
- else {
- newSet.allocHash(runtime);
+ } else {
+ newSet.allocHash(context);
// do_with_enum(enum) { |o| newSet.add(o) if include?(o) }
- doWithEnum(context, enume, new EachBody(runtime) {
+ doWithEnum(context, enume, new EachBody(context) {
IRubyObject yieldImpl(ThreadContext context, IRubyObject obj) {
- if ( containsImpl(obj) ) newSet.addImpl(runtime, obj);
+ if (containsImpl(obj)) newSet.addImpl(context, obj);
return context.nil;
}
});
@@ -874,13 +825,14 @@ IRubyObject yieldImpl(ThreadContext context, IRubyObject obj) {
*/
@JRubyMethod(name = "^")
public IRubyObject op_xor(final ThreadContext context, IRubyObject enume) {
- final Ruby runtime = context.runtime;
-
- RubySet newSet = new RubySet(runtime, runtime.getClass("Set"));
+ RubySet newSet = new RubySet(context.runtime, context.runtime.getClass("Set"));
newSet.initialize(context, enume, Block.NULL_BLOCK); // Set.new(enum)
- for ( IRubyObject o : elementsOrdered() ) {
- if ( newSet.containsImpl(o) ) newSet.deleteImpl(o); // exclusive or
- else newSet.addImpl(runtime, o);
+ for (IRubyObject o : elementsOrdered()) {
+ if (newSet.containsImpl(o)) {
+ newSet.deleteImpl(o); // exclusive or
+ } else {
+ newSet.addImpl(context, o);
+ }
}
return newSet;
@@ -889,15 +841,14 @@ public IRubyObject op_xor(final ThreadContext context, IRubyObject enume) {
@Override
@JRubyMethod(name = "==")
public IRubyObject op_equal(ThreadContext context, IRubyObject other) {
- if ( this == other ) return context.tru;
- if ( getMetaClass().isInstance(other) ) {
- return this.hash.op_equal(context, ((RubySet) other).hash); // @hash == ...
- }
- if ( other instanceof RubySet ) {
- RubySet that = (RubySet) other;
- if ( this.size() == that.size() ) { // && includes all of our elements :
- for ( IRubyObject obj : elementsOrdered() ) {
- if ( ! that.containsImpl(obj) ) return context.fals;
+ if (this == other) return context.tru;
+ if (getMetaClass().isInstance(other)) {
+ return hash.op_equal(context, ((RubySet) other).hash); // @hash == ...
+ }
+ if (other instanceof RubySet that) {
+ if (size() == that.size()) { // && includes all of our elements :
+ for (IRubyObject obj: elementsOrdered()) {
+ if (!that.containsImpl(obj)) return context.fals;
}
return context.tru;
}
@@ -920,10 +871,10 @@ public IRubyObject op_eql(ThreadContext context, IRubyObject other) {
}
@Override
- public boolean eql(IRubyObject other) {
- if ( other instanceof RubySet ) {
- final Ruby runtime = getRuntime();
- return this.hash.op_eql(runtime.getCurrentContext(), ((RubySet) other).hash) == runtime.getTrue();
+ public boolean eql(IRubyObject otherArg) {
+ if ( otherArg instanceof RubySet set) {
+ final ThreadContext context = getRuntime().getCurrentContext();
+ return hash.op_eql(context, set.hash) == context.tru;
}
return false;
}
@@ -943,21 +894,18 @@ public RubyFixnum hash() { // @hash.hash
@JRubyMethod(name = "classify")
public IRubyObject classify(ThreadContext context, final Block block) {
- if ( ! block.isGiven() ) {
- return enumeratorizeWithSize(context, this, "classify", RubySet::size);
- }
+ if (!block.isGiven()) return enumeratorizeWithSize(context, this, "classify", RubySet::size);
- final Ruby runtime = context.runtime;
-
- final RubyHash h = new RubyHash(runtime, size());
+ final RubyHash h = new RubyHash(context.runtime, size());
for ( IRubyObject i : elementsOrdered() ) {
final IRubyObject key = block.yield(context, i);
- IRubyObject set;
- if ( ( set = h.fastARef(key) ) == null ) {
- h.fastASet(key, set = newSetFast(runtime));
+ RubySet set = (RubySet) h.fastARef(key);
+ if (set == null) {
+ set = newSetFast(context.runtime);
+ h.fastASet(key, set);
}
- ((RubySet) set).invokeAdd(context, i);
+ set.invokeAdd(context, i);
}
return h;
@@ -983,19 +931,13 @@ public IRubyObject classify(ThreadContext context, final Block block) {
*/
@JRubyMethod(name = "divide")
public IRubyObject divide(ThreadContext context, final Block block) {
- if ( ! block.isGiven() ) {
- return enumeratorizeWithSize(context, this, "divide", RubySet::size);
- }
-
- if ( block.getSignature().arityValue() == 2 ) {
- return divideTSort(context, block);
- }
+ if (!block.isGiven()) return enumeratorizeWithSize(context, this, "divide", RubySet::size);
- final Ruby runtime = context.runtime; // Set.new(classify(&func).values) :
+ if (block.getSignature().arityValue() == 2) return divideTSort(context, block);
RubyHash vals = (RubyHash) classify(context, block);
- final RubySet set = new RubySet(runtime, runtime.getClass("Set"));
- set.allocHash(runtime, vals.size());
+ final RubySet set = new RubySet(context.runtime, context.runtime.getClass("Set"));
+ set.allocHash(context, vals.size());
for ( IRubyObject val : (Collection) vals.directValues() ) {
set.invokeAdd(context, val);
}
@@ -1004,7 +946,6 @@ public IRubyObject divide(ThreadContext context, final Block block) {
private IRubyObject divideTSort(ThreadContext context, final Block block) {
final Ruby runtime = context.runtime;
-
final RubyHash dig = DivideTSortHash.newInstance(context);
/*
@@ -1031,7 +972,7 @@ private IRubyObject divideTSort(ThreadContext context, final Block block) {
*/
final RubyClass Set = runtime.getClass("Set");
final RubySet set = new RubySet(runtime, Set);
- set.allocHash(runtime, dig.size());
+ set.allocHash(context, dig.size());
sites(context).each_strongly_connected_component.call(context, this, dig, new Block(
new JavaInternalBlockBody(runtime, Signature.ONE_REQUIRED) {
@Override
@@ -1042,7 +983,7 @@ public IRubyObject yield(ThreadContext context, IRubyObject[] args) {
@Override
protected IRubyObject doYield(ThreadContext context, Block block, IRubyObject css) {
// set.add( self.class.new(css) ) :
- set.addImpl(runtime, newSet(context, Set, (RubyArray) css));
+ set.addImpl(context, newSet(context, Set, (RubyArray) css));
return context.nil;
}
})
@@ -1252,8 +1193,13 @@ protected Set elementsOrdered() {
return elements(); // potentially -> to be re-defined by SortedSet
}
+ @Deprecated
protected final void modifyCheck(final Ruby runtime) {
- if ((flags & FROZEN_F) != 0) throw runtime.newFrozenError("Set", this);
+ modifyCheck(runtime.getCurrentContext());
+ }
+
+ protected final void modifyCheck(final ThreadContext context) {
+ if ((flags & FROZEN_F) != 0) throw context.runtime.newFrozenError("Set", this);
}
// java.util.Set
@@ -1301,7 +1247,7 @@ public Object[] toArray(final Object[] ary) {
public boolean add(Object element) {
final Ruby runtime = getRuntime();
final int size = size();
- addImpl(runtime, toRuby(runtime, element));
+ addImpl(runtime.getCurrentContext(), toRuby(runtime, element));
return size() > size; // if added
}
@@ -1318,9 +1264,10 @@ public boolean containsAll(Collection coll) {
public boolean addAll(Collection coll) {
final Ruby runtime = getRuntime();
+ ThreadContext context = runtime.getCurrentContext();
final int size = size();
- for ( Object elem : coll ) {
- addImpl(runtime, toRuby(runtime, elem));
+ for (Object elem: coll) {
+ addImpl(context, toRuby(runtime, elem));
}
return size() > size; // if added
}
diff --git a/core/src/main/java/org/jruby/ext/socket/Addrinfo.java b/core/src/main/java/org/jruby/ext/socket/Addrinfo.java
index d2e470cce84..0179a556274 100644
--- a/core/src/main/java/org/jruby/ext/socket/Addrinfo.java
+++ b/core/src/main/java/org/jruby/ext/socket/Addrinfo.java
@@ -302,7 +302,7 @@ private void initializeCommon(ThreadContext context, IRubyObject sockaddrArg, IR
}
} else {
- this.socketAddress = Sockaddr.sockaddrFromBytes(runtime, sockaddrArg.convertToString().getBytes());
+ this.socketAddress = Sockaddr.sockaddrFromBytes(context, sockaddrArg.convertToString().getBytes());
this.pfamily = protocolFamilyArg.isNil() ? PF_UNSPEC: SocketUtils.protocolFamilyFromArg(protocolFamilyArg);
if (!protocolArg.isNil()) this.protocol = SocketUtils.protocolFromArg(protocolArg);
if (!socketTypeArg.isNil()) this.sock = SocketUtils.sockFromArg(socketTypeArg);
diff --git a/core/src/main/java/org/jruby/ext/socket/RubyBasicSocket.java b/core/src/main/java/org/jruby/ext/socket/RubyBasicSocket.java
index 203245c0213..18f21b19eda 100644
--- a/core/src/main/java/org/jruby/ext/socket/RubyBasicSocket.java
+++ b/core/src/main/java/org/jruby/ext/socket/RubyBasicSocket.java
@@ -481,12 +481,9 @@ public IRubyObject getsockopt(ThreadContext context, IRubyObject _level, IRubyOb
@JRubyMethod
public IRubyObject setsockopt(ThreadContext context, IRubyObject option) {
- if (option instanceof Option) {
- Option rsockopt = (Option) option;
- return setsockopt(context, rsockopt.level(context), rsockopt.optname(context), rsockopt.data(context));
- } else {
- throw context.runtime.newArgumentError(option.toString() + " is not a Socket::Option");
- }
+ if (!(option instanceof Option sockopt)) throw argumentError(context, option + " is not a Socket::Option");
+
+ return setsockopt(context, sockopt.level(context), sockopt.optname(context), sockopt.data(context));
}
@JRubyMethod
@@ -857,7 +854,6 @@ private boolean validTcpSockOpt(int intOpt) {
}
private static IRubyObject shutdownInternal(ThreadContext context, OpenFile fptr, int how) {
- Ruby runtime = context.runtime;
Channel channel;
switch (how) {
@@ -865,36 +861,31 @@ private static IRubyObject shutdownInternal(ThreadContext context, OpenFile fptr
channel = fptr.channel();
try {
SocketType.forChannel(channel).shutdownInput(channel);
- }
- catch (IOException e) {
+ } catch (IOException e) {
// MRI ignores errors from shutdown()
}
fptr.setMode(fptr.getMode() & ~OpenFile.READABLE);
- return RubyFixnum.zero(runtime);
-
+ return RubyFixnum.zero(context.runtime);
case 1:
channel = fptr.channel();
try {
SocketType.forChannel(channel).shutdownOutput(channel);
- }
- catch (IOException e) {
+ } catch (IOException e) {
// MRI ignores errors from shutdown()
}
fptr.setMode(fptr.getMode() & ~OpenFile.WRITABLE);
- return RubyFixnum.zero(runtime);
-
+ return RubyFixnum.zero(context.runtime);
case 2:
shutdownInternal(context, fptr, 0);
shutdownInternal(context, fptr, 1);
- return RubyFixnum.zero(runtime);
-
+ return RubyFixnum.zero(context.runtime);
default:
- throw runtime.newArgumentError("`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR");
+ throw argumentError(context, "`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR");
}
}
diff --git a/core/src/main/java/org/jruby/ext/socket/RubyIPSocket.java b/core/src/main/java/org/jruby/ext/socket/RubyIPSocket.java
index ba59bc12ba5..50946ca0670 100644
--- a/core/src/main/java/org/jruby/ext/socket/RubyIPSocket.java
+++ b/core/src/main/java/org/jruby/ext/socket/RubyIPSocket.java
@@ -43,6 +43,7 @@
import static org.jruby.api.Create.newFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
/**
* @author Ola Bini
@@ -182,25 +183,23 @@ public static Boolean doReverseLookup(ThreadContext context, IRubyObject norever
} else if (noreverse == context.nil) {
return null;
} else {
- Ruby runtime = context.runtime;
-
- TypeConverter.checkType(context, noreverse, runtime.getSymbol());
- switch (noreverse.toString()) {
- case "numeric": return true;
- case "hostname": return false;
- default: throw runtime.newArgumentError("invalid reverse_lookup flag: " + noreverse);
- }
+ TypeConverter.checkType(context, noreverse, context.runtime.getSymbol());
+ return switch (noreverse.toString()) {
+ case "numeric" -> true;
+ case "hostname" -> false;
+ default -> throw argumentError(context, "invalid reverse_lookup flag: " + noreverse);
+ };
}
}
@Deprecated
public IRubyObject addr() {
- return addr(getRuntime().getCurrentContext());
+ return addr(getCurrentContext());
}
@Deprecated
public IRubyObject peeraddr() {
- return peeraddr(getRuntime().getCurrentContext());
+ return peeraddr(getCurrentContext());
}
@Deprecated
diff --git a/core/src/main/java/org/jruby/ext/socket/RubyServerSocket.java b/core/src/main/java/org/jruby/ext/socket/RubyServerSocket.java
index 361ba564ef5..27c101947a2 100644
--- a/core/src/main/java/org/jruby/ext/socket/RubyServerSocket.java
+++ b/core/src/main/java/org/jruby/ext/socket/RubyServerSocket.java
@@ -52,6 +52,7 @@
import java.nio.channels.SocketChannel;
import static org.jruby.api.Convert.asFixnum;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
/**
@@ -130,14 +131,12 @@ protected ChannelFD initChannelFD(Ruby runtime) {
try {
if (soType == Sock.SOCK_STREAM) {
channel = ServerSocketChannel.open();
- }
- else {
+ } else {
throw runtime.newArgumentError("unsupported server socket type '" + soType + "'");
}
return newChannelFD(runtime, channel);
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw sockerr(runtime, "initialize: " + e.toString(), e);
}
}
diff --git a/core/src/main/java/org/jruby/ext/socket/RubySocket.java b/core/src/main/java/org/jruby/ext/socket/RubySocket.java
index 1cfa525ec3f..75b73b677bf 100644
--- a/core/src/main/java/org/jruby/ext/socket/RubySocket.java
+++ b/core/src/main/java/org/jruby/ext/socket/RubySocket.java
@@ -87,6 +87,7 @@
import static org.jruby.api.Convert.castAsFixnum;
import static org.jruby.api.Create.newFixnum;
import static org.jruby.api.Create.newSymbol;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
/**
@@ -672,7 +673,7 @@ private SocketAddress addressForChannel(ThreadContext context, IRubyObject arg)
return Sockaddr.addressFromSockaddr_in(context, arg);
default:
- throw context.runtime.newArgumentError("unsupported protocol family '" + soProtocolFamily + "'");
+ throw argumentError(context, "unsupported protocol family '" + soProtocolFamily + "'");
}
}
diff --git a/core/src/main/java/org/jruby/ext/thread/Queue.java b/core/src/main/java/org/jruby/ext/thread/Queue.java
index 74d3b4c08e6..1321d108ee3 100644
--- a/core/src/main/java/org/jruby/ext/thread/Queue.java
+++ b/core/src/main/java/org/jruby/ext/thread/Queue.java
@@ -57,6 +57,7 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
/*
@@ -414,17 +415,12 @@ public IRubyObject pop(ThreadContext context, IRubyObject _nonblock, IRubyObject
long timeoutNS = 0;
IRubyObject _timeout = ArgsUtil.extractKeywordArg(context, "timeout", _opts);
-
if (!_timeout.isNil()) {
- if (nonblock) {
- throw context.runtime.newArgumentError("can't set a timeout if non_block is enabled");
- }
+ if (nonblock) throw argumentError(context, "can't set a timeout if non_block is enabled");
timeoutNS = queueTimeoutToNanos(context, _timeout);
- if (timeoutNS == 0 && count.get() == 0) {
- return context.nil;
- }
+ if (timeoutNS == 0 && count.get() == 0) return context.nil;
}
return popCommon(context, nonblock, timeoutNS);
diff --git a/core/src/main/java/org/jruby/ext/thread/SizedQueue.java b/core/src/main/java/org/jruby/ext/thread/SizedQueue.java
index 8e2e13ab162..debdf0a43a3 100644
--- a/core/src/main/java/org/jruby/ext/thread/SizedQueue.java
+++ b/core/src/main/java/org/jruby/ext/thread/SizedQueue.java
@@ -46,6 +46,7 @@
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newFixnum;
+import static org.jruby.api.Error.argumentError;
/**
* The "SizedQueue" class from the 'thread' library.
@@ -82,18 +83,14 @@ public RubyNumeric max(ThreadContext context) {
@JRubyMethod(name = "max=")
public synchronized IRubyObject max_set(ThreadContext context, IRubyObject arg) {
initializedCheck();
- Ruby runtime = context.runtime;
- int max = RubyNumeric.num2int(arg), diff = 0;
- if (max <= 0) {
- throw runtime.newArgumentError("queue size must be positive");
- }
+ int max = RubyNumeric.num2int(arg), diff = 0;
+ if (max <= 0) throw argumentError(context, "queue size must be positive");
fullyLock();
try {
- if (count.get() >= capacity && max > capacity) {
- diff = max - capacity;
- }
+ if (count.get() >= capacity && max > capacity) diff = max - capacity;
+
capacity = max;
while (diff-- > 0) {
notFull.signal();
@@ -178,17 +175,12 @@ public IRubyObject push(ThreadContext context, final IRubyObject arg0, final IRu
long timeoutNS = 0;
IRubyObject _timeout = ArgsUtil.extractKeywordArg(context, "timeout", _opts);
-
if (!_timeout.isNil()) {
- if (nonblock) {
- throw context.runtime.newArgumentError("can't set a timeout if non_block is enabled");
- }
+ if (nonblock) throw argumentError(context, "can't set a timeout if non_block is enabled");
timeoutNS = queueTimeoutToNanos(context, _timeout);
- if (timeoutNS == 0 && count.get() == capacity) {
- return context.nil;
- }
+ if (timeoutNS == 0 && count.get() == capacity) return context.nil;
}
return pushCommon(context, arg0, nonblock, timeoutNS);
@@ -198,19 +190,14 @@ private IRubyObject pushCommon(ThreadContext context, IRubyObject arg0, boolean
try {
RubyThread thread = context.getThread();
if (nonblock) {
- boolean result = offerInternal(context, arg0);
- if (!result) {
- throw context.runtime.newThreadError("queue full");
- }
+ if (!offerInternal(context, arg0)) throw context.runtime.newThreadError("queue full");
+
return this;
}
- RubyThread.Task task;
- if (timeoutNS != 0) {
- task = new BlockingOfferTask(timeoutNS);
- } else {
- task = blockingPutTask;
- }
+ RubyThread.Task task = timeoutNS != 0 ?
+ new BlockingOfferTask(timeoutNS) :
+ blockingPutTask;
return thread.executeTaskBlocking(context, arg0, task);
} catch (InterruptedException ie) {
diff --git a/core/src/main/java/org/jruby/ext/tracepoint/TracePoint.java b/core/src/main/java/org/jruby/ext/tracepoint/TracePoint.java
index d2532d58986..3d83fc0763f 100644
--- a/core/src/main/java/org/jruby/ext/tracepoint/TracePoint.java
+++ b/core/src/main/java/org/jruby/ext/tracepoint/TracePoint.java
@@ -22,6 +22,7 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.util.RubyStringBuilder.str;
public class TracePoint extends RubyObject {
@@ -45,11 +46,9 @@ public TracePoint(Ruby runtime, RubyClass klass) {
@JRubyMethod(rest = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(ThreadContext context, IRubyObject[] _events, final Block block) {
- final Ruby runtime = context.runtime;
-
ArrayList events = new ArrayList(_events.length);
for (int i = 0; i < _events.length; i++) {
- RubySymbol _event = (RubySymbol) TypeConverter.convertToType(context, _events[i], runtime.getSymbol(), sites(context).to_sym);
+ RubySymbol _event = (RubySymbol) TypeConverter.convertToType(context, _events[i], context.runtime.getSymbol(), sites(context).to_sym);
String eventName = _event.asJavaString().toUpperCase();
RubyEvent event = null;
@@ -57,7 +56,7 @@ public IRubyObject initialize(ThreadContext context, IRubyObject[] _events, fina
event = RubyEvent.valueOf(eventName);
} catch (IllegalArgumentException iae) {}
- if (event == null) throw runtime.newArgumentError(str(runtime, "unknown event: ", _event));
+ if (event == null) throw argumentError(context, str(context.runtime, "unknown event: ", _event));
// a_call is call | b_call | c_call, and same as a_return.
if (event == RubyEvent.A_CALL) {
@@ -73,14 +72,10 @@ public IRubyObject initialize(ThreadContext context, IRubyObject[] _events, fina
}
}
- final EnumSet eventSet;
- if (events.size() > 0) {
- eventSet = EnumSet.copyOf(events);
- } else {
- eventSet = RubyEvent.ALL_EVENTS_ENUMSET;
- }
+ final EnumSet eventSet = !events.isEmpty() ?
+ EnumSet.copyOf(events) : RubyEvent.ALL_EVENTS_ENUMSET;
- if (!block.isGiven()) throw runtime.newArgumentError("must be called with a block");
+ if (!block.isGiven()) throw argumentError(context, "must be called with a block");
final ThreadContext threadToTrace = context;
hook = new EventHook() {
diff --git a/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipReader.java b/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipReader.java
index 9bc65d69582..4e40e5512fb 100644
--- a/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipReader.java
+++ b/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipReader.java
@@ -65,6 +65,7 @@
import static org.jruby.api.Convert.castAsString;
import static org.jruby.api.Create.newFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.runtime.Visibility.PRIVATE;
/**
@@ -326,16 +327,10 @@ public IRubyObject read(ThreadContext context, IRubyObject[] args) {
if (argc == 0 || args[0].isNil()) return readAll();
int len = RubyNumeric.fix2int(args[0]);
-
- if (len < 0) throw runtime.newArgumentError("negative length " + len + " given");
-
- if (len > 0) {
- // rb_gzfile_read
+ if (len < 0) throw argumentError(context, "negative length " + len + " given");
+ if (len > 0) { // rb_gzfile_read
ByteList buf = readSize(len);
-
- if (buf == null) return runtime.getNil();
-
- return runtime.newString(buf);
+ return buf == null ? context.nil : newString(context, buf);
}
return RubyString.newEmptyBinaryString(runtime);
@@ -363,37 +358,33 @@ public IRubyObject readpartial(IRubyObject[] args) {
@JRubyMethod(name = "readpartial", required = 1, optional = 1, checkArity = false)
public IRubyObject readpartial(ThreadContext context, IRubyObject[] args) {
- Ruby runtime = context.runtime;
-
int argc = Arity.checkArgumentCount(context, args, 1, 2);
try {
int len = RubyNumeric.fix2int(args[0]);
- if (len < 0) throw runtime.newArgumentError("negative length " + len + " given");
+ if (len < 0) throw argumentError(context, "negative length " + len + " given");
- if (argc > 1 && !args[1].isNil()) {
- return readPartial(runtime, len, castAsString(context, args[1]));
- }
-
- return readPartial(runtime, len, null);
+ return argc > 1 && !args[1].isNil() ?
+ readPartial(context, len, castAsString(context, args[1])) :
+ readPartial(context, len, null);
} catch (IOException ioe) {
- throw runtime.newIOErrorFromException(ioe);
+ throw context.runtime.newIOErrorFromException(ioe);
}
}
- private IRubyObject readPartial(Ruby runtime, int len, RubyString outbuf) throws IOException {
+ private IRubyObject readPartial(ThreadContext context, int len, RubyString outbuf) throws IOException {
ByteList val = newReadByteList(10);
byte[] buffer = new byte[len];
int read = bufferedStream.read(buffer, 0, len);
- if (read == -1) return runtime.getNil();
+ if (read == -1) return context.nil;
val.append(buffer, 0, read);
this.position += val.length();
if (outbuf != null) outbuf.view(val);
- return newStr(runtime, val);
+ return newStr(context.runtime, val);
}
private RubyString readAll() throws IOException {
diff --git a/core/src/main/java/org/jruby/internal/runtime/methods/DynamicMethod.java b/core/src/main/java/org/jruby/internal/runtime/methods/DynamicMethod.java
index c88f60bce8d..a7eda42df98 100644
--- a/core/src/main/java/org/jruby/internal/runtime/methods/DynamicMethod.java
+++ b/core/src/main/java/org/jruby/internal/runtime/methods/DynamicMethod.java
@@ -51,6 +51,8 @@
import org.jruby.runtime.ivars.MethodData;
import org.jruby.util.CodegenUtils;
+import static org.jruby.api.Error.argumentError;
+
/**
* DynamicMethod represents a method handle in JRuby, to provide both entry
* points into AST and bytecode interpreters, but also to provide handles to
@@ -252,11 +254,11 @@ public boolean callRespondTo(ThreadContext context, IRubyObject self, String res
if (required == 1) {
return call(context, self, klazz, respondToMethodName, name).isTrue();
} else if (required != 2) {
- throw context.runtime.newArgumentError(respondToMethodName + " " + "must accept 1 or 2 arguments (requires " + required + ")");
+ throw argumentError(context, respondToMethodName + " " + "must accept 1 or 2 arguments (requires " + required + ")");
}
}
- return call(context, self, klazz, respondToMethodName, name, context.runtime.getTrue()).isTrue();
+ return call(context, self, klazz, respondToMethodName, name, context.tru).isTrue();
}
/**
diff --git a/core/src/main/java/org/jruby/ir/runtime/IRRuntimeHelpers.java b/core/src/main/java/org/jruby/ir/runtime/IRRuntimeHelpers.java
index 3630f1e762d..db34a30f743 100644
--- a/core/src/main/java/org/jruby/ir/runtime/IRRuntimeHelpers.java
+++ b/core/src/main/java/org/jruby/ir/runtime/IRRuntimeHelpers.java
@@ -91,6 +91,7 @@
import static org.jruby.api.Convert.*;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.ir.operands.UndefinedValue.UNDEFINED;
import static org.jruby.runtime.Block.Type.LAMBDA;
@@ -965,7 +966,7 @@ public void raiseIfError(ThreadContext context) {
RubyString errorMessage = (RubyString) invalidKwargs.join(context, newString(context, ", "));
String prefix = invalidKwargs.size() == 1 ? "unknown keyword: " : "unknown keywords: ";
- throw context.runtime.newArgumentError(prefix + errorMessage);
+ throw argumentError(context, prefix + errorMessage);
}
}
}
@@ -2117,7 +2118,7 @@ public static IRubyObject irNot(ThreadContext context, IRubyObject obj) {
@JIT
public static RaiseException newRequiredKeywordArgumentError(ThreadContext context, String id) {
- return context.runtime.newArgumentError(str(context.runtime, "missing keyword: ", ids(context.runtime, id)));
+ return argumentError(context, str(context.runtime, "missing keyword: ", ids(context.runtime, id)));
}
public static void pushExitBlock(ThreadContext context, Block blk) {
diff --git a/core/src/main/java/org/jruby/java/invokers/RubyToJavaInvoker.java b/core/src/main/java/org/jruby/java/invokers/RubyToJavaInvoker.java
index 75ffc575774..b031a1ade58 100644
--- a/core/src/main/java/org/jruby/java/invokers/RubyToJavaInvoker.java
+++ b/core/src/main/java/org/jruby/java/invokers/RubyToJavaInvoker.java
@@ -55,6 +55,7 @@
import org.jruby.util.collections.IntHashMap;
import org.jruby.util.collections.NonBlockingHashMapLong;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.util.CodegenUtils.prettyParams;
public abstract class RubyToJavaInvoker extends JavaMethod {
@@ -695,12 +696,14 @@ private RaiseException newErrorDueNoMatchingCallable(final IRubyObject receiver,
final StringBuilder error = new StringBuilder(48);
error.append("no ");
- if ( isConstructor() ) error.append("constructor");
- else {
- error.append("method '").append( name ).append("'");
+ if (isConstructor()) {
+ error.append("constructor");
+ } else {
+ error.append("method '").append(name).append("'");
}
- error.append(" (for zero arguments) on ").append( formatReceiver(receiver) );
- return runtime.newArgumentError( error.toString() );
+ error.append(" (for zero arguments) on ").append(formatReceiver(receiver));
+
+ return argumentError(runtime.getCurrentContext(), error.toString());
}
private static Class> getClass(final IRubyObject object) {
diff --git a/core/src/main/java/org/jruby/java/proxies/JavaInterfaceTemplate.java b/core/src/main/java/org/jruby/java/proxies/JavaInterfaceTemplate.java
index 5f6a22a1f5b..287a137d1e7 100644
--- a/core/src/main/java/org/jruby/java/proxies/JavaInterfaceTemplate.java
+++ b/core/src/main/java/org/jruby/java/proxies/JavaInterfaceTemplate.java
@@ -58,6 +58,7 @@
import org.jruby.runtime.builtin.IRubyObject;
import static org.jruby.api.Convert.castAsModule;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
public class JavaInterfaceTemplate {
@@ -368,9 +369,7 @@ public static IRubyObject op_aref(ThreadContext context, IRubyObject self, IRuby
public static IRubyObject impl(ThreadContext context, IRubyObject self, IRubyObject[] args, final Block implBlock) {
final Ruby runtime = context.runtime;
- if ( ! implBlock.isGiven() ) {
- throw runtime.newArgumentError("block required to call #impl on a Java interface");
- }
+ if (!implBlock.isGiven()) throw argumentError(context, "block required to call #impl on a Java interface");
boolean allMethods = true;
final IRubyObject[] methodNames;
diff --git a/core/src/main/java/org/jruby/javasupport/Java.java b/core/src/main/java/org/jruby/javasupport/Java.java
index c72dc31eeb0..0d5bdb0e222 100644
--- a/core/src/main/java/org/jruby/javasupport/Java.java
+++ b/core/src/main/java/org/jruby/javasupport/Java.java
@@ -99,8 +99,7 @@
import org.jruby.util.collections.NonBlockingHashMapLong;
import static org.jruby.api.Convert.*;
-import static org.jruby.api.Error.typeError;
-import static org.jruby.api.Error.withException;
+import static org.jruby.api.Error.*;
import static org.jruby.runtime.Visibility.*;
@JRubyModule(name = "Java")
@@ -715,17 +714,14 @@ private JavaProxyConstructor matchConstructor0ArityOne(final ThreadContext conte
final JavaProxyConstructor[] constructors, final IRubyObject arg0) {
JavaProxyConstructor forArity = checkCallableForArity(1, constructors, 0);
- if ( forArity == null ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if (forArity == null) throw argumentError(context, "wrong number of arguments for constructor");
final JavaProxyConstructor matching = CallableSelector.matchingCallableArityOne(
context.runtime, this, new JavaProxyConstructor[] { forArity }, arg0
);
- if ( matching == null ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if ( matching == null ) throw argumentError(context, "wrong number of arguments for constructor");
+
return matching;
}
@@ -734,17 +730,14 @@ private JavaProxyConstructor matchConstructor0(final ThreadContext context,
final JavaProxyConstructor[] constructors, final int arity, final IRubyObject[] args) {
JavaProxyConstructor forArity = checkCallableForArity(arity, constructors, 0);
- if ( forArity == null ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if ( forArity == null ) throw argumentError(context, "wrong number of arguments for constructor");
final JavaProxyConstructor matching = CallableSelector.matchingCallableArityN(
context.runtime, this, new JavaProxyConstructor[] { forArity }, args
);
- if ( matching == null ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if ( matching == null ) throw argumentError(context, "wrong number of arguments for constructor");
+
return matching;
}
@@ -752,17 +745,14 @@ private JavaProxyConstructor matchConstructorArityOne(final ThreadContext contex
final JavaProxyConstructor[] constructors, final IRubyObject arg0) {
ArrayList forArity = findCallablesForArity(1, constructors);
- if ( forArity.size() == 0 ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if (forArity.isEmpty()) throw argumentError(context, "wrong number of arguments for constructor");
final JavaProxyConstructor matching = CallableSelector.matchingCallableArityOne(
context.runtime, this, forArity.toArray(new JavaProxyConstructor[forArity.size()]), arg0
);
- if ( matching == null ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if (matching == null) throw argumentError(context, "wrong number of arguments for constructor");
+
return matching;
}
@@ -771,16 +761,14 @@ public JavaProxyConstructor matchConstructor(final ThreadContext context,
final JavaProxyConstructor[] constructors, final int arity, final IRubyObject... args) {
ArrayList forArity = findCallablesForArity(arity, constructors);
- if ( forArity.size() == 0 ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if (forArity.isEmpty()) throw argumentError(context, "wrong number of arguments for constructor");
+
final JavaProxyConstructor matching = CallableSelector.matchingCallableArityN(
context.runtime, this, forArity.toArray(new JavaProxyConstructor[forArity.size()]), args
);
- if ( matching == null ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if (matching == null) throw argumentError(context, "wrong number of arguments for constructor");
+
return matching;
}
@@ -789,16 +777,14 @@ public static T matchConstructorIndex(final ThreadCon
final T[] constructors, final CallableCache cache, final int arity, final IRubyObject... args) {
ArrayList forArity = findCallablesForArity(arity, constructors);
- if ( forArity.size() == 0 ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if (forArity.isEmpty()) throw argumentError(context, "wrong number of arguments for constructor");
+
final ParameterTypes matching = CallableSelector.matchingCallableArityN(
context.runtime, cache, forArity.toArray(new ParameterTypes[forArity.size()]), args
);
- if ( matching == null ) {
- throw context.runtime.newArgumentError("wrong number of arguments for constructor");
- }
+ if (matching == null) throw argumentError(context, "wrong number of arguments for constructor");
+
return (T) matching;
}
@@ -947,9 +933,7 @@ static RubyModule getProxyOrPackageUnderPackage(final ThreadContext context,
final RubyModule parentPackage, final String name, final boolean cacheMethod) {
final Ruby runtime = context.runtime;
- if ( name.length() == 0 ) {
- throw runtime.newArgumentError("empty class or package name");
- }
+ if (name.isEmpty()) throw argumentError(context, "empty class or package name");
final String fullName = JavaPackage.buildPackageName(parentPackage, name).toString();
@@ -1264,9 +1248,8 @@ public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klaz
private static RubyModule getProxyUnderClass(final ThreadContext context,
final RubyModule enclosingClass, final String name) {
- final Ruby runtime = context.runtime;
- if (name.length() == 0) throw runtime.newArgumentError("empty class name");
+ if (name.isEmpty()) throw argumentError(context, "empty class name");
Class> enclosing = JavaUtil.getJavaClass(enclosingClass, null);
@@ -1274,7 +1257,7 @@ private static RubyModule getProxyUnderClass(final ThreadContext context,
final String fullName = enclosing.getName() + '$' + name;
- final RubyModule result = getProxyClassOrNull(runtime, fullName);
+ final RubyModule result = getProxyClassOrNull(context.runtime, fullName);
//if ( result != null && cacheMethod ) bindJavaPackageOrClassMethod(enclosingClass, name, result);
return result;
}
@@ -1332,7 +1315,7 @@ public static IRubyObject method_missing(ThreadContext context, final IRubyObjec
final IRubyObject name = args[0];
if ( args.length > 1 ) {
final int count = args.length - 1;
- throw context.runtime.newArgumentError("Java does not have a method '"+ name +"' with " + count + " arguments");
+ throw argumentError(context, "Java does not have a method '"+ name +"' with " + count + " arguments");
}
return method_missing(context, self, name);
}
diff --git a/core/src/main/java/org/jruby/javasupport/ext/JavaLang.java b/core/src/main/java/org/jruby/javasupport/ext/JavaLang.java
index 63484e60a62..3efe6f34769 100644
--- a/core/src/main/java/org/jruby/javasupport/ext/JavaLang.java
+++ b/core/src/main/java/org/jruby/javasupport/ext/JavaLang.java
@@ -59,6 +59,7 @@
import static org.jruby.api.Convert.asBoolean;
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.javasupport.JavaUtil.convertJavaToUsableRubyObject;
import static org.jruby.javasupport.JavaUtil.isJavaObject;
@@ -805,9 +806,8 @@ public static IRubyObject new_array(ThreadContext context, IRubyObject self, IRu
if (length instanceof RubyArray) { // n-dimensional array
IRubyObject[] aryLengths = ((RubyArray) length).toJavaArrayMaybeUnsafe();
final int len = aryLengths.length;
- if (len == 0) {
- throw context.runtime.newArgumentError("empty dimensions specifier for java array");
- }
+ if (len == 0) throw argumentError(context, "empty dimensions specifier for java array");
+
final int[] dimensions = new int[len];
for (int i = len; --i >= 0; ) {
dimensions[i] = Convert.castAsInteger(context, aryLengths[i]).getIntValue();
@@ -815,7 +815,7 @@ public static IRubyObject new_array(ThreadContext context, IRubyObject self, IRu
return ArrayJavaProxy.newArray(context.runtime, klass, dimensions);
}
- throw context.runtime.newArgumentError("invalid length or dimensions specifier for java array - must be Integer or Array of Integer");
+ throw argumentError(context, "invalid length or dimensions specifier for java array - must be Integer or Array of Integer");
}
}
diff --git a/core/src/main/java/org/jruby/runtime/backtrace/TraceType.java b/core/src/main/java/org/jruby/runtime/backtrace/TraceType.java
index 383702eb7a0..bf5b862b2a0 100644
--- a/core/src/main/java/org/jruby/runtime/backtrace/TraceType.java
+++ b/core/src/main/java/org/jruby/runtime/backtrace/TraceType.java
@@ -25,6 +25,8 @@
import org.jruby.util.TypeConverter;
import static org.jruby.api.Convert.asBoolean;
+import static org.jruby.api.Create.newSymbol;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.util.RubyStringBuilder.str;
public class TraceType {
@@ -380,10 +382,9 @@ private static boolean checkOrderKeyword(ThreadContext context, IRubyObject optA
}
private static IRubyObject checkHighlightKeyword(ThreadContext context, IRubyObject optArg, boolean autoTTYDetect) {
- Ruby runtime = context.runtime;
IRubyObject highlightArg = context.nil;
- RubySymbol highlightSym = runtime.newSymbol("highlight");
+ RubySymbol highlightSym = newSymbol(context, "highlight");
if (!optArg.isNil()) {
RubyHash optHash = (RubyHash) optArg;
@@ -393,12 +394,12 @@ private static IRubyObject checkHighlightKeyword(ThreadContext context, IRubyObj
if (!(highlightArg.isNil()
|| highlightArg == context.tru
|| highlightArg == context.fals)) {
- throw context.runtime.newArgumentError("expected true or false as highlight: " + highlightArg);
+ throw argumentError(context, "expected true or false as highlight: " + highlightArg);
}
}
if (highlightArg.isNil()) {
- highlightArg = asBoolean(context, autoTTYDetect && RubyException.to_tty_p(context, runtime.getException()).isTrue());
+ highlightArg = asBoolean(context, autoTTYDetect && RubyException.to_tty_p(context, context.runtime.getException()).isTrue());
}
return highlightArg;
@@ -408,9 +409,9 @@ private static boolean determineDirection(ThreadContext context, IRubyObject vOr
if (vOrder == null || vOrder.isNil()) return false;
IRubyObject id = TypeConverter.checkID(vOrder);
- if (id == context.runtime.newSymbol("bottom")) return true;
- if (id == context.runtime.newSymbol("top")) return false;
- throw context.runtime.newArgumentError(str(context.runtime, "expected :top or :bottom as order: ", vOrder));
+ if (id == newSymbol(context, "bottom")) return true;
+ if (id == newSymbol(context, "top")) return false;
+ throw argumentError(context, str(context.runtime, "expected :top or :bottom as order: ", vOrder));
}
private static RubyString printBacktraceMRI(IRubyObject exception, IRubyObject opts, boolean highlight, boolean reverse) {
diff --git a/core/src/main/java/org/jruby/runtime/marshal/NewMarshal.java b/core/src/main/java/org/jruby/runtime/marshal/NewMarshal.java
index 97b6c1e52bf..f0c277b56c1 100644
--- a/core/src/main/java/org/jruby/runtime/marshal/NewMarshal.java
+++ b/core/src/main/java/org/jruby/runtime/marshal/NewMarshal.java
@@ -72,6 +72,7 @@
import static org.jruby.api.Convert.castAsString;
import static org.jruby.api.Create.newFixnum;
import static org.jruby.api.Create.newSymbol;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.runtime.marshal.MarshalCommon.TYPE_IVAR;
import static org.jruby.runtime.marshal.MarshalCommon.TYPE_UCLASS;
@@ -141,7 +142,7 @@ public void start(RubyOutputStream out) {
public void dumpObject(ThreadContext context, RubyOutputStream out, IRubyObject value) {
depth++;
- if (depth > depthLimit) throw context.runtime.newArgumentError("exceed depth limit");
+ if (depth > depthLimit) throw argumentError(context, "exceed depth limit");
writeAndRegister(context, out, value);
diff --git a/core/src/main/java/org/jruby/util/ShellLauncher.java b/core/src/main/java/org/jruby/util/ShellLauncher.java
index 07c103e88e6..93e9fd32c06 100644
--- a/core/src/main/java/org/jruby/util/ShellLauncher.java
+++ b/core/src/main/java/org/jruby/util/ShellLauncher.java
@@ -32,6 +32,7 @@
import static com.headius.backport9.buffer.Buffers.flipBuffer;
import static java.lang.System.out;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import java.io.File;
@@ -237,9 +238,12 @@ private static String[] getCurrentEnv(Ruby runtime, Map mergeEnv) {
return getModifiedEnv(runtime, mergeEnv == null ? Collections.EMPTY_LIST : mergeEnv.entrySet(), false);
}
+ @Deprecated
public static String[] getModifiedEnv(Ruby runtime, Collection mergeEnv, boolean clearEnv) {
- ThreadContext context = runtime.getCurrentContext();
+ return getModifiedEnv(runtime.getCurrentContext(), mergeEnv, clearEnv);
+ }
+ public static String[] getModifiedEnv(ThreadContext context, Collection mergeEnv, boolean clearEnv) {
// disable tracing for the dup call below
boolean traceEnabled = context.isEventHooksEnabled();
context.setEventHooksEnabled(false);
@@ -248,9 +252,9 @@ public static String[] getModifiedEnv(Ruby runtime, Collection mergeEnv, boolean
// dup for JRUBY-6603 (avoid concurrent modification while we walk it)
RubyHash hash = null;
if (clearEnv) {
- hash = RubyHash.newHash(runtime);
+ hash = RubyHash.newHash(context.runtime);
} else {
- hash = (RubyHash) runtime.getObject().getConstant("ENV").dup();
+ hash = (RubyHash) context.runtime.getObject().getConstant("ENV").dup();
}
if (mergeEnv != null) {
@@ -272,9 +276,7 @@ public static String[] getModifiedEnv(Ruby runtime, Collection mergeEnv, boolean
for (int j = 0; j < mergeEnv.size(); j++) {
RubyArray e = ((RubyArray)mergeEnv).eltOk(j).convertToArray();
// if there are not two elements, raise ArgumentError
- if (e.size() != 2) {
- throw runtime.newArgumentError("env assignments must come in pairs");
- }
+ if (e.size() != 2) throw argumentError(context, "env assignments must come in pairs");
// if the key is nil, raise TypeError
IRubyObject key = e.eltOk(0);
diff --git a/core/src/main/java/org/jruby/util/Sprintf.java b/core/src/main/java/org/jruby/util/Sprintf.java
index e9ad0b33721..36ffd597830 100644
--- a/core/src/main/java/org/jruby/util/Sprintf.java
+++ b/core/src/main/java/org/jruby/util/Sprintf.java
@@ -364,6 +364,7 @@ private static void rubySprintfToBuffer(ByteList buf, CharSequence charFormat, A
private static void rubySprintfToBuffer(final ByteList buf, final CharSequence charFormat,
final Args args, final boolean usePrefixForZero) {
final Ruby runtime = args.runtime;
+ ThreadContext context = runtime.getCurrentContext();
final byte[] format;
final Encoding encoding;
@@ -603,7 +604,6 @@ private static void rubySprintfToBuffer(final ByteList buf, final CharSequence c
case 'c': {
arg = args.getArg();
- ThreadContext context = runtime.getCurrentContext();
int c; int n;
IRubyObject tmp = arg.checkStringType();
@@ -656,7 +656,7 @@ else if ((flags & FLAG_MINUS) != 0) {
ByteList bytes = new ByteList();
final boolean positive = isPositive(arg);
- double fval = RubyKernel.new_float(runtime, arg).getDoubleValue();
+ double fval = RubyKernel.new_float(context, arg).getDoubleValue();
boolean negative = fval < 0.0d || (fval == 0.0d && Double.doubleToLongBits(fval) == Double.doubleToLongBits(-0.0));
boolean isnan = Double.isNaN(fval);
boolean isinf = fval == Double.POSITIVE_INFINITY || fval == Double.NEGATIVE_INFINITY;
@@ -972,8 +972,6 @@ else if (arg instanceof RubyRational) {
if (num != null) { // else -> goto float_value;
if ((flags & FLAG_PRECISION) == 0) precision = 6; // default_float_precision;
- ThreadContext context = runtime.getCurrentContext();
-
if (num.isNegative()) {
num = (RubyInteger) num.op_uminus(context);
sign = -1;
@@ -1047,7 +1045,7 @@ else if (precision > 0) {
float_value: {
arg = args.getArg();
- double fval = RubyKernel.new_float(runtime, arg).getDoubleValue();
+ double fval = RubyKernel.new_float(context, arg).getDoubleValue();
boolean isnan = Double.isNaN(fval);
boolean isinf = fval == Double.POSITIVE_INFINITY || fval == Double.NEGATIVE_INFINITY;
boolean negative = fval < 0.0d || (fval == 0.0d && Double.doubleToLongBits(fval) == Double.doubleToLongBits(-0.0));
diff --git a/core/src/main/java/org/jruby/util/StringSupport.java b/core/src/main/java/org/jruby/util/StringSupport.java
index dd6c474de9d..28715098c39 100644
--- a/core/src/main/java/org/jruby/util/StringSupport.java
+++ b/core/src/main/java/org/jruby/util/StringSupport.java
@@ -65,6 +65,7 @@
import java.util.List;
import static org.jruby.RubyString.scanForCodeRange;
+import static org.jruby.api.Error.argumentError;
public final class StringSupport {
public static final int CR_7BIT_F = ObjectFlags.CR_7BIT_F;
@@ -576,11 +577,15 @@ public static int codePoint(Encoding enc, byte[] bytes, int p, int end) {
return enc.mbcToCode(bytes, p, end);
}
+ @Deprecated
public static int codePoint(Ruby runtime, Encoding enc, byte[] bytes, int p, int end) {
+ return codePoint(runtime.getCurrentContext(), enc, bytes, p, end);
+ }
+ public static int codePoint(ThreadContext context, Encoding enc, byte[] bytes, int p, int end) {
try {
return codePoint(enc, bytes, p, end);
} catch (IllegalArgumentException e) {
- throw runtime.newArgumentError(e.getMessage());
+ throw argumentError(context, e.getMessage());
}
}
diff --git a/core/src/main/java/org/jruby/util/TypeConverter.java b/core/src/main/java/org/jruby/util/TypeConverter.java
index 851915c4067..360cc1a98cd 100644
--- a/core/src/main/java/org/jruby/util/TypeConverter.java
+++ b/core/src/main/java/org/jruby/util/TypeConverter.java
@@ -51,6 +51,8 @@
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
+import static org.jruby.api.Create.newSymbol;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.util.RubyStringBuilder.str;
import static org.jruby.util.RubyStringBuilder.types;
@@ -493,7 +495,7 @@ public static RubyArray to_ary(ThreadContext context, IRubyObject ary) {
private static IRubyObject raiseIntegerBaseError(ThreadContext context, boolean exception) {
if (!exception) return context.nil;
- throw context.runtime.newArgumentError("base specified for non string value");
+ throw argumentError(context, "base specified for non string value");
}
public static TypeConverterSites sites(ThreadContext context) {
@@ -578,6 +580,7 @@ public static boolean booleanExpected(ThreadContext context, IRubyObject object,
if (object == context.tru) return true;
if (object == context.fals) return false;
- throw context.runtime.newArgumentError(str(context.runtime, "true or false is expected as ", context.runtime.newSymbol(id), ": ", object));
+ throw argumentError(context,
+ str(context.runtime, "true or false is expected as ", newSymbol(context, id), ": ", object));
}
}
diff --git a/core/src/main/java/org/jruby/util/io/EncodingUtils.java b/core/src/main/java/org/jruby/util/io/EncodingUtils.java
index 116042978e6..bfc37b36090 100644
--- a/core/src/main/java/org/jruby/util/io/EncodingUtils.java
+++ b/core/src/main/java/org/jruby/util/io/EncodingUtils.java
@@ -61,8 +61,8 @@
import static org.jruby.RubyString.newEmptyString;
import static org.jruby.api.Convert.checkToInteger;
import static org.jruby.api.Convert.asInt;
-import static org.jruby.api.Create.newFixnum;
-import static org.jruby.api.Create.newString;
+import static org.jruby.api.Create.*;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.api.Error.typeError;
import static org.jruby.util.StringSupport.CR_UNKNOWN;
import static org.jruby.util.StringSupport.searchNonAscii;
@@ -85,15 +85,21 @@ public static Encoding rbToEncoding(ThreadContext context, IRubyObject enc) {
public static Encoding toEncoding(ThreadContext context, IRubyObject enc) {
RubyString encStr = enc.convertToString();
if (!encStr.getEncoding().isAsciiCompatible()) {
- throw context.runtime.newArgumentError("invalid encoding name (non ASCII)");
+ throw argumentError(context, "invalid encoding name (non ASCII)");
}
Encoding idx = context.runtime.getEncodingService().getEncodingFromObject(encStr);
// check for missing encoding is in getEncodingFromObject
return idx;
}
+ @Deprecated
public static IRubyObject[] openArgsToArgs(Ruby runtime, IRubyObject firstElement, RubyHash options) {
- IRubyObject value = hashARef(runtime, options, "open_args");
+ return openArgsToArgs(runtime.getCurrentContext(), firstElement, options);
+ }
+
+ @Deprecated
+ public static IRubyObject[] openArgsToArgs(ThreadContext context, IRubyObject firstElement, RubyHash options) {
+ IRubyObject value = hashARef(context, options, "open_args");
if (value.isNil()) return new IRubyObject[] { firstElement, options };
@@ -110,39 +116,44 @@ public static IRubyObject[] openArgsToArgs(Ruby runtime, IRubyObject firstElemen
return args;
}
+ @Deprecated
+ public static void extractBinmode(Ruby runtime, IRubyObject optionsArg, int[] fmode_p) {
+ extractBinmode(runtime.getCurrentContext(), optionsArg, fmode_p);
+ }
+
// FIXME: This could be smarter amount determining whether optionsArg is a RubyHash and !null (invariant)
// mri: extract_binmode
- public static void extractBinmode(Ruby runtime, IRubyObject optionsArg, int[] fmode_p) {
+ public static void extractBinmode(ThreadContext context, IRubyObject optionsArg, int[] fmode_p) {
int fmodeMask = 0;
- IRubyObject textMode = hashARef(runtime, optionsArg, "textmode");
- IRubyObject binMode = hashARef(runtime, optionsArg, "binmode");
+ IRubyObject textMode = hashARef(context, optionsArg, "textmode");
+ IRubyObject binMode = hashARef(context, optionsArg, "binmode");
boolean textKwarg = !textMode.isNil();
boolean textOption = (fmode_p[0] & OpenFile.TEXTMODE) != 0;
boolean binKwarg = !binMode.isNil();
boolean binOption = (fmode_p[0] & OpenFile.BINMODE) != 0;
- if ((textKwarg || textOption) && (binKwarg || binOption)) throw runtime.newArgumentError("both textmode and binmode specified");
+ if ((textKwarg || textOption) && (binKwarg || binOption)) throw argumentError(context, "both textmode and binmode specified");
if (textKwarg) {
- if (textOption) throw runtime.newArgumentError("textmode specified twice");
+ if (textOption) throw argumentError(context, "textmode specified twice");
if (textMode.isTrue()) fmodeMask |= OpenFile.TEXTMODE;
}
if (binKwarg) {
- if (binOption) throw runtime.newArgumentError("binmode specified twice");
+ if (binOption) throw argumentError(context, "binmode specified twice");
if (binMode.isTrue()) fmodeMask |= OpenFile.BINMODE;
}
fmode_p[0] |= fmodeMask;
}
- private static IRubyObject hashARef(Ruby runtime, IRubyObject hash, String symbol) {
- if (hash == null || !(hash instanceof RubyHash)) return runtime.getNil();
+ private static IRubyObject hashARef(ThreadContext context, IRubyObject hash, String symbol) {
+ if (hash == null || !(hash instanceof RubyHash)) return context.nil;
- IRubyObject value = ((RubyHash) hash).fastARef(runtime.newSymbol(symbol));
+ IRubyObject value = ((RubyHash) hash).fastARef(newSymbol(context, symbol));
- return value == null ? runtime.getNil() : value;
+ return value == null ? context.nil : value;
}
// MRI: rb_ascii8bit_encoding
@@ -245,7 +256,7 @@ public static void extractModeEncoding(ThreadContext context,
fmode_p[0] = ModeFlags.getOpenFileFlagsFor(oflags_p[0]);
} else {
String p = vmode(vmodeAndVperm_p).convertToString().asJavaString();
- fmode_p[0] = OpenFile.ioModestrFmode(runtime, p);
+ fmode_p[0] = OpenFile.ioModestrFmode(context, p);
oflags_p[0] = OpenFile.ioFmodeOflags(fmode_p[0]);
int colonSplit = p.indexOf(":");
@@ -272,10 +283,10 @@ public static void extractModeEncoding(ThreadContext context,
ecopts_p[0] = context.nil;
} else {
if (!hasVmode) {
- IRubyObject v = ((RubyHash) options).op_aref(context, runtime.newSymbol("mode"));
+ IRubyObject v = ((RubyHash) options).op_aref(context, newSymbol(context, "mode"));
if (!v.isNil()) {
if (vmode(vmodeAndVperm_p) != null && !vmode(vmodeAndVperm_p).isNil()) {
- throw runtime.newArgumentError("mode specified twice");
+ throw argumentError(context, "mode specified twice");
}
hasVmode = true;
vmode(vmodeAndVperm_p, v);
@@ -283,7 +294,7 @@ public static void extractModeEncoding(ThreadContext context,
}
}
- IRubyObject v = ((RubyHash) options).op_aref(context, runtime.newSymbol("flags"));
+ IRubyObject v = ((RubyHash) options).op_aref(context, newSymbol(context, "flags"));
if (!v.isNil()) {
v = v.convertToInteger();
oflags_p[0] |= RubyNumeric.num2int(v);
@@ -291,7 +302,7 @@ public static void extractModeEncoding(ThreadContext context,
fmode_p[0] = ModeFlags.getOpenFileFlagsFor(oflags_p[0]);
}
- extractBinmode(runtime, options, fmode_p);
+ extractBinmode(context, options, fmode_p);
// Differs from MRI but we open with ModeFlags
if ((fmode_p[0] & OpenFile.BINMODE) != 0) {
oflags_p[0] |= ModeFlags.BINARY;
@@ -303,10 +314,10 @@ public static void extractModeEncoding(ThreadContext context,
fmode_p[0] |= DEFAULT_TEXTMODE;
}
- v = hashARef(runtime, options, "perm");
+ v = hashARef(context, options, "perm");
if (!v.isNil()) {
if (vperm(vmodeAndVperm_p) != null && !vperm(vmodeAndVperm_p).isNil()) {
- throw runtime.newArgumentError("perm specified twice");
+ throw argumentError(context, "perm specified twice");
}
vperm(vmodeAndVperm_p, v);
@@ -314,7 +325,7 @@ public static void extractModeEncoding(ThreadContext context,
/* perm no use, just ignore */
}
- IRubyObject extraFlags = hashARef(runtime, options, "flags");
+ IRubyObject extraFlags = hashARef(context, options, "flags");
if (!extraFlags.isNil()) {
oflags_p[0] |= extraFlags.convertToInteger().getIntValue();
}
@@ -327,7 +338,7 @@ public static void extractModeEncoding(ThreadContext context,
}
if (ioExtractEncodingOption(context, ioEncodable, options, fmode_p)) {
- if (hasEnc) throw runtime.newArgumentError("encoding specified twice");
+ if (hasEnc) throw argumentError(context, "encoding specified twice");
}
ecflags = SET_UNIVERSAL_NEWLINE_DECORATOR_IF_ENC2(ioEncodable.getEnc2(), ecflags);
@@ -605,7 +616,7 @@ public static ByteList econvAppend(ThreadContext context, EConv ec, byte[] bytes
if ((dst.getUnsafeBytes().length - dst.getBegin()) - dlen < length + maxOutput) {
long newCapa = dlen + length + maxOutput;
if (Integer.MAX_VALUE < newCapa) {
- throw context.runtime.newArgumentError("too long string");
+ throw argumentError(context, "too long string");
}
dst.ensure((int)newCapa);
dst.setRealSize(dlen);
@@ -650,18 +661,18 @@ public static int econvPrepareOptions(ThreadContext context, IRubyObject opthash
RubyHash optHash2 = (RubyHash)opthash;
ecflags = econvOpts(context, opthash, ecflags);
- v = optHash2.op_aref(context, context.runtime.newSymbol("replace"));
+ v = optHash2.op_aref(context, newSymbol(context, "replace"));
if (!v.isNil()) {
RubyString v_str = v.convertToString();
if (v_str.scanForCodeRange() == StringSupport.CR_BROKEN) {
- throw context.runtime.newArgumentError("replacement string is broken: " + v_str);
+ throw argumentError(context, "replacement string is broken: " + v_str);
}
v = v_str.freeze(context);
newhash = RubyHash.newHash(context.runtime);
- ((RubyHash)newhash).op_aset(context, context.runtime.newSymbol("replace"), v);
+ ((RubyHash)newhash).op_aset(context, newSymbol(context, "replace"), v);
}
- v = optHash2.op_aref(context, context.runtime.newSymbol("fallback"));
+ v = optHash2.op_aref(context, newSymbol(context, "fallback"));
if (!v.isNil()) {
IRubyObject h = TypeConverter.checkHashType(context.runtime, v);
boolean condition;
@@ -673,16 +684,14 @@ public static int econvPrepareOptions(ThreadContext context, IRubyObject opthash
}
if (condition) {
- if (newhash.isNil()) {
- newhash = RubyHash.newHash(context.runtime);
- }
- ((RubyHash)newhash).op_aset(context, context.runtime.newSymbol("fallback"), v);
+ if (newhash.isNil()) newhash = RubyHash.newHash(context.runtime);
+
+ ((RubyHash)newhash).op_aset(context, newSymbol(context, "fallback"), v);
}
}
- if (!newhash.isNil()) {
- newhash.setFrozen(true);
- }
+ if (!newhash.isNil()) newhash.setFrozen(true);
+
opts[0] = newhash;
return ecflags;
@@ -690,42 +699,35 @@ public static int econvPrepareOptions(ThreadContext context, IRubyObject opthash
// econv_opts
public static int econvOpts(ThreadContext context, IRubyObject opt, int ecflags) {
- Ruby runtime = context.runtime;
- IRubyObject v;
-
- v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("invalid"));
- if (v.isNil()) {
- } else if (v.toString().equals("replace")) {
+ IRubyObject v = ((RubyHash)opt).op_aref(context, newSymbol(context, "invalid"));
+ if (!v.isNil()) {
+ if (!v.toString().equals("replace")) throw argumentError(context, "unknown value for invalid character option");
ecflags |= EConvFlags.INVALID_REPLACE;
- } else {
- throw runtime.newArgumentError("unknown value for invalid character option");
}
- v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("undef"));
- if (v.isNil()) {
- } else if (v.toString().equals("replace")) {
+ v = ((RubyHash)opt).op_aref(context, newSymbol(context, "undef"));
+ if (!v.isNil()) {
+ if (!v.toString().equals("replace")) throw argumentError(context, "unknown value for undefined character option");
ecflags |= EConvFlags.UNDEF_REPLACE;
- } else {
- throw runtime.newArgumentError("unknown value for undefined character option");
}
- v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("replace"));
+ v = ((RubyHash)opt).op_aref(context, newSymbol(context, "replace"));
if (!v.isNil() && (ecflags & EConvFlags.INVALID_REPLACE) != 0) {
ecflags |= EConvFlags.UNDEF_REPLACE;
}
- v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("xml"));
+ v = ((RubyHash)opt).op_aref(context, newSymbol(context, "xml"));
if (!v.isNil()) {
if (v.toString().equals("text")) {
ecflags |= EConvFlags.XML_TEXT_DECORATOR | EConvFlags.UNDEF_HEX_CHARREF;
} else if (v.toString().equals("attr")) {
ecflags |= EConvFlags.XML_ATTR_CONTENT_DECORATOR | EConvFlags.XML_ATTR_QUOTE_DECORATOR | EConvFlags.UNDEF_HEX_CHARREF;
} else {
- throw runtime.newArgumentError("unexpected value for xml option: " + v);
+ throw argumentError(context, "unexpected value for xml option: " + v);
}
}
- v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("newline"));
+ v = ((RubyHash)opt).op_aref(context, newSymbol(context, "newline"));
if (!v.isNil()) {
ecflags &= ~EConvFlags.NEWLINE_DECORATOR_MASK;
if (v.toString().equals("universal")) {
@@ -736,29 +738,29 @@ public static int econvOpts(ThreadContext context, IRubyObject opt, int ecflags)
ecflags |= EConvFlags.CR_NEWLINE_DECORATOR;
} else if (v.toString().equals("lf")) {
// ecflags |= ECONV_LF_NEWLINE_DECORATOR;
- } else if (v instanceof RubySymbol) {
- throw runtime.newArgumentError("unexpected value for newline option: " + ((RubySymbol) v).to_s(context).toString());
+ } else if (v instanceof RubySymbol sym) {
+ throw argumentError(context, "unexpected value for newline option: " + sym.to_s(context).toString());
} else {
- throw runtime.newArgumentError("unexpected value for newline option");
+ throw argumentError(context, "unexpected value for newline option");
}
}
int setflags = 0;
boolean newlineflag = false;
- v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("universal_newline"));
+ v = ((RubyHash)opt).op_aref(context, newSymbol(context, "universal_newline"));
if (v.isTrue()) {
setflags |= EConvFlags.UNIVERSAL_NEWLINE_DECORATOR;
}
newlineflag |= !v.isNil();
- v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("crlf_newline"));
+ v = ((RubyHash)opt).op_aref(context, newSymbol(context, "crlf_newline"));
if (v.isTrue()) {
setflags |= EConvFlags.CRLF_NEWLINE_DECORATOR;
}
newlineflag |= !v.isNil();
- v = ((RubyHash)opt).op_aref(context, runtime.newSymbol("cr_newline"));
+ v = ((RubyHash)opt).op_aref(context, newSymbol(context, "cr_newline"));
if (v.isTrue()) {
setflags |= EConvFlags.CR_NEWLINE_DECORATOR;
}
@@ -999,7 +1001,7 @@ public static ByteList rbByteEncode(ThreadContext context, byte[] bytes, int sta
transcodeLoop(context, bytes, fromPos, dest.unsafeBytes(), new Ptr(destBegin), start + slen, destBegin + blen, dest, strTranscodingResize, sname, dname, ecflags, ecopt);
if (fromPos.p != start + slen) {
- throw context.runtime.newArgumentError("not fully converted, " + (slen - fromPos.p) + " bytes left");
+ throw argumentError(context, "not fully converted, " + (slen - fromPos.p) + " bytes left");
}
dest.setEncoding(to);
@@ -1035,7 +1037,7 @@ public static IRubyObject strTranscode(ThreadContext context, IRubyObject toEnco
public static IRubyObject strTranscode(ThreadContext context, IRubyObject toEncoding, IRubyObject forcedEncoding, IRubyObject opts, RubyString str, TranscodeResult result) {
IRubyObject tmp = TypeConverter.checkHashType(context.runtime, opts);
if (tmp.isNil()) {
- throw context.runtime.newArgumentError(3, 0, 2);
+ throw argumentError(context, 3, 0, 2);
}
IRubyObject[] ecopts_p = {context.nil};
@@ -1083,8 +1085,6 @@ private static IRubyObject strTranscode2(ThreadContext context, IRubyObject toEn
}
private static RubyString strTranscode(ThreadContext context, IRubyObject toEncoding, IRubyObject forceEncoding, RubyString str, int ecflags, IRubyObject ecopts, TranscodeResult result, boolean explicitlyInvalidReplace) {
- Ruby runtime = context.runtime;
-
// simplified strTranscodeEncArgs logic to avoid the carrier arrays
Encoding denc = toEncodingIndex(context, toEncoding);
byte[] dname = (denc == null) ? toEncoding.convertToString().getBytes() : denc.getName();
@@ -1114,7 +1114,7 @@ private static RubyString strTranscode(ThreadContext context, IRubyObject toEnco
ByteList fromp = sp;
int slen = str.size();
int blen = slen + 30;
- dest = RubyString.newStringLight(runtime, blen);
+ dest = RubyString.newStringLight(context.runtime, blen);
ByteList destp = dest.getByteList();
byte[] frompBytes = fromp.unsafeBytes();
@@ -1124,14 +1124,12 @@ private static RubyString strTranscode(ThreadContext context, IRubyObject toEnco
transcodeLoop(context, frompBytes, frompPos, destpBytes, destpPos, frompPos.p + slen, destpPos.p + blen, destp, strTranscodingResize, sname, dname, ecflags, ecopts);
if (frompPos.p != sp.begin() + slen) {
- throw runtime.newArgumentError("not fully converted, " + (slen - frompPos.p) + " bytes left");
+ throw argumentError(context, "not fully converted, " + (slen - frompPos.p) + " bytes left");
}
// MRI sets length of dest here, but we've already done it in the inner transcodeLoop
- if (denc == null) {
- denc = defineDummyEncoding(context, dname);
- }
+ if (denc == null) denc = defineDummyEncoding(context, dname);
return result.apply(context, str, denc, dest);
}
@@ -1188,7 +1186,7 @@ public static boolean encRegistered(byte[] name) {
// enc_check_duplication
public static void encCheckDuplication(ThreadContext context, byte[] name) {
if (encRegistered(name)) {
- throw context.runtime.newArgumentError("encoding " + new String(name) + " is already registered");
+ throw argumentError(context, "encoding " + new String(name) + " is already registered");
}
}
@@ -1805,18 +1803,17 @@ public static Encoding ioStripBOM(ThreadContext context, RubyIO io) {
// validate_enc_binmode
public static void validateEncodingBinmode(ThreadContext context, int[] fmode_p, int ecflags, IOEncodable ioEncodable) {
- Ruby runtime = context.runtime;
int fmode = fmode_p[0];
if ((fmode & OpenFile.READABLE) != 0 &&
ioEncodable.getEnc2() == null &&
(fmode & OpenFile.BINMODE) == 0 &&
- !(ioEncodable.getEnc() != null ? ioEncodable.getEnc() : runtime.getDefaultExternalEncoding()).isAsciiCompatible()) {
- throw runtime.newArgumentError("ASCII incompatible encoding needs binmode");
+ !(ioEncodable.getEnc() != null ? ioEncodable.getEnc() : context.runtime.getDefaultExternalEncoding()).isAsciiCompatible()) {
+ throw argumentError(context, "ASCII incompatible encoding needs binmode");
}
if ((fmode & OpenFile.BINMODE) != 0 && (ecflags & EConvFlags.NEWLINE_DECORATOR_MASK) != 0) {
- throw runtime.newArgumentError("newline decorator with binary mode");
+ throw argumentError(context, "newline decorator with binary mode");
}
if ((fmode & OpenFile.BINMODE) == 0 && (EncodingUtils.DEFAULT_TEXTMODE != 0 || (ecflags & EConvFlags.NEWLINE_DECORATOR_MASK) != 0)) {
@@ -1830,9 +1827,7 @@ public static void validateEncodingBinmode(ThreadContext context, int[] fmode_p,
// rb_enc_set_default_external
public static void rbEncSetDefaultExternal(ThreadContext context, IRubyObject encoding) {
- if (encoding.isNil()) {
- throw context.runtime.newArgumentError("default external can not be nil");
- }
+ if (encoding.isNil()) throw argumentError(context, "default external can not be nil");
Encoding[] enc_p = {context.runtime.getDefaultExternalEncoding()};
encSetDefaultEncoding(context, enc_p, encoding, "external");
@@ -2031,7 +2026,6 @@ public static int encCrStrBufCat(Ruby runtime, CodeRangeable str, byte[] ptrByte
// econv_args
public static void econvArgs(ThreadContext context, IRubyObject[] args, byte[][] encNames, Encoding[] encs, int[] ecflags_p, IRubyObject[] ecopts_p) {
- Ruby runtime = context.runtime;
IRubyObject snamev = context.nil;
IRubyObject dnamev = context.nil;
IRubyObject flags = context.nil;
@@ -2049,16 +2043,15 @@ public static void econvArgs(ThreadContext context, IRubyObject[] args, byte[][]
}
IRubyObject tmp;
- if (!(tmp = TypeConverter.checkHashType(runtime, flags)).isNil()) {
+ if (!(tmp = TypeConverter.checkHashType(context.runtime, flags)).isNil()) {
opt = tmp;
flags = context.nil;
}
}
if (!flags.isNil()) {
- if (!opt.isNil()) {
- throw runtime.newArgumentError(args.length, 3);
- }
+ if (!opt.isNil()) throw context.runtime.newArgumentError(args.length, 3);
+
ecflags_p[0] = (int)flags.convertToInteger().getLongValue();
ecopts_p[0] = context.nil;
} else if (!opt.isNil()) {
@@ -2068,25 +2061,19 @@ public static void econvArgs(ThreadContext context, IRubyObject[] args, byte[][]
ecopts_p[0] = context.nil;
}
- encs[0] = runtime.getEncodingService().getEncodingFromObjectNoError(snamev);
- if (encs[0] == null) {
- snamev = snamev.convertToString();
- }
- encs[1] = runtime.getEncodingService().getEncodingFromObjectNoError(dnamev);
- if (encs[1] == null) {
- dnamev = dnamev.convertToString();
- }
+ encs[0] = context.runtime.getEncodingService().getEncodingFromObjectNoError(snamev);
+ if (encs[0] == null) snamev = snamev.convertToString();
+
+ encs[1] = context.runtime.getEncodingService().getEncodingFromObjectNoError(dnamev);
+ if (encs[1] == null) dnamev = dnamev.convertToString();
encNames[0] = encs[0] != null ? encs[0].getName() : ((RubyString)snamev).getBytes();
encNames[1] = encs[1] != null ? encs[1].getName() : ((RubyString)dnamev).getBytes();
-
- return;
}
// rb_econv_init_by_convpath
- public static EConv econvInitByConvpath(ThreadContext context, IRubyObject convpath, byte[][] encNames, Encoding[] encs) {
- final Ruby runtime = context.runtime;
- final EConv ec = TranscoderDB.alloc(convpath.convertToArray().size());
+ public static EConv econvInitByConvpath(ThreadContext context, IRubyObject convpathArg, byte[][] encNames, Encoding[] encs) {
+ final EConv ec = TranscoderDB.alloc(convpathArg.convertToArray().size());
IRubyObject[] sname_v = {context.nil};
IRubyObject[] dname_v = {context.nil};
@@ -2097,12 +2084,14 @@ public static EConv econvInitByConvpath(ThreadContext context, IRubyObject convp
boolean first = true;
- for (int i = 0; i < ((RubyArray)convpath).size(); i++) {
- IRubyObject elt = ((RubyArray)convpath).eltOk(i);
+ var convpath = (RubyArray) convpathArg;
+
+ for (int i = 0; i < convpath.size(); i++) {
+ IRubyObject elt = convpath.eltOk(i);
IRubyObject pair;
if (!(pair = elt.checkArrayType()).isNil()) {
if (((RubyArray)pair).size() != 2) {
- throw context.runtime.newArgumentError("not a 2-element array in convpath");
+ throw argumentError(context, "not a 2-element array in convpath");
}
sname_v[0] = ((RubyArray)pair).eltOk(0);
encArg(context, sname_v[0], sname, senc);
@@ -2115,7 +2104,7 @@ public static EConv econvInitByConvpath(ThreadContext context, IRubyObject convp
if (DECORATOR_P(sname[0], dname[0])) {
boolean ret = ec.addConverter(sname[0], dname[0], ec.numTranscoders);
if (!ret) {
- throw runtime.newArgumentError("decoration failed: " + new String(dname[0]));
+ throw argumentError(context, "decoration failed: " + new String(dname[0]));
}
} else {
int j = ec.numTranscoders;
@@ -2129,7 +2118,7 @@ public void call(byte[] source, byte[] destination, int depth) {
}
});
if (ret == -1 || arg[1] == -1) {
- throw runtime.newArgumentError("adding conversion failed: " + new String(sname[0]) + " to " + new String(dname[0]));
+ throw argumentError(context, "adding conversion failed: " + new String(sname[0]) + " to " + new String(dname[0]));
}
if (first) {
first = false;
@@ -2272,11 +2261,16 @@ public static int encCodepointLength(byte[] pBytes, int p, int e, int[] len_p, E
return StringSupport.codePoint(enc, pBytes, p, e);
}
+ @Deprecated
public static int encCodepointLength(Ruby runtime, byte[] pBytes, int p, int e, int[] len_p, Encoding enc) {
+ return encCodepointLength(runtime.getCurrentContext(), pBytes, p, e, len_p, enc);
+ }
+
+ public static int encCodepointLength(ThreadContext context, byte[] pBytes, int p, int e, int[] len_p, Encoding enc) {
try {
return encCodepointLength(pBytes, p, e, len_p, enc);
} catch (IllegalArgumentException ex) {
- throw runtime.newArgumentError(ex.getMessage());
+ throw argumentError(context, ex.getMessage());
}
}
@@ -2286,7 +2280,7 @@ public static IRubyObject strCompatAndValid(ThreadContext context, IRubyObject _
RubyString str = _str.convertToString();
cr = str.scanForCodeRange();
if (cr == StringSupport.CR_BROKEN) {
- throw context.runtime.newArgumentError("replacement must be valid byte sequence '" + str + "'");
+ throw argumentError(context, "replacement must be valid byte sequence '" + str + "'");
}
else {
Encoding e = STR_ENC_GET(str);
@@ -2407,7 +2401,7 @@ public static Charset charsetForEncoding(Encoding enc) throws UnsupportedCharset
public static int encCodelen(ThreadContext context, int c, Encoding enc) {
int n = enc.codeToMbcLength(c);
if (n == 0) {
- throw context.runtime.newArgumentError("invalid codepoint 0x" + Long.toHexString(c & 0xFFFFFFFFL) + " in " + enc);
+ throw argumentError(context, "invalid codepoint 0x" + Long.toHexString(c & 0xFFFFFFFFL) + " in " + enc);
}
return n;
}
diff --git a/core/src/main/java/org/jruby/util/io/Getline.java b/core/src/main/java/org/jruby/util/io/Getline.java
index 66b48aac81c..322db2c4d94 100644
--- a/core/src/main/java/org/jruby/util/io/Getline.java
+++ b/core/src/main/java/org/jruby/util/io/Getline.java
@@ -11,6 +11,7 @@
import org.jruby.util.StringSupport;
import org.jruby.util.TypeConverter;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.runtime.ThreadContext.resetCallInfo;
/**
@@ -192,7 +193,7 @@ public static Return getlineCall(ThreadContex
// We get args from multiple sources so we are form-fitting this as if we are processing it from
// the original method. We should not be doing this processing this deep into this IO processing.
if (argc == 3) {
- throw runtime.newArgumentError(argc, 0, 2);
+ throw argumentError(context, argc, 0, 2);
} else {
throw runtime.newTypeError("no implicit conversion of Hash into Integer");
}
@@ -239,9 +240,8 @@ public static Return getlineCall(ThreadContex
(rs_s.size() > 0 && !enc_io.isAsciiCompatible()))) {
if (rs == runtime.getGlobalVariables().getDefaultSeparator()) {
rs = RubyString.newStringLight(runtime, 2, enc_io).cat('\n', enc_io);
- }
- else {
- throw runtime.newArgumentError("encoding mismatch: " + enc_io + " IO with " + enc_rs + " RS");
+ } else {
+ throw argumentError(context, "encoding mismatch: " + enc_io + " IO with " + enc_rs + " RS");
}
}
}
diff --git a/core/src/main/java/org/jruby/util/io/OpenFile.java b/core/src/main/java/org/jruby/util/io/OpenFile.java
index d129814be55..c370d8b1e48 100644
--- a/core/src/main/java/org/jruby/util/io/OpenFile.java
+++ b/core/src/main/java/org/jruby/util/io/OpenFile.java
@@ -51,6 +51,7 @@
import static org.jruby.api.Convert.asFixnum;
import static org.jruby.api.Create.newFixnum;
+import static org.jruby.api.Error.argumentError;
import static org.jruby.util.StringSupport.*;
public class OpenFile implements Finalizable {
@@ -212,12 +213,15 @@ public int getMode() {
return mode;
}
+ @Deprecated
public String getModeAsString(Ruby runtime) {
+ return getModeAsString(runtime.getCurrentContext());
+ }
+
+ public String getModeAsString(ThreadContext context) {
String modeString = getStringFromMode(mode);
- if (modeString == null) {
- throw runtime.newArgumentError("Illegal access modenum " + Integer.toOctalString(mode));
- }
+ if (modeString == null) throw argumentError(context, "Illegal access modenum " + Integer.toOctalString(mode));
return modeString;
}
@@ -246,10 +250,15 @@ public static int getModeFlagsAsIntFrom(int fmode) {
return oflags;
}
- // MRI: rb_io_oflags_modestr
+ @Deprecated
public static String ioOflagsModestr(Ruby runtime, int oflags) {
+ return ioOflagsModestr(runtime.getCurrentContext(), oflags);
+ }
+
+ // MRI: rb_io_oflags_modestr
+ public static String ioOflagsModestr(ThreadContext context, int oflags) {
if ((oflags & OpenFlags.O_EXLOCK.intValue()) != 0) {
- throw runtime.newArgumentError("exclusive access mode is not supported");
+ throw argumentError(context, "exclusive access mode is not supported");
}
int accmode = oflags & (OpenFlags.O_RDONLY.intValue()|OpenFlags.O_WRONLY.intValue()|OpenFlags.O_RDWR.intValue());
if ((oflags & OpenFlags.O_APPEND.intValue()) != 0) {
@@ -262,7 +271,7 @@ public static String ioOflagsModestr(Ruby runtime, int oflags) {
}
switch (OpenFlags.valueOf(oflags & (OpenFlags.O_RDONLY.intValue()|OpenFlags.O_WRONLY.intValue()|OpenFlags.O_RDWR.intValue()))) {
default:
- throw runtime.newArgumentError("invalid access oflags 0x" + Integer.toHexString(oflags));
+ throw argumentError(context, "invalid access oflags 0x" + Integer.toHexString(oflags));
case O_RDONLY:
return MODE_BINARY(oflags, "r", "rb");
case O_WRONLY:
@@ -272,9 +281,14 @@ public static String ioOflagsModestr(Ruby runtime, int oflags) {
}
}
- // MRI: rb_io_modestr_oflags
+ @Deprecated
public static int ioModestrOflags(Ruby runtime, String modestr) {
- return ioFmodeOflags(ioModestrFmode(runtime, modestr));
+ return ioModestrOflags(runtime.getCurrentContext(), modestr);
+ }
+
+ // MRI: rb_io_modestr_oflags
+ public static int ioModestrOflags(ThreadContext context, String modestr) {
+ return ioFmodeOflags(ioModestrFmode(context, modestr));
}
// MRI: rb_io_fmode_oflags
@@ -314,12 +328,17 @@ public static int ioFmodeOflags(int fmode) {
return oflags;
}
+ @Deprecated
public static int ioModestrFmode(Ruby runtime, String modestr) {
+ return ioModestrFmode(runtime.getCurrentContext(), modestr);
+ }
+
+ public static int ioModestrFmode(ThreadContext context, String modestr) {
int fmode = 0;
char[] mChars = modestr.toCharArray(), pChars = null;
int m = 0, p = 0;
- if (mChars.length == 0) throw runtime.newArgumentError("invalid access mode " + modestr);
+ if (mChars.length == 0) throw argumentError(context, "invalid access mode " + modestr);
switch (mChars[m++]) {
case 'r':
@@ -332,7 +351,7 @@ public static int ioModestrFmode(Ruby runtime, String modestr) {
fmode |= OpenFile.WRITABLE | OpenFile.APPEND | OpenFile.CREATE;
break;
default:
- throw runtime.newArgumentError("invalid access mode " + modestr);
+ throw argumentError(context, "invalid access mode " + modestr);
}
loop: while (m < mChars.length) {
@@ -347,26 +366,28 @@ public static int ioModestrFmode(Ruby runtime, String modestr) {
fmode |= OpenFile.READWRITE;
break;
case 'x':
- if (mChars[0] != 'w') {
- throw runtime.newArgumentError("invalid access mode " + modestr);
- }
+ if (mChars[0] != 'w') throw argumentError(context, "invalid access mode " + modestr);
+
fmode |= OpenFile.EXCLUSIVE;
break;
case ':':
pChars = mChars;
p = m;
- if ((fmode & OpenFile.BINMODE) != 0 && (fmode & OpenFile.TEXTMODE) != 0)
- throw runtime.newArgumentError("invalid access mode " + modestr);
+ if ((fmode & OpenFile.BINMODE) != 0 && (fmode & OpenFile.TEXTMODE) != 0) {
+ throw argumentError(context, "invalid access mode " + modestr);
+ }
break loop;
default:
- throw runtime.newArgumentError("invalid access mode " + modestr);
+ throw argumentError(context, "invalid access mode " + modestr);
}
}
- if ((fmode & OpenFile.BINMODE) != 0 && (fmode & OpenFile.TEXTMODE) != 0)
- throw runtime.newArgumentError("invalid access mode " + modestr);
- if (p != 0 && ioEncnameBomP(new String(pChars, p, pChars.length - p), 0))
+ if ((fmode & OpenFile.BINMODE) != 0 && (fmode & OpenFile.TEXTMODE) != 0) {
+ throw argumentError(context, "invalid access mode " + modestr);
+ }
+ if (p != 0 && ioEncnameBomP(new String(pChars, p, pChars.length - p), 0)) {
fmode |= OpenFile.SETENC_BY_BOM;
+ }
return fmode;
}
@@ -2337,7 +2358,7 @@ protected Encoding getCommonEncodingForWriteConv(ThreadContext context, Encoding
if (writeconvAsciicompat != null)
common_encoding = writeconvAsciicompat;
else if (EncodingUtils.MODE_BTMODE(fmode, EncodingUtils.DEFAULT_TEXTMODE, 0, 1) != 0 && !strEncoding.isAsciiCompatible()) {
- throw context.runtime.newArgumentError("ASCII incompatible string written for text mode IO without encoding conversion: %s" + strEncoding.toString());
+ throw argumentError(context, "ASCII incompatible string written for text mode IO without encoding conversion: %s" + strEncoding.toString());
}
} else {
if (encs.enc2 != null)
diff --git a/core/src/main/java/org/jruby/util/io/PopenExecutor.java b/core/src/main/java/org/jruby/util/io/PopenExecutor.java
index 68fbb105b59..72088bbb2bf 100644
--- a/core/src/main/java/org/jruby/util/io/PopenExecutor.java
+++ b/core/src/main/java/org/jruby/util/io/PopenExecutor.java
@@ -355,7 +355,7 @@ public static IRubyObject popen(ThreadContext context, IRubyObject[] argv, RubyC
if (!env.isNil()) execargSetenv(context, eargp, env);
}
EncodingUtils.extractModeEncoding(context, convconfig, pmode, opt, oflags_p, fmode_p);
- modestr = OpenFile.ioOflagsModestr(runtime, oflags_p[0]);
+ modestr = OpenFile.ioOflagsModestr(context, oflags_p[0]);
port = new PopenExecutor().pipeOpen(context, eargp, modestr, fmode_p[0], convconfig);
// This is cleanup for failure to exec in the child.
@@ -380,32 +380,20 @@ static void execargSetenv(ThreadContext context, ExecArg eargp, IRubyObject env)
// MRI: rb_check_exec_env
public static RubyArray checkExecEnv(ThreadContext context, RubyHash hash, ExecArg pathArg) {
Ruby runtime = context.runtime;
- RubyArray env;
+ RubyArray env = runtime.newArray();
- env = runtime.newArray();
for (Map.Entry entry : (Set>)hash.directEntrySet()) {
IRubyObject key = entry.getKey();
IRubyObject val = entry.getValue();
- String k;
-
RubyString keyString = StringSupport.checkEmbeddedNulls(runtime, key).export(context);
+ String k = keyString.toString();
- k = keyString.toString();
-
- if (k.indexOf('=') != -1)
- throw runtime.newArgumentError("environment name contains a equal : " + k);
-
- if (!val.isNil()) {
- val = StringSupport.checkEmbeddedNulls(runtime, val);
- }
+ if (k.indexOf('=') != -1) throw argumentError(context, "environment name contains a equal : " + k);
- if (!val.isNil()) {
- val = ((RubyString) val).export(context);
- }
+ if (!val.isNil()) val = StringSupport.checkEmbeddedNulls(runtime, val);
+ if (!val.isNil()) val = ((RubyString) val).export(context);
- if (k.equalsIgnoreCase("PATH")) {
- pathArg.path_env = val;
- }
+ if (k.equalsIgnoreCase("PATH")) pathArg.path_env = val;
env.push(runtime.newArray(keyString, val));
}
@@ -1042,7 +1030,7 @@ int execargRunOptions(ThreadContext context, ExecArg eargp, ExecArg sargp, Strin
RubyArray env = eargp.env_modification;
if (env != null) {
- eargp.envp_str = ShellLauncher.getModifiedEnv(context.runtime, env, clearEnv);
+ eargp.envp_str = ShellLauncher.getModifiedEnv(context, env, clearEnv);
}
if (eargp.umaskGiven) {
@@ -1242,7 +1230,7 @@ static int checkExecFds1(ThreadContext context, ExecArg eargp, RubyHash h, int m
IRubyObject elt = ((RubyArray)ary).eltOk(i);
int fd = RubyNumeric.fix2int(((RubyArray)elt).eltOk(0));
if (h.fastARef(newFixnum(context, fd)) != null) {
- throw context.runtime.newArgumentError("fd " + fd + " specified twice");
+ throw argumentError(context, "fd " + fd + " specified twice");
}
if (ary == eargp.fd_open || ary == eargp.fd_dup2)
h.op_aset(context, newFixnum(context, fd), context.tru);
@@ -1524,7 +1512,7 @@ static void checkExecRedirect(ThreadContext context, IRubyObject key, IRubyObjec
if (flags.isNil())
intFlags = OpenFlags.O_RDONLY.intValue();
else if (flags instanceof RubyString)
- intFlags = OpenFile.ioModestrOflags(context.runtime, flags.toString());
+ intFlags = OpenFile.ioModestrOflags(context, flags.toString());
else
intFlags = flags.convertToInteger().getIntValue();
flags = newFixnum(context, intFlags);
@@ -1742,9 +1730,8 @@ public static RubyString checkArgv(ThreadContext context, IRubyObject[] argv) {
tmp = TypeConverter.checkArrayType(runtime, argv[0]);
if (!tmp.isNil()) {
RubyArray arrayArg = (RubyArray) tmp;
- if (arrayArg.size() != 2) {
- throw runtime.newArgumentError("wrong first argument");
- }
+ if (arrayArg.size() != 2) throw argumentError(context, "wrong first argument");
+
prog = arrayArg.eltOk(0).convertToString();
argv[0] = arrayArg.eltOk(1);
StringSupport.checkEmbeddedNulls(runtime, prog);
diff --git a/core/src/main/java/org/jruby/util/io/Sockaddr.java b/core/src/main/java/org/jruby/util/io/Sockaddr.java
index 9371fd8bb3c..9748fca2719 100644
--- a/core/src/main/java/org/jruby/util/io/Sockaddr.java
+++ b/core/src/main/java/org/jruby/util/io/Sockaddr.java
@@ -84,11 +84,8 @@ public static InetSocketAddress addressFromSockaddr_in(ThreadContext context, By
}
public static SocketAddress addressFromSockaddr(ThreadContext context, IRubyObject arg) {
- Ruby runtime = context.runtime;
-
ByteList val = arg.convertToString().getByteList();
-
- AddressFamily af = getAddressFamilyFromSockaddr(runtime, val);
+ AddressFamily af = getAddressFamilyFromSockaddr(context, val);
switch (af) {
case AF_UNIX:
@@ -97,7 +94,7 @@ public static SocketAddress addressFromSockaddr(ThreadContext context, IRubyObje
case AF_INET6:
return addressFromSockaddr_in(context, val);
default:
- throw runtime.newArgumentError("can't resolve socket address of wrong type");
+ throw argumentError(context, "can't resolve socket address of wrong type");
}
}
@@ -220,22 +217,15 @@ public static IRubyObject pack_sockaddr_in(ThreadContext context, InetSocketAddr
}
public static RubyArray unpack_sockaddr_in(ThreadContext context, IRubyObject addr) {
- final Ruby runtime = context.runtime;
-
- if (addr instanceof Addrinfo) {
- Addrinfo addrinfo = (Addrinfo)addr;
-
+ if (addr instanceof Addrinfo addrinfo) {
if (((RubyBoolean)addrinfo.ip_p(context)).isFalse()) {
- throw runtime.newArgumentError("not an AF_INET/AF_INET6 sockaddr");
+ throw argumentError(context, "not an AF_INET/AF_INET6 sockaddr");
}
- return RubyArray.newArray(runtime, addrinfo.ip_port(context),
- addrinfo.ip_address(context));
+ return RubyArray.newArray(context.runtime, addrinfo.ip_port(context), addrinfo.ip_address(context));
}
- ByteList val = addr.convertToString().getByteList();
-
- return unpack_sockaddr_in(context, val);
+ return unpack_sockaddr_in(context, addr.convertToString().getByteList());
}
public static RubyArray unpack_sockaddr_in(ThreadContext context, ByteList val) {
@@ -271,16 +261,12 @@ public static RubyArray unpack_sockaddr_in(ThreadContext context, ByteList val)
}
public static IRubyObject pack_sockaddr_un(ThreadContext context, String unixpath) {
- final Ruby runtime = context.runtime;
-
ByteBuffer buf = ByteBuffer.allocate(SOCKADDR_UN_SIZE);
-
byte[] path = unixpath.getBytes();
if (path.length > SOCKADDR_UN_PATH) {
String errorMsg = "too long unix socket path (%d bytes given but %d bytes max)";
- String formattedErrorMsg = String.format(errorMsg, path.length, SOCKADDR_UN_PATH);
- throw runtime.newArgumentError(formattedErrorMsg);
+ throw argumentError(context, String.format(errorMsg, path.length, SOCKADDR_UN_PATH));
}
int afamily = AddressFamily.AF_UNIX.intValue();
@@ -290,27 +276,23 @@ public static IRubyObject pack_sockaddr_un(ThreadContext context, String unixpat
buf.put((byte)low);
buf.put(path);
- return RubyString.newString(runtime, buf.array());
+ return newString(context, new ByteList(buf.array()));
}
public static IRubyObject unpack_sockaddr_un(ThreadContext context, IRubyObject addr) {
- final Ruby runtime = context.runtime;
-
if (addr instanceof Addrinfo) {
Addrinfo addrinfo = (Addrinfo)addr;
if (((RubyBoolean)addrinfo.unix_p(context)).isFalse()) {
- throw runtime.newArgumentError("not an AF_UNIX sockaddr");
+ throw argumentError(context, "not an AF_UNIX sockaddr");
}
return addrinfo.unix_path(context);
}
ByteList val = addr.convertToString().getByteList();
- AddressFamily af = getAddressFamilyFromSockaddr(runtime, val);
+ AddressFamily af = getAddressFamilyFromSockaddr(context, val);
- if (af != AddressFamily.AF_UNIX) {
- throw runtime.newArgumentError("not an AF_UNIX sockaddr");
- }
+ if (af != AddressFamily.AF_UNIX) throw argumentError(context, "not an AF_UNIX sockaddr");
return pathFromSockaddr_un(context, val.bytes());
}
@@ -356,11 +338,16 @@ private static RuntimeException sockerr(Ruby runtime, String msg) {
return RaiseException.from(runtime, runtime.getClass("SocketError"), msg);
}
+ @Deprecated
public static SocketAddress sockaddrFromBytes(Ruby runtime, byte[] val) throws IOException {
+ return sockaddrFromBytes(runtime.getCurrentContext(), val);
+ }
+
+ public static SocketAddress sockaddrFromBytes(ThreadContext context, byte[] val) throws IOException {
AddressFamily afamily = AddressFamily.valueOf(uint16(val[0], val[1]));
if (afamily == null || afamily == AddressFamily.__UNKNOWN_CONSTANT__) {
- throw runtime.newArgumentError("can't resolve socket address of wrong type");
+ throw argumentError(context, "can't resolve socket address of wrong type");
}
int port;
@@ -377,7 +364,7 @@ public static SocketAddress sockaddrFromBytes(Ruby runtime, byte[] val) throws I
String path = new String(val, 2, val.length - 2);
return new UnixSocketAddress(new File(path));
default:
- throw runtime.newArgumentError("can't resolve socket address of wrong type");
+ throw argumentError(context, "can't resolve socket address of wrong type");
}
}
diff --git a/core/src/main/java/org/jruby/util/time/TimeArgs.java b/core/src/main/java/org/jruby/util/time/TimeArgs.java
index 2dd768d0b5c..a962f381246 100644
--- a/core/src/main/java/org/jruby/util/time/TimeArgs.java
+++ b/core/src/main/java/org/jruby/util/time/TimeArgs.java
@@ -201,7 +201,7 @@ public void initializeTime(ThreadContext context, RubyTime time, DateTimeZone dt
private static int parseYear(ThreadContext context, IRubyObject _year) {
if (_year instanceof RubyString yr) {
if (!yr.getEncoding().isAsciiCompatible()) {
- throw context.runtime.newArgumentError("time string should have ASCII compatible encoding");
+ throw argumentError(context, "time string should have ASCII compatible encoding");
}
_year = RubyNumeric.str2inum(context.runtime, yr, 10, false);
}
@@ -238,14 +238,14 @@ private static int parseMonth(ThreadContext context, IRubyObject _month) {
try {
month = Integer.parseInt(monthStr);
} catch (NumberFormatException ex) {
- throw context.runtime.newArgumentError("argument out of range.");
+ throw argumentError(context, "argument out of range.");
}
} else {
month = RubyNumeric.num2int(_month);
}
if (month < 1 || month > 12) {
- throw context.runtime.newArgumentError("argument out of range: for month: " + month);
+ throw argumentError(context, "argument out of range: for month: " + month);
}
return month;
@@ -266,16 +266,16 @@ private static IRubyObject parseIntArg(ThreadContext context, IRubyObject arg) {
}
private void validateDayHourMinuteSecond(ThreadContext context) {
- if (day < 1 || day > 31) throw context.runtime.newArgumentError("argument out of range for day");
+ if (day < 1 || day > 31) throw argumentError(context, "argument out of range for day");
- if (hour < 0 || hour > 24) throw context.runtime.newArgumentError("argument out of range for hour");
+ if (hour < 0 || hour > 24) throw argumentError(context, "argument out of range for hour");
if ((minute < 0 || minute > 59) || (hour == 24 && minute > 0)) {
- throw context.runtime.newArgumentError("argument out of range for minute");
+ throw argumentError(context, "argument out of range for minute");
}
if ((second < 0 || second > 60) || (hour == 24 && second > 0)) {
- throw context.runtime.newArgumentError("argument out of range");
+ throw argumentError(context, "argument out of range");
}
}
diff --git a/core/src/test/java/org/jruby/test/TestRubyException.java b/core/src/test/java/org/jruby/test/TestRubyException.java
index 85236be261a..b8116ca6d3e 100644
--- a/core/src/test/java/org/jruby/test/TestRubyException.java
+++ b/core/src/test/java/org/jruby/test/TestRubyException.java
@@ -43,14 +43,17 @@
import java.util.List;
import static org.jruby.api.Create.newString;
+import static org.jruby.api.Error.argumentError;
public class TestRubyException extends TestCase {
private Ruby runtime;
+ private ThreadContext context;
private RubyException exception;
public void setUp() {
runtime = Ruby.newInstance();
+ context = runtime.getCurrentContext();
exception = new RubyException(runtime, runtime.getClass("StandardError"), "test");
}
@@ -67,7 +70,7 @@ public void testToJava() {
}
public void testConcreteToJava() {
- RaiseException raise = runtime.newArgumentError("BLAH");
+ RaiseException raise = argumentError(context, "BLAH");
assertSame(raise, raise.getException().toJava(Throwable.class));
assertNotNull(raise.getException().toJava(Object.class));
@@ -86,7 +89,7 @@ public void testPrintBacktrace() {
}
public void testPrintNilBacktrace() {
- exception.set_backtrace(runtime.getNil());
+ exception.set_backtrace(context.nil);
String[] lines = printError();
@@ -94,7 +97,7 @@ public void testPrintNilBacktrace() {
}
public void testPrintBackTraceWithString() {
- exception.set_backtrace(RubyArray.newArray(runtime, newString(runtime.getCurrentContext(), testLine(0))));
+ exception.set_backtrace(RubyArray.newArray(runtime, newString(context, testLine(0))));
String[] lines = printError();
@@ -115,10 +118,10 @@ private String[] printError() {
}
private void setBackTrace(int lineCount) {
- ThreadContext context = runtime.getCurrentContext();
List traceLines = new ArrayList();
- for (int i=0; i