diff --git a/core/src/main/java/org/jruby/AbstractRubyMethod.java b/core/src/main/java/org/jruby/AbstractRubyMethod.java index 7b3a8e6e399..ec74690aa66 100644 --- a/core/src/main/java/org/jruby/AbstractRubyMethod.java +++ b/core/src/main/java/org/jruby/AbstractRubyMethod.java @@ -52,6 +52,7 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; /** * @see RubyMethod @@ -125,11 +126,9 @@ public IRubyObject owner(ThreadContext context) { public IRubyObject source_location(ThreadContext context) { String filename = getFilename(); - if (filename != null) { - return context.runtime.newArray(Convert.asString(context, filename), asFixnum(context, getLine())); - } - - return context.nil; + return filename != null ? + newArray(context, Convert.asString(context, filename), asFixnum(context, getLine())) : + context.nil; } public String getFilename() { diff --git a/core/src/main/java/org/jruby/Ruby.java b/core/src/main/java/org/jruby/Ruby.java index 29b0017f6be..36dce1f36d4 100644 --- a/core/src/main/java/org/jruby/Ruby.java +++ b/core/src/main/java/org/jruby/Ruby.java @@ -422,7 +422,7 @@ private Ruby(RubyInstanceConfig config) { if (profile.allowClass("Array")) { arrayClass = RubyArray.createArrayClass(this); - emptyFrozenArray = newEmptyArray(); + emptyFrozenArray = Create.newEmptyArray(getCurrentContext()); emptyFrozenArray.setFrozen(true); } else { arrayClass = null; @@ -3395,42 +3395,52 @@ public ProfilingService getProfilingService() { // new factory methods ------------------------------------------------------------------------ + @Deprecated(since = "10.0") public RubyArray newEmptyArray() { return RubyArray.newEmptyArray(this); } + @Deprecated(since = "10.0") public RubyArray newArray() { return RubyArray.newArray(this); } + @Deprecated(since = "10.0") public RubyArray newArrayLight() { return RubyArray.newArrayLight(this); } + @Deprecated(since = "10.0") public RubyArray newArray(IRubyObject object) { return RubyArray.newArray(this, object); } + @Deprecated(since = "10.0") public RubyArray newArray(IRubyObject car, IRubyObject cdr) { return RubyArray.newArray(this, car, cdr); } + @Deprecated(since = "10.0") public RubyArray newArray(IRubyObject... objects) { return RubyArray.newArray(this, objects); } + @Deprecated(since = "10.0") public RubyArray newArrayNoCopy(IRubyObject... objects) { return RubyArray.newArrayNoCopy(this, objects); } + @Deprecated(since = "10.0") public RubyArray newArrayNoCopyLight(IRubyObject... objects) { return RubyArray.newArrayNoCopyLight(this, objects); } + @Deprecated(since = "10.0") public RubyArray newArray(List list) { return RubyArray.newArray(this, list); } + @Deprecated(since = "10.0") public RubyArray newArray(int size) { return RubyArray.newArray(this, size); } diff --git a/core/src/main/java/org/jruby/RubyArgsFile.java b/core/src/main/java/org/jruby/RubyArgsFile.java index 313bebe41c2..718d54946e7 100644 --- a/core/src/main/java/org/jruby/RubyArgsFile.java +++ b/core/src/main/java/org/jruby/RubyArgsFile.java @@ -44,7 +44,7 @@ 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.newString; +import static org.jruby.api.Create.*; import static org.jruby.api.Error.argumentError; import static org.jruby.runtime.ThreadContext.CALL_KEYWORD; import static org.jruby.runtime.ThreadContext.resetCallInfo; @@ -53,8 +53,6 @@ import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; import org.jruby.internal.runtime.GlobalVariable; -import org.jruby.internal.runtime.ReadonlyAccessor; -import org.jruby.internal.runtime.ValueAccessor; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; import org.jruby.runtime.CallSite; @@ -79,7 +77,7 @@ public static void initArgsFile(final Ruby runtime) { argfClass.defineAnnotatedMethods(RubyArgsFile.class); - IRubyObject argsFile = argfClass.newInstance(runtime.getCurrentContext(), new IRubyObject[] { null }, (Block) null); + IRubyObject argsFile = argfClass.newInstance(runtime.getCurrentContext(), new IRubyObject[] { null }, null); runtime.setArgsFile(argsFile); runtime.getGlobalVariables().defineReadonly("$<", new ArgsFileAccessor(runtime), GlobalVariable.Scope.GLOBAL); @@ -104,13 +102,10 @@ public IRubyObject setValue(IRubyObject newValue) { @JRubyMethod(name = "initialize", visibility = PRIVATE, rest = true) public IRubyObject initialize(ThreadContext context, IRubyObject[] args) { - final Ruby runtime = context.runtime; - final RubyArray argv; - if (args.length == 1 && args[0] == null) { - argv = runtime.getObject().getConstant("ARGV").convertToArray(); - } else { - argv = runtime.newArray(args); - } + var runtime = context.runtime; + final var argv = args.length == 1 && args[0] == null ? + runtime.getObject().getConstant("ARGV").convertToArray() : + newArray(context, args); // ARGF is intended to be a singleton from a Ruby perspective but it is still // possible for someone to ARGF.class.new. We do still want a global view of @@ -437,14 +432,13 @@ public static IRubyObject readline(ThreadContext context, IRubyObject recv, IRub public static IRubyObject readlines(ThreadContext context, IRubyObject recv, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 0, 1); - Ruby runtime = context.runtime; - ArgsFileData data = ArgsFileData.getArgsFileData(runtime); + ArgsFileData data = ArgsFileData.getArgsFileData(context.runtime); - if (!data.next_argv(context)) return runtime.newEmptyArray(); + if (!data.next_argv(context)) return newEmptyArray(context); if (!(data.currentFile instanceof RubyIO)) return data.currentFile.callMethod(context, "readlines", args); - var ary = runtime.newArray(); + var ary = newArray(context); IRubyObject line; while(!(line = argf_getline(context, recv, args)).isNil()) { ary.append(context, line); @@ -456,13 +450,12 @@ public static IRubyObject readlines(ThreadContext context, IRubyObject recv, IRu public static IRubyObject to_a(ThreadContext context, IRubyObject recv, IRubyObject[] args) { Arity.checkArgumentCount(context, args, 0, 1); - Ruby runtime = context.runtime; - ArgsFileData data = ArgsFileData.getArgsFileData(runtime); + ArgsFileData data = ArgsFileData.getArgsFileData(context.runtime); - if (!data.next_argv(context)) return runtime.newEmptyArray(); + if (!data.next_argv(context)) return newEmptyArray(context); if (!(data.currentFile instanceof RubyIO)) return data.currentFile.callMethod(context, "to_a", args); - var ary = runtime.newArray(); + var ary = newArray(context); IRubyObject line; while ((line = argf_getline(context, recv, args)) != context.nil) { ary.append(context, line); diff --git a/core/src/main/java/org/jruby/RubyArithmeticSequence.java b/core/src/main/java/org/jruby/RubyArithmeticSequence.java index ebbcee78750..3a09d025e39 100644 --- a/core/src/main/java/org/jruby/RubyArithmeticSequence.java +++ b/core/src/main/java/org/jruby/RubyArithmeticSequence.java @@ -207,7 +207,7 @@ public IRubyObject first(ThreadContext context, IRubyObject num) { long n = numericToLong(context, num); if (n < 0) throw argumentError(context, "attempt to take negative size"); - if (n == 0) return context.runtime.newEmptyArray(); + if (n == 0) return newEmptyArray(context); boolean x = excludeEnd.isTrue(); @@ -275,12 +275,9 @@ public IRubyObject first(ThreadContext context, IRubyObject num) { if (n > len) n = (long)len; if (Double.isInfinite(unit)) { - if (len > 0) { - ary = newArray(context, 1); - ary.append(context, newFloat(context, beg)); - } else { - ary = context.runtime.newEmptyArray(); - } + ary = len > 0 ? + newArray(context, 1).append(context, newFloat(context, beg)) : + newEmptyArray(context); } else if (unit == 0) { IRubyObject val = newFloat(context, beg); ary = newArray(context, n); @@ -453,13 +450,12 @@ public IRubyObject last(ThreadContext context) { @JRubyMethod public IRubyObject last(ThreadContext context, IRubyObject num) { IRubyObject b = begin, e = end, s = step, len_1, len; - RubyArray ary; boolean last_is_adjusted; if (e.isNil()) throw context.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)) return num == null ? context.nil : context.runtime.newEmptyArray(); + if (Numeric.f_negative_p(context, len_1)) return num == null ? context.nil : newEmptyArray(context); 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()) { @@ -485,7 +481,7 @@ public IRubyObject last(ThreadContext context, IRubyObject num) { long n = numericToLong(context, nv); if (n < 0) throw argumentError(context, "negative array size"); - ary = newArray(context, n); + var ary = newArray(context, n); b = ((RubyNumeric)last).op_minus(context, Numeric.f_mul(context, s, nv)); while (n > 0) { b = ((RubyNumeric)b).op_plus(context, s); @@ -500,28 +496,19 @@ public IRubyObject last(ThreadContext context, IRubyObject num) { public IRubyObject size(ThreadContext context) { Ruby runtime = context.runtime; IRubyObject len_1, len, last; - int x; if (begin instanceof RubyFloat || end instanceof RubyFloat || step instanceof RubyFloat) { double ee, n; if (end.isNil()) { - if (Numeric.f_negative_p(context, step)) { - ee = Double.NEGATIVE_INFINITY; - } else { - ee = Double.POSITIVE_INFINITY; - } + ee = Numeric.f_negative_p(context, step) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } else { ee = num2dbl(end); } n = floatStepSize(num2dbl(begin), ee, num2dbl(step), excludeEnd.isTrue()); - if (Double.isInfinite(n)) { - return dbl2num(runtime, n); - } - if (RubyNumeric.posFixable(n)) { - return int2fix(runtime, (long)n); - } + if (Double.isInfinite(n)) return dbl2num(runtime, n); + if (RubyNumeric.posFixable(n)) return int2fix(runtime, (long)n); return RubyBignum.newBignorm(runtime, n); } diff --git a/core/src/main/java/org/jruby/RubyArray.java b/core/src/main/java/org/jruby/RubyArray.java index 9d03f0860af..ad52862f20a 100644 --- a/core/src/main/java/org/jruby/RubyArray.java +++ b/core/src/main/java/org/jruby/RubyArray.java @@ -335,17 +335,13 @@ public static RubyArray newArrayMayCopy(Ruby runtime, IRubyObject[] args, int st * @return an array referencing the given elements */ public static RubyArray newArrayMayCopy(Ruby runtime, IRubyObject[] args, int start, int length) { - if (length == 0) { - return newEmptyArray(runtime); - } + if (length == 0) return newEmptyArray(runtime); + if (USE_PACKED_ARRAYS) { - if (length == 1) { - return new RubyArrayOneObject(runtime, args[start]); - } - if (length == 2) { - return new RubyArrayTwoObject(runtime, args[start], args[start + 1]); - } + if (length == 1) return new RubyArrayOneObject(runtime, args[start]); + if (length == 2) return new RubyArrayTwoObject(runtime, args[start], args[start + 1]); } + return newArrayNoCopy(runtime, args, start, length); } @@ -2027,9 +2023,9 @@ public IRubyObject first(IRubyObject arg0) { } else if (n < 0) { throw argumentError(context, "negative array size (or size too big)"); } else if (n == 1) { - return newArray(context.runtime, eltOk(0)); + return Create.newArray(context, eltOk(0)); } else if (n == 2) { - return newArray(context.runtime, eltOk(0), eltOk(1)); + return Create.newArray(context, eltOk(0), eltOk(1)); } unpack(context); @@ -3140,13 +3136,11 @@ public IRubyObject delete_at(IRubyObject obj) { * */ public final IRubyObject rejectCommon(ThreadContext context, Block block) { - RubyArray ary = RubyArray.newArray(context.runtime); + var ary = Create.newArray(context); for (int i = 0; i < realLength; i++) { IRubyObject v = eltOk(i); - if (!block.yieldSpecific(context, v).isTrue()) { - ary.push(v); - } + if (!block.yieldSpecific(context, v).isTrue()) ary.push(v); } return ary; } @@ -3379,20 +3373,16 @@ private IRubyObject slice_internal(ThreadContext context, int pos, int len) { if (pos < 0) { pos += orig_len; if (pos < 0) return context.nil; - } else if (orig_len < pos) { - return context.nil; } - if (orig_len < pos + len) { - len = orig_len - pos; - } - if (len == 0) { - return context.runtime.newEmptyArray(); - } + if (orig_len < pos) return context.nil; + if (orig_len < pos + len) len = orig_len - pos; + + if (len == 0) return Create.newEmptyArray(context); unpack(context); - RubyArray result = makeShared(begin + pos, len, context.runtime.getArray()); + var result = makeShared(begin + pos, len, context.runtime.getArray()); splice(context, pos, len, null, 0); return result; @@ -3877,7 +3867,7 @@ public IRubyObject difference(ThreadContext context, IRubyObject[] args) { RubyArray[] arrays = new RubyArray[args.length]; RubyHash[] hashes = new RubyHash[args.length]; - RubyArray diff = newArray(context.runtime); + var diff = Create.newArray(context); for (int i = 0; i < args.length; i++) { arrays[i] = args[i].convertToArray(); @@ -4024,7 +4014,6 @@ public IRubyObject op_or(IRubyObject other) { */ @JRubyMethod(name = "union", rest = true) public IRubyObject union(ThreadContext context, IRubyObject[] args) { - Ruby runtime = context.runtime; RubyArray[] arrays = new RubyArray[args.length]; RubyArray result; @@ -4033,10 +4022,10 @@ public IRubyObject union(ThreadContext context, IRubyObject[] args) { arrays[i] = args[i].convertToArray(); maxSize += arrays[i].realLength; } - if (maxSize == 0) return newEmptyArray(runtime); + if (maxSize == 0) return Create.newEmptyArray(context); if (maxSize <= ARRAY_DEFAULT_SIZE) { - result = newArray(runtime); + result = Create.newArray(context); result.unionInternal(context, this); result.unionInternal(context, arrays); @@ -4044,7 +4033,7 @@ public IRubyObject union(ThreadContext context, IRubyObject[] args) { return result; } - RubyHash set = makeHash(runtime); + RubyHash set = makeHash(context.runtime); for (int i = 0; i < arrays.length; i++) { for (int j = 0; j < arrays[i].realLength; j++) { @@ -4211,8 +4200,7 @@ public int compare(IRubyObject obj1, IRubyObject obj2) { } protected final IRubyObject yieldBlock(IRubyObject obj1, IRubyObject obj2) { - final ThreadContext context = context(); - return block.yieldArray(context, context.runtime.newArray(obj1, obj2), self); + return block.yieldArray(context, Create.newArray(context, obj1, obj2), self); } protected final ThreadContext context() { @@ -4296,7 +4284,7 @@ public IRubyObject drop(ThreadContext context, IRubyObject n) { if (pos < 0) throw argumentError(context, "attempt to drop negative size"); IRubyObject result = subseq(pos, realLength); - return result.isNil() ? context.runtime.newEmptyArray() : result; + return result.isNil() ? Create.newEmptyArray(context) : result; } /** rb_ary_take_while @@ -4304,15 +4292,14 @@ public IRubyObject drop(ThreadContext context, IRubyObject n) { */ @JRubyMethod(name = "drop_while") public IRubyObject drop_while(ThreadContext context, Block block) { - Ruby runtime = context.runtime; - if (!block.isGiven()) return enumeratorize(runtime, this, "drop_while"); + if (!block.isGiven()) return enumeratorize(context.runtime, this, "drop_while"); int i = 0; for (; i < realLength; i++) { if (!block.yield(context, eltOk(i)).isTrue()) break; } IRubyObject result = subseq(i, realLength); - return result.isNil() ? runtime.newEmptyArray() : result; + return result.isNil() ? Create.newEmptyArray(context) : result; } /** rb_ary_cycle @@ -5466,7 +5453,7 @@ public static RubyArray unmarshalFrom(UnmarshalStream input) throws IOException // FIXME: We used to use newArrayBlankInternal but this will not hash into a HashSet without an NPE. // we create this now with an empty, nulled array so it's available for links in the marshal data - RubyArray result = (RubyArray) input.entry(newArray(context.runtime, size)); + var result = (RubyArray) input.entry(Create.newArray(context, size)); for (int i = 0; i < size; i++) { result.storeInternal(context, i, input.unmarshalObject()); @@ -5596,7 +5583,8 @@ private IRubyObject maxWithBlock(ThreadContext context, Block block) { for (int i = 0; i < realLength; i++) { IRubyObject v = eltOk(i); - if (result == UNDEF || RubyComparable.cmpint(context, op_gt, op_lt, block.yieldArray(context, runtime.newArray(v, result), null), v, result) > 0) { + if (result == UNDEF || + RubyComparable.cmpint(context, op_gt, op_lt, block.yieldArray(context, Create.newArray(context, v, result), null), v, result) > 0) { result = v; } } @@ -5648,7 +5636,8 @@ private IRubyObject minWithBlock(ThreadContext context, Block block) { for (int i = 0; i < realLength; i++) { IRubyObject v = eltOk(i); - if (result == UNDEF || RubyComparable.cmpint(context, op_gt, op_lt, block.yieldArray(context, runtime.newArray(v, result), null), v, result) < 0) { + if (result == UNDEF || + RubyComparable.cmpint(context, op_gt, op_lt, block.yieldArray(context, Create.newArray(context, v, result), null), v, result) < 0) { result = v; } } diff --git a/core/src/main/java/org/jruby/RubyBasicObject.java b/core/src/main/java/org/jruby/RubyBasicObject.java index 1edeaa50f79..025894ad4d7 100644 --- a/core/src/main/java/org/jruby/RubyBasicObject.java +++ b/core/src/main/java/org/jruby/RubyBasicObject.java @@ -68,8 +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.Create.newArray; -import static org.jruby.api.Create.newSymbol; +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; @@ -2298,17 +2297,17 @@ public IRubyObject methods(ThreadContext context, IRubyObject... args) { } final IRubyObject methodsImpl(ThreadContext context, final boolean all) { - final RubyArray methods = RubyArray.newArray(context.runtime); + final var methods = newArray(context); final Set seen = new HashSet<>(); RubyClass metaClass = getMetaClass(); if (metaClass.isSingleton()) { - metaClass.populateInstanceMethodNames(seen, methods, PRIVATE, false, true, false); + metaClass.populateInstanceMethodNames(context, seen, methods, PRIVATE, false, true, false); if (all) { - metaClass.getSuperClass().populateInstanceMethodNames(seen, methods, PRIVATE, false, true, true); + metaClass.getSuperClass().populateInstanceMethodNames(context, seen, methods, PRIVATE, false, true, true); } } else if (all) { - metaClass.populateInstanceMethodNames(seen, methods, PRIVATE, false, true, true); + metaClass.populateInstanceMethodNames(context, seen, methods, PRIVATE, false, true, true); } // else - do nothing, leave empty return methods; @@ -2397,19 +2396,16 @@ public IRubyObject private_methods(ThreadContext context, IRubyObject[] args) { * a.singleton_methods #=> ["two", "one", "three"] */ // TODO: This is almost RubyModule#instance_methods on the metaClass. Perhaps refactor. - public RubyArray singleton_methods(ThreadContext context, IRubyObject[] args) { - Ruby runtime = context.runtime; - boolean all = (args.length == 1) ? args[0].isTrue() : true; - + public RubyArray singleton_methods(final ThreadContext context, IRubyObject[] args) { + boolean all = args.length != 1 || args[0].isTrue(); RubyClass klass = metaClass; RubyModule origin = klass.getMethodLocation(); - Set names = (klass.isSingleton() || all) ? new HashSet<>() : Collections.EMPTY_SET; if (klass.isSingleton()) { // TODO: needs to use method_entry_i logic from MRI origin.getMethods().forEach((k, v) -> { - if (v.getVisibility() != PRIVATE) names.add(runtime.newSymbol(k)); + if (v.getVisibility() != PRIVATE) names.add(newSymbol(context, k)); }); klass = klass.getSuperClass(); } @@ -2418,16 +2414,16 @@ public RubyArray singleton_methods(ThreadContext context, IRubyObject[] args) { while (klass != null && (klass.isSingleton() || klass.isIncluded())) { if (klass != origin) { klass.getMethods().forEach((k, v) -> { - if (v.getVisibility() != PRIVATE) names.add(runtime.newSymbol(k)); + if (v.getVisibility() != PRIVATE) names.add(newSymbol(context, k)); }); } klass = klass.getSuperClass(); } } - if (names.isEmpty()) return runtime.newEmptyArray(); + if (names.isEmpty()) return newEmptyArray(context); - return RubyArray.newArray(runtime, names); + return RubyArray.newArray(context.runtime, names); } public IRubyObject singleton_method(IRubyObject name) { @@ -2520,9 +2516,8 @@ public IRubyObject to_s() { * The default to_a method is deprecated. */ public RubyArray to_a(ThreadContext context) { - Ruby runtime = context.runtime; - runtime.getWarnings().warn(ID.DEPRECATED_METHOD, "default 'to_a' will be obsolete"); - return runtime.newArray(this); + context.runtime.getWarnings().warn(ID.DEPRECATED_METHOD, "default 'to_a' will be obsolete"); + return newArray(context,this); } /** rb_obj_instance_eval diff --git a/core/src/main/java/org/jruby/RubyBignum.java b/core/src/main/java/org/jruby/RubyBignum.java index b3bc481351c..11b16e404a8 100644 --- a/core/src/main/java/org/jruby/RubyBignum.java +++ b/core/src/main/java/org/jruby/RubyBignum.java @@ -398,12 +398,12 @@ public RubyString to_s(IRubyObject arg0) { */ @Override public IRubyObject coerce(IRubyObject other) { - final Ruby runtime = getRuntime(); - 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); + var context = getRuntime().getCurrentContext(); + + if (other instanceof RubyFixnum fix) return newArray(context, newBignum(context.runtime, fix.value), this); + if (other instanceof RubyBignum big) return newArray(context, newBignum(context.runtime, big.value), this); - return RubyArray.newArray(runtime, RubyKernel.new_float(context, other), RubyKernel.new_float(context, this)); + return newArray(context, RubyKernel.new_float(context, other), RubyKernel.new_float(context, this)); } /** rb_big_uminus @@ -579,14 +579,13 @@ public IRubyObject idiv(ThreadContext context, long other) { @JRubyMethod(name = "divmod") public IRubyObject divmod(ThreadContext context, IRubyObject other) { final BigInteger otherValue; - if (other instanceof RubyFixnum) { - otherValue = fix2big((RubyFixnum) other); - } else if (other instanceof RubyBignum) { - otherValue = ((RubyBignum) other).value; + if (other instanceof RubyFixnum fix) { + otherValue = fix2big(fix); + } else if (other instanceof RubyBignum big) { + otherValue = big.value; } else { - if (other instanceof RubyFloat && ((RubyFloat) other).value == 0) { - throw context.runtime.newZeroDivisionError(); - } + if (other instanceof RubyFloat flote && flote.value == 0) throw context.runtime.newZeroDivisionError(); + return coerceBin(context, sites(context).divmod, other); } @@ -598,8 +597,7 @@ public IRubyObject divmod(ThreadContext context, IRubyObject other) { results[1] = otherValue.add(results[1]); } - Ruby runtime = context.runtime; - return RubyArray.newArray(runtime, bignorm(runtime, results[0]), bignorm(runtime, results[1])); + return newArray(context, bignorm(context.runtime, results[0]), bignorm(context.runtime, results[1])); } /** rb_big_modulo diff --git a/core/src/main/java/org/jruby/RubyBinding.java b/core/src/main/java/org/jruby/RubyBinding.java index 9280fa0e23c..8320f1a8eb2 100644 --- a/core/src/main/java/org/jruby/RubyBinding.java +++ b/core/src/main/java/org/jruby/RubyBinding.java @@ -50,6 +50,7 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; import static org.jruby.util.RubyStringBuilder.str; /** @@ -201,6 +202,6 @@ public IRubyObject receiver(ThreadContext context) { public IRubyObject source_location(ThreadContext context) { IRubyObject filename = Convert.asString(context, binding.getFile()).freeze(context); RubyFixnum line = asFixnum(context, binding.getLine() + 1); /* zero-based */ - return context.runtime.newArray(filename, line); + return newArray(context, filename, line); } } diff --git a/core/src/main/java/org/jruby/RubyClass.java b/core/src/main/java/org/jruby/RubyClass.java index 4963b1831bc..7d52d91a7a0 100644 --- a/core/src/main/java/org/jruby/RubyClass.java +++ b/core/src/main/java/org/jruby/RubyClass.java @@ -31,6 +31,7 @@ package org.jruby; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Error.*; import static org.jruby.runtime.Visibility.PRIVATE; import static org.jruby.runtime.Visibility.PUBLIC; @@ -1013,10 +1014,8 @@ protected void setModuleSuperClass(RubyClass superClass) { @JRubyMethod public IRubyObject subclasses(ThreadContext context) { - var subs = RubyArray.newArray(context.runtime); - + var subs = newArray(context); concreteSubclasses(subs); - return subs; } diff --git a/core/src/main/java/org/jruby/RubyComplex.java b/core/src/main/java/org/jruby/RubyComplex.java index 2aa36154e42..888b3c15c8f 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.Create.newArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.Helpers.invokedynamic; @@ -845,10 +846,10 @@ public IRubyObject op_equal(ThreadContext context, IRubyObject other) { */ @JRubyMethod(name = "coerce") public IRubyObject coerce(ThreadContext context, IRubyObject other) { - if (other instanceof RubyComplex) return context.runtime.newArray(other, this); + if (other instanceof RubyComplex) return newArray(context, other, this); if (other instanceof RubyNumeric numeric && f_real_p(context, other)) { - return context.runtime.newArray(newComplexBang(context, getMetaClass(), numeric), this); + return newArray(context, newComplexBang(context, getMetaClass(), numeric), this); } Ruby runtime = context.runtime; @@ -890,7 +891,7 @@ public IRubyObject arg(ThreadContext context) { @JRubyMethod(name = {"rectangular", "rect"}) @Override public IRubyObject rect(ThreadContext context) { - return context.runtime.newArray(real, image); + return newArray(context, real, image); } /** nucomp_polar @@ -899,7 +900,7 @@ public IRubyObject rect(ThreadContext context) { @JRubyMethod(name = "polar") @Override public IRubyObject polar(ThreadContext context) { - return context.runtime.newArray(f_abs(context, this), f_arg(context, this)); + return newArray(context, f_abs(context, this), f_arg(context, this)); } /** nucomp_conjugate @@ -1076,7 +1077,7 @@ private static boolean lastCharDigit(RubyString str) { */ @JRubyMethod(name = "marshal_dump", visibility = Visibility.PRIVATE) public IRubyObject marshal_dump(ThreadContext context) { - RubyArray dump = context.runtime.newArray(real, image); + var dump = newArray(context, real, image); if (hasVariables()) dump.syncVariables(this); return dump; } diff --git a/core/src/main/java/org/jruby/RubyConverter.java b/core/src/main/java/org/jruby/RubyConverter.java index 215376de748..7fdc1ef5d47 100644 --- a/core/src/main/java/org/jruby/RubyConverter.java +++ b/core/src/main/java/org/jruby/RubyConverter.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.newArray; import static org.jruby.api.Create.newString; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; @@ -189,18 +190,16 @@ public IRubyObject inspect(ThreadContext context) { @JRubyMethod public IRubyObject convpath(ThreadContext context) { - Ruby runtime = context.runtime; - - RubyArray result = runtime.newArray(); + var result = newArray(context); for (int i = 0; i < ec.numTranscoders; i++) { Transcoder tr = ec.elements[i].transcoding.transcoder; IRubyObject v; if (EncodingUtils.DECORATOR_P(tr.getSource(), tr.getDestination())) { - v = RubyString.newString(runtime, tr.getDestination()); + v = RubyString.newString(context.runtime, tr.getDestination()); } else { - var encodingService = runtime.getEncodingService(); - v = runtime.newArray( + var encodingService = context.runtime.getEncodingService(); + v = newArray(context, encodingService.convertEncodingToRubyEncoding(encodingService.findEncodingOrAliasEntry(tr.getSource()).getEncoding()), encodingService.convertEncodingToRubyEncoding(encodingService.findEncodingOrAliasEntry(tr.getDestination()).getEncoding())); } @@ -515,8 +514,7 @@ public IRubyObject primitive_errinfo(ThreadContext context) { } @JRubyMethod(meta = true, required = 2, optional = 1, checkArity = false) - public static IRubyObject search_convpath(ThreadContext context, IRubyObject self, IRubyObject[] argv) { - final Ruby runtime = context.runtime; + public static IRubyObject search_convpath(final ThreadContext context, IRubyObject self, IRubyObject[] argv) { final IRubyObject nil = context.nil; final byte[][] encNames = {null, null}; final Encoding[] encs = {null, null}; @@ -527,30 +525,22 @@ public static IRubyObject search_convpath(ThreadContext context, IRubyObject sel EncodingUtils.econvArgs(context, argv, encNames, encs, ecflags_p, ecopts_p); TranscoderDB.searchPath(encNames[0], encNames[1], new TranscoderDB.SearchPathCallback() { - final EncodingService es = runtime.getEncodingService(); + final EncodingService es = context.runtime.getEncodingService(); public void call(byte[] source, byte[] destination, int depth) { - IRubyObject v; - - if (convpath[0] == nil) { - convpath[0] = runtime.newArray(); - } + if (convpath[0] == nil) convpath[0] = newArray(context); - if (EncodingUtils.DECORATOR_P(encNames[0], encNames[1])) { - v = RubyString.newString(runtime, encNames[2]); - } else { - v = runtime.newArray( - es.convertEncodingToRubyEncoding(es.findEncodingOrAliasEntry(source).getEncoding()), - es.convertEncodingToRubyEncoding(es.findEncodingOrAliasEntry(destination).getEncoding())); - } + IRubyObject v = EncodingUtils.DECORATOR_P(encNames[0], encNames[1]) ? + RubyString.newString(context.runtime, encNames[2]) : + newArray(context, + es.convertEncodingToRubyEncoding(es.findEncodingOrAliasEntry(source).getEncoding()), + es.convertEncodingToRubyEncoding(es.findEncodingOrAliasEntry(destination).getEncoding())); - ((RubyArray)convpath[0]).store(depth, v); + ((RubyArray)convpath[0]).store(depth, v); } }); - if (convpath[0].isNil()) { - throw EncodingUtils.econvOpenExc(context, encNames[0], encNames[1], 0); - } + if (convpath[0].isNil()) throw EncodingUtils.econvOpenExc(context, encNames[0], encNames[1], 0); if (EncodingUtils.decorateConvpath(context, convpath[0], ecflags_p[0]) == -1) { throw EncodingUtils.econvOpenExc(context, encNames[0], encNames[1], ecflags_p[0]); diff --git a/core/src/main/java/org/jruby/RubyEncoding.java b/core/src/main/java/org/jruby/RubyEncoding.java index 8d98301971e..bc1ba5e8ac6 100755 --- a/core/src/main/java/org/jruby/RubyEncoding.java +++ b/core/src/main/java/org/jruby/RubyEncoding.java @@ -592,7 +592,7 @@ public IRubyObject inspect(ThreadContext context) { public IRubyObject names(ThreadContext context) { EncodingService service = context.runtime.getEncodingService(); Entry entry = service.findEncodingOrAliasEntry(name); - var result = context.runtime.newArray(); + var result = newArray(context); HashEntryIterator i; i = service.getEncodings().entryIterator(); while (i.hasNext()) { diff --git a/core/src/main/java/org/jruby/RubyEnumerable.java b/core/src/main/java/org/jruby/RubyEnumerable.java index aeef05da6f1..66ffa0aa1f6 100644 --- a/core/src/main/java/org/jruby/RubyEnumerable.java +++ b/core/src/main/java/org/jruby/RubyEnumerable.java @@ -69,7 +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.Create.newArray; +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.Helpers.arrayOf; @@ -271,9 +271,9 @@ public static IRubyObject take(ThreadContext context, IRubyObject self, IRubyObj final long len = numericToLong(context, n); if (len < 0) throw argumentError(context, "attempt to take negative size"); - if (len == 0) return context.runtime.newEmptyArray(); + if (len == 0) return newEmptyArray(context); - final RubyArray result = context.runtime.newArray(); + final var result = newArray(context); try { // Atomic ? @@ -299,12 +299,9 @@ public IRubyObject yield(ThreadContext context1, IRubyObject value) { @JRubyMethod(name = "take_while") public static IRubyObject take_while(ThreadContext context, IRubyObject self, final Block block) { - if (!block.isGiven()) { - return enumeratorize(context.runtime, self, "take_while"); - } + if (!block.isGiven()) return enumeratorize(context.runtime, self, "take_while"); - final Ruby runtime = context.runtime; - final RubyArray result = runtime.newArray(); + final var result = newArray(context); try { callEach(context, eachSite(context), self, Signature.OPTIONAL, (ctx, largs, unused) -> { @@ -319,22 +316,20 @@ public static IRubyObject take_while(ThreadContext context, IRubyObject self, fi synchronized (result) { result.append(context, larg); } return ctx.nil; }); - } catch (JumpException.SpecialJump sj) {} + } catch (JumpException.SpecialJump ignored) {} return result; } @JRubyMethod(name = "drop") public static IRubyObject drop(ThreadContext context, IRubyObject self, IRubyObject n, final Block block) { - final Ruby runtime = context.runtime; final long len = numericToLong(context, n); - if (len < 0) throw argumentError(context, "attempt to drop negative size"); - final RubyArray result = runtime.newArray(); + final var result = newArray(context); 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) { @@ -359,15 +354,12 @@ public IRubyObject yield(ThreadContext context1, IRubyObject value) { @JRubyMethod public static IRubyObject drop_while(ThreadContext context, IRubyObject self, final Block block) { - if (!block.isGiven()) { - return enumeratorize(context.runtime, self, "drop_while"); - } + if (!block.isGiven()) return enumeratorize(context.runtime, self, "drop_while"); - final Ruby runtime = context.runtime; - final RubyArray result = runtime.newArray(); + final var result = newArray(context); try { - each(context, eachSite(context), self, new JavaInternalBlockBody(runtime, context, "Enumerable#drop_while", Signature.OPTIONAL) { + each(context, eachSite(context), self, new JavaInternalBlockBody(context.runtime, context, "Enumerable#drop_while", Signature.OPTIONAL) { boolean memo = false; @Override public IRubyObject yield(ThreadContext context1, IRubyObject[] args) { @@ -409,9 +401,9 @@ public IRubyObject yield(ThreadContext context1, IRubyObject value) { @JRubyMethod(name = "first") public static IRubyObject first(ThreadContext context, IRubyObject self, final IRubyObject num) { final long firstCount = numericToLong(context, num); - - if (firstCount == 0) return context.runtime.newEmptyArray(); + if (firstCount == 0) return newEmptyArray(context); if (firstCount < 0) throw argumentError(context, "attempt to take negative size"); + final RubyArray result = newArray(context, firstCount); try { @@ -450,15 +442,14 @@ public static IRubyObject tally(ThreadContext context, IRubyObject self, IRubyOb @JRubyMethod(name = {"to_a", "entries"}) public static IRubyObject to_a(ThreadContext context, IRubyObject self) { - RubyArray result = context.runtime.newArray(); + var result = newArray(context); callEach(context, eachSite(context), self, Signature.OPTIONAL, new AppendBlockCallback(result)); return result; } @JRubyMethod(name = {"to_a", "entries"}, keywords = true) public static IRubyObject to_a(ThreadContext context, IRubyObject self, IRubyObject arg) { - final Ruby runtime = context.runtime; - final RubyArray result = runtime.newArray(); + var result = newArray(context); Helpers.invoke(context, self, "each", arg, CallBlock.newCallClosure(context, self, Signature.OPTIONAL, new AppendBlockCallback(result))); return result; @@ -466,8 +457,7 @@ public static IRubyObject to_a(ThreadContext context, IRubyObject self, IRubyObj @JRubyMethod(name = {"to_a", "entries"}, rest = true, keywords = true) public static IRubyObject to_a(ThreadContext context, IRubyObject self, IRubyObject[] args) { - final Ruby runtime = context.runtime; - final RubyArray result = runtime.newArray(); + final var result = newArray(context); Helpers.invoke(context, self, "each", args, CallBlock.newCallClosure(context, self, Signature.OPTIONAL, new AppendBlockCallback(result))); return result; @@ -484,7 +474,7 @@ public static IRubyObject to_h(ThreadContext context, IRubyObject self, IRubyObj @JRubyMethod public static IRubyObject sort(ThreadContext context, IRubyObject self, final Block block) { - final RubyArray result = context.runtime.newArray(); + final var result = newArray(context); callEach(context, eachSite(context), self, Signature.OPTIONAL, new AppendBlockCallback(result)); result.sort_bang(context, block); @@ -543,8 +533,7 @@ public static IRubyObject inverseGrep(ThreadContext context, IRubyObject self, f private static IRubyObject grep(ThreadContext context, IRubyObject self, final IRubyObject pattern, final Block block, final boolean isPresent) { - final Ruby runtime = context.runtime; - final RubyArray result = runtime.newArray(); + final var result = newArray(context); final CachingCallSite each = eachSite(context); if (block.isGiven()) { @@ -743,11 +732,9 @@ public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { } public static IRubyObject selectCommon(ThreadContext context, IRubyObject self, final Block block, String methodName) { - if (!block.isGiven()) { - return enumeratorizeWithSize(context, self, methodName, (SizeFn) RubyEnumerable::size); - } + if (!block.isGiven()) return enumeratorizeWithSize(context, self, methodName, (SizeFn) RubyEnumerable::size); - final RubyArray result = context.runtime.newArray(); + final var result = newArray(context); callEach(context, eachSite(context), self, Signature.OPTIONAL, new BlockCallback() { public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { @@ -777,11 +764,9 @@ public static IRubyObject find_all(ThreadContext context, IRubyObject self, fina @JRubyMethod public static IRubyObject reject(ThreadContext context, IRubyObject self, final Block block) { - if (!block.isGiven()) { - return enumeratorizeWithSize(context, self, "reject", (SizeFn) RubyEnumerable::size); - } + if (!block.isGiven()) return enumeratorizeWithSize(context, self, "reject", (SizeFn) RubyEnumerable::size); - final RubyArray result = context.runtime.newArray(); + final var result = newArray(context); callEach(context, eachSite(context), self, Signature.OPTIONAL, new BlockCallback() { public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { @@ -817,74 +802,68 @@ public static IRubyObject map(ThreadContext context, IRubyObject self, final Blo } private static IRubyObject collectCommon(ThreadContext context, IRubyObject self, final Block block, String methodName) { - final Ruby runtime = context.runtime; - if (block.isGiven()) { - final RubyArray result = runtime.newArray(); + if (!block.isGiven()) return enumeratorizeWithSize(context, self, methodName, (SizeFn) RubyEnumerable::size); - eachSite(context).call(context, self, self, CallBlock19.newCallClosure(self, runtime.getEnumerable(), block.getSignature(), new BlockCallback() { - public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { - final IRubyObject larg; boolean ary = false; - switch (largs.length) { - case 0: larg = ctx.nil; break; - case 1: larg = largs[0]; break; - default: larg = RubyArray.newArrayMayCopy(ctx.runtime, largs); ary = true; - } - IRubyObject val = ary ? block.yieldArray(ctx, larg, null) : block.yield(ctx, larg); + final var result = newArray(context); - synchronized (result) { result.append(ctx, val); } - return ctx.nil; + eachSite(context).call(context, self, self, CallBlock19.newCallClosure(self, context.runtime.getEnumerable(), block.getSignature(), new BlockCallback() { + public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { + final IRubyObject larg; boolean ary = false; + switch (largs.length) { + case 0: larg = ctx.nil; break; + case 1: larg = largs[0]; break; + default: larg = RubyArray.newArrayMayCopy(ctx.runtime, largs); ary = true; } - @Override - public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { - IRubyObject val = block.yield(ctx, larg); + IRubyObject val = ary ? block.yieldArray(ctx, larg, null) : block.yield(ctx, larg); - synchronized (result) { result.append(ctx, val); } - return ctx.nil; - } - }, context)); - return result; - } else { - return enumeratorizeWithSize(context, self, methodName, (SizeFn) RubyEnumerable::size); - } + synchronized (result) { result.append(ctx, val); } + return ctx.nil; + } + @Override + public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { + IRubyObject val = block.yield(ctx, larg); + + synchronized (result) { result.append(ctx, val); } + return ctx.nil; + } + }, context)); + + return result; } @JRubyMethod public static IRubyObject filter_map(ThreadContext context, IRubyObject self, Block block) { - Ruby runtime = context.runtime; + if (!block.isGiven()) return enumeratorizeWithSize(context, self, "filter_map", (SizeFn) RubyEnumerable::size); - if (block.isGiven()) { - RubyArray result = runtime.newArray(); + var result = newArray(context); - eachSite(context).call(context, self, self, CallBlock19.newCallClosure(self, runtime.getEnumerable(), block.getSignature(), new BlockCallback() { - public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { - final IRubyObject larg; boolean ary = false; - switch (largs.length) { - case 0: larg = ctx.nil; break; - case 1: larg = largs[0]; break; - default: larg = RubyArray.newArrayMayCopy(ctx.runtime, largs); ary = true; - } - IRubyObject val = ary ? block.yieldArray(ctx, larg, null) : block.yield(ctx, larg); + eachSite(context).call(context, self, self, CallBlock19.newCallClosure(self, context.runtime.getEnumerable(), block.getSignature(), new BlockCallback() { + public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { + final IRubyObject larg; boolean ary = false; + switch (largs.length) { + case 0: larg = ctx.nil; break; + case 1: larg = largs[0]; break; + default: larg = RubyArray.newArrayMayCopy(ctx.runtime, largs); ary = true; + } + IRubyObject val = ary ? block.yieldArray(ctx, larg, null) : block.yield(ctx, larg); - if (val.isTrue()) { - synchronized (result) { result.append(ctx, val); } - } - return ctx.nil; + if (val.isTrue()) { + synchronized (result) { result.append(ctx, val); } } - @Override - public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { - IRubyObject val = block.yield(ctx, larg); + return ctx.nil; + } + @Override + public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { + IRubyObject val = block.yield(ctx, larg); - if (val.isTrue()) { - synchronized (result) { result.append(ctx, val); } - } - return ctx.nil; + if (val.isTrue()) { + synchronized (result) { result.append(ctx, val); } } - }, context)); + return ctx.nil; + } + }, context)); - return result; - } else { - return enumeratorizeWithSize(context, self, "filter_map", (SizeFn) RubyEnumerable::size); - } + return result; } @JRubyMethod(name = "flat_map") @@ -898,31 +877,30 @@ public static IRubyObject collect_concat(ThreadContext context, IRubyObject self } private static IRubyObject flatMapCommon(ThreadContext context, IRubyObject self, final Block block, String methodName) { - if (block.isGiven()) { - final RubyArray ary = context.runtime.newArray(); + if (!block.isGiven()) return enumeratorizeWithSize(context, self, methodName, (SizeFn) RubyEnumerable::size); - callEach(context, eachSite(context), self, block.getSignature(), new BlockCallback() { - public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { - return call(ctx, packEnumValues(ctx, largs), blk); - } - @Override - public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { - IRubyObject i = block.yield(ctx, larg); - IRubyObject tmp = i.checkArrayType(); - synchronized(ary) { - if (tmp.isNil()) { - ary.append(ctx, i); - } else { - ary.concat(ctx, tmp); - } + final var ary = newArray(context); + + callEach(context, eachSite(context), self, block.getSignature(), new BlockCallback() { + public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { + return call(ctx, packEnumValues(ctx, largs), blk); + } + @Override + public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { + IRubyObject i = block.yield(ctx, larg); + IRubyObject tmp = i.checkArrayType(); + synchronized(ary) { + if (tmp.isNil()) { + ary.append(ctx, i); + } else { + ary.concat(ctx, tmp); } - return ctx.nil; } - }); - return ary; - } else { - return enumeratorizeWithSize(context, self, methodName, (SizeFn) RubyEnumerable::size); - } + return ctx.nil; + } + }); + + return ary; } @JRubyMethod @@ -1055,14 +1033,13 @@ public static IRubyObject sumAdd(final ThreadContext context, IRubyObject lhs, I } public static IRubyObject injectCommon(final ThreadContext context, IRubyObject self, IRubyObject init, final Block block) { - final Ruby runtime = context.runtime; final SingleObject result = new SingleObject(init); callEach(context, eachSite(context), self, Signature.OPTIONAL, (ctx, largs, blk) -> { IRubyObject larg = packEnumValues(ctx, largs); checkContext(context, ctx, "inject"); result.object = result.object == null ? - larg : block.yieldArray(ctx, runtime.newArray(result.object, larg), null); + larg : block.yieldArray(ctx, newArray(ctx, result.object, larg), null); return ctx.nil; }); @@ -1112,30 +1089,23 @@ public IRubyObject call(ThreadContext ctx, IRubyObject larg) { @JRubyMethod public static IRubyObject partition(ThreadContext context, IRubyObject self, final Block block) { - final Ruby runtime = context.runtime; - final RubyArray arr_true = runtime.newArray(); - final RubyArray arr_false = runtime.newArray(); + if (!block.isGiven()) return enumeratorizeWithSize(context, self, "partition", (SizeFn) RubyEnumerable::size); - if (!block.isGiven()) { - return enumeratorizeWithSize(context, self, "partition", (SizeFn) RubyEnumerable::size); - } + final var arr_true = newArray(context); + final var arr_false = newArray(context); callEach(context, eachSite(context), self, Signature.OPTIONAL, (ctx, largs, blk) -> { IRubyObject larg = packEnumValues(ctx, largs); if (block.yield(ctx, larg).isTrue()) { - synchronized (arr_true) { - arr_true.append(ctx, larg); - } + synchronized (arr_true) { arr_true.append(ctx, larg); } } else { - synchronized (arr_false) { - arr_false.append(ctx, larg); - } + synchronized (arr_false) { arr_false.append(ctx, larg); } } return ctx.nil; }); - return runtime.newArray(arr_true, arr_false); + return newArray(context, arr_true, arr_false); } static class EachWithIndex implements BlockCallback { @@ -1261,13 +1231,13 @@ static IRubyObject each_sliceCommon(ThreadContext context, IRubyObject self, fin final Ruby runtime = context.runtime; if (size <= 0) throw argumentError(context, "invalid slice size"); - final SingleObject result = new SingleObject<>(runtime.newArray(size)); + final SingleObject result = new SingleObject<>(newArray(context, size)); callEach(context, eachSite(context), self, Signature.OPTIONAL, (ctx, largs, blk) -> { result.object.append(context, packEnumValues(ctx, largs)); if (result.object.size() == size) { block.yield(ctx, result.object); - result.object = runtime.newArray(size); + result.object = newArray(ctx, size); } return ctx.nil; }); @@ -1282,17 +1252,13 @@ static IRubyObject each_sliceCommon(ThreadContext context, IRubyObject self, fin * @see SizeFn#size(ThreadContext, IRubyObject, IRubyObject[]) */ private static IRubyObject eachSliceSize(ThreadContext context, IRubyObject self, IRubyObject[] args) { - Ruby runtime = context.runtime; 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 argumentError(context, "invalid slice size"); - } + if (sliceSize <= 0) throw argumentError(context, "invalid slice size"); IRubyObject size = RubyEnumerable.size(context, self, args); - if (size == null || size.isNil()) { - return runtime.getNil(); - } + if (size == null || size.isNil()) return context.nil; IRubyObject n = sites(context).each_slice_op_plus.call(context, size, size, sliceSize - 1); return sites(context).each_slice_op_div.call(context, n, n, sliceSize); @@ -1306,7 +1272,7 @@ public static IRubyObject each_cons(ThreadContext context, IRubyObject self, IRu } static IRubyObject each_consCommon(ThreadContext context, IRubyObject self, final int size, final Block block) { - final RubyArray result = context.runtime.newArray(size); + final var result = newArray(context, size); callEach(context, eachSite(context), self, Signature.OPTIONAL, (ctx, largs, blk) -> { if (result.size() == size) result.shift(ctx); @@ -1324,21 +1290,15 @@ static IRubyObject each_consCommon(ThreadContext context, IRubyObject self, fina * @see SizeFn#size(ThreadContext, IRubyObject, IRubyObject[]) */ private static IRubyObject eachConsSize(ThreadContext context, IRubyObject self, IRubyObject[] args) { - Ruby runtime = context.runtime; 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 argumentError(context, "invalid size"); - } + if (consSize <= 0) throw argumentError(context, "invalid size"); IRubyObject size = ((SizeFn) RubyEnumerable::size).size(context, self, args); - if (size == null || size.isNil()) { - return runtime.getNil(); - } - + if (size == null || size.isNil()) return context.nil; IRubyObject n = sites(context).each_cons_op_plus.call(context, size, size, 1 - consSize); - RubyFixnum zero = RubyFixnum.zero(runtime); + RubyFixnum zero = RubyFixnum.zero(context.runtime); return RubyComparable.cmpint(context, sites(context).each_cons_op_cmp.call(context, n, n, zero), n, zero) == -1 ? zero : n; } @@ -1443,7 +1403,6 @@ public static IRubyObject min_by(ThreadContext context, IRubyObject self, IRubyO private static final int SORT_MAX = 1; private static final int SORT_MIN = -1; private static IRubyObject singleExtent(final ThreadContext context, IRubyObject self, final String op, final int sortDirection, final Block block) { - final Ruby runtime = context.runtime; final SingleObject result = new SingleObject<>(null); Signature signature = block.isGiven() ? block.getSignature() : Signature.ONE_REQUIRED; @@ -1453,7 +1412,7 @@ private static IRubyObject singleExtent(final ThreadContext context, IRubyObject if (result.object == null || (block.isGiven() && - RubyComparable.cmpint(ctx, block.yieldArray(ctx, runtime.newArray(larg, result.object), null), larg, result.object) * sortDirection > 0) || + RubyComparable.cmpint(ctx, block.yieldArray(ctx, newArray(context, larg, result.object), null), larg, result.object) * sortDirection > 0) || (!block.isGiven() && RubyComparable.cmpint(ctx, invokedynamic(ctx, larg, OP_CMP, result.object), larg, result.object) * sortDirection > 0)) { result.object = larg; @@ -1488,7 +1447,6 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { @JRubyMethod public static IRubyObject minmax(final ThreadContext context, IRubyObject self, final Block block) { - final Ruby runtime = context.runtime; final DoubleObject result = new DoubleObject<>(null, null); if (block.isGiven()) { @@ -1499,13 +1457,11 @@ public static IRubyObject minmax(final ThreadContext context, IRubyObject self, if (result.object1 == null) { result.object1 = result.object2 = arg; } else { - if (RubyComparable.cmpint(ctx, - block.yield(ctx, runtime.newArray(arg, result.object1)), arg, result.object1) < 0) { + if (RubyComparable.cmpint(ctx, block.yield(ctx, newArray(context, arg, result.object1)), arg, result.object1) < 0) { result.object1 = arg; } - if (RubyComparable.cmpint(ctx, - block.yield(ctx, runtime.newArray(arg, result.object2)), arg, result.object2) > 0) { + if (RubyComparable.cmpint(ctx, block.yield(ctx, newArray(context, arg, result.object2)), arg, result.object2) > 0) { result.object2 = arg; } } @@ -1531,17 +1487,12 @@ public static IRubyObject minmax(final ThreadContext context, IRubyObject self, }); } - if (result.object1 == null) { - IRubyObject nil = context.nil; - return RubyArray.newArray(runtime, nil, nil); - } - - return RubyArray.newArray(runtime, result.object1, result.object2); + return result.object1 == null ? + newArray(context, 2) : newArray(context, result.object1, result.object2); } @JRubyMethod public static IRubyObject minmax_by(final ThreadContext context, IRubyObject self, final Block block) { - if (!block.isGiven()) return enumeratorizeWithSize(context, self, "minmax_by", RubyEnumerable::size); final DoubleObject result = new DoubleObject<>(context.nil, context.nil); @@ -1569,7 +1520,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { return ctx.nil; } }); - return RubyArray.newArray(context.runtime, result.object1, result.object2); + return newArray(context, result.object1, result.object2); } @JRubyMethod(name = "none?") @@ -1966,13 +1917,12 @@ public static IRubyObject zipCommonEnum(ThreadContext context, IRubyObject self, // See enum_zip + zip_i in Ruby source public static IRubyObject zipCommon(ThreadContext context, IRubyObject self, final IRubyObject[] args, final Block block, ObjectObjectIntFunction nextElement) { - final Ruby runtime = context.runtime; final int len = args.length + 1; final AtomicInteger ix = new AtomicInteger(0); if (block.isGiven()) { callEach(context, eachSite(context), self, (ctx, largs, unused) -> { - RubyArray array = RubyArray.newBlankArrayInternal(runtime, len); + var array = RubyArray.newBlankArrayInternal(ctx.runtime, len); int myIx = ix.getAndIncrement(); array.eltInternalSet(0, packEnumValues(ctx, largs)); for (int i = 0, j = args.length; i < j; i++) { @@ -1984,9 +1934,9 @@ public static IRubyObject zipCommon(ThreadContext context, IRubyObject self, }); return context.nil; } else { - final RubyArray zip = runtime.newArray(); + final var zip = newArray(context); callEach(context, eachSite(context), self, Signature.ONE_REQUIRED, (ctx, largs, unused) -> { - RubyArray array = RubyArray.newBlankArrayInternal(runtime, len); + var array = RubyArray.newBlankArrayInternal(ctx.runtime, len); int myIx = ix.getAndIncrement(); array.eltInternalSet(0, packEnumValues(ctx, largs)); for (int i = 0, j = args.length; i < j; i++) { @@ -2009,17 +1959,15 @@ public static IRubyObject zipCommon(ThreadContext context, IRubyObject self, if (block.isGiven()) { callEach(context, eachSite(context), self, (ctx, largs, unused) -> { int myIx = ix.getAndIncrement(); - RubyArray array = RubyArray.newArray(ctx.runtime, - packEnumValues(ctx, largs), nextElement.apply(ctx, arg0, myIx)); - block.yield(ctx, array); + block.yield(ctx, newArray(ctx, packEnumValues(ctx, largs), nextElement.apply(ctx, arg0, myIx))); return ctx.nil; }); return context.nil; } else { - final RubyArray zip = context.runtime.newArray(); + final var zip = newArray(context); callEach(context, eachSite(context), self, Signature.ONE_REQUIRED, (ctx, largs, unused) -> { int myIx = ix.getAndIncrement(); - RubyArray array = RubyArray.newArray(ctx.runtime, packEnumValues(ctx, largs), nextElement.apply(ctx, arg0, myIx)); + var array = newArray(ctx, packEnumValues(ctx, largs), nextElement.apply(ctx, arg0, myIx)); synchronized (zip) { zip.append(ctx, array); } return ctx.nil; }); @@ -2037,7 +1985,7 @@ public static IRubyObject zipCommon(ThreadContext context, IRubyObject self, * @return an array of the object's elements */ public static IRubyObject takeItems(ThreadContext context, IRubyObject enumerable) { - final RubyArray array = context.runtime.newArray(); + final var array = newArray(context); synchronized (array) { callEach(context, eachSite(context), enumerable, Signature.ONE_ARGUMENT, new BlockCallback() { public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { @@ -2077,20 +2025,18 @@ public static IRubyObject zipEnumNext(ThreadContext context, IRubyObject arg) { @JRubyMethod public static IRubyObject group_by(ThreadContext context, IRubyObject self, final Block block) { - final Ruby runtime = context.runtime; - if (!block.isGiven()) return enumeratorizeWithSize(context, self, "group_by", RubyEnumerable::size); - final RubyHash result = new RubyHash(runtime); + final RubyHash result = new RubyHash(context.runtime); callEach(context, eachSite(context), self, Signature.OPTIONAL, (ctx, largs, blk) -> { IRubyObject larg = packEnumValues(ctx, largs); IRubyObject key = block.yield(ctx, larg); synchronized (result) { - RubyArray curr = (RubyArray)result.fastARef(key); + var curr = (RubyArray)result.fastARef(key); if (curr == null) { - curr = runtime.newArray(); + curr = newArray(context); result.fastASet(key, curr); } curr.append(context, larg); @@ -2223,8 +2169,8 @@ public IRubyObject call(ThreadContext context, IRubyObject[] args, Block block) final IRubyObject yielder = packEnumValues(context, args); final ChunkArg arg = new ChunkArg(context); - final RubySymbol alone = runtime.newSymbol("_alone"); - final RubySymbol separator = runtime.newSymbol("_separator"); + final RubySymbol alone = newSymbol(context, "_alone"); + final RubySymbol separator = newSymbol(context, "_separator"); final EnumerableSites sites = sites(context); final CallSite chunk_call = sites.chunk_call; final CallSite chunk_op_lshift = sites.chunk_op_lshift; @@ -2233,44 +2179,34 @@ public IRubyObject call(ThreadContext context, IRubyObject[] args, Block block) // else we let it spread the args as it sees fit for its arity callEach(context, eachSite(context), enumerable, Signature.OPTIONAL, (ctx, largs, blk) -> { final IRubyObject larg = packEnumValues(ctx, largs); - final IRubyObject v; - if ( categorize.getBlock().getSignature().arityValue() == 1 ) { - // if chunk's categorize block has arity one, we pass it the packed args - v = chunk_call.call(ctx, categorize, categorize, larg); - } else { - // else we let it spread the args as it sees fit for its arity - v = chunk_call.call(ctx, categorize, categorize, largs); - } + final IRubyObject v = categorize.getBlock().getSignature().arityValue() == 1 ? + chunk_call.call(ctx, categorize, categorize, larg) : // categorize block has arity one, we pass it the packed args + chunk_call.call(ctx, categorize, categorize, largs); // else spread the args as it sees fit for its arity if ( v == alone ) { if ( ! arg.prev_value.isNil() ) { - chunk_op_lshift.call(ctx, yielder, yielder, runtime.newArray(arg.prev_value, arg.prev_elts)); + chunk_op_lshift.call(ctx, yielder, yielder, newArray(context, arg.prev_value, arg.prev_elts)); arg.prev_value = arg.prev_elts = ctx.nil; } - chunk_op_lshift.call(ctx, yielder, yielder, runtime.newArray(v, runtime.newArray(larg))); - } - else if ( v.isNil() || v == separator ) { + chunk_op_lshift.call(ctx, yielder, yielder, newArray(ctx, v, newArray(context, larg))); + } else if ( v.isNil() || v == separator ) { if( ! arg.prev_value.isNil() ) { - chunk_op_lshift.call(ctx, yielder, yielder, runtime.newArray(arg.prev_value, arg.prev_elts)); + chunk_op_lshift.call(ctx, yielder, yielder, newArray(ctx, arg.prev_value, arg.prev_elts)); arg.prev_value = arg.prev_elts = ctx.nil; } - } - else if ( (v instanceof RubySymbol) && v.toString().charAt(0) == '_' ) { + } else if ( (v instanceof RubySymbol) && v.toString().charAt(0) == '_' ) { throw runtime.newRuntimeError("symbol begins with an underscore is reserved"); - } - else { + } else { if ( arg.prev_value.isNil() ) { arg.prev_value = v; - arg.prev_elts = runtime.newArray(larg); - } - else { + arg.prev_elts = newArray(ctx, larg); + } else { if ( arg.prev_value.equals(v) ) { - ((RubyArray) arg.prev_elts).append(context, larg); - } - else { - chunk_op_lshift.call(ctx, yielder, yielder, runtime.newArray(arg.prev_value, arg.prev_elts)); + ((RubyArray) arg.prev_elts).append(ctx, larg); + } else { + chunk_op_lshift.call(ctx, yielder, yielder, newArray(ctx, arg.prev_value, arg.prev_elts)); arg.prev_value = v; - arg.prev_elts = runtime.newArray(larg); + arg.prev_elts = newArray(ctx, larg); } } } @@ -2278,7 +2214,7 @@ else if ( (v instanceof RubySymbol) && v.toString().charAt(0) == '_' ) { }); if ( ! arg.prev_elts.isNil() ) { - chunk_op_lshift.call(context, yielder, yielder, runtime.newArray(arg.prev_value, arg.prev_elts)); + chunk_op_lshift.call(context, yielder, yielder, newArray(context, arg.prev_value, arg.prev_elts)); } return context.nil; @@ -2342,7 +2278,6 @@ public PutKeyValueCallback(Ruby runtime, RubyHash result, Block block) { public IRubyObject call(ThreadContext context, IRubyObject[] largs, Block blk) { ThreadContext.resetCallInfo(context); - final Ruby runtime = context.runtime; final boolean blockGiven = block.isGiven(); IRubyObject value; @@ -2354,24 +2289,23 @@ public IRubyObject call(ThreadContext context, IRubyObject[] largs, Block blk) { value = blockGiven ? block.yield(context, largs[0]) : largs[0]; break; default: - IRubyObject v = RubyArray.newArrayMayCopy(runtime, largs); + IRubyObject v = RubyArray.newArrayMayCopy(context.runtime, largs); value = blockGiven ? block.yield(context, v) : v; break; } - callImpl(runtime, value); + callImpl(context, value); return context.nil; } - private void callImpl(final Ruby runtime, IRubyObject value) { - ThreadContext context = runtime.getCurrentContext(); - IRubyObject ary = TypeConverter.checkArrayType(runtime, value); + private void callImpl(ThreadContext context, IRubyObject value) { + IRubyObject ary = TypeConverter.checkArrayType(context.runtime, value); if (ary.isNil()) throw typeError(context, "wrong element type ", value, " (expected array)"); final RubyArray array = (RubyArray) ary; if (array.size() != 2) { throw argumentError(context, "element has wrong array length (expected 2, was " + array.size() + ")"); } - result.fastASetCheckString(runtime, array.eltOk(0), array.eltOk(1)); + result.fastASetCheckString(context.runtime, array.eltOk(0), array.eltOk(1)); } } @@ -2392,7 +2326,7 @@ public IRubyObject call(ThreadContext context, IRubyObject[] largs, Block blk) { } else if (largs.length == 1) { value = largs[0]; } else { - value = RubyArray.newArrayNoCopy(context.runtime, largs); + value = newArrayNoCopy(context, largs); } IRubyObject count = result.fastARef(value); diff --git a/core/src/main/java/org/jruby/RubyFile.java b/core/src/main/java/org/jruby/RubyFile.java index 14bca32694e..a6897f0e3c6 100644 --- a/core/src/main/java/org/jruby/RubyFile.java +++ b/core/src/main/java/org/jruby/RubyFile.java @@ -82,8 +82,7 @@ import static org.jruby.RubyInteger.singleCharByteList; 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.runtime.ThreadContext.hasKeywords; import static org.jruby.runtime.Visibility.PRIVATE; @@ -1189,10 +1188,9 @@ public static IRubyObject rename(ThreadContext context, IRubyObject recv, IRubyO @JRubyMethod(meta = true) public static RubyArray split(ThreadContext context, IRubyObject recv, IRubyObject arg) { - Ruby runtime = context.runtime; - RubyString filename = StringSupport.checkEmbeddedNulls(runtime, get_path(context, arg)); + RubyString filename = StringSupport.checkEmbeddedNulls(context.runtime, get_path(context, arg)); - return runtime.newArray(dirname(context, recv, filename), basename(context, recv, filename)); + return newArray(context, dirname(context, recv, filename), basename(context, recv, filename)); } @JRubyMethod(meta = true) diff --git a/core/src/main/java/org/jruby/RubyFixnum.java b/core/src/main/java/org/jruby/RubyFixnum.java index 7c3a0962690..a53dda6bba5 100644 --- a/core/src/main/java/org/jruby/RubyFixnum.java +++ b/core/src/main/java/org/jruby/RubyFixnum.java @@ -40,6 +40,7 @@ import java.math.BigInteger; import org.jcodings.specific.USASCIIEncoding; +import org.jruby.api.Create; import org.jruby.compiler.Constantizable; import org.jruby.runtime.Block; import org.jruby.runtime.CallSite; @@ -60,6 +61,8 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; +import static org.jruby.api.Create.newEmptyArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.util.Numeric.f_odd_p; @@ -386,7 +389,7 @@ public RubyArray digits(ThreadContext context, IRubyObject base) { if (value == 0) return RubyArray.newArray(context.runtime, zero(context.runtime)); - RubyArray res = RubyArray.newArray(context.runtime, 0); + var res = newArray(context, 0); while (value > 0) { res.append(context, newFixnum(context.runtime, value % longBase)); value /= longBase; @@ -769,20 +772,16 @@ public IRubyObject divmod(ThreadContext context, IRubyObject other) { } private IRubyObject divmodFixnum(ThreadContext context, RubyFixnum other) { - final Ruby runtime = context.runtime; - final long x = this.value; final long y = other.value; - if (y == 0) { - throw runtime.newZeroDivisionError(); - } + if (y == 0) throw context.runtime.newZeroDivisionError(); long mod; final RubyInteger integerDiv; if (y == -1) { if (x == MIN) { - integerDiv = RubyBignum.newBignum(runtime, BigInteger.valueOf(x).negate()); + integerDiv = RubyBignum.newBignum(context.runtime, BigInteger.valueOf(x).negate()); } else { - integerDiv = RubyFixnum.newFixnum(runtime, -x); + integerDiv = Create.newFixnum(context, -x); } mod = 0; } else { @@ -794,10 +793,10 @@ private IRubyObject divmodFixnum(ThreadContext context, RubyFixnum other) { div -= 1; // horrible sudden thought: might this overflow? probably not? mod += y; } - integerDiv = RubyFixnum.newFixnum(runtime, div); + integerDiv = Create.newFixnum(context, div); } - IRubyObject fixMod = RubyFixnum.newFixnum(runtime, mod); - return RubyArray.newArray(runtime, integerDiv, fixMod); + IRubyObject fixMod = Create.newFixnum(context, mod); + return newArray(context, integerDiv, fixMod); } /** fix_pow diff --git a/core/src/main/java/org/jruby/RubyFloat.java b/core/src/main/java/org/jruby/RubyFloat.java index 2b0273616db..e140a764b3c 100644 --- a/core/src/main/java/org/jruby/RubyFloat.java +++ b/core/src/main/java/org/jruby/RubyFloat.java @@ -46,6 +46,7 @@ import org.jcodings.specific.USASCIIEncoding; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; +import org.jruby.api.Create; import org.jruby.ast.util.ArgsUtil; import org.jruby.runtime.Arity; import org.jruby.runtime.ClassIndex; @@ -63,6 +64,7 @@ import org.jruby.util.Sprintf; import static org.jruby.api.Convert.asBoolean; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.util.Numeric.f_abs; @@ -301,8 +303,8 @@ public IRubyObject to_s() { @JRubyMethod(name = "coerce") @Override public IRubyObject coerce(IRubyObject other) { - final Ruby runtime = metaClass.runtime; - return runtime.newArray(RubyKernel.new_float(runtime.getCurrentContext(), other), this); + var context = metaClass.runtime.getCurrentContext(); + return newArray(context, RubyKernel.new_float(context, other), this); } /** flo_uminus @@ -446,18 +448,15 @@ public IRubyObject divmod(ThreadContext context, IRubyObject other) { double mod = Math.IEEEremainder(x, y); // MRI behavior: - if (Double.isNaN(mod)) { - throw context.runtime.newFloatDomainError("NaN"); - } + if (Double.isNaN(mod)) throw context.runtime.newFloatDomainError("NaN"); + double div = Math.floor(x / y); - if (y * mod < 0) { - mod += y; - } - final Ruby runtime = context.runtime; - RubyInteger car = dbl2ival(runtime, div); - RubyFloat cdr = RubyFloat.newFloat(runtime, mod); - return RubyArray.newArray(runtime, car, cdr); + if (y * mod < 0) mod += y; + + RubyInteger car = dbl2ival(context.runtime, div); + RubyFloat cdr = Create.newFloat(context, mod); + return newArray(context, car, cdr); default: return coerceBin(context, sites(context).divmod, other); } diff --git a/core/src/main/java/org/jruby/RubyGlobal.java b/core/src/main/java/org/jruby/RubyGlobal.java index e4bbe3454b1..6cd506e0da1 100644 --- a/core/src/main/java/org/jruby/RubyGlobal.java +++ b/core/src/main/java/org/jruby/RubyGlobal.java @@ -71,6 +71,7 @@ import org.jruby.util.io.OpenFile; import org.jruby.util.io.STDIO; +import static org.jruby.api.Create.*; import static org.jruby.api.Error.typeError; import static org.jruby.internal.runtime.GlobalVariable.Scope.*; import static org.jruby.util.RubyStringBuilder.str; @@ -99,7 +100,7 @@ public class RubyGlobal { public static void initARGV(Ruby runtime) { var context = runtime.getCurrentContext(); // define ARGV and $* for this runtime - var argvArray = runtime.newArray(); + var argvArray = newArray(context); String[] argv = runtime.getInstanceConfig().getArgv(); for (String arg : argv) { @@ -120,6 +121,7 @@ public static void createGlobals(Ruby runtime) { } public static RubyHash createGlobalsAndENV(Ruby runtime) { + var context = runtime.getCurrentContext(); GlobalVariables globals = runtime.getGlobalVariables(); runtime.setTopLevelBinding(runtime.newBinding()); @@ -127,20 +129,17 @@ public static RubyHash createGlobalsAndENV(Ruby runtime) { initARGV(runtime); - IAccessor d = new ValueAccessor(runtime.newString( - runtime.getInstanceConfig().displayedFileName())); + IAccessor d = new ValueAccessor(newString(context, runtime.getInstanceConfig().displayedFileName())); globals.define("$PROGRAM_NAME", d, GLOBAL); globals.define("$0", d, GLOBAL); // Version information: - IRubyObject version; - IRubyObject patchlevel; IRubyObject release = RubyString.newFString(runtime, Constants.COMPILE_DATE); IRubyObject platform = RubyString.newFString(runtime, Constants.PLATFORM); IRubyObject engine = RubyString.newFString(runtime, Constants.ENGINE); + IRubyObject version = RubyString.newFString(runtime, Constants.RUBY_VERSION); + IRubyObject patchlevel = newFixnum(context, 0); - version = RubyString.newFString(runtime, Constants.RUBY_VERSION); - patchlevel = runtime.newFixnum(0); runtime.defineGlobalConstant("RUBY_VERSION", version); runtime.defineGlobalConstant("RUBY_PATCHLEVEL", patchlevel); runtime.defineGlobalConstant("RUBY_RELEASE_DATE", release); @@ -190,11 +189,11 @@ public static RubyHash createGlobalsAndENV(Ruby runtime) { RubyInstanceConfig.Verbosity verbose = runtime.getInstanceConfig().getVerbosity(); IRubyObject verboseValue; if (verbose == RubyInstanceConfig.Verbosity.NIL) { - verboseValue = runtime.getNil(); + verboseValue = context.nil; } else if(verbose == RubyInstanceConfig.Verbosity.TRUE) { - verboseValue = runtime.getTrue(); + verboseValue = context.tru; } else { - verboseValue = runtime.getFalse(); + verboseValue = context.fals; } runtime.setVerbose(verboseValue); runtime.defineVariable(new VerboseGlobalVariable(runtime, "$VERBOSE"), GLOBAL); @@ -232,7 +231,7 @@ public static RubyHash createGlobalsAndENV(Ruby runtime) { // Fixme: Do we need the check or does Main.java not call this...they should consolidate if (globals.get("$*").isNil()) { - globals.defineReadonly("$*", new ValueAccessor(runtime.newArray()), GLOBAL); + globals.defineReadonly("$*", new ValueAccessor(newArray(context)), GLOBAL); } globals.defineReadonly("$-p", @@ -250,9 +249,9 @@ public static RubyHash createGlobalsAndENV(Ruby runtime) { String inplace = runtime.config.getInPlaceBackupExtension(); if (inplace != null) { - runtime.defineVariable(new ArgfGlobalVariable(runtime, "$-i", runtime.newString(inplace)), GLOBAL); + runtime.defineVariable(new ArgfGlobalVariable(runtime, "$-i", newString(context, inplace)), GLOBAL); } else { - runtime.defineVariable(new ArgfGlobalVariable(runtime, "$-i", runtime.getNil()), GLOBAL); + runtime.defineVariable(new ArgfGlobalVariable(runtime, "$-i", context.nil), GLOBAL); } globals.alias("$-0", "$/"); diff --git a/core/src/main/java/org/jruby/RubyHash.java b/core/src/main/java/org/jruby/RubyHash.java index b75e6114050..3cc0a1bedd0 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.Create.newArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.Visibility.PRIVATE; @@ -1008,7 +1009,7 @@ public RubyArray to_a(ThreadContext context) { private static final VisitorWithState StoreKeyValueVisitor = new VisitorWithState() { @Override public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, RubyArray result) { - result.storeInternal(context, index, RubyArray.newArray(context.runtime, key, value)); + result.storeInternal(context, index, newArray(context, key, value)); } }; @@ -1115,12 +1116,12 @@ protected RubyHash to_h_block(ThreadContext context, Block block) { RubyHash result = newHash(context.runtime); visitAll(context, (ctxt, self, key, value, index) -> { - IRubyObject elt = block.yieldArray(ctxt, ctxt.runtime.newArray(key, value), null); + IRubyObject elt = block.yieldArray(ctxt, newArray(ctxt, key, value), null); IRubyObject keyValue = elt.checkArrayType(); if (keyValue == ctxt.nil) throw typeError(context, "wrong element type ", elt, " (expected array)"); - RubyArray ary = (RubyArray) keyValue; + var ary = (RubyArray) keyValue; if (ary.getLength() != 2) { throw argumentError(context, "element has wrong array length " + "(expected 2, was " + ary.getLength() + ")"); } @@ -1591,7 +1592,7 @@ public RubyHash eachCommon(final ThreadContext context, final Block block) { private static final VisitorWithState YieldArrayVisitor = new VisitorWithState() { @Override public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, Block block) { - block.yieldArray(context, context.runtime.newArray(key, value), null); + block.yieldArray(context, newArray(context, key, value), null); } }; @@ -1613,11 +1614,11 @@ public RubyHash each_pairCommon(final ThreadContext context, final Block block) @Override public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, Block block) { if (block.type == Block.Type.LAMBDA) { - block.call(context, context.runtime.newArray(key, value)); + block.call(context, newArray(context, key, value)); } else if (block.getSignature().isSpreadable()) { block.yieldSpecific(context, key, value); } else { - block.yield(context, context.runtime.newArray(key, value)); + block.yield(context, newArray(context, key, value)); } } }; @@ -1794,7 +1795,7 @@ public boolean keep_ifCommon(final ThreadContext context, final Block block) { testFrozen("Hash"); boolean[] modified = new boolean[] { false }; iteratorVisitAll(context, (ctxt, self, key, value, index) -> { - if (!block.yieldArray(ctxt, ctxt.runtime.newArray(key, value), null).isTrue()) { + if (!block.yieldArray(ctxt, newArray(ctxt, key, value), null).isTrue()) { testFrozen(); modified[0] = true; self.remove(key); @@ -1917,7 +1918,7 @@ public IRubyObject shift(ThreadContext context) { RubyHashEntry entry = head.nextAdded; if (entry != head) { - RubyArray result = RubyArray.newArray(context.runtime, entry.key, entry.value); + var result = newArray(context, entry.key, entry.value); internalDeleteEntry(entry); return result; } @@ -2006,7 +2007,7 @@ public RubyHash delete_ifInternal(ThreadContext context, Block block) { private static final VisitorWithState DeleteIfVisitor = new VisitorWithState() { @Override public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, Block block) { - if (block.yieldArray(context, RubyArray.newArray(context.runtime, key, value), null).isTrue()) { + if (block.yieldArray(context, newArray(context, key, value), null).isTrue()) { self.delete(context, key, Block.NULL_BLOCK); } } @@ -2105,7 +2106,7 @@ public RubyHash merge_bang(ThreadContext context, IRubyObject[] others, Block bl if (block.isGiven()) { IRubyObject existing = internalGet(key); if (existing != null) { - value = block.yield(ctxt, RubyArray.newArray(ctxt.runtime, key, existing, value)); + value = block.yield(ctxt, newArray(ctxt, key, existing, value)); } } op_aset(ctxt, key, value); @@ -2211,7 +2212,7 @@ public IRubyObject assoc(final ThreadContext context, final IRubyObject obj) { visitAll(context, FoundPairIfEqualKeyVisitor, obj); return context.nil; } catch (FoundPair found) { - return context.runtime.newArray(found.key, found.value); + return newArray(context, found.key, found.value); } } @@ -2221,7 +2222,7 @@ public IRubyObject rassoc(final ThreadContext context, final IRubyObject obj) { visitAll(context, FoundPairIfEqualValueVisitor, obj); return context.nil; } catch (FoundPair found) { - return context.runtime.newArray(found.key, found.value); + return newArray(context, found.key, found.value); } } @@ -2340,7 +2341,7 @@ protected IRubyObject any_p_i(ThreadContext context, Block block) { iteratorEntry(); try { for (RubyHashEntry entry = head.nextAdded; entry != head; entry = entry.nextAdded) { - IRubyObject newAssoc = RubyArray.newArray(context.runtime, entry.key, entry.value); + IRubyObject newAssoc = newArray(context, entry.key, entry.value); if (block.yield(context, newAssoc).isTrue()) return context.tru; } @@ -2354,8 +2355,7 @@ protected IRubyObject any_p_i_fast(ThreadContext context, Block block) { iteratorEntry(); try { for (RubyHashEntry entry = head.nextAdded; entry != head; entry = entry.nextAdded) { - if (block.yieldArray(context, context.runtime.newArray(entry.key, entry.value), null).isTrue()) - return context.tru; + if (block.yieldArray(context, newArray(context, entry.key, entry.value), null).isTrue()) return context.tru; } return context.fals; } finally { @@ -2367,9 +2367,8 @@ protected IRubyObject any_p_p(ThreadContext context, IRubyObject pattern) { iteratorEntry(); try { for (RubyHashEntry entry = head.nextAdded; entry != head; entry = entry.nextAdded) { - IRubyObject newAssoc = RubyArray.newArray(context.runtime, entry.key, entry.value); - if (pattern.callMethod(context, "===", newAssoc).isTrue()) - return context.tru; + IRubyObject newAssoc = newArray(context, entry.key, entry.value); + if (pattern.callMethod(context, "===", newAssoc).isTrue()) return context.tru; } return context.fals; } finally { diff --git a/core/src/main/java/org/jruby/RubyIO.java b/core/src/main/java/org/jruby/RubyIO.java index 0127cb37133..8cfaaf4d7e6 100644 --- a/core/src/main/java/org/jruby/RubyIO.java +++ b/core/src/main/java/org/jruby/RubyIO.java @@ -2667,7 +2667,7 @@ public RubyIO getline(ThreadContext context, RubyIO self, IRubyObject rs, int li @Override public RubyArray getline(ThreadContext context, RubyIO self, IRubyObject rs, int limit, boolean chomp, Block block) { - var ary = context.runtime.newArray(); + var ary = newArray(context); IRubyObject line; while ((line = self.getlineImpl(context, rs, limit, chomp)) != context.nil) { @@ -4674,8 +4674,7 @@ public static IRubyObject pipe(ThreadContext context, IRubyObject klass, IRubyOb PosixShim posix = new PosixShim(runtime); Channel[] fds = posix.pipe(); - if (fds == null) - throw runtime.newErrnoFromErrno(posix.getErrno(), "opening pipe"); + if (fds == null) throw runtime.newErrnoFromErrno(posix.getErrno(), "opening pipe"); // args[0] = klass; // args[1] = INT2NUM(pipes[0]); @@ -4730,11 +4729,9 @@ public static IRubyObject pipe(ThreadContext context, IRubyObject klass, IRubyOb } fptr2.setMode(fptr2.getMode() | fmode_p[0]); - ret = runtime.newArray(r, w); - if (block.isGiven()) { - return ensureYieldClosePipes(context, ret, r, w, block); - } - return ret; + ret = newArray(context, r, w); + return block.isGiven() ? + ensureYieldClosePipes(context, ret, r, w, block) : ret; } // MRI: rb_ensure(... pipe_pair_close ...) diff --git a/core/src/main/java/org/jruby/RubyIOBuffer.java b/core/src/main/java/org/jruby/RubyIOBuffer.java index db38d2d5e72..d7d0269ab26 100644 --- a/core/src/main/java/org/jruby/RubyIOBuffer.java +++ b/core/src/main/java/org/jruby/RubyIOBuffer.java @@ -1089,7 +1089,7 @@ public IRubyObject get_values(ThreadContext context, IRubyObject dataTypes, IRub } int dataTypesSize = dataTypesArray.size(); - RubyArray values = RubyArray.newArray(context.runtime, dataTypesSize); + var values = newArray(context, dataTypesSize); for (long i = 0; i < dataTypesSize; i++) { IRubyObject type = dataTypesArray.eltOk(i); @@ -1178,12 +1178,9 @@ public IRubyObject values(ThreadContext context, IRubyObject _dataType, IRubyObj } private RubyArray values(ThreadContext context, ByteBuffer buffer, DataType dataType, int offset, int count) { - Ruby runtime = context.runtime; - - RubyArray values = RubyArray.newArray(runtime, count); + var values = newArray(context, count); for (int i = 0 ; i < count; i++) { - int currentOffset = offset; IRubyObject value = getValue(context, buffer, size, dataType, offset); offset += dataType.type.size(); values.push(value); diff --git a/core/src/main/java/org/jruby/RubyInteger.java b/core/src/main/java/org/jruby/RubyInteger.java index 31b78c54bfd..130720f695a 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.Create.newArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.util.Numeric.f_gcd; @@ -796,7 +797,7 @@ public IRubyObject lcm(ThreadContext context, IRubyObject other) { @JRubyMethod(name = "gcdlcm") public IRubyObject gcdlcm(ThreadContext context, IRubyObject other) { final RubyInteger otherInt = RubyInteger.intValue(context, other); - return context.runtime.newArray(f_gcd(context, this, otherInt), f_lcm(context, this, otherInt)); + return newArray(context, f_gcd(context, this, otherInt), f_lcm(context, this, otherInt)); } static RubyInteger intValue(ThreadContext context, IRubyObject num) { diff --git a/core/src/main/java/org/jruby/RubyKernel.java b/core/src/main/java/org/jruby/RubyKernel.java index 07bebefc9da..987c6cbc0d5 100644 --- a/core/src/main/java/org/jruby/RubyKernel.java +++ b/core/src/main/java/org/jruby/RubyKernel.java @@ -950,7 +950,7 @@ private static void exit(Ruby runtime, IRubyObject[] args, boolean hard) { */ @JRubyMethod(name = "global_variables", module = true, visibility = PRIVATE) public static RubyArray global_variables(ThreadContext context, IRubyObject recv) { - RubyArray globalVariables = context.runtime.newArray(); + var globalVariables = newArray(context); for (String globalVariableName : context.runtime.getGlobalVariables().getNames()) { globalVariables.append(context, newSymbol(context, globalVariableName)); diff --git a/core/src/main/java/org/jruby/RubyMatchData.java b/core/src/main/java/org/jruby/RubyMatchData.java index d442444d062..e4360372abe 100644 --- a/core/src/main/java/org/jruby/RubyMatchData.java +++ b/core/src/main/java/org/jruby/RubyMatchData.java @@ -48,6 +48,7 @@ import org.joni.exception.ValueException; import org.jruby.anno.JRubyMethod; import org.jruby.anno.JRubyClass; +import org.jruby.api.Create; import org.jruby.ast.util.ArgsUtil; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; @@ -60,8 +61,8 @@ import org.jruby.util.RegexpOptions; import org.jruby.util.StringSupport; -import static org.jruby.RubyFixnum.newFixnum; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.*; import static org.jruby.api.Error.typeError; import static org.jruby.util.RubyStringBuilder.str; @@ -167,16 +168,15 @@ public int compareTo(Pair pair) { private static void updatePairs(ByteList value, Encoding encoding, Pair[] pairs) { Arrays.sort(pairs); - int length = pairs.length; byte[] bytes = value.getUnsafeBytes(); int p = value.getBegin(); int s = p; int c = 0; - for (int i = 0; i < length; i++) { - int q = s + pairs[i].bytePos; + for (Pair pair : pairs) { + int q = s + pair.bytePos; c += StringSupport.strLength(encoding, bytes, p, q); - pairs[i].charPos = c; + pair.charPos = c; p = q; } } @@ -308,29 +308,24 @@ private RubyRegexp getRegexp() { } private RubyArray match_array(ThreadContext context, int start) { - Ruby runtime = context.runtime; check(); if (regs == null) { - if (start != 0) return runtime.newEmptyArray(); - if (begin == -1) { - return runtime.newArray(context.nil); - } else { - RubyString ss = str.makeSharedString(runtime, begin, end - begin); - return runtime.newArray(ss); - } - } else { - int count = regs.getNumRegs() - start; - var arr = RubyArray.newBlankArray(runtime, count); - for (int i=0; i < count; i++) { - int beg = regs.getBeg(i+start); - arr.storeInternal(context, i, beg == -1 ? - context.nil : - str.makeSharedString(runtime, beg, regs.getEnd(i+start) - beg)); - } - return arr; + if (start != 0) return newEmptyArray(context); + return begin == -1 ? + newArray(context, context.nil) : + newArray(context, str.makeSharedString(context.runtime, begin, end - begin)); } + int count = regs.getNumRegs() - start; + var arr = newArray(context, count); + for (int i=0; i < count; i++) { + int beg = regs.getBeg(i+start); + arr.storeInternal(context, i, beg == -1 ? + context.nil : + str.makeSharedString(context.runtime, beg, regs.getEnd(i+start) - beg)); + } + return arr; } public IRubyObject group(long n) { @@ -371,19 +366,15 @@ public IRubyObject[] getNamedBackrefValues(Ruby runtime) { @JRubyMethod public IRubyObject byteoffset(ThreadContext context, IRubyObject group) { - Ruby runtime = context.runtime; - int index = backrefNumber(runtime, group); + int index = backrefNumber(context.runtime, group); Region regs = this.regs; - backrefNumberCheck(runtime, index); + backrefNumberCheck(context, index); int start = regs.getBeg(index); + if (start < 0) return newArray(context, 2); - if (start < 0) return runtime.newArray(context.nil, context.nil); - - int end = regs.getEnd(index); - - return runtime.newArray(asFixnum(context, start), asFixnum(context, end)); + return newArray(context, asFixnum(context, start), asFixnum(context, regs.getEnd(index))); } @JRubyMethod @@ -450,9 +441,8 @@ public RubyArray to_a(ThreadContext context) { @JRubyMethod(rest = true) public IRubyObject values_at(ThreadContext context, IRubyObject[] args) { check(); - Ruby runtime = context.runtime; - RubyArray result = RubyArray.newArray(runtime, args.length); + var result = newArray(context, args.length); for (IRubyObject arg : args) { if (arg instanceof RubyFixnum) { @@ -555,7 +545,7 @@ private IRubyObject matchArySubseq(ThreadContext context, int beg, int len, Ruby int olen = regs.getNumRegs(); int wantedEnd = beg + len; - int j, end = olen < wantedEnd ? olen : wantedEnd; + int j, end = Math.min(olen, wantedEnd); if (len == 0) return result; @@ -638,8 +628,7 @@ public final IRubyObject at(final int nth) { @JRubyMethod(name = {"size", "length"}) public IRubyObject size(ThreadContext context) { check(); - Ruby runtime = context.runtime; - return regs == null ? RubyFixnum.one(runtime) : newFixnum(runtime, regs.getNumRegs()); + return regs == null ? RubyFixnum.one(context.runtime) : newFixnum(context, regs.getNumRegs()); } /** @@ -648,18 +637,16 @@ public IRubyObject size(ThreadContext context) { @JRubyMethod public IRubyObject begin(ThreadContext context, IRubyObject index) { check(); - final Ruby runtime = context.runtime; - final int i = backrefNumber(runtime, index); + final int i = backrefNumber(context.runtime, index); - backrefNumberCheck(runtime, i); + backrefNumberCheck(context, i); int b = regs == null ? begin : regs.getBeg(i); - if (b < 0) return context.nil; updateCharOffset(); - return newFixnum(runtime, charOffsets.getBeg(i)); + return newFixnum(context, charOffsets.getBeg(i)); } /** match_end @@ -669,13 +656,11 @@ public IRubyObject begin(ThreadContext context, IRubyObject index) { public IRubyObject end(ThreadContext context, IRubyObject index) { check(); - final Ruby runtime = context.runtime; - final int i = backrefNumber(runtime, index); + final int i = backrefNumber(context.runtime, index); - backrefNumberCheck(runtime, i); + backrefNumberCheck(context, i); int e = regs == null ? end : regs.getEnd(i); - if (e < 0) return context.nil; if ( ! str.singleByteOptimizable() ) { @@ -683,7 +668,7 @@ public IRubyObject end(ThreadContext context, IRubyObject index) { e = charOffsets.getEnd(i); } - return newFixnum(runtime, e); + return newFixnum(context, e); } @Deprecated @@ -698,10 +683,8 @@ public IRubyObject offset19(ThreadContext context, IRubyObject index) { public IRubyObject offset(ThreadContext context, IRubyObject index) { check(); - final Ruby runtime = context.runtime; - final int i = backrefNumber(runtime, index); - - backrefNumberCheck(runtime, i); + final int i = backrefNumber(context.runtime, index); + backrefNumberCheck(context, i); int b, e; if (regs == null) { @@ -712,7 +695,7 @@ public IRubyObject offset(ThreadContext context, IRubyObject index) { e = regs.getEnd(i); } - if (b < 0) return runtime.newArray(context.nil, context.nil); + if (b < 0) return newArray(context, 2); if ( ! str.singleByteOptimizable() ) { updateCharOffset(); @@ -720,7 +703,7 @@ public IRubyObject offset(ThreadContext context, IRubyObject index) { e = charOffsets.getEnd(i); } - return runtime.newArray(newFixnum(runtime, b), newFixnum(runtime, e)); + return newArray(context, newFixnum(context, b), newFixnum(context, e)); } /** match_pre_match @@ -736,13 +719,10 @@ public IRubyObject pre_match(ThreadContext context) { @JRubyMethod public IRubyObject match(ThreadContext context, IRubyObject nth) { - Ruby runtime = context.runtime; - int index = nthToIndex(context, nth); - Region regs = this.regs; - backrefNumberCheck(runtime, index); + backrefNumberCheck(context, index); int start = regs.getBeg(index); @@ -750,25 +730,20 @@ public IRubyObject match(ThreadContext context, IRubyObject nth) { int end = regs.getEnd(index); - return str.makeSharedString(runtime, start, end - start); + return str.makeSharedString(context.runtime, start, end - start); } @JRubyMethod public IRubyObject match_length(ThreadContext context, IRubyObject nth) { - Ruby runtime = context.runtime; - int index = nthToIndex(context, nth); - Region regs = this.regs; - backrefNumberCheck(runtime, index); + backrefNumberCheck(context, index); int start = regs.getBeg(index); - if (start < 0) return context.nil; int end = regs.getEnd(index); - ByteList strBytes = str.getByteList(); int length = StringSupport.strLength( @@ -778,7 +753,7 @@ public IRubyObject match_length(ThreadContext context, IRubyObject nth) { end, str.getCodeRange()); - return newFixnum(runtime, length); + return newFixnum(context, length); } private int nthToIndex(ThreadContext context, IRubyObject id) { @@ -790,9 +765,9 @@ private int nthToIndex(ThreadContext context, IRubyObject id) { return index; } - private void backrefNumberCheck(Ruby runtime, int i) { + private void backrefNumberCheck(ThreadContext context, int i) { if (i < 0 || (regs == null ? 1 : regs.getNumRegs()) <= i) { - throw runtime.newIndexError("index " + i + " out of matches"); + throw context.runtime.newIndexError("index " + i + " out of matches"); } } @@ -873,7 +848,7 @@ public int hashCode() { @JRubyMethod @Override public RubyFixnum hash() { - return newFixnum(getRuntime(), hashCode()); + return newFixnum(getRuntime().getCurrentContext(), hashCode()); } @JRubyMethod(keywords = true, optional = 1) diff --git a/core/src/main/java/org/jruby/RubyMath.java b/core/src/main/java/org/jruby/RubyMath.java index 61a9b50aba7..f6a4c73da75 100644 --- a/core/src/main/java/org/jruby/RubyMath.java +++ b/core/src/main/java/org/jruby/RubyMath.java @@ -38,6 +38,7 @@ import org.jruby.runtime.Visibility; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newFloat; @JRubyModule(name="Math") @@ -46,10 +47,11 @@ public class RubyMath { * */ public static RubyModule createMathModule(Ruby runtime) { + var context = runtime.getCurrentContext(); RubyModule result = runtime.defineModule("Math"); - result.defineConstant("E", RubyFloat.newFloat(runtime, Math.E)); - result.defineConstant("PI", RubyFloat.newFloat(runtime, Math.PI)); + result.defineConstant("E", newFloat(context, Math.E)); + result.defineConstant("PI", newFloat(context, Math.PI)); result.defineAnnotatedMethods(RubyMath.class); @@ -84,25 +86,22 @@ public static double sign(double x, double y) { @JRubyMethod(name = "atan2", module = true, visibility = Visibility.PRIVATE) public static RubyFloat atan2(ThreadContext context, IRubyObject recv, IRubyObject x, IRubyObject y) { - double valuea = RubyNumeric.num2dbl(context, x); - double valueb = RubyNumeric.num2dbl(context, y); - - return RubyFloat.newFloat(context.runtime, Math.atan2(valuea, valueb)); + return newFloat(context, Math.atan2(RubyNumeric.num2dbl(context, x), RubyNumeric.num2dbl(context, y))); } @JRubyMethod(name = "cos", module = true, visibility = Visibility.PRIVATE) public static RubyFloat cos(ThreadContext context, IRubyObject recv, IRubyObject x) { - return RubyFloat.newFloat(context.runtime, Math.cos(RubyNumeric.num2dbl(context, x))); + return newFloat(context, Math.cos(RubyNumeric.num2dbl(context, x))); } @JRubyMethod(name = "sin", module = true, visibility = Visibility.PRIVATE) public static RubyFloat sin(ThreadContext context, IRubyObject recv, IRubyObject x) { - return RubyFloat.newFloat(context.runtime, Math.sin(RubyNumeric.num2dbl(context, x))); + return newFloat(context, Math.sin(RubyNumeric.num2dbl(context, x))); } @JRubyMethod(name = "tan", module = true, visibility = Visibility.PRIVATE) public static RubyFloat tan(ThreadContext context, IRubyObject recv, IRubyObject x) { - return RubyFloat.newFloat(context.runtime, Math.tan(RubyNumeric.num2dbl(context, x))); + return newFloat(context, Math.tan(RubyNumeric.num2dbl(context, x))); } @JRubyMethod(name = "asin", module = true, visibility = Visibility.PRIVATE) @@ -111,7 +110,7 @@ public static RubyFloat asin(ThreadContext context, IRubyObject recv, IRubyObjec if (value < -1.0 || value > 1.0) throw context.runtime.newMathDomainError("asin"); - return RubyFloat.newFloat(context.runtime, Math.asin(value)); + return newFloat(context, Math.asin(value)); } @JRubyMethod(name = "acos", module = true, visibility = Visibility.PRIVATE) @@ -120,31 +119,31 @@ public static RubyFloat acos(ThreadContext context, IRubyObject recv, IRubyObjec if (value < -1.0 || value > 1.0) throw context.runtime.newMathDomainError("acos"); - return RubyFloat.newFloat(context.runtime, Math.acos(value)); + return newFloat(context, Math.acos(value)); } @JRubyMethod(name = "atan", module = true, visibility = Visibility.PRIVATE) public static RubyFloat atan(ThreadContext context, IRubyObject recv, IRubyObject x) { - return RubyFloat.newFloat(context.runtime, Math.atan(RubyNumeric.num2dbl(context, x))); + return newFloat(context, Math.atan(RubyNumeric.num2dbl(context, x))); } @JRubyMethod(name = "cosh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat cosh(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); - return RubyFloat.newFloat(context.runtime, (Math.exp(value) + Math.exp(-value)) / 2.0); + return newFloat(context, (Math.exp(value) + Math.exp(-value)) / 2.0); } @JRubyMethod(name = "sinh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat sinh(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); - return RubyFloat.newFloat(context.runtime, (Math.exp(value) - Math.exp(-value)) / 2.0); + return newFloat(context, (Math.exp(value) - Math.exp(-value)) / 2.0); } @JRubyMethod(name = "tanh", module = true, visibility = Visibility.PRIVATE) public static RubyFloat tanh(ThreadContext context, IRubyObject recv, IRubyObject x) { - return RubyFloat.newFloat(context.runtime, Math.tanh(RubyNumeric.num2dbl(context, x))); + return newFloat(context, Math.tanh(RubyNumeric.num2dbl(context, x))); } @JRubyMethod(name = "acosh", module = true, visibility = Visibility.PRIVATE) @@ -162,7 +161,7 @@ public static RubyFloat acosh(ThreadContext context, IRubyObject recv, IRubyObje result = 0.69314718055994530941723212145818 + Math.log(value); } - return RubyFloat.newFloat(context.runtime,result); + return newFloat(context, result); } public static final double[] ASINH_COEF = { @@ -208,7 +207,7 @@ public static RubyFloat asinh(ThreadContext context, IRubyObject recv, IRubyObje if (value < 0) result *= -1; } - return RubyFloat.newFloat(context.runtime, result); + return newFloat(context, result); } public static final double[] ATANH_COEF = { @@ -253,7 +252,7 @@ public static RubyFloat atanh(ThreadContext context, IRubyObject recv, IRubyObje result = Double.NaN; } - return RubyFloat.newFloat(context.runtime, result); + return newFloat(context, result); } @JRubyMethod(name = "exp", module = true, visibility = Visibility.PRIVATE) @@ -262,7 +261,7 @@ public static RubyFloat exp(ThreadContext context, IRubyObject recv, IRubyObject } public static RubyFloat exp(ThreadContext context, IRubyObject exponent) { - return RubyFloat.newFloat(context.runtime, Math.exp(RubyNumeric.num2dbl(context, exponent))); + return newFloat(context, Math.exp(RubyNumeric.num2dbl(context, exponent))); } // MRI : get_double_rshift @@ -296,14 +295,12 @@ public static RubyFloat log(ThreadContext context, IRubyObject recv, IRubyObject } public static RubyFloat log(ThreadContext context, IRubyObject val) { - double [] ret = get_double_rshift(context, val); + double[] ret = get_double_rshift(context, val); - if (ret[0] < 0) { - throw context.runtime.newMathDomainError("log"); - } + if (ret[0] < 0) throw context.runtime.newMathDomainError("log"); /* log(d * 2 ** numbits) */ - return RubyFloat.newFloat(context.runtime, Math.log(ret[0]) + ret[1] * LOG_E_2); + return newFloat(context, Math.log(ret[0]) + ret[1] * LOG_E_2); } @JRubyMethod(name = "log", module = true, visibility = Visibility.PRIVATE) @@ -311,19 +308,14 @@ public static RubyFloat log(ThreadContext context, IRubyObject recv, IRubyObject double [] ret = get_double_rshift(context, val); double _base = RubyNumeric.num2dbl(context, base); - if (ret[0] < 0 || _base < 0) { - throw context.runtime.newMathDomainError("log"); - } + if (ret[0] < 0 || _base < 0) throw context.runtime.newMathDomainError("log"); /* log(d * 2 ** numbits) / log(base) */ - return RubyFloat.newFloat(context.runtime, Math.log(ret[0]) / Math.log(_base) + ret[1]); + return newFloat(context, Math.log(ret[0]) / Math.log(_base) + ret[1]); } public static RubyFloat log(ThreadContext context, IRubyObject recv, IRubyObject... args) { - if (args.length == 2) { - return log(context, recv, args[0], args[1]); - } - return log(context, recv, args[0]); + return args.length == 2 ? log(context, recv, args[0], args[1]) : log(context, recv, args[0]); } /** Returns the base 10 logarithm of x. @@ -333,12 +325,10 @@ public static RubyFloat log(ThreadContext context, IRubyObject recv, IRubyObject public static RubyFloat log10(ThreadContext context, IRubyObject recv, IRubyObject x) { double [] ret = get_double_rshift(context, x); - if (ret[0] < 0) { - throw context.runtime.newMathDomainError("log10"); - } + if (ret[0] < 0) throw context.runtime.newMathDomainError("log10"); /* log10(d * 2 ** numbits) */ - return RubyFloat.newFloat(context.runtime, Math.log10(ret[0]) + ret[1] * LOG_10_2); + return newFloat(context, Math.log10(ret[0]) + ret[1] * LOG_10_2); } /** Returns the base 2 logarithm of x. @@ -348,12 +338,10 @@ public static RubyFloat log10(ThreadContext context, IRubyObject recv, IRubyObje public static RubyFloat log2(ThreadContext context, IRubyObject recv, IRubyObject x) { double [] ret = get_double_rshift(context, x); - if (ret[0] < 0) { - throw context.runtime.newMathDomainError("log2"); - } + if (ret[0] < 0) throw context.runtime.newMathDomainError("log2"); /* log2(d * 2 ** numbits) */ - return RubyFloat.newFloat(context.runtime, Math.log(ret[0]) / LOG_E_2 + ret[1]); + return newFloat(context, Math.log(ret[0]) / LOG_E_2 + ret[1]); } @JRubyMethod(name = "sqrt", module = true, visibility = Visibility.PRIVATE) @@ -362,14 +350,12 @@ public static RubyFloat sqrt(ThreadContext context, IRubyObject recv, IRubyObjec if (value < 0) throw context.runtime.newMathDomainError("sqrt"); - return RubyFloat.newFloat(context.runtime, value == 0.0 ? 0.0 : Math.sqrt(value)); + return newFloat(context, value == 0.0 ? 0.0 : Math.sqrt(value)); } @JRubyMethod(name = "cbrt", module = true, visibility = Visibility.PRIVATE) public static RubyFloat cbrt(ThreadContext context, IRubyObject recv, IRubyObject x) { - double result = Math.cbrt(RubyNumeric.num2dbl(context, x)); - - return RubyFloat.newFloat(context.runtime, result); + return newFloat(context, Math.cbrt(RubyNumeric.num2dbl(context, x))); } @Deprecated @@ -395,7 +381,7 @@ public static RubyFloat hypot(ThreadContext context, IRubyObject recv, IRubyObje result = 0; } - return RubyFloat.newFloat(context.runtime,result); + return newFloat(context, result); } @@ -425,9 +411,7 @@ public static RubyArray frexp(ThreadContext context, IRubyObject recv, IRubyObje for (; mantissa >= 1.0; mantissa *= 0.5, exponent +=1) { } } - return RubyArray.newArray(context.runtime, - RubyFloat.newFloat(context.runtime, sign * mantissa), - RubyNumeric.int2fix(context.runtime, exponent)); + return newArray(context, newFloat(context, sign * mantissa), RubyNumeric.int2fix(context.runtime, exponent)); } /* @@ -438,12 +422,9 @@ public static RubyFloat ldexp(ThreadContext context, IRubyObject recv, IRubyObje double m = RubyNumeric.num2dbl(context, mantissa); int e = RubyNumeric.num2int(exponent); - if (e > 1023) { - // avoid overflow. Math.power(2.0, 1024) is greater than Math.MAX_VALUE. - return RubyFloat.newFloat(context.runtime, m * Math.pow(2.0, e - 1023) * Math.pow(2.0, 1023)); - } - - return RubyFloat.newFloat(context.runtime, m * Math.pow(2.0, e)); + return e > 1023 ? // avoid overflow. Math.power(2.0, 1024) is greater than Math.MAX_VALUE. + newFloat(context, m * Math.pow(2.0, e - 1023) * Math.pow(2.0, 1023)) : + newFloat(context, m * Math.pow(2.0, e)); } public static final double[] ERFC_COEF = { @@ -466,23 +447,22 @@ public static RubyFloat ldexp(ThreadContext context, IRubyObject recv, IRubyObje @JRubyMethod(name = "erf", module = true, visibility = Visibility.PRIVATE) public static RubyFloat erf(ThreadContext context, IRubyObject recv, IRubyObject x) { double value = RubyNumeric.num2dbl(context, x); - - double result; double y = Math.abs(value); + double result; if (y <= 1.49012e-08) { result = 2 * value / 1.77245385090551602729816748334; } else if (y <= 1) { result = value * (1 + chebylevSerie(2 * value * value - 1, ERFC_COEF)); } else if (y < 6.013687357) { - result = sign(1 - erfc(context, recv, RubyFloat.newFloat(context.runtime, y)).value, value); + result = sign(1 - erfc(context, recv, newFloat(context, y)).value, value); } else if (Double.isNaN(y)) { result = Double.NaN; } else { result = sign(1, value); } - return RubyFloat.newFloat(context.runtime,result); + return newFloat(context,result); } public static final double[] ERFC2_COEF = { @@ -571,7 +551,7 @@ public static RubyFloat erfc(ThreadContext context, IRubyObject recv, IRubyObjec if (value < 0) result = 2.0 - result; } } - return RubyFloat.newFloat(context.runtime,result); + return newFloat(context, result); } private static final double FACTORIAL[] = { @@ -680,8 +660,7 @@ public static RubyArray lgamma(ThreadContext context, IRubyObject recv, IRubyObj NemesLogGamma l = new NemesLogGamma(value); - return RubyArray.newArray(context.runtime, - newFloat(context, l.value), RubyInteger.int2fix(context.runtime, (int) l.sign)); + return newArray(context, 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/RubyMethod.java b/core/src/main/java/org/jruby/RubyMethod.java index 01dbf95ff82..f6b955a2cbb 100644 --- a/core/src/main/java/org/jruby/RubyMethod.java +++ b/core/src/main/java/org/jruby/RubyMethod.java @@ -54,6 +54,7 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newFixnum; import static org.jruby.ir.runtime.IRRuntimeHelpers.dupIfKeywordRestAtCallsite; @@ -277,11 +278,8 @@ public IRubyObject receiver(ThreadContext context) { @JRubyMethod public IRubyObject source_location(ThreadContext context) { String filename = getFilename(); - if (filename != null) { - return context.runtime.newArray(Convert.asString(context, filename), asFixnum(context, getLine())); - } - - return context.nil; + return filename == null ? context.nil : + newArray(context, Convert.asString(context, filename), asFixnum(context, getLine())); } @JRubyMethod diff --git a/core/src/main/java/org/jruby/RubyModule.java b/core/src/main/java/org/jruby/RubyModule.java index 8fa861b9411..b40f1d48a0a 100644 --- a/core/src/main/java/org/jruby/RubyModule.java +++ b/core/src/main/java/org/jruby/RubyModule.java @@ -140,9 +140,9 @@ import static org.jruby.anno.FrameField.SELF; import static org.jruby.anno.FrameField.VISIBILITY; import static org.jruby.api.Convert.*; -import static org.jruby.api.Create.newSymbol; +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.newArray; import static org.jruby.runtime.Visibility.MODULE_FUNCTION; import static org.jruby.runtime.Visibility.PRIVATE; import static org.jruby.runtime.Visibility.PROTECTED; @@ -220,17 +220,14 @@ void setClassIndex(ClassIndex classIndex) { @JRubyMethod public IRubyObject autoload(ThreadContext context, IRubyObject symbol, IRubyObject file) { - final Ruby runtime = context.runtime; - - final RubyString fileString = - StringSupport.checkEmbeddedNulls(runtime, RubyFile.get_path(context, file)); + final RubyString fileString = StringSupport.checkEmbeddedNulls(context.runtime, RubyFile.get_path(context, file)); - if (fileString.isEmpty()) throw runtime.newArgumentError("empty file name"); + if (fileString.isEmpty()) throw argumentError(context, "empty file name"); final String symbolStr = symbol.asJavaString(); if (!IdUtil.isValidConstantName(symbolStr)) { - throw runtime.newNameError("autoload must be constant name", symbolStr); + throw context.runtime.newNameError("autoload must be constant name", symbolStr); } IRubyObject existingValue = fetchConstant(symbolStr); @@ -1126,7 +1123,7 @@ public static Map newActivatedRefinementsMap() { @JRubyMethod(name = "used_modules", reads = SCOPE) public IRubyObject used_modules(ThreadContext context) { StaticScope cref = context.getCurrentStaticScope(); - RubyArray ary = context.runtime.newArray(); + var ary = newArray(context); while (cref != null) { RubyModule overlay; if ((overlay = cref.getOverlayModuleForRead()) != null && @@ -2750,12 +2747,10 @@ public void syncClassVariables(RubyModule other) { */ @JRubyMethod(name = "included_modules") public RubyArray included_modules(ThreadContext context) { - RubyArray ary = context.runtime.newArray(); + var ary = newArray(context); for (RubyModule p = getSuperClass(); p != null; p = p.getSuperClass()) { - if (p.isIncluded()) { - ary.append(context, p.getDelegate().getOrigin()); - } + if (p.isIncluded()) ary.append(context, p.getDelegate().getOrigin()); } return ary; @@ -2770,12 +2765,16 @@ public boolean hasPrepends() { */ @JRubyMethod(name = "ancestors") public RubyArray ancestors(ThreadContext context) { - return context.runtime.newArray(getAncestorList()); + return newArray(context, getAncestorList()); } - @Deprecated + /** + * @return "" + * @deprecated Use {@link RubyModule#ancestors(ThreadContext)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public RubyArray ancestors() { - return getRuntime().newArray(getAncestorList()); + return ancestors(getCurrentContext()); } public List getAncestorList() { @@ -3078,24 +3077,15 @@ public IRubyObject ruby2_keywords(ThreadContext context, IRubyObject[] args) { */ @JRubyMethod(name = "attr", rest = true, reads = VISIBILITY) public IRubyObject attr(ThreadContext context, IRubyObject[] args) { - Ruby runtime = context.runtime; - - if (args.length == 2 && (args[1] == runtime.getTrue() || args[1] == runtime.getFalse())) { - runtime.getWarnings().warnDeprecated(ID.OBSOLETE_ARGUMENT, "optional boolean argument is obsoleted"); + if (args.length == 2 && (args[1] == context.tru || args[1] == context.fals)) { + context.runtime.getWarnings().warnDeprecated(ID.OBSOLETE_ARGUMENT, "optional boolean argument is obsoleted"); boolean writeable = args[1].isTrue(); RubySymbol sym = TypeConverter.checkID(args[0]); addAccessor(context, sym, getCurrentVisibilityForDefineMethod(context), args[0].isTrue(), writeable); - RubyArray result; - if (writeable) { - ByteList writer = sym.getBytes().dup(); - writer.append('='); - result = RubyArray.newArray(runtime, sym, runtime.newSymbol(writer)); - } else { - result = RubyArray.newArray(runtime, sym); - } - - return result; + return writeable ? + newArray(context, sym, newSymbol(context, sym.getBytes().dup().append('='))) : + newArray(context, sym); } return attr_reader(context, args); @@ -3122,7 +3112,7 @@ public IRubyObject attr_reader(ThreadContext context, IRubyObject[] args) { addAccessor(context, sym, visibility, true, false); } - return context.runtime.newArray(result); + return newArray(context, result); } /** rb_mod_attr_writer @@ -3138,12 +3128,12 @@ public IRubyObject attr_writer(ThreadContext context, IRubyObject[] args) { RubySymbol sym = TypeConverter.checkID(args[i]); ByteList writer = sym.getBytes().dup(); writer.append('='); - result[i] = context.runtime.newSymbol(writer); + result[i] = newSymbol(context, writer); addAccessor(context, sym, visibility, false, true); } - return context.runtime.newArray(result); + return newArray(context, result); } @@ -3166,11 +3156,11 @@ public IRubyObject attr_accessor(ThreadContext context, IRubyObject[] args) { RubySymbol sym = TypeConverter.checkID(args[i]); ByteList reader = sym.getBytes().shallowDup(); - result[i*2] = context.runtime.newSymbol(reader); + result[i*2] = newSymbol(context, reader); ByteList writer = sym.getBytes().dup(); writer.append('='); - result[i*2+1] = context.runtime.newSymbol(writer); + result[i*2+1] = newSymbol(context, writer); // This is almost always already interned, since it will be called with a symbol in most cases // but when created from Java code, we might getService an argument that needs to be interned. @@ -3178,7 +3168,7 @@ public IRubyObject attr_accessor(ThreadContext context, IRubyObject[] args) { addAccessor(context, sym, visibility, true, true); } - return context.runtime.newArray(result); + return newArray(context, result); } /** @@ -3201,16 +3191,16 @@ public RubyArray instanceMethods(IRubyObject[] args, Visibility visibility, bool } public RubyArray instanceMethods(Visibility visibility, boolean includeSuper, boolean obj, boolean not) { - RubyArray ary = getRuntime().newArray(); + var context = getRuntime().getCurrentContext(); + var ary = newArray(context); - populateInstanceMethodNames(new HashSet<>(), ary, visibility, obj, not, includeSuper); + populateInstanceMethodNames(context, new HashSet<>(), ary, visibility, obj, not, includeSuper); return ary; } - final void populateInstanceMethodNames(final Set seen, final RubyArray ary, Visibility visibility, - boolean obj, boolean not, boolean recur) { - Ruby runtime = getRuntime(); + final void populateInstanceMethodNames(ThreadContext context, final Set seen, final RubyArray ary, + Visibility visibility, boolean obj, boolean not, boolean recur) { RubyModule mod = this; boolean prepended = false; @@ -3220,7 +3210,7 @@ final void populateInstanceMethodNames(final Set seen, final RubyArray a } for (; mod != null; mod = mod.getSuperClass()) { - mod.addMethodSymbols(runtime, seen, ary, not, visibility); + mod.addMethodSymbols(context.runtime, seen, ary, not, visibility); if (!prepended && mod.isIncluded()) continue; if (obj && mod.isSingleton()) continue; @@ -3334,7 +3324,7 @@ public RubyArray private_instance_methods(ThreadContext context, IRubyObject[] a @JRubyMethod(name = "undefined_instance_methods") public IRubyObject undefined_instance_method(ThreadContext context) { - var list = context.runtime.newArray(); + var list = newArray(context); getMethods().forEach((id, method) -> { if (method instanceof RefinedMarker) return; @@ -3444,7 +3434,7 @@ public IRubyObject mix(ThreadContext context, IRubyObject modArg) { for (Map.Entry entry : mod.methods.entrySet()) { if (methodLocation.getMethods().containsKey(entry.getKey())) { - throw context.runtime.newArgumentError("method would conflict - " + entry.getKey()); + throw argumentError(context, "method would conflict - " + entry.getKey()); } } @@ -3463,18 +3453,18 @@ public IRubyObject mix(ThreadContext context, IRubyObject modArg, IRubyObject ha for (Map.Entry entry : (Set>)methodNames.directEntrySet()) { String name = entry.getValue().toString(); - if (methods.containsKey(name)) throw context.runtime.newArgumentError("constant would conflict - " + name); + if (methods.containsKey(name)) throw argumentError(context, "constant would conflict - " + name); } for (Map.Entry entry : mod.methods.entrySet()) { if (methods.containsKey(entry.getKey())) { - throw context.runtime.newArgumentError("method would conflict - " + entry.getKey()); + throw argumentError(context, "method would conflict - " + entry.getKey()); } } for (Map.Entry entry : mod.methods.entrySet()) { String id = entry.getKey(); - IRubyObject mapped = methodNames.fastARef(context.runtime.newSymbol(id)); + IRubyObject mapped = methodNames.fastARef(newSymbol(context, id)); if (mapped == NEVER) { // unmapped } else if (mapped == context.nil) { @@ -3510,7 +3500,7 @@ public IRubyObject _public(ThreadContext context, IRubyObject[] args) { switch (args.length) { case 0: return context.nil; case 1: return args[0]; - default: return RubyArray.newArray(context.runtime, args); + default: return newArray(context, args); } } @@ -3531,7 +3521,7 @@ public IRubyObject _protected(ThreadContext context, IRubyObject[] args) { switch (args.length) { case 0: return context.nil; case 1: return args[0]; - default: return RubyArray.newArray(context.runtime, args); + default: return newArray(context, args); } } @@ -3552,7 +3542,7 @@ public IRubyObject _private(ThreadContext context, IRubyObject[] args) { switch (args.length) { case 0: return context.nil; case 1: return args[0]; - default: return RubyArray.newArray(context.runtime, args); + default: return newArray(context, args); } } @@ -3589,7 +3579,7 @@ public IRubyObject _module_function(ThreadContext context, IRubyObject[] args) { switch (args.length) { case 0: return context.nil; case 1: return args[0]; - default: return RubyArray.newArray(context.runtime, args); + default: return newArray(context, args); } } @@ -3787,7 +3777,7 @@ public IRubyObject module_eval(ThreadContext context, IRubyObject[] args, Block case 3: return module_eval(context, args[0], args[1], args[2], block); } - throw context.runtime.newArgumentError(args.length, 1, 3); + throw argumentError(context, args.length, 1, 3); } @JRubyMethod(name = {"module_exec", "class_exec"}, @@ -3847,7 +3837,7 @@ public static RubyModule unmarshalFrom(UnmarshalStream input) throws java.io.IOE public static RubyArray nesting(ThreadContext context, IRubyObject recv, Block block) { RubyModule object = context.runtime.getObject(); StaticScope scope = context.getCurrentStaticScope(); - var result = context.runtime.newArray(); + var result = newArray(context); for (StaticScope current = scope; current.getModule() != object; current = current.getPreviousCRefScope()) { result.append(context, current.getModule()); @@ -4111,24 +4101,18 @@ public IRubyObject remove_class_variable19(ThreadContext context, IRubyObject na @JRubyMethod(name = "class_variables") public RubyArray class_variables(ThreadContext context) { - Ruby runtime = context.runtime; - RubyArray ary = runtime.newArray(); - - Collection names = classVariablesCommon(true); - for (String name : names) { - ary.add(runtime.newSymbol(name)); + var ary = newArray(context); + for (String name : classVariablesCommon(true)) { + ary.add(newSymbol(context, name)); } return ary; } @JRubyMethod(name = "class_variables") public RubyArray class_variables(ThreadContext context, IRubyObject inherit) { - Ruby runtime = context.runtime; - RubyArray ary = runtime.newArray(); - - Collection names = classVariablesCommon(inherit.isTrue()); - for (String name : names) { - ary.add(runtime.newSymbol(name)); + var ary = newArray(context); + for (String name : classVariablesCommon(inherit.isTrue())) { + ary.add(newSymbol(context, name)); } return ary; } @@ -4252,28 +4236,22 @@ public IRubyObject const_get(ThreadContext context, IRubyObject arg0, IRubyObjec } private IRubyObject constGetCommon(ThreadContext context, IRubyObject symbol, boolean inherit) { - final Ruby runtime = context.runtime; - RubySymbol fullName = TypeConverter.checkID(symbol); String name = fullName.idString(); int sep = name.indexOf("::"); // symbol form does not allow :: - if (symbol instanceof RubySymbol && sep != -1) { - throw runtime.newNameError("wrong constant name ", fullName); - } + if (symbol instanceof RubySymbol && sep != -1) throw context.runtime.newNameError("wrong constant name ", fullName); RubyModule mod = this; if (sep == 0) { // ::Foo::Bar - mod = runtime.getObject(); + mod = context.runtime.getObject(); name = name.substring(2); } // Bare :: - if (name.isEmpty()) { - throw runtime.newNameError("wrong constant name ", fullName); - } + if (name.isEmpty()) throw context.runtime.newNameError("wrong constant name ", fullName); boolean firstConstant = true; while ( ( sep = name.indexOf("::") ) != -1 ) { @@ -4334,8 +4312,6 @@ public static boolean isValidConstantName(ByteList bytelist, int start, int end) @JRubyMethod(required = 1, optional = 1, checkArity = false) public IRubyObject const_source_location(ThreadContext context, IRubyObject[] args) { int argc = Arity.checkArgumentCount(context, args, 1, 2); - - final Ruby runtime = context.runtime; boolean inherit = argc == 1 || ( ! args[1].isNil() && args[1].isTrue() ); final IRubyObject symbol = args[0]; @@ -4349,21 +4325,17 @@ public IRubyObject const_source_location(ThreadContext context, IRubyObject[] ar int sep = name.indexOf("::"); // symbol form does not allow :: - if (symbol instanceof RubySymbol && sep != -1) { - throw runtime.newNameError("wrong constant name", symbol); - } + if (symbol instanceof RubySymbol && sep != -1) throw context.runtime.newNameError("wrong constant name", symbol); RubyModule mod = this; if (sep == 0) { // ::Foo::Bar - mod = runtime.getObject(); + mod = context.runtime.getObject(); name = name.substring(2); } // Bare :: - if (name.isEmpty()) { - throw runtime.newNameError("wrong constant name ", symbol); - } + if (name.isEmpty()) throw context.runtime.newNameError("wrong constant name ", symbol); while ( ( sep = name.indexOf("::") ) != -1 ) { final String segment = name.substring(0, sep); @@ -4376,10 +4348,9 @@ public IRubyObject const_source_location(ThreadContext context, IRubyObject[] ar SourceLocation location = mod.getConstantSourceLocation(validateConstant(name, symbol), inherit, inherit); if (location != null && location.getFile() != null) { - if (location.getFile().equals(BUILTIN_CONSTANT)) { - return RubyArray.newEmptyArray(context.runtime); - } - return RubyArray.newArray(context.runtime, runtime.newString(location.getFile()), asFixnum(context, location.getLine())); + return location.getFile().equals(BUILTIN_CONSTANT) ? + newEmptyArray(context) : + newArray(context, newString(context, location.getFile()), asFixnum(context, location.getLine())); } return context.nil; @@ -4609,11 +4580,10 @@ public final void setConstantVisibility(Ruby runtime, String name, boolean hidde @JRubyMethod(name = "refinements") public IRubyObject refinements(ThreadContext context) { - RubyArray refinementModules = newArray(context); + var refinementModules = newArray(context); + + refinements.forEach((key, value) -> refinementModules.append(context, value)); - refinements.forEach((key, value) -> { - refinementModules.append(context, value); - }); return refinementModules; } @@ -4628,20 +4598,18 @@ public IRubyObject refined_class(ThreadContext context) { } private IRubyObject getRefinedClassOrThrow(ThreadContext context, boolean nameIsTarget) { - if (!isRefinement()) { - String methodName = nameIsTarget ? "target" : "refined_class"; - String errMsg = RubyStringBuilder.str(context.runtime, - "undefined method '"+ methodName +"' for ", rubyBaseName(), - ":", getMetaClass()); - throw context.runtime.newNoMethodError(errMsg, this, "target", context.runtime.newEmptyArray()); - } - return refinedClass; + if (isRefinement()) return refinedClass; + + String methodName = nameIsTarget ? "target" : "refined_class"; + String errMsg = RubyStringBuilder.str(context.runtime, + "undefined method '"+ methodName +"' for ", rubyBaseName(), ":", getMetaClass()); + throw context.runtime.newNoMethodError(errMsg, this, "target", newEmptyArray(context)); } @JRubyMethod(name = "used_refinements") public IRubyObject used_refinements(ThreadContext context) { // TODO: not implemented - return RubyArray.newEmptyArray(context.runtime); + return newEmptyArray(context); } // @@ -6131,7 +6099,6 @@ public static IRubyObject import_methods(ThreadContext context, IRubyObject self Arity.checkArgumentCount(context, modules, 1, -1); RubyModule selfModule = (RubyModule) self; - RubyClass objectClass = context.runtime.getObject(); for (IRubyObject _module : modules) { RubyModule module = castAsModule(context, _module); @@ -6158,7 +6125,7 @@ private static void refinementImportMethodsIter(ThreadContext context, RubyModul DynamicMethod method = entry.getValue(); if (!(method instanceof AbstractIRMethod)) { - throw context.runtime.newArgumentError("Can't import method which is not defined with Ruby code: " + module.getName() + "#" + entry.getKey()); + throw argumentError(context, "Can't import method which is not defined with Ruby code: " + module.getName() + "#" + entry.getKey()); } DynamicMethod dup = entry.getValue().dup(); diff --git a/core/src/main/java/org/jruby/RubyNil.java b/core/src/main/java/org/jruby/RubyNil.java index 344d316cbee..a7de9d7bf41 100644 --- a/core/src/main/java/org/jruby/RubyNil.java +++ b/core/src/main/java/org/jruby/RubyNil.java @@ -47,6 +47,7 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newEmptyArray; /** * @@ -149,7 +150,7 @@ public static RubyString to_s(ThreadContext context, IRubyObject recv) { */ @JRubyMethod public static RubyArray to_a(ThreadContext context, IRubyObject recv) { - return context.runtime.newEmptyArray(); + return newEmptyArray(context); } @JRubyMethod diff --git a/core/src/main/java/org/jruby/RubyNumeric.java b/core/src/main/java/org/jruby/RubyNumeric.java index d4d97c3301e..5d5d9761c0e 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.Create.newArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.util.Numeric.f_abs; @@ -717,14 +718,13 @@ 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); + var context = getRuntime().getCurrentContext(); + if (metaClass == other.getMetaClass()) return newArray(context, other, this); IRubyObject cdr = RubyKernel.new_float(context, this); IRubyObject car = RubyKernel.new_float(context, other); - return runtime.newArray(car, cdr); + return newArray(context, car, cdr); } /** num_uplus @@ -821,7 +821,7 @@ public IRubyObject idiv(ThreadContext context, long other) { */ @JRubyMethod(name = "divmod") public IRubyObject divmod(ThreadContext context, IRubyObject other) { - return RubyArray.newArray(context.runtime, div(context, other), modulo(context, other)); + return newArray(context, div(context, other), modulo(context, other)); } /** num_fdiv */ @@ -1505,7 +1505,7 @@ public IRubyObject arg(ThreadContext context) { */ @JRubyMethod(name = {"rectangular", "rect"}) public IRubyObject rect(ThreadContext context) { - return context.runtime.newArray(this, RubyFixnum.zero(context.runtime)); + return newArray(context, this, RubyFixnum.zero(context.runtime)); } /** numeric_polar @@ -1513,7 +1513,7 @@ public IRubyObject rect(ThreadContext context) { */ @JRubyMethod(name = "polar") public IRubyObject polar(ThreadContext context) { - return context.runtime.newArray(f_abs(context, this), f_arg(context, this)); + return newArray(context, f_abs(context, this), f_arg(context, this)); } /** numeric_real diff --git a/core/src/main/java/org/jruby/RubyObjectSpace.java b/core/src/main/java/org/jruby/RubyObjectSpace.java index 26f29fc6826..7d7a92af176 100644 --- a/core/src/main/java/org/jruby/RubyObjectSpace.java +++ b/core/src/main/java/org/jruby/RubyObjectSpace.java @@ -50,6 +50,9 @@ import org.jruby.runtime.ThreadContext; import static org.jruby.api.Convert.*; +import static org.jruby.api.Create.newArray; +import static org.jruby.api.Create.newArrayNoCopy; +import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.Visibility.*; import static org.jruby.util.Inspector.inspectPrefix; @@ -85,8 +88,7 @@ public static IRubyObject define_finalizer(IRubyObject recv, IRubyObject[] args, @JRubyMethod(required = 1, optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject define_finalizer(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { - Ruby runtime = context.runtime; - + var runtime = context.runtime; int argc = Arity.checkArgumentCount(context, args, 1, 2); IRubyObject finalizer; @@ -94,7 +96,7 @@ public static IRubyObject define_finalizer(ThreadContext context, IRubyObject re if (argc == 2) { finalizer = args[1]; if (!finalizer.respondsTo("call")) { - throw runtime.newArgumentError("wrong type argument " + finalizer.getType() + " (should be callable)"); + throw argumentError(context, "wrong type argument " + finalizer.getType() + " (should be callable)"); } if (finalizer instanceof RubyMethod) { if (((RubyMethod) finalizer).getReceiver() == obj) referenceWarning(runtime); @@ -107,7 +109,7 @@ public static IRubyObject define_finalizer(ThreadContext context, IRubyObject re finalizer = runtime.newProc(Block.Type.PROC, block); } finalizer = runtime.getObjectSpace().addFinalizer(context, obj, finalizer); - return runtime.newArray(RubyFixnum.zero(runtime), finalizer); + return newArray(context, RubyFixnum.zero(runtime), finalizer); } private static void referenceWarning(Ruby runtime) { @@ -270,18 +272,12 @@ public IRubyObject key_p(ThreadContext context, IRubyObject key) { @JRubyMethod(name = "keys") public IRubyObject keys(ThreadContext context) { - return context.runtime.newArrayNoCopy( - getEntryStream() - .map(Map.Entry::getKey) - .toArray(IRubyObject[]::new)); + return newArrayNoCopy(context, getEntryStream().map(Map.Entry::getKey).toArray(IRubyObject[]::new)); } @JRubyMethod(name = "values") public IRubyObject values(ThreadContext context) { - return context.runtime.newArrayNoCopy( - getEntryStream() - .map(Map.Entry::getValue) - .toArray(IRubyObject[]::new)); + return newArrayNoCopy(context, getEntryStream().map(Map.Entry::getValue).toArray(IRubyObject[]::new)); } @JRubyMethod(name = {"each", "each_pair"}) diff --git a/core/src/main/java/org/jruby/RubyProc.java b/core/src/main/java/org/jruby/RubyProc.java index a584654bb1d..8d55e4b0c36 100644 --- a/core/src/main/java/org/jruby/RubyProc.java +++ b/core/src/main/java/org/jruby/RubyProc.java @@ -59,8 +59,7 @@ 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.runtime.ThreadContext.resetCallInfo; import static org.jruby.util.RubyStringBuilder.types; @@ -411,14 +410,14 @@ public RubyProc to_proc() { @JRubyMethod public IRubyObject source_location(ThreadContext context) { - if (file != null) return context.runtime.newArray(newString(context, file), asFixnum(context, line + 1 /*zero-based*/)); + if (file != null) return newArray(context, newString(context, file), asFixnum(context, line + 1 /*zero-based*/)); if (block != null) { Binding binding = block.getBinding(); // block+binding may exist for a core method, which will have a null filename if (binding.getFile() != null) { - return context.runtime.newArray( + return newArray(context, Convert.asString(context, binding.getFile()), asFixnum(context, binding.getLine() + 1 /*zero-based*/)); } @@ -445,8 +444,7 @@ public IRubyObject parameters(ThreadContext context, IRubyObject opts) { private IRubyObject parametersCommon(ThreadContext context, boolean isLambda) { BlockBody body = this.getBlock().getBody(); - return Helpers.argumentDescriptorsToParameters(context.runtime, - body.getArgumentDescriptors(), isLambda); + return Helpers.argumentDescriptorsToParameters(context, body.getArgumentDescriptors(), isLambda); } @JRubyMethod(name = "lambda?") diff --git a/core/src/main/java/org/jruby/RubyProcess.java b/core/src/main/java/org/jruby/RubyProcess.java index 927508136e9..49a6a44619b 100644 --- a/core/src/main/java/org/jruby/RubyProcess.java +++ b/core/src/main/java/org/jruby/RubyProcess.java @@ -1218,24 +1218,32 @@ public static IRubyObject wait(Ruby runtime, IRubyObject[] args) { @Deprecated public static IRubyObject waitall(IRubyObject recv) { - return waitall(recv.getRuntime()); + return waitall(recv.getRuntime().getCurrentContext()); } @JRubyMethod(name = "waitall", module = true, visibility = PRIVATE) public static IRubyObject waitall(ThreadContext context, IRubyObject recv) { - return waitall(context.runtime); + return waitall(context); } + + /** + * @param runtime + * @return "" + * @deprecated Use {@link RubyProcess#waitall(ThreadContext)} + */ + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject waitall(Ruby runtime) { - POSIX posix = runtime.getPosix(); - var results = runtime.newArray(); + return waitall(runtime.getCurrentContext()); + } + public static IRubyObject waitall(ThreadContext context) { + POSIX posix = context.runtime.getPosix(); + var results = newArray(context); int[] status = new int[1]; - var context = runtime.getCurrentContext(); - int result = pthreadKillable(context, ctx -> posix.wait(status)); while (result != -1) { - results.append(context, runtime.newArray(asFixnum(context, result), - RubyProcess.RubyStatus.newProcessStatus(runtime, status[0], result))); + results.append(context, newArray(context, asFixnum(context, result), + RubyProcess.RubyStatus.newProcessStatus(context.runtime, status[0], result))); result = pthreadKillable(context, ctx -> posix.wait(status)); } @@ -1381,9 +1389,7 @@ public static IRubyObject uid(Ruby runtime) { public static IRubyObject waitpid2(ThreadContext context, IRubyObject recv, IRubyObject[] args) { IRubyObject pid = waitpid(context, recv, args); - if (pid.isNil()) return pid; - - return context.runtime.newArray(pid, context.getLastExitStatus()); + return pid.isNil() ? context.nil : newArray(context, pid, context.getLastExitStatus()); } public static IRubyObject waitpid2(Ruby runtime, IRubyObject[] args) { @@ -1521,19 +1527,21 @@ public static IRubyObject getrlimit(ThreadContext context, IRubyObject recv, IRu return getrlimit(context.runtime, arg); } public static IRubyObject getrlimit(Ruby runtime, IRubyObject arg) { + var context = runtime.getCurrentContext(); + if (Platform.IS_WINDOWS) { throw runtime.newNotImplementedError("Process#getrlimit is not implemented on Windows"); } if (!runtime.getPosix().isNative()) { runtime.getWarnings().warn("Process#getrlimit not supported on this platform"); - RubyFixnum max = runtime.newFixnum(Long.MAX_VALUE); - return runtime.newArray(max, max); + RubyFixnum max = newFixnum(context, Long.MAX_VALUE); + return newArray(context, max, max); } RLimit rlimit = runtime.getPosix().getrlimit(rlimitResourceType(runtime, arg)); - return runtime.newArray(runtime.newFixnum(rlimit.rlimCur()), runtime.newFixnum(rlimit.rlimMax())); + return newArray(context, newFixnum(context, rlimit.rlimCur()), newFixnum(context, rlimit.rlimMax())); } @Deprecated diff --git a/core/src/main/java/org/jruby/RubyRange.java b/core/src/main/java/org/jruby/RubyRange.java index eb4d1c5a2a4..e6dfc5244e9 100644 --- a/core/src/main/java/org/jruby/RubyRange.java +++ b/core/src/main/java/org/jruby/RubyRange.java @@ -1153,13 +1153,11 @@ public IRubyObject first(ThreadContext context, IRubyObject arg) { if (arg == null) return begin; - final Ruby runtime = context.runtime; final int num = RubyNumeric.num2int(arg); - if (num < 0) { - throw context.runtime.newArgumentError("negative array size (or size too big)"); - } + if (num < 0) throw argumentError(context, "negative array size (or size too big)"); + // TODO (CON): this could be packed if we know there are at least num elements in range - final RubyArray result = runtime.newArray(num); + final var result = newArray(context, num); try { RubyEnumerable.callEach(context, sites(context).each, this, Signature.ONE_ARGUMENT, new BlockCallback() { int n = num; @@ -1198,7 +1196,7 @@ public IRubyObject count(ThreadContext context, Block block) { public IRubyObject minmax(ThreadContext context, Block block) { if (block.isGiven()) return Helpers.invokeSuper(context, this, context.runtime.getRange(), "minmax", NULL_ARRAY, block); - return RubyArray.newArray(context.runtime, callMethod("min"), callMethod("max")); + return newArray(context, callMethod("min"), callMethod("max")); } @JRubyMethod diff --git a/core/src/main/java/org/jruby/RubyRational.java b/core/src/main/java/org/jruby/RubyRational.java index 187969a482c..55066344829 100644 --- a/core/src/main/java/org/jruby/RubyRational.java +++ b/core/src/main/java/org/jruby/RubyRational.java @@ -53,6 +53,7 @@ import org.jruby.util.TypeConverter; import static org.jruby.api.Convert.*; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newString; import static org.jruby.api.Error.typeError; import static org.jruby.ast.util.ArgsUtil.hasExceptionOption; @@ -992,22 +993,21 @@ public IRubyObject eql_p(ThreadContext context, IRubyObject other) { */ @JRubyMethod(name = "coerce") public IRubyObject op_coerce(ThreadContext context, IRubyObject other) { - Ruby runtime = context.runtime; if (other instanceof RubyFixnum || other instanceof RubyBignum) { - return runtime.newArray(RubyRational.newRationalBang(context, getMetaClass(), other), this); + return newArray(context, RubyRational.newRationalBang(context, getMetaClass(), other), this); } else if (other instanceof RubyFloat) { - return runtime.newArray(other, r_to_f(context, this)); + return newArray(context, other, r_to_f(context, this)); } else if (other instanceof RubyRational) { - return runtime.newArray(other, this); + return newArray(context, other, this); } else if (other instanceof RubyComplex otherComplex) { if (k_exact_p(otherComplex.getImage()) && f_zero_p(context, otherComplex.getImage())) { - return runtime.newArray(RubyRational.newRationalBang(context, getMetaClass(), otherComplex.getReal()), this); + return newArray(context, RubyRational.newRationalBang(context, getMetaClass(), otherComplex.getReal()), this); } else { - return runtime.newArray(other, RubyComplex.newComplexCanonicalize(context, this)); + return newArray(context, other, RubyComplex.newComplexCanonicalize(context, this)); } } - throw typeError(context, str(runtime, other.getMetaClass(), " can't be coerced into ", getMetaClass())); + throw typeError(context, str(context.runtime, other.getMetaClass(), " can't be coerced into ", getMetaClass())); } @Override @@ -1031,7 +1031,7 @@ public IRubyObject op_divmod(ThreadContext context, IRubyObject other) { if (num2dbl(context, other) == 0.0) throw context.runtime.newZeroDivisionError(); IRubyObject val = f_floor(context, f_div(context, this, other)); - return context.runtime.newArray(val, f_sub(context, this, f_mul(context, other, val))); + return newArray(context, val, f_sub(context, this, f_mul(context, other, val))); } /** nurat_rem @@ -1435,7 +1435,7 @@ private RubyString inspectImpl(Ruby runtime) { */ @JRubyMethod(name = "marshal_dump", visibility = Visibility.PRIVATE) public IRubyObject marshal_dump(ThreadContext context) { - RubyArray dump = context.runtime.newArray(num, den); + var dump = newArray(context, num, den); if (hasVariables()) dump.syncVariables(this); return dump; } diff --git a/core/src/main/java/org/jruby/RubyRegexp.java b/core/src/main/java/org/jruby/RubyRegexp.java index 846e56ff2c0..363eda8b5bf 100755 --- a/core/src/main/java/org/jruby/RubyRegexp.java +++ b/core/src/main/java/org/jruby/RubyRegexp.java @@ -80,8 +80,7 @@ import org.jruby.util.collections.WeakValuedMap; 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.resetCallInfo; @@ -1539,14 +1538,14 @@ public String[] getNames() { @JRubyMethod public IRubyObject names(ThreadContext context) { check(); - final Ruby runtime = context.runtime; - if (pattern.numberOfNames() == 0) return runtime.newEmptyArray(); - RubyArray ary = RubyArray.newBlankArray(runtime, pattern.numberOfNames()); + if (pattern.numberOfNames() == 0) return newEmptyArray(context); + + var ary = RubyArray.newBlankArray(context.runtime, pattern.numberOfNames()); int index = 0; for (Iterator i = pattern.namedBackrefIterator(); i.hasNext();) { NameEntry e = i.next(); - RubyString name = RubyString.newStringShared(runtime, e.name, e.nameP, e.nameEnd - e.nameP, pattern.getEncoding()); + RubyString name = RubyString.newStringShared(context.runtime, e.name, e.nameP, e.nameEnd - e.nameP, pattern.getEncoding()); ary.storeInternal(context, index++, name); } return ary; diff --git a/core/src/main/java/org/jruby/RubyString.java b/core/src/main/java/org/jruby/RubyString.java index 8c4f12803e5..4c0a277111b 100644 --- a/core/src/main/java/org/jruby/RubyString.java +++ b/core/src/main/java/org/jruby/RubyString.java @@ -95,7 +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.Create.*; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.Visibility.PRIVATE; @@ -1357,7 +1357,7 @@ public IRubyObject op_plus(ThreadContext context, IRubyObject arg) { long len = (long) value.getRealSize() + str.value.getRealSize(); // we limit to int because ByteBuffer can only allocate int sizes - if (len > Integer.MAX_VALUE) throw context.runtime.newArgumentError("argument too big"); + if (len > Integer.MAX_VALUE) throw argumentError(context, "argument too big"); RubyString resultStr = newStringNoCopy(context.runtime, StringSupport.addByteLists(value, str.value), enc, CodeRangeSupport.codeRangeAnd(getCodeRange(), str.getCodeRange())); return resultStr; @@ -1772,12 +1772,8 @@ public IRubyObject initialize(ThreadContext context, IRubyObject arg0) { @JRubyMethod(name = "initialize", visibility = PRIVATE) public IRubyObject initialize(ThreadContext context, IRubyObject arg0, IRubyObject opts) { - Ruby runtime = context.runtime; - IRubyObject tmp = ArgsUtil.getOptionsArg(context.runtime, opts); - if (tmp.isNil()) { - throw runtime.newArgumentError(2, 1); - } + if (tmp.isNil()) throw context.runtime.newArgumentError(2, 1); return initialize(context, arg0, (RubyHash) tmp); } @@ -2940,16 +2936,12 @@ public RubyString crypt(ThreadContext context, IRubyObject other) { otherStr.modify(); otherStr.associateEncoding(ascii8bit); ByteList otherBL = otherStr.getByteList(); - if (otherBL.length() < 2) { - throw context.runtime.newArgumentError("salt too short (need >=2 bytes)"); - } + if (otherBL.length() < 2) throw argumentError(context, "salt too short (need >=2 bytes)"); POSIX posix = context.runtime.getPosix(); byte[] keyBytes = Arrays.copyOfRange(value.unsafeBytes(), value.begin(), value.begin() + value.realSize()); byte[] saltBytes = Arrays.copyOfRange(otherBL.unsafeBytes(), otherBL.begin(), otherBL.begin() + otherBL.realSize()); - if (saltBytes[0] == 0 || saltBytes[1] == 0) { - throw context.runtime.newArgumentError("salt too short (need >=2 bytes)"); - } + if (saltBytes[0] == 0 || saltBytes[1] == 0) throw argumentError(context, "salt too short (need >=2 bytes)"); byte[] cryptedString = posix.crypt(keyBytes, saltBytes); // We differ from MRI in that we do not process salt to make it work and we will // return any errors via errno. @@ -3918,7 +3910,7 @@ public IRubyObject bytesplice(ThreadContext context, IRubyObject[] args) { case 5: break; default: - throw context.runtime.newArgumentError("wrong number of arguments (given " + args.length + ", expected 2, 3, or 5)"); + throw argumentError(context, "wrong number of arguments (given " + args.length + ", expected 2, 3, or 5)"); } int[] beglen = {RubyNumeric.num2int(args[0]), RubyNumeric.num2int(args[1])}; @@ -4334,8 +4326,6 @@ final IRubyObject uptoCommon(ThreadContext context, IRubyObject arg, boolean exc } final IRubyObject uptoCommon(ThreadContext context, RubyString end, boolean excl, Block block, boolean asSymbol) { - final Ruby runtime = context.runtime; - Encoding enc = checkEncoding(end); boolean isAscii = scanForCodeRange() == CR_7BIT && end.scanForCodeRange() == CR_7BIT; if (value.getRealSize() == 1 && end.value.getRealSize() == 1 && isAscii) { @@ -4344,7 +4334,7 @@ final IRubyObject uptoCommon(ThreadContext context, RubyString end, boolean excl if (c > e || (excl && c == e)) return this; while (true) { ByteList s = RubyInteger.singleCharByteList(c); - block.yield(context, asSymbol ? runtime.newSymbol(s) : newStringShared(runtime, s, enc, CR_7BIT)); + block.yield(context, asSymbol ? newSymbol(context, s) : newStringShared(context.runtime, s, enc, CR_7BIT)); if (!excl && c == e) break; c++; @@ -4375,7 +4365,7 @@ final IRubyObject uptoCommon(ThreadContext context, RubyString end, boolean excl IRubyObject b = stringToInum(10); IRubyObject e = end.stringToInum(10); - RubyArray argsArr = RubyArray.newArray(runtime, RubyFixnum.newFixnum(runtime, value.length()), context.nil); + RubyArray argsArr = newArray(context, newFixnum(context, value.length()), context.nil); if (b instanceof RubyFixnum && e instanceof RubyFixnum) { long bl = RubyNumeric.fix2long(b); @@ -4383,11 +4373,11 @@ final IRubyObject uptoCommon(ThreadContext context, RubyString end, boolean excl while (bl <= el) { if (excl && bl == el) break; - argsArr.eltSetOk(1, RubyFixnum.newFixnum(runtime, bl)); + argsArr.eltSetOk(1, newFixnum(context, bl)); ByteList to = new ByteList(value.length() + 5); Sprintf.sprintf(to, "%.*d", argsArr); - RubyString str = RubyString.newStringNoCopy(runtime, to, USASCIIEncoding.INSTANCE, CR_7BIT); - block.yield(context, asSymbol ? runtime.newSymbol(str.toString()) : str); + RubyString str = RubyString.newStringNoCopy(context.runtime, to, USASCIIEncoding.INSTANCE, CR_7BIT); + block.yield(context, asSymbol ? newSymbol(context, str.toString()) : str); bl++; context.pollThreadEvents(); } @@ -4399,8 +4389,8 @@ final IRubyObject uptoCommon(ThreadContext context, RubyString end, boolean excl argsArr.eltSetOk(1, b); ByteList to = new ByteList(value.length() + 5); Sprintf.sprintf(to, "%.*d", argsArr); - RubyString str = RubyString.newStringNoCopy(runtime, to, USASCIIEncoding.INSTANCE, CR_7BIT); - block.yield(context, asSymbol ? runtime.newSymbol(str.toString()) : str); + RubyString str = RubyString.newStringNoCopy(context.runtime, to, USASCIIEncoding.INSTANCE, CR_7BIT); + block.yield(context, asSymbol ? newSymbol(context, str.toString()) : str); b = sites.succ.call(context, b, b); context.pollThreadEvents(); } @@ -4434,7 +4424,6 @@ private IRubyObject uptoCommonNoDigits(ThreadContext context, RubyString end, bo } final IRubyObject uptoEndless(ThreadContext context, Block block) { - Ruby runtime = context.runtime; StringSites sites = sites(context); CallSite succ = sites.succ; @@ -4443,26 +4432,26 @@ final IRubyObject uptoEndless(ThreadContext context, Block block) { if (isAscii && ASCII.isDigit(value.getUnsafeBytes()[value.getBegin()])) { IRubyObject b = stringToInum(10); - RubyArray argsArr = RubyArray.newArray(runtime, RubyFixnum.newFixnum(runtime, value.length()), context.nil); + RubyArray argsArr = newArray(context, newFixnum(context, value.length()), context.nil); ByteList to; if (b instanceof RubyFixnum) { long bl = RubyNumeric.fix2long(b); while (bl < RubyFixnum.MAX) { - argsArr.eltSetOk(1, RubyFixnum.newFixnum(runtime, bl)); + argsArr.eltSetOk(1, newFixnum(context, bl)); to = new ByteList(value.length() + 5); Sprintf.sprintf(to, "%.*d", argsArr); - current = RubyString.newStringNoCopy(runtime, to, USASCIIEncoding.INSTANCE, CR_7BIT); + current = RubyString.newStringNoCopy(context.runtime, to, USASCIIEncoding.INSTANCE, CR_7BIT); block.yield(context, current); bl++; context.pollThreadEvents(); } - argsArr.eltSetOk(1, RubyFixnum.newFixnum(runtime, bl)); + argsArr.eltSetOk(1, newFixnum(context, bl)); to = new ByteList(value.length() + 5); Sprintf.sprintf(to, "%.*d", argsArr); - current = RubyString.newStringNoCopy(runtime, to, USASCIIEncoding.INSTANCE, CR_7BIT); + current = RubyString.newStringNoCopy(context.runtime, to, USASCIIEncoding.INSTANCE, CR_7BIT); } } @@ -4471,7 +4460,7 @@ final IRubyObject uptoEndless(ThreadContext context, Block block) { block.yield(context, current); if (next == null) break; current = next.convertToString(); - if (current.getByteList().length() == 0) break; + if (current.getByteList().isEmpty()) break; context.pollThreadEvents(); } @@ -4494,11 +4483,10 @@ public IRubyObject chr(ThreadContext context) { @JRubyMethod public IRubyObject getbyte(ThreadContext context, IRubyObject index) { - Ruby runtime = context.runtime; int i = RubyNumeric.num2int(index); if (i < 0) i += value.getRealSize(); if (i < 0 || i >= value.getRealSize()) return context.nil; - return RubyFixnum.newFixnum(runtime, value.getUnsafeBytes()[value.getBegin() + i] & 0xff); + return newFixnum(context, value.getUnsafeBytes()[value.getBegin() + i] & 0xff); } @JRubyMethod @@ -4669,15 +4657,11 @@ public RubyArray split(RubyString delimiter, int limit) { // MRI: rb_str_split_m, overall structure private RubyArray splitCommon(ThreadContext context, IRubyObject pat, int lim) { - Ruby runtime = context.runtime; - // limit of 1 is the whole value. - if (lim == 1) { - return value.getRealSize() == 0 ? runtime.newArray() : runtime.newArray(this.strDup(runtime, runtime.getString())); - } + if (lim == 1) return value.isEmpty() ? newArray(context) : newArray(context, strDup(context.runtime, context.runtime.getString())); boolean limit = lim > 0; // We have an explicit number of values we want to split into. - RubyArray result; + RubyArray result; Object splitPattern = determineSplitPattern(context, pat); if (splitPattern == context.nil) { // AWK SPLIT @@ -4726,7 +4710,7 @@ private RubyArray splitCommon(ThreadContext context, IRubyObject pat, int lim) { } if (!limit && lim == 0) { - while (result.size() > 0 && ((RubyString) result.eltInternal(result.size() - 1)).value.getRealSize() == 0) { + while (!result.isEmpty() && ((RubyString) result.eltInternal(result.size() - 1)).value.getRealSize() == 0) { result.pop(context); } } @@ -4775,10 +4759,7 @@ private Object determineSplitPattern(ThreadContext context, IRubyObject pat) { * Call regexpSplit using a thread-local backref holder to avoid cross-thread pollution. */ private RubyArray regexSplit(ThreadContext context, RubyRegexp pattern, boolean limit, int lim) { - Ruby runtime = context.runtime; - - var result = runtime.newArray(); - + var result = newArray(context); int ptr = value.getBegin(); int len = value.getRealSize(); byte[] bytes = value.getUnsafeBytes(); @@ -4795,10 +4776,10 @@ private RubyArray regexSplit(ThreadContext context, RubyRegexp pattern, boolean end = match.begin(0); if (start == end && match.begin(0) == match.end(0)) { if (len == 0 && start != 0) { - result.append(context, newEmptyString(runtime, metaClass)); + result.append(context, newEmptyString(context.runtime, metaClass)); break; } else if (lastNull) { - result.append(context, makeSharedString(runtime, beg, StringSupport.length(enc, bytes, ptr + beg, ptr + len))); + result.append(context, makeSharedString(context.runtime, beg, StringSupport.length(enc, bytes, ptr + beg, ptr + len))); beg = start; } else { if ((ptr + start) == ptr + len) { @@ -4810,7 +4791,7 @@ private RubyArray regexSplit(ThreadContext context, RubyRegexp pattern, boolean continue; } } else { - result.append(context, makeSharedString(runtime, beg, end - beg)); + result.append(context, makeSharedString(context.runtime, beg, end - beg)); beg = match.end(0); start = beg; } @@ -4820,14 +4801,14 @@ private RubyArray regexSplit(ThreadContext context, RubyRegexp pattern, boolean if (limit && lim <= ++i) break; } - if (len > 0 && (limit || len > beg || lim < 0)) result.append(context, makeSharedString(runtime, beg, len - beg)); + if (len > 0 && (limit || len > beg || lim < 0)) result.append(context, makeSharedString(context.runtime, beg, len - beg)); return result; } // MRI: rb_str_split_m, when split_type = awk private RubyArray awkSplit(final ThreadContext context, boolean limit, int lim) { - RubyArray result = context.runtime.newArray(); + var result = newArray(context); byte[]bytes = value.getUnsafeBytes(); int p = value.getBegin(); @@ -4876,8 +4857,7 @@ private RubyArray awkSplit(final ThreadContext context, boolean limit, int lim) } private RubyArray asciiStringSplitOne(ThreadContext context, byte pat, boolean limit, int lim) { - Ruby runtime = context.runtime; - RubyArray result = runtime.newArray(); + var result = newArray(context); int realSize = value.getRealSize(); if (realSize == 0) return result; @@ -4891,16 +4871,16 @@ private RubyArray asciiStringSplitOne(ThreadContext context, byte pat, boolean l for (; index < realSize; index++) { if (bytes[begin + index] == pat) { - result.append(context, makeSharedString(runtime, startSegment, index - startSegment)); + result.append(context, makeSharedString(context.runtime, startSegment, index - startSegment)); startSegment = index + 1; if (limit && lim <= ++i) break; } } if (limit) { - result.append(context, makeSharedString(runtime, startSegment, realSize - startSegment)); + result.append(context, makeSharedString(context.runtime, startSegment, realSize - startSegment)); } else if (index > startSegment || lim < 0) { - result.append(context, makeSharedString(runtime, startSegment, index - startSegment)); + result.append(context, makeSharedString(context.runtime, startSegment, index - startSegment)); } return result; @@ -4908,9 +4888,7 @@ private RubyArray asciiStringSplitOne(ThreadContext context, byte pat, boolean l // Only for use with two clean 7BIT ASCII strings. private RubyArray asciiStringSplit(ThreadContext context, ByteList pattern, boolean limit, int lim) { - Ruby runtime = context.runtime; - - RubyArray result = runtime.newArray(); + var result = newArray(context); byte[] patternBytes = pattern.getUnsafeBytes(); int patternBegin = pattern.getBegin(); @@ -4924,13 +4902,13 @@ private RubyArray asciiStringSplit(ThreadContext context, ByteList pattern, bool int i = 1; while (p < realSize && (e = asciiIndexOf(bytes, begin, realSize, patternBytes, patternBegin, patternRealSize, p)) >= 0) { - result.append(context, makeSharedString(runtime, p, e - p)); + result.append(context, makeSharedString(context.runtime, p, e - p)); p = e + pattern.getRealSize(); if (limit && lim <= ++i) break; } if (realSize > 0 && (limit || realSize > p || lim < 0)) { - result.append(context, makeSharedString(runtime, p, realSize - p)); + result.append(context, makeSharedString(context.runtime, p, realSize - p)); } return result; @@ -4938,10 +4916,9 @@ private RubyArray asciiStringSplit(ThreadContext context, ByteList pattern, bool // MRI: rb_str_split_m, when split_type = string private RubyArray stringSplit(ThreadContext context, RubyString spat, boolean limit, int lim) { - Ruby runtime = context.runtime; mustnotBroken(context); - RubyArray result = runtime.newArray(); + var result = newArray(context); Encoding enc = checkEncoding(spat); ByteList pattern = spat.value; @@ -4962,13 +4939,13 @@ private RubyArray stringSplit(ThreadContext context, RubyString spat, boolean li p = t; continue; } - result.append(context, makeSharedString(runtime, p, e - p)); + result.append(context, makeSharedString(context.runtime, p, e - p)); p = e + pattern.getRealSize(); if (limit && lim <= ++i) break; } if (realSize > 0 && (limit || realSize > p || lim < 0)) { - result.append(context, makeSharedString(runtime, p, realSize - p)); + result.append(context, makeSharedString(context.runtime, p, realSize - p)); } return result; @@ -5096,11 +5073,11 @@ public IRubyObject scan(ThreadContext context, IRubyObject pat, Block block) { while ((result = scanOnce(context, str, pat, startp)) != context.nil) { last = prev; prev = startp[0]; - if (ary == null) ary = context.runtime.newArray(4); + if (ary == null) ary = newArray(context, 4); ary.append(context, result); } if (last >= 0) patternSearch(context, pat, str, last); - return ary == null ? context.runtime.newEmptyArray() : ary; + return ary == null ? newEmptyArray(context) : ary; } final byte[] pBytes = value.unsafeBytes(); @@ -5118,9 +5095,7 @@ public IRubyObject scan(ThreadContext context, IRubyObject pat, Block block) { // MRI: mustnot_broken private void mustnotBroken(ThreadContext context) { - if (scanForCodeRange() == CR_BROKEN) { - throw context.runtime.newArgumentError("invalid byte sequence in " + getEncoding()); - } + if (scanForCodeRange() == CR_BROKEN) throw argumentError(context, "invalid byte sequence in " + getEncoding()); } // MRI: scan_once @@ -5555,11 +5530,8 @@ public IRubyObject partition(ThreadContext context, IRubyObject arg, Block block if (pos < 0) return partitionMismatch(runtime); } - return RubyArray.newArrayNoCopy(runtime, new IRubyObject[] { - makeSharedString(runtime, 0, pos), - sep, - makeSharedString(runtime, pos + sep.value.getRealSize(), value.getRealSize() - pos - sep.value.getRealSize()) - }); + return newArrayNoCopy(context, makeSharedString(runtime, 0, pos), sep, + makeSharedString(runtime, pos + sep.value.getRealSize(), value.getRealSize() - pos - sep.value.getRealSize())); } private RubyArray partitionMismatch(Ruby runtime) { @@ -5569,12 +5541,11 @@ private RubyArray partitionMismatch(Ruby runtime) { @JRubyMethod(name = "rpartition", writes = BACKREF) public IRubyObject rpartition(ThreadContext context, IRubyObject arg) { - Ruby runtime = context.runtime; final int pos; final RubyString sep; if (arg instanceof RubyRegexp) { IRubyObject tmp = rindex(context, arg); - if (tmp.isNil()) return rpartitionMismatch(runtime); + if (tmp.isNil()) return rpartitionMismatch(context); pos = tmp.convertToInteger().getIntValue(); sep = (RubyString)RubyRegexp.nth_match(0, context.getLocalMatchOrNil()); } else { @@ -5582,21 +5553,18 @@ public IRubyObject rpartition(ThreadContext context, IRubyObject arg) { if (tmp.isNil()) throw typeError(context, "type mismatch: ", arg, " given"); sep = (RubyString)tmp; pos = StringSupport.rindex(value, StringSupport.strLengthFromRubyString(this, this.checkEncoding(sep)), StringSupport.strLengthFromRubyString(sep, this.checkEncoding(sep)), subLength(value.getRealSize()), sep, this.checkEncoding(sep)); - if (pos < 0) return rpartitionMismatch(runtime); + if (pos < 0) return rpartitionMismatch(context); } int beg = pos + sep.strLength(); int len = value.getRealSize(); - return RubyArray.newArrayNoCopy(runtime, new IRubyObject[] { - substrEnc(runtime, 0, pos), - sep, - substrEnc(runtime, beg, len) - }); + return newArrayNoCopy(context, substrEnc(context.runtime, 0, pos), sep, substrEnc(context.runtime, beg, len)); } - private IRubyObject rpartitionMismatch(Ruby runtime) { + private IRubyObject rpartitionMismatch(ThreadContext context) { final Encoding enc = getEncoding(); - return RubyArray.newArrayNoCopy(runtime, newEmptyString(runtime, enc), newEmptyString(runtime, enc), this.strDup(runtime, runtime.getString())); + return newArrayNoCopy(context, newEmptyString(context.runtime, enc), + newEmptyString(context.runtime, enc), this.strDup(context.runtime, context.runtime.getString())); } /** rb_str_chop / rb_str_chop_bang @@ -5907,7 +5875,7 @@ public IRubyObject strip_bang(ThreadContext context) { @JRubyMethod(name = "count") public IRubyObject count(ThreadContext context) { - throw context.runtime.newArgumentError("wrong number of arguments"); + throw argumentError(context, "wrong number of arguments"); } // MRI: rb_str_count, first half @@ -5973,7 +5941,7 @@ public IRubyObject count(ThreadContext context, IRubyObject[] args) { @JRubyMethod(name = "delete") public IRubyObject delete(ThreadContext context) { - throw context.runtime.newArgumentError("wrong number of arguments"); + throw argumentError(context, "wrong number of arguments"); } @JRubyMethod(name = "delete") @@ -5992,7 +5960,7 @@ public IRubyObject delete(ThreadContext context, IRubyObject[] args) { @JRubyMethod(name = "delete!") public IRubyObject delete_bang(ThreadContext context) { - throw context.runtime.newArgumentError("wrong number of arguments"); + throw argumentError(context, "wrong number of arguments"); } @JRubyMethod(name = "delete!") @@ -6337,7 +6305,6 @@ public IRubyObject codepoints(ThreadContext context, Block block) { // MRI: rb_str_enumerate_chars private IRubyObject enumerateChars(ThreadContext context, String name, Block block, boolean wantarray) { - Ruby runtime = context.runtime; RubyString str = this; int len, n; byte[] ptrBytes; @@ -6346,11 +6313,10 @@ private IRubyObject enumerateChars(ThreadContext context, String name, Block blo 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; } - } - else if (!wantarray) { + } else if (!wantarray) { return enumeratorizeWithSize(context, str, name, RubyString::eachCharSize); } @@ -6368,7 +6334,7 @@ else if (!wantarray) { case CR_7BIT: for (int i = 0; i < len; i += n) { n = StringSupport.encFastMBCLen(ptrBytes, ptr + i, ptr + len, enc); - IRubyObject substr = str.substr(runtime, i, n); + IRubyObject substr = str.substr(context.runtime, i, n); if (wantarray) ary[a++] = substr; else block.yield(context, substr); } @@ -6376,7 +6342,7 @@ else if (!wantarray) { default: for (int i = 0; i < len; i += n) { n = StringSupport.length(enc, ptrBytes, ptr + i, ptr + len); - IRubyObject substr = str.substr(runtime, i, n); + IRubyObject substr = str.substr(context.runtime, i, n); if (wantarray) ary[a++] = substr; else block.yield(context, substr); } @@ -6384,7 +6350,7 @@ else if (!wantarray) { assert !wantarray || a == ary.length; - return wantarray ? RubyArray.newArrayNoCopy(runtime, ary) : this; + return wantarray ? newArrayNoCopy(context, ary) : this; } // MRI: rb_str_enumerate_codepoints @@ -6401,8 +6367,7 @@ private IRubyObject enumerateCodepoints(ThreadContext context, String name, Bloc context.runtime.getWarnings().warning(ID.BLOCK_DEPRECATED, "passing a block to String#" + name + " is deprecated"); wantarray = false; } - } - else if (!wantarray) { + } else if (!wantarray) { return enumeratorizeWithSize(context, str, name, RubyString::codepointSize); } @@ -6413,7 +6378,7 @@ else if (!wantarray) { end = ptr + strByteList.getRealSize(); enc = EncodingUtils.getEncoding(strByteList); - RubyArray ary = wantarray ? RubyArray.newArray(context.runtime, str.strLength(strByteList, enc)) : null; + var ary = wantarray ? newArray(context, str.strLength(strByteList, enc)) : null; while (ptr < end) { int c = codePoint(context, enc, ptrBytes, ptr, end); @@ -6427,27 +6392,24 @@ else if (!wantarray) { } private IRubyObject enumerateBytes(ThreadContext context, String name, Block block, boolean wantarray) { - Ruby runtime = context.runtime; - 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; } - } - else if (!wantarray) { + } else if (!wantarray) { return enumeratorizeWithSize(context, this, name, RubyString::byteSize); } IRubyObject[] ary = wantarray ? new IRubyObject[value.getRealSize()] : null; // Check the length every iteration, since the block can modify this string. for (int i=0; i < value.getRealSize(); i++) { - RubyFixnum bite = RubyFixnum.newFixnum(runtime, value.get(i) & 0xFF); + RubyFixnum bite = newFixnum(context, value.get(i) & 0xFF); if (wantarray) ary[i] = bite; else block.yield(context, bite); } - return wantarray ? RubyArray.newArrayNoCopy(runtime, ary) : this; + return wantarray ? newArrayNoCopy(context, ary) : this; } /** @@ -6491,17 +6453,14 @@ private IRubyObject enumerateGraphemeClusters(ThreadContext context, String name Ruby runtime = context.runtime; RubyString str = this; Encoding enc = str.getEncoding(); - if (!enc.isUnicode()) { - return enumerateChars(context, name, block, wantarray); - } + if (!enc.isUnicode()) return enumerateChars(context, name, block, wantarray); if (block.isGiven()) { if (wantarray) { runtime.getWarnings().warning(ID.BLOCK_DEPRECATED, "passing a block to String#" + name + " is deprecated"); wantarray = false; } - } - else if (!wantarray) { + } else if (!wantarray) { return enumeratorizeWithSize(context, str, name, RubyString::eachGraphemeClusterSize); } @@ -6514,7 +6473,7 @@ else if (!wantarray) { int end = ptr + strByteList.getRealSize(); Matcher matcher = reg.matcher(ptrBytes, ptr, end); - RubyArray ary = wantarray ? RubyArray.newArray(runtime, end - ptr) : null; + RubyArray ary = wantarray ? newArray(context, end - ptr) : null; while (ptr < end) { int len = matcher.match(ptr, end, Option.DEFAULT); @@ -6674,8 +6633,8 @@ private static long unpackOffset(ThreadContext context, IRubyObject opt) { RubyHash options = (RubyHash) opt; long offset = 0; if (options.size() == 1) { - IRubyObject offsetArg = options.fastARef(context.runtime.newSymbol("offset")); - if (offsetArg == null) throw context.runtime.newArgumentError("unknown keyword: " + options.keys().first().inspect()); + IRubyObject offsetArg = options.fastARef(newSymbol(context, "offset")); + if (offsetArg == null) throw argumentError(context, "unknown keyword: " + options.keys().first().inspect()); offset = offsetArg.convertToInteger().getLongValue(); } // FIXME: keyword arg processing incomplete. We need a better system. @@ -6947,17 +6906,11 @@ public IRubyObject encStrScrub(ThreadContext context, Encoding enc, IRubyObject int rep; int replen; - if (block.isGiven()) { - if (repl != context.nil) { - throw runtime.newArgumentError("both of block and replacement given"); - } - } + if (block.isGiven() && repl != context.nil) throw argumentError(context, "both of block and replacement given"); if (cr == CR_7BIT || cr == CR_VALID) return context.nil; - if (repl != context.nil) { - repl = EncodingUtils.strCompatAndValid(context, repl, enc); - } + if (repl != context.nil) repl = EncodingUtils.strCompatAndValid(context, repl, enc); if (enc.isDummy()) return context.nil; diff --git a/core/src/main/java/org/jruby/RubyStruct.java b/core/src/main/java/org/jruby/RubyStruct.java index 571b826a81c..2decd6f8623 100644 --- a/core/src/main/java/org/jruby/RubyStruct.java +++ b/core/src/main/java/org/jruby/RubyStruct.java @@ -60,8 +60,7 @@ import static org.jruby.RubyEnumerator.enumeratorizeWithSize; import static org.jruby.api.Convert.*; -import static org.jruby.api.Create.newString; -import static org.jruby.api.Create.newSymbol; +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.Helpers.invokedynamic; @@ -243,12 +242,11 @@ public static RubyClass newInstance(IRubyObject recv, IRubyObject[] args, Block */ @JRubyMethod(name = "new", rest = true, checkArity = false, meta = true, keywords = true) public static RubyClass newInstance(ThreadContext context, IRubyObject recv, IRubyObject[] args, Block block) { - Ruby runtime = context.runtime; int argc = Arity.checkArgumentCount(context, args, 0, -1); String name = null; boolean nilName = false; - var member = runtime.newArray(); + var member = newArray(context); IRubyObject keywordInitValue = context.nil; if (argc > 0) { @@ -256,7 +254,7 @@ public static RubyClass newInstance(ThreadContext context, IRubyObject recv, IRu if (!firstArgAsString.isNil()) { RubySymbol nameSym = ((RubyString)firstArgAsString).intern(); if (!nameSym.validConstantName()) { - throw runtime.newNameError(IDENTIFIER_NEEDS_TO_BE_CONSTANT, recv, nameSym.toString()); + throw context.runtime.newNameError(IDENTIFIER_NEEDS_TO_BE_CONSTANT, recv, nameSym.toString()); } name = nameSym.idString(); } else if (args[0].isNil()) { @@ -277,7 +275,7 @@ public static RubyClass newInstance(ThreadContext context, IRubyObject recv, IRu if (arg instanceof RubySymbol sym1) { sym = sym1; } else if (arg instanceof RubyString) { - sym = runtime.newSymbol(arg.convertToString().getByteList()); + sym = newSymbol(context, arg.convertToString().getByteList()); } else { sym = newSymbol(context, arg.asJavaString()); } @@ -291,14 +289,14 @@ public static RubyClass newInstance(ThreadContext context, IRubyObject recv, IRu RubyClass superClass = (RubyClass)recv; if (name == null || nilName) { - newStruct = RubyClass.newClass(runtime, superClass); + newStruct = RubyClass.newClass(context.runtime, superClass); newStruct.setAllocator(RubyStruct::new); newStruct.makeMetaClass(superClass.metaClass); newStruct.inherit(superClass); } else { IRubyObject type = superClass.getConstantAt(name); if (type != null) { - runtime.getWarnings().warn(ID.STRUCT_CONSTANT_REDEFINED, context.getFile(), context.getLine(), "redefining constant " + type); + context.runtime.getWarnings().warn(ID.STRUCT_CONSTANT_REDEFINED, context.getFile(), context.getLine(), "redefining constant " + type); superClass.deleteConstant(name); } newStruct = superClass.defineClassUnder(name, superClass, RubyStruct::new); @@ -574,11 +572,9 @@ public RubyArray members() { @JRubyMethod public IRubyObject select(ThreadContext context, Block block) { - if (!block.isGiven()) { - return enumeratorizeWithSize(context, this, "select", RubyStruct::size); - } + if (!block.isGiven()) return enumeratorizeWithSize(context, this, "select", RubyStruct::size); - RubyArray array = RubyArray.newArray(context.runtime); + var array = newArray(context); for (int i = 0; i < values.length; i++) { if (block.yield(context, values[i]).isTrue()) { @@ -713,7 +709,7 @@ public RubyString inspect(final ThreadContext context) { @JRubyMethod(name = {"to_a", "deconstruct", "values"}) @Override public RubyArray to_a(ThreadContext context) { - return context.runtime.newArray(values); + return newArray(context, values); } @Deprecated @@ -773,10 +769,10 @@ public IRubyObject each(final ThreadContext context, final Block block) { } public IRubyObject each_pairInternal(ThreadContext context, Block block) { - RubyArray member = __member__(); + var member = __member__(); for (int i = 0; i < values.length; i++) { - block.yield(context, RubyArray.newArray(context.runtime, member.eltInternal(i), values[i])); + block.yield(context, newArray(context, member.eltInternal(i), values[i])); } return this; @@ -843,12 +839,20 @@ private IRubyObject aset(int idx, IRubyObject value) { return values[newIdx] = value; } - @JRubyMethod(rest = true) + /** + * @param args + * @return "" + * @deprecated Use {@link RubyStruct#values_at(ThreadContext, IRubyObject[])} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public IRubyObject values_at(IRubyObject[] args) { - final Ruby runtime = metaClass.runtime; - var context = runtime.getCurrentContext(); + return values_at(getCurrentContext(), args); + } + + @JRubyMethod(rest = true) + public IRubyObject values_at(ThreadContext context, IRubyObject[] args) { final int olen = values.length; - RubyArray result = getRuntime().newArray(args.length); + var result = newArray(context, args.length); for (int i = 0; i < args.length; i++) { final IRubyObject arg = args[i]; @@ -858,8 +862,7 @@ public IRubyObject values_at(IRubyObject[] args) { } final int [] begLen = new int[2]; - if (arg instanceof RubyRange && - RubyRange.rangeBeginLength(runtime.getCurrentContext(), args[i], olen, begLen, 1).isTrue()) { + if (arg instanceof RubyRange && RubyRange.rangeBeginLength(context, args[i], olen, begLen, 1).isTrue()) { final int beg = begLen[0]; final int len = begLen[1]; int end = Math.min(olen, beg + len); @@ -869,7 +872,7 @@ public IRubyObject values_at(IRubyObject[] args) { } if ( beg + len > j ) { IRubyObject [] tmp = new IRubyObject[beg + len - j]; - Helpers.fillNil(tmp, runtime); + Helpers.fillNil(tmp, context.runtime); result.push(context, tmp); } continue; @@ -1077,10 +1080,10 @@ private static StructSites sites(ThreadContext context) { return context.sites.Struct; } - @Deprecated + @Deprecated(since = "9.4-") @Override public RubyArray to_a() { - return getRuntime().newArray(values); + return to_a(getCurrentContext()); } } diff --git a/core/src/main/java/org/jruby/RubySymbol.java b/core/src/main/java/org/jruby/RubySymbol.java index 5a8d4c2ef91..2d9537a9c9e 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.newArray; import static org.jruby.api.Create.newString; import static org.jruby.api.Error.typeError; import static org.jruby.util.RubyStringBuilder.str; @@ -1416,7 +1417,7 @@ public RubyArray all_symbols() { public RubyArray all_symbols(ThreadContext context) { SymbolEntry[] table = this.symbolTable; - RubyArray array = runtime.newArray(this.size); + var array = newArray(context, size); for (int i = table.length; --i >= 0; ) { for (SymbolEntry e = table[i]; e != null; e = e.next) { diff --git a/core/src/main/java/org/jruby/RubyThreadGroup.java b/core/src/main/java/org/jruby/RubyThreadGroup.java index fe3978078a0..38682fdd31e 100644 --- a/core/src/main/java/org/jruby/RubyThreadGroup.java +++ b/core/src/main/java/org/jruby/RubyThreadGroup.java @@ -42,6 +42,7 @@ import org.jruby.util.collections.WeakHashSet; import static org.jruby.api.Convert.asBoolean; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Error.typeError; /** @@ -145,7 +146,7 @@ public IRubyObject list(Block block) { @JRubyMethod public IRubyObject list(ThreadContext context, Block block) { - var ary = RubyArray.newArray(context.runtime); + var ary = newArray(context); synchronized (rubyThreadList) { for (RubyThread thread : rubyThreadList) { if (thread != null) ary.append(context, thread); diff --git a/core/src/main/java/org/jruby/RubyTime.java b/core/src/main/java/org/jruby/RubyTime.java index 8637d1f9a22..a57a449149c 100644 --- a/core/src/main/java/org/jruby/RubyTime.java +++ b/core/src/main/java/org/jruby/RubyTime.java @@ -83,7 +83,7 @@ import static org.jruby.RubyComparable.invcmp; import static org.jruby.api.Convert.*; -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.Helpers.invokedynamic; @@ -574,9 +574,18 @@ public IRubyObject initialize_copy(IRubyObject original) { return this; } - @JRubyMethod(name = {"gmtime", "utc", "to_time"}) + /** + * @return "" + * @deprecated Use {@link RubyTime#gmtime(ThreadContext)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public RubyTime gmtime() { - return adjustTimeZone(getRuntime(), DateTimeZone.UTC, false); + return gmtime(getCurrentContext()); + } + + @JRubyMethod(name = {"gmtime", "utc", "to_time"}) + public RubyTime gmtime(ThreadContext context) { + return adjustTimeZone(context, DateTimeZone.UTC, false); } public final RubyTime localtime() { @@ -585,26 +594,22 @@ public final RubyTime localtime() { @JRubyMethod(name = "localtime") public RubyTime localtime(ThreadContext context) { - return adjustTimeZone(context.runtime, getLocalTimeZone(context.runtime), false); + return adjustTimeZone(context, getLocalTimeZone(context.runtime), false); } @JRubyMethod(name = "localtime") public RubyTime localtime(ThreadContext context, IRubyObject arg) { - Ruby runtime = context.runtime; - final DateTimeZone zone = getTimeZoneFromUtcOffset(context, arg); - if (zone == null) throw invalidUTCOffset(runtime); + if (zone == null) throw invalidUTCOffset(context.runtime); - return adjustTimeZone(runtime, zone, true); + return adjustTimeZone(context, zone, true); } - private RubyTime adjustTimeZone(Ruby runtime, final DateTimeZone zone, boolean isTzRelative) { + private RubyTime adjustTimeZone(ThreadContext context, final DateTimeZone zone, boolean isTzRelative) { boolean zoneOk = zone.equals(dt.getZone()); if (zoneOk && isTzRelative == this.isTzRelative) return this; - if (isFrozen()) { - throw runtime.newFrozenError("Time", this); - } + if (isFrozen()) throw context.runtime.newFrozenError("Time", this); if (!zoneOk) dt = dt.withZone(zone); setIsTzRelative(isTzRelative); return this; @@ -640,11 +645,7 @@ public RubyTime getlocal(ThreadContext context) { @JRubyMethod(name = "getlocal") public RubyTime getlocal(ThreadContext context, IRubyObject off) { - Ruby runtime = context.runtime; - - if (off == context.nil) { - return newTime(runtime, dt.withZone(getLocalTimeZone(runtime)), nsec); - } + if (off == context.nil) return newTime(context.runtime, dt.withZone(getLocalTimeZone(context.runtime)), nsec); IRubyObject zone = off; DateTimeZone dtz; @@ -656,14 +657,14 @@ public RubyTime getlocal(ThreadContext context, IRubyObject off) { if ((dtz = getTimeZoneFromUtcOffset(context, off)) == null) { zone = findTimezone(context, zone); RubyTime t = (RubyTime) dup(); - if (!zoneLocalTime(context, zone, t)) throw invalidUTCOffset(runtime, zone); + if (!zoneLocalTime(context, zone, t)) throw invalidUTCOffset(context.runtime, zone); return t; } else if (dtz == DateTimeZone.UTC) { - return ((RubyTime) dup()).gmtime(); + return ((RubyTime) dup()).gmtime(context); } - return ((RubyTime) dup()).adjustTimeZone(runtime, dtz, false); + return ((RubyTime) dup()).adjustTimeZone(context, dtz, false); } @Deprecated @@ -909,8 +910,7 @@ public String toString() { @JRubyMethod @Override public RubyArray to_a(ThreadContext context) { - return RubyArray.newArrayNoCopy( - context.runtime, + return newArrayNoCopy(context, sec(), min(), hour(), mday(), month(), year(), wday(), yday(), isdst(), @@ -1499,11 +1499,9 @@ private static IRubyObject atOpts(ThreadContext context, IRubyObject recv, IRuby if (arg2.isNil() && (arg3 == null || arg3.isNil())) { RubyTime time = at1(context, recv, arg1); - time = time.gmtime(); + time = time.gmtime(context); - if (!zone.isNil()) { - time = timeZoneLocal(context, zone, time); - } + if (!zone.isNil()) time = timeZoneLocal(context, zone, time); return time; } @@ -1638,7 +1636,7 @@ private static RubyTime atMulti(ThreadContext context, RubyClass recv, IRubyObje time.setNSec(nanosecs % 1000000); if (!zone.isNil()) { - time = timeZoneLocal(context, zone, time.gmtime()); + time = timeZoneLocal(context, zone, time.gmtime(context)); } return time; @@ -2214,10 +2212,10 @@ public static RubyTime timeZoneLocal(ThreadContext context, IRubyObject off, Rub if (!zoneLocalTime(context, zone, time)) throw invalidUTCOffset(context.runtime, zone); return time; } else if (dtz == DateTimeZone.UTC) { - return time.gmtime(); + return time.gmtime(context); } - time.adjustTimeZone(context.runtime, dtz, false); + time.adjustTimeZone(context, dtz, false); return time; } @@ -2228,7 +2226,7 @@ private static long extractTime(ThreadContext context, IRubyObject time) { if (time instanceof RubyTime) { return ((RubyTime) time).getDateTime().withZoneRetainFields(DateTimeZone.UTC).getMillis(); } else if (time instanceof RubyStruct) { - t = ((RubyStruct) time).aref(context.runtime.newSymbol("to_i")).convertToInteger().getLongValue(); + t = ((RubyStruct) time).aref(newSymbol(context, "to_i")).convertToInteger().getLongValue(); } else { t = time.callMethod(context, "to_i").convertToInteger().getLongValue(); } diff --git a/core/src/main/java/org/jruby/api/Create.java b/core/src/main/java/org/jruby/api/Create.java index 1e191b11936..9647cfecc82 100644 --- a/core/src/main/java/org/jruby/api/Create.java +++ b/core/src/main/java/org/jruby/api/Create.java @@ -7,27 +7,26 @@ import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; +import java.util.List; + import static org.jruby.RubyArray.checkLength; import static org.jruby.runtime.Helpers.validateBufferLength; public class Create { /** - * Create a new array that is sized with the specificed length. + * Create a new array with the default allocation size * * @param context the current thread context - * @param length the size to allocate for the array * @return the new array */ - public static RubyArray newArray(ThreadContext context, int length) { - var values = IRubyObject.array(validateBufferLength(context.runtime, length)); - Helpers.fillNil(values, 0, length, context.runtime); - return new RubyArray<>(context.runtime, values, 0, 0); + // mri: rb_ary_new2 + public static RubyArray newArray(ThreadContext context) { + return RubyArray.newArray(context.runtime); } /** - * Create a new array with the allocation size specified by the provided length. - * This method will additionally make sure the long value will fit into an - * int size. + * Create a new array with the allocation size specified by the provided length filled with nil. + * This method will additionally make sure the long value will fit into an int size. * * @param context the current thread context * @param length the size to allocate for the array @@ -36,9 +35,80 @@ public static RubyArray newArray(ThreadContext context, int length) { // mri: rb_ary_new2 public static RubyArray newArray(ThreadContext context, long length) { checkLength(context, length); + // FIXME: This should be newBlankArray but things go very wrong in a tough to figure out where sort of way. return RubyArray.newArray(context.runtime, (int)length); } + /** + * Create a new array with a single element. + * + * @param context the current thread context + * @param one the lone element in the array + * @return the new array + */ + public static RubyArray newArray(ThreadContext context, IRubyObject one) { + return RubyArray.newArray(context.runtime, one); + } + + /** + * Create a new array with two elements. + * + * @param context the current thread context + * @param one the lone element in the array + * @param two the lone element in the array + * @return the new array + */ + // mri: rb_assoc_new + public static RubyArray newArray(ThreadContext context, IRubyObject one, IRubyObject two) { + return RubyArray.newArray(context.runtime, one, two); + } + + /** + * Create a new array with many elements. + * + * @param context the current thread context + * @param elements the elements of the array + * @return the new array + */ + public static RubyArray newArray(ThreadContext context, IRubyObject... elements) { + return RubyArray.newArray(context.runtime, elements); + } + + /** + * Create a new array with many elements from a java.util.List. + * + * @param context the current thread context + * @param list the elements of the array + * @return the new array + */ + public static RubyArray newArray(ThreadContext context, List list) { + return RubyArray.newArray(context.runtime, list); + } + + /** + * Create a new array with many elements but do not copy the incoming array of elements.. + * + * @param context the current thread context + * @param elements the elements of the array + * @return the new array + */ + public static RubyArray newArrayNoCopy(ThreadContext context, IRubyObject... elements) { + return RubyArray.newArrayNoCopy(context.runtime, elements); + } + + + /** + * Create a new array which is intended to be empty for its entire lifetime. + * It can still grow but the intention is you think it won't grow (or cannot). + * + * @param context the current thread context + * @return the new array + */ + // mri: rb_ary_new2 + public static RubyArray newEmptyArray(ThreadContext context) { + return RubyArray.newEmptyArray(context.runtime); + } + /** * Creates a new RubyString from the provided int. * @@ -121,10 +191,22 @@ public static RubyString newString(ThreadContext context, String string) { * Creates a new RubySymbol from the provided java String. * * @param context the current thread context - * @param string the contents to become a string + * @param string the contents to become a symbol * @return the new RubyString */ public static RubySymbol newSymbol(ThreadContext context, String string) { return context.runtime.newSymbol(string); } + + /** + * Creates a new RubySymbol from the provided java String. + * + * @param context the current thread context + * @param bytelist the contents to become a symbol + * @return the new RubyString + */ + public static RubySymbol newSymbol(ThreadContext context, ByteList bytelist) { + return context.runtime.newSymbol(bytelist); + } + } diff --git a/core/src/main/java/org/jruby/embed/variable/Argv.java b/core/src/main/java/org/jruby/embed/variable/Argv.java index 0040990cbbe..bac5c039c48 100644 --- a/core/src/main/java/org/jruby/embed/variable/Argv.java +++ b/core/src/main/java/org/jruby/embed/variable/Argv.java @@ -117,7 +117,7 @@ public static boolean isValidName(Object name) { public synchronized void inject() { final Ruby runtime = getRuntime(); - final RubyArray argv = RubyArray.newArray(runtime); + final var argv = RubyArray.newArray(runtime); if ( javaObject instanceof Collection ) { argv.addAll( (Collection) javaObject ); } 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 16932a5cb44..31e221f1dcc 100644 --- a/core/src/main/java/org/jruby/ext/bigdecimal/RubyBigDecimal.java +++ b/core/src/main/java/org/jruby/ext/bigdecimal/RubyBigDecimal.java @@ -1725,7 +1725,7 @@ public IRubyObject coerce(IRubyObject other) { @JRubyMethod public RubyArray coerce(ThreadContext context, IRubyObject other) { - return context.runtime.newArray(getVpValue(context, other, true), this); + return newArray(context, getVpValue(context, other, true), this); } @Override @@ -1771,15 +1771,15 @@ public IRubyObject divmod(ThreadContext context, IRubyObject other) { if (val == null) return callCoerced(context, sites(context).divmod, other, true); if (isNaN() || val.isNaN() || isInfinity() && val.isInfinity()) { - return RubyArray.newArray(runtime, getNaN(context), getNaN(context)); + return newArray(context, 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(context, sign), getNaN(context)); + return newArray(context, getInfinity(context, sign), getNaN(context)); } - 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())); + if (val.isInfinity()) return newArray(context, getZero(context, val.value.signum()), this); + if (isZero()) return newArray(context, getZero(context, value.signum()), getZero(context, value.signum())); // Java and MRI definitions of divmod are different. BigDecimal[] divmod = value.divideAndRemainder(val.value); @@ -1792,7 +1792,7 @@ public IRubyObject divmod(ThreadContext context, IRubyObject other) { mod = mod.add(val.value); } - return RubyArray.newArray(runtime, new RubyBigDecimal(runtime, div), new RubyBigDecimal(runtime, mod)); + return newArray(context, new RubyBigDecimal(runtime, div), new RubyBigDecimal(runtime, mod)); } @Deprecated @@ -1894,7 +1894,7 @@ public IRubyObject scale(ThreadContext context) { @JRubyMethod public RubyArray precision_scale(ThreadContext context) { int [] ary = getPrecisionScale(); - return context.runtime.newArray(newFixnum(context, ary[0]), newFixnum(context, ary[1])); + return newArray(context, newFixnum(context, ary[0]), newFixnum(context, ary[1])); } private int [] getPrecisionScale() { @@ -1947,7 +1947,7 @@ private int getPrec() { @JRubyMethod public IRubyObject precs(ThreadContext context) { context.runtime.getWarnings().warn(IRubyWarnings.ID.DEPRECATED_METHOD, "BigDecimal#precs is deprecated and will be removed in the future; use BigDecimal#precision instead."); - return RubyArray.newArray(context.runtime, + return newArray(context, asFixnum(context, getSignificantDigits().length()), asFixnum(context, ((getAllDigits().length() / 4) + 1) * 4)); } diff --git a/core/src/main/java/org/jruby/ext/coverage/CoverageModule.java b/core/src/main/java/org/jruby/ext/coverage/CoverageModule.java index b72ec3570a1..568bdcd6637 100644 --- a/core/src/main/java/org/jruby/ext/coverage/CoverageModule.java +++ b/core/src/main/java/org/jruby/ext/coverage/CoverageModule.java @@ -42,8 +42,7 @@ import org.jruby.util.collections.IntList; import static org.jruby.api.Convert.castAsSymbol; -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.typeError; import static org.jruby.ext.coverage.CoverageData.CoverageDataState.*; import static org.jruby.ext.coverage.CoverageData.EVAL; @@ -246,7 +245,7 @@ private static IRubyObject convertCoverageToRuby(ThreadContext context, Map) arrParam; final int count = arr.getLength(); long off = getOffset(offset); diff --git a/core/src/main/java/org/jruby/ext/ffi/Struct.java b/core/src/main/java/org/jruby/ext/ffi/Struct.java index 246c454c8c4..fef7e1f8c2f 100644 --- a/core/src/main/java/org/jruby/ext/ffi/Struct.java +++ b/core/src/main/java/org/jruby/ext/ffi/Struct.java @@ -270,12 +270,12 @@ public static IRubyObject offset_of(ThreadContext context, IRubyObject structCla @JRubyMethod(name = "[]") public IRubyObject getFieldValue(ThreadContext context, IRubyObject fieldName) { - return layout.getMember(context.runtime, fieldName).get(context, this, getMemory()); + return layout.getMember(context, fieldName).get(context, this, getMemory()); } @JRubyMethod(name = "[]=") public IRubyObject setFieldValue(ThreadContext context, IRubyObject fieldName, IRubyObject fieldValue) { - layout.getMember(context.runtime, fieldName).put(context, this, getMemory(), fieldValue); + layout.getMember(context, fieldName).put(context, this, getMemory(), fieldValue); return fieldValue; } diff --git a/core/src/main/java/org/jruby/ext/ffi/StructLayout.java b/core/src/main/java/org/jruby/ext/ffi/StructLayout.java index 1c107d5dee5..e0a67b46799 100644 --- a/core/src/main/java/org/jruby/ext/ffi/StructLayout.java +++ b/core/src/main/java/org/jruby/ext/ffi/StructLayout.java @@ -61,7 +61,9 @@ import org.jruby.util.ByteList; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; 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.*; @@ -260,7 +262,7 @@ public IRubyObject put(ThreadContext context, IRubyObject ptr, IRubyObject name, */ @JRubyMethod(name = "members") public IRubyObject members(ThreadContext context) { - var mbrs = RubyArray.newArray(context.runtime, fieldNames.size()); + var mbrs = newArray(context, fieldNames.size()); for (IRubyObject name : fieldNames) { mbrs.append(context, name); } @@ -274,15 +276,10 @@ public IRubyObject members(ThreadContext context) { */ @JRubyMethod(name = "offsets") public IRubyObject offsets(ThreadContext context) { - var offsets = RubyArray.newArray(context.runtime); + var offsets = newArray(context, fieldNames.size()); - for (IRubyObject name : fieldNames) { - var offset = RubyArray.newArray(context.runtime); - // Assemble a [ :name, offset ] array - - offset.append(context, name); - offset.append(context, newFixnum(context, getMember(context.runtime, name).offset)); - offsets.append(context, offset); + for (IRubyObject name : fieldNames) { // Assemble a [ :name, offset ] array + offsets.append(context, newArray(context, name, newFixnum(context, getMember(context, name).offset))); } return offsets; @@ -290,12 +287,12 @@ public IRubyObject offsets(ThreadContext context) { @JRubyMethod(name = "offset_of") public IRubyObject offset_of(ThreadContext context, IRubyObject fieldName) { - return getField(context.runtime, fieldName).offset(context); + return getField(context, fieldName).offset(context); } @JRubyMethod(name = "[]") public IRubyObject aref(ThreadContext context, IRubyObject fieldName) { - return getField(context.runtime, fieldName); + return getField(context, fieldName); } @JRubyMethod @@ -305,15 +302,12 @@ public IRubyObject fields(ThreadContext context) { @JRubyMethod(name = "__union!") public IRubyObject union_bang(ThreadContext context) { - Ruby runtime = context.runtime; - NativeType[] alignmentTypes = { NativeType.CHAR, NativeType.SHORT, NativeType.INT, NativeType.LONG, NativeType.FLOAT, NativeType.DOUBLE, NativeType.LONGDOUBLE }; NativeType t = null; - int count, i; for (NativeType alignmentType : alignmentTypes) { if (Type.getNativeAlignment(alignmentType) == alignment) { @@ -323,7 +317,7 @@ public IRubyObject union_bang(ThreadContext context) { } if (t == null) { - throw runtime.newRuntimeError("cannot create libffi union representation for alignment " + alignment); + throw context.runtime.newRuntimeError("cannot create libffi union representation for alignment " + alignment); } // FIXME: wot @@ -339,11 +333,11 @@ public IRubyObject union_bang(ThreadContext context) { } final IRubyObject getValue(ThreadContext context, IRubyObject name, Storage cache, IRubyObject ptr) { - return getMember(context.runtime, name).get(context, cache, AbstractMemory.cast(context, ptr)); + return getMember(context, name).get(context, cache, AbstractMemory.cast(context, ptr)); } final void putValue(ThreadContext context, IRubyObject name, Storage cache, IRubyObject ptr, IRubyObject value) { - getMember(context.runtime, name).put(context, cache, AbstractMemory.cast(context, ptr), value); + getMember(context, name).put(context, cache, AbstractMemory.cast(context, ptr), value); } @Override @@ -380,7 +374,7 @@ private static int nextIndex(int idx, int length) { * @param name The name of the struct field. * @return A Member descriptor. */ - final Member getMember(Ruby runtime, IRubyObject name) { + final Member getMember(ThreadContext context, IRubyObject name) { Member m; int idx = symbolIndex(name, identityLookupTable.length); while ((m = identityLookupTable[idx]) != null) { @@ -391,11 +385,9 @@ final Member getMember(Ruby runtime, IRubyObject name) { } Member f = memberMap.get(name); - if (f != null) { - return f; - } + if (f != null) return f; - throw runtime.newArgumentError("Unknown field: " + name); + throw argumentError(context, "Unknown field: " + name); } /** @@ -404,8 +396,8 @@ final Member getMember(Ruby runtime, IRubyObject name) { * @param name The name of the struct field. * @return A Member descriptor. */ - final Field getField(Ruby runtime, IRubyObject name) { - return getMember(runtime, name).field; + final Field getField(ThreadContext context, IRubyObject name) { + return getMember(context, name).field; } public final int getSize() { diff --git a/core/src/main/java/org/jruby/ext/ffi/jffi/VariadicInvoker.java b/core/src/main/java/org/jruby/ext/ffi/jffi/VariadicInvoker.java index b68624f509a..47e1dcf0d82 100644 --- a/core/src/main/java/org/jruby/ext/ffi/jffi/VariadicInvoker.java +++ b/core/src/main/java/org/jruby/ext/ffi/jffi/VariadicInvoker.java @@ -21,6 +21,8 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newArray; +import static org.jruby.api.Create.newSymbol; import static org.jruby.api.Error.typeError; @JRubyClass(name = "FFI::VariadicInvoker", parent = "Object") @@ -80,22 +82,22 @@ public static VariadicInvoker newInstance(ThreadContext context, IRubyObject kla boolean saveError = true; IRubyObject typeMap = null; - IRubyObject rbConvention = options.fastARef(context.runtime.newSymbol("convention")); + IRubyObject rbConvention = options.fastARef(newSymbol(context, "convention")); if (rbConvention != null && !rbConvention.isNil()) { convention = rbConvention.asJavaString(); } - IRubyObject rbSaveErrno = options.fastARef(context.runtime.newSymbol("save_errno")); + IRubyObject rbSaveErrno = options.fastARef(newSymbol(context, "save_errno")); if (rbSaveErrno != null && !rbSaveErrno.isNil()) { saveError = rbSaveErrno.isTrue(); } - enums = options.fastARef(context.runtime.newSymbol("enums")); + enums = options.fastARef(newSymbol(context, "enums")); if (enums != null && !enums.isNil() && !(enums instanceof RubyHash || enums instanceof Enums)) { throw typeError(context, "wrong type for options[:enum] ", enums, " (expected Hash or Enums)"); } - typeMap = options.fastARef(context.runtime.newSymbol("type_map")); + typeMap = options.fastARef(newSymbol(context, "type_map")); if (typeMap != null && !typeMap.isNil() && !(typeMap instanceof RubyHash)) { throw typeError(context, "wrong type for options[:type_map] ", typeMap, " (expected Hash)"); } @@ -106,13 +108,12 @@ public static VariadicInvoker newInstance(ThreadContext context, IRubyObject kla throw typeError(context, "Invalid parameter array ", rbParameterTypes, " (expected Array)"); } - if (!(rbFunction instanceof Pointer)) throw typeError(context, rbFunction, context.runtime.getFFI().pointerClass); - final Pointer address = (Pointer) rbFunction; + if (!(rbFunction instanceof Pointer address)) throw typeError(context, rbFunction, context.runtime.getFFI().pointerClass); - CallingConvention callConvention = "stdcall".equals(convention) - ? CallingConvention.STDCALL : CallingConvention.DEFAULT; + CallingConvention callConvention = "stdcall".equals(convention) ? + CallingConvention.STDCALL : CallingConvention.DEFAULT; - var fixed = RubyArray.newArray(context.runtime); + var fixed = newArray(context); int fixedParamCount = 0; for (int i = 0; i < paramTypes.getLength(); ++i) { Type type = (Type)paramTypes.entry(i); diff --git a/core/src/main/java/org/jruby/ext/jruby/JRubyLibrary.java b/core/src/main/java/org/jruby/ext/jruby/JRubyLibrary.java index a16d1715cbe..6a29dd1aace 100644 --- a/core/src/main/java/org/jruby/ext/jruby/JRubyLibrary.java +++ b/core/src/main/java/org/jruby/ext/jruby/JRubyLibrary.java @@ -54,6 +54,7 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Error.typeError; import static org.jruby.parser.ParserType.INLINE; @@ -322,7 +323,7 @@ public static IRubyObject subclasses(ThreadContext context, IRubyObject recv, IR private static RubyArray subclasses(ThreadContext context, final IRubyObject recv, final RubyClass klass, final boolean recurseAll) { - final RubyArray subclasses = RubyArray.newArray(context.runtime); + final var subclasses = newArray(context); RubyClass singletonClass = klass.getSingletonClass(); RubyObjectSpace.each_objectInternal(context, recv, new IRubyObject[] { singletonClass }, 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 f127fc6ca3a..97c61b32db0 100644 --- a/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java +++ b/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java @@ -50,8 +50,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.Create.newSymbol; +import static org.jruby.api.Create.*; import static org.jruby.api.Error.argumentError; import static org.jruby.util.URLUtil.getPath; @@ -134,7 +133,7 @@ public static IRubyObject class_loader_resources(ThreadContext context, IRubyObj int argc = Arity.checkArgumentCount(context, args, 1, 2); final ClassLoader loader = context.runtime.getJRubyClassLoader(); final String name = args[0].convertToString().asJavaString(); - final var resources = RubyArray.newArray(context.runtime); + final var resources = newArray(context); boolean raw = false, path = false; if (argc > 1 && args[1] instanceof RubyHash) { @@ -426,12 +425,9 @@ public static IRubyObject cache_stats(ThreadContext context, IRubyObject self) { * This was added for Bootsnap in https://github.com/Shopify/bootsnap/issues/162 */ @JRubyMethod(module = true) - @Deprecated + @Deprecated(since = "9.4-", forRemoval = true) public static RubyArray internal_libraries(ThreadContext context, IRubyObject self) { - Ruby runtime = context.runtime; - - runtime.getWarnings().warn("JRuby::Util.internal_libraries is deprecated"); - - return runtime.newEmptyArray(); + context.runtime.getWarnings().warn("JRuby::Util.internal_libraries is deprecated"); + return newEmptyArray(context); } } diff --git a/core/src/main/java/org/jruby/ext/ripper/RipperParserBase.java b/core/src/main/java/org/jruby/ext/ripper/RipperParserBase.java index f5db1948858..30200d6b3a0 100644 --- a/core/src/main/java/org/jruby/ext/ripper/RipperParserBase.java +++ b/core/src/main/java/org/jruby/ext/ripper/RipperParserBase.java @@ -50,6 +50,8 @@ import org.jruby.util.ByteList; import org.jruby.util.StringSupport; +import static org.jruby.api.Create.newArray; +import static org.jruby.api.Create.newEmptyArray; import static org.jruby.util.CommonByteLists.*; import static org.jruby.util.RubyStringBuilder.inspectIdentifierByteList; import static org.jruby.util.RubyStringBuilder.str; @@ -380,26 +382,17 @@ public void add_forwarding_args() { } public IRubyObject method_optarg(IRubyObject method, IRubyObject arg) { - if (arg == null) return method; - - return dispatch("on_method_add_arg", method, arg); + return arg == null ? method : dispatch("on_method_add_arg", method, arg); } public IRubyObject keyword_arg(IRubyObject key, IRubyObject value) { - var array = RubyArray.newArray(context.runtime, 2); - - array.append(context, key); - array.append(context, value != null ? value : context.nil); - - return array; + return newArray(context, key, value != null ? value : context.nil); } public IRubyObject new_args(int _line, IRubyObject f, IRubyObject o, IRubyObject r, IRubyObject p, ArgsTailHolder tail) { - if (tail != null) { - return dispatch("on_params", f, o, r, p, tail.getKeywordArgs(), tail.getKeywordRestArg(), tail.getBlockArg()); - } - - return dispatch("on_params", f, o, r, p, null, null, null); + return tail != null ? + dispatch("on_params", f, o, r, p, tail.getKeywordArgs(), tail.getKeywordRestArg(), tail.getBlockArg()) : + dispatch("on_params", f, o, r, p, null, null, null); } public ArgsTailHolder new_args_tail(int line, IRubyObject kwarg, IRubyObject kwargRest, ByteList block) { @@ -440,11 +433,11 @@ public IRubyObject internalId() { } public IRubyObject new_array(IRubyObject ...args) { - return context.runtime.newArray(args); + return newArray(context, args); } public IRubyObject new_assoc(IRubyObject key, IRubyObject value) { - return RubyArray.newArray(context.runtime, key, value); + return newArray(context, key, value); } public IRubyObject new_bv(ByteList identifier) { @@ -685,8 +678,7 @@ public IRubyObject new_array_pattern(int _line, IRubyObject constant, IRubyObjec if (preArgs != null) { preArgs.unshift(context, preArg); } else { - preArgs = RubyArray.newArray(context.runtime); - preArgs.add(preArg); + preArgs = newArray(context, preArg); } } @@ -745,21 +737,13 @@ public IRubyObject none() { } public RubyArray new_hash_pattern_tail(int _line, IRubyObject keywordArgs, IRubyObject keywordRestValue) { - IRubyObject restArg; - - // To not make parser construct an array we will just detect the case of '**' with no arguments - // before it. - if (keywordArgs == null) { - keywordArgs = getRuntime().newEmptyArray(); - } + // To not make parser construct an array we will just detect the case of '**' with no arguments before it. + if (keywordArgs == null) keywordArgs = newEmptyArray(context); - if (keywordRestValue != null) { - restArg = dispatch("on_var_field", keywordRestValue); - } else { // '**' - restArg = context.nil; - } + IRubyObject restArg = keywordRestValue != null ? + dispatch("on_var_field", keywordRestValue) : context.nil; - return RubyArray.newArray(getRuntime(), keywordArgs, restArg); + return newArray(context, keywordArgs, restArg); } public IRubyObject makeNullNil(IRubyObject value) { 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 88a7ad336fd..061f1c5d182 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.Create.newArray; import static org.jruby.api.Error.argumentError; /** @@ -945,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); /* @@ -955,7 +955,7 @@ private IRubyObject divideTSort(ThreadContext context, final Block block) { } */ for ( IRubyObject u : elementsOrdered() ) { - var a = runtime.newArray(); + var a = newArray(context); dig.fastASet(u, a); for ( IRubyObject v : elementsOrdered() ) { IRubyObject ret = block.call(context, u, v); @@ -970,11 +970,11 @@ private IRubyObject divideTSort(ThreadContext context, final Block block) { } set */ - final RubyClass Set = runtime.getClass("Set"); - final RubySet set = new RubySet(runtime, Set); + final RubyClass Set = context.runtime.getClass("Set"); + final RubySet set = new RubySet(context.runtime, Set); set.allocHash(context, dig.size()); sites(context).each_strongly_connected_component.call(context, this, dig, new Block( - new JavaInternalBlockBody(runtime, Signature.ONE_REQUIRED) { + new JavaInternalBlockBody(context.runtime, Signature.ONE_REQUIRED) { @Override public IRubyObject yield(ThreadContext context, IRubyObject[] args) { return doYield(context, null, args[0]); 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 2dd5f2057e7..ea14df26640 100644 --- a/core/src/main/java/org/jruby/ext/socket/Addrinfo.java +++ b/core/src/main/java/org/jruby/ext/socket/Addrinfo.java @@ -879,7 +879,7 @@ public IRubyObject getnameinfo(ThreadContext context, int flags) { serviceName = Service.getServiceByPort(getPort(), protocol.getName()).getName(); } - return context.runtime.newArray(hostname, newString(context, serviceName)); + return newArray(context, hostname, newString(context, serviceName)); } diff --git a/core/src/main/java/org/jruby/ext/socket/Option.java b/core/src/main/java/org/jruby/ext/socket/Option.java index 791851c5429..a17a6b3b434 100644 --- a/core/src/main/java/org/jruby/ext/socket/Option.java +++ b/core/src/main/java/org/jruby/ext/socket/Option.java @@ -23,10 +23,8 @@ import java.nio.ByteBuffer; import java.util.Locale; -import static org.jruby.api.Convert.asFixnum; -import static org.jruby.api.Convert.checkToInteger; -import static org.jruby.api.Create.newFixnum; -import static org.jruby.api.Create.newString; +import static org.jruby.api.Convert.*; +import static org.jruby.api.Create.*; import static org.jruby.api.Error.typeError; public class Option extends RubyObject { @@ -240,8 +238,7 @@ public IRubyObject linger(ThreadContext context) { int[] linger = Option.unpackLinger(data); - Ruby runtime = context.runtime; - return runtime.newArray(runtime.newBoolean(linger[0] != 0), newFixnum(context, linger[1])); + return newArray(context, asBoolean(context,linger[0] != 0), newFixnum(context, linger[1])); } @JRubyMethod 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 50946ca0670..735ad9bebe2 100644 --- a/core/src/main/java/org/jruby/ext/socket/RubyIPSocket.java +++ b/core/src/main/java/org/jruby/ext/socket/RubyIPSocket.java @@ -41,8 +41,7 @@ import java.net.InetSocketAddress; -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; /** @@ -104,14 +103,13 @@ public IRubyObject recvfrom(ThreadContext context, IRubyObject _length) { hostAddress = sender.getAddress().getHostAddress(); } - IRubyObject addressArray = context.runtime.newArrayNoCopy( + IRubyObject addressArray = newArrayNoCopy(context, newString(context, "AF_INET"), newFixnum(context, port), newString(context, hostName), - newString(context, hostAddress) - ); + newString(context, hostAddress)); - return context.runtime.newArray(result, addressArray); + return newArray(context, result, addressArray); } @JRubyMethod 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 27c101947a2..1ce694376d5 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.Create.newArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; @@ -158,9 +159,7 @@ public static IRubyObject doAcceptNonblock(RubySocket sock, ThreadContext contex SocketChannel socketChannel = (SocketChannel)((RubySocket)socket).getChannel(); InetSocketAddress addr = (InetSocketAddress)socketChannel.socket().getRemoteSocketAddress(); - return context.runtime.newArray( - socket, - Sockaddr.packSockaddrFromAddress(context, addr)); + return newArray(context, socket, Sockaddr.packSockaddrFromAddress(context, addr)); } finally { selectable.configureBlocking(oldBlocking); } @@ -197,7 +196,7 @@ public static IRubyObject doAccept(RubySocket sock, ThreadContext context, boole RubySocket rubySocket = new RubySocket(runtime, runtime.getClass("Socket")); rubySocket.initFromServer(runtime, sock, socket); - return runtime.newArray(rubySocket, new Addrinfo(runtime, runtime.getClass("Addrinfo"), socket.getRemoteAddress())); + return newArray(context, rubySocket, new Addrinfo(runtime, runtime.getClass("Addrinfo"), socket.getRemoteAddress())); } throw runtime.newErrnoENOPROTOOPTError(); } 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 4383103850a..17e05b24c5c 100644 --- a/core/src/main/java/org/jruby/ext/socket/RubySocket.java +++ b/core/src/main/java/org/jruby/ext/socket/RubySocket.java @@ -85,8 +85,7 @@ import java.util.regex.Pattern; 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.Create.*; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; @@ -261,7 +260,7 @@ public static IRubyObject gethostname(ThreadContext context, IRubyObject recv) { @JRubyMethod(meta = true) public static IRubyObject getifaddrs(ThreadContext context, IRubyObject recv) { - RubyArray list = RubyArray.newArray(context.runtime); + var list = newArray(context); RubyClass Ifaddr = (RubyClass) context.runtime.getClassFromPath("Socket::Ifaddr"); try { Enumeration en = NetworkInterface.getNetworkInterfaces(); @@ -383,8 +382,7 @@ public static IRubyObject socketpair(ThreadContext context, IRubyObject recv, IR sock1.initFieldsFromDescriptor(runtime, fd1); sock1.initSocket(fd1); - return runtime.newArray(sock0, sock1); - + return newArray(context, sock0, sock1); } catch (IOException ioe) { throw runtime.newIOErrorFromException(ioe); } diff --git a/core/src/main/java/org/jruby/ext/socket/RubyTCPSocket.java b/core/src/main/java/org/jruby/ext/socket/RubyTCPSocket.java index f44df254526..ede800976e8 100644 --- a/core/src/main/java/org/jruby/ext/socket/RubyTCPSocket.java +++ b/core/src/main/java/org/jruby/ext/socket/RubyTCPSocket.java @@ -57,7 +57,7 @@ import static jnr.constants.platform.AddressFamily.AF_INET; import static jnr.constants.platform.AddressFamily.AF_INET6; -import static org.jruby.api.Create.newString; +import static org.jruby.api.Create.*; public class RubyTCPSocket extends RubyIPSocket { static void createTCPSocket(Ruby runtime) { @@ -226,28 +226,17 @@ public IRubyObject initialize(ThreadContext context, String remoteHost, int remo @JRubyMethod(meta = true) public static IRubyObject gethostbyname(ThreadContext context, IRubyObject recv, IRubyObject hostname) { - Ruby runtime = context.runtime; - IRubyObject ret0, ret1, ret2, ret3; - String hostString = hostname.convertToString().toString(); - try { - InetAddress addr = InetAddress.getByName(hostString); - - ret0 = newString(context, do_not_reverse_lookup(context, recv).isTrue() ? addr.getHostAddress() : addr.getCanonicalHostName()); - ret1 = runtime.newArray(); - - if (addr instanceof Inet4Address) { - ret2 = runtime.newFixnum(AF_INET); - } else { // if (addr instanceof Inet6Address) { - ret2 = runtime.newFixnum(AF_INET6); - } - - ret3 = newString(context, addr.getHostAddress()); + var addr = InetAddress.getByName(hostname.convertToString().toString()); - return RubyArray.newArray(runtime, ret0, ret1, ret2, ret3); + return RubyArray.newArray(context.runtime, + newString(context, do_not_reverse_lookup(context, recv).isTrue() ? addr.getHostAddress() : addr.getCanonicalHostName()), + newArray(context), + newFixnum(context, addr instanceof Inet4Address ? AF_INET.longValue() : AF_INET6.longValue()), + newString(context, addr.getHostAddress())); } catch(UnknownHostException e) { - throw SocketUtils.sockerr(runtime, "gethostbyname: name or service not known"); + throw SocketUtils.sockerr(context.runtime, "gethostbyname: name or service not known"); } } diff --git a/core/src/main/java/org/jruby/ext/socket/RubyUDPSocket.java b/core/src/main/java/org/jruby/ext/socket/RubyUDPSocket.java index 37fe57007d7..84911175eb6 100644 --- a/core/src/main/java/org/jruby/ext/socket/RubyUDPSocket.java +++ b/core/src/main/java/org/jruby/ext/socket/RubyUDPSocket.java @@ -74,8 +74,7 @@ import java.nio.channels.NotYetConnectedException; import java.nio.channels.UnsupportedAddressTypeException; -import static org.jruby.api.Create.newFixnum; -import static org.jruby.api.Create.newString; +import static org.jruby.api.Create.*; import static org.jruby.runtime.Helpers.extractExceptionOnlyArg; /** @@ -274,13 +273,11 @@ public static IRubyObject recvfrom_nonblock(RubyBasicSocket socket, ThreadContex private static IRubyObject recvfrom_nonblock(RubyBasicSocket socket, ThreadContext context, IRubyObject length, IRubyObject flags, IRubyObject str, boolean exception) { - final Ruby runtime = context.runtime; - try { - ReceiveTuple tuple = doReceiveNonblockTuple(socket, runtime, RubyNumeric.fix2int(length)); + ReceiveTuple tuple = doReceiveNonblockTuple(socket, context.runtime, RubyNumeric.fix2int(length)); if (tuple == null) { - if (!exception) return context.runtime.newSymbol("wait_readable"); + if (!exception) return newSymbol(context, "wait_readable"); throw context.runtime.newErrnoEAGAINReadableError("recvfrom(2)"); } @@ -288,27 +285,23 @@ private static IRubyObject recvfrom_nonblock(RubyBasicSocket socket, ThreadConte if (str != null && !str.isNil()) { str = str.convertToString(); ((RubyString) str).setValue(tuple.result.getByteList()); - } - else { + } else { str = tuple.result; } IRubyObject addressArray = socket.addrFor(context, tuple.sender, false); - return runtime.newArray(str, addressArray); - } - catch (UnknownHostException e) { - throw SocketUtils.sockerr(runtime, "recvfrom: name or service not known"); - } - catch (PortUnreachableException e) { - throw runtime.newErrnoECONNREFUSEDError(); - } - catch (IOException e) { // SocketException - throw runtime.newIOErrorFromException(e); - } - catch (RaiseException e) { throw e; } - catch (Exception e) { - throw sockerr(runtime, e.getLocalizedMessage(), e); + return newArray(context, str, addressArray); + } catch (UnknownHostException e) { + throw SocketUtils.sockerr(context.runtime, "recvfrom: name or service not known"); + } catch (PortUnreachableException e) { + throw context.runtime.newErrnoECONNREFUSEDError(); + } catch (IOException e) { // SocketException + throw context.runtime.newIOErrorFromException(e); + } catch (RaiseException e) { + throw e; + } catch (Exception e) { + throw sockerr(context.runtime, e.getLocalizedMessage(), e); } } @@ -478,7 +471,7 @@ public static IRubyObject recvfrom(RubyBasicSocket socket, ThreadContext context IRubyObject addressArray = socket.addrFor(context, tuple.sender, false); - return runtime.newArray(tuple.result, addressArray); + return newArray(context, tuple.result, addressArray); } catch (UnknownHostException e) { throw SocketUtils.sockerr(runtime, "recvfrom: name or service not known"); diff --git a/core/src/main/java/org/jruby/ext/socket/RubyUNIXServer.java b/core/src/main/java/org/jruby/ext/socket/RubyUNIXServer.java index e20a4611768..67d22f06033 100644 --- a/core/src/main/java/org/jruby/ext/socket/RubyUNIXServer.java +++ b/core/src/main/java/org/jruby/ext/socket/RubyUNIXServer.java @@ -47,6 +47,7 @@ import java.nio.channels.SelectionKey; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newString; @JRubyClass(name="UNIXServer", parent="UNIXSocket") @@ -166,7 +167,7 @@ public IRubyObject path(ThreadContext context) { @JRubyMethod public IRubyObject addr(ThreadContext context) { - return context.runtime.newArray(newString(context, "AF_UNIX"), newString(context, openFile.getPath())); + return newArray(context, newString(context, "AF_UNIX"), newString(context, openFile.getPath())); } @JRubyMethod diff --git a/core/src/main/java/org/jruby/ext/socket/RubyUNIXSocket.java b/core/src/main/java/org/jruby/ext/socket/RubyUNIXSocket.java index d4bcb371257..59b716eaaa2 100644 --- a/core/src/main/java/org/jruby/ext/socket/RubyUNIXSocket.java +++ b/core/src/main/java/org/jruby/ext/socket/RubyUNIXSocket.java @@ -68,8 +68,7 @@ import static com.headius.backport9.buffer.Buffers.flipBuffer; 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.typeError; @@ -112,48 +111,24 @@ public IRubyObject path(ThreadContext context) { @JRubyMethod public IRubyObject addr(ThreadContext context) { - final Ruby runtime = context.runtime; - - return runtime.newArray(newString(context, "AF_UNIX"), RubyString.newEmptyString(runtime) ); + return newArray(context, newString(context, "AF_UNIX"), RubyString.newEmptyString(context.runtime) ); } @JRubyMethod public IRubyObject peeraddr(ThreadContext context) { - final Ruby runtime = context.runtime; final String _path = getUnixRemoteSocket().path(); - final RubyString path = _path == null ? RubyString.newEmptyString(runtime) : newString(context, _path); - return runtime.newArray( newString(context, "AF_UNIX"), path ); + final RubyString path = _path == null ? RubyString.newEmptyString(context.runtime) : newString(context, _path); + return newArray(context, newString(context, "AF_UNIX"), path); } @JRubyMethod(name = "recvfrom", required = 1, optional = 1, checkArity = false) public IRubyObject recvfrom(ThreadContext context, IRubyObject[] args) { int argc = Arity.checkArgumentCount(context, args, 1, 2); - - Ruby runtime = context.runtime; - IRubyObject _length = args[0]; - IRubyObject _flags; - - if(argc == 2) { - _flags = args[1]; - } else { - _flags = runtime.getNil(); - } - - // TODO - int flags; - - _length = args[0]; - - if(_flags.isNil()) { - flags = 0; - } else { - flags = RubyNumeric.fix2int(_flags); - } + IRubyObject _flags = argc == 2 ? args[1] : context.nil; + int flags = _flags.isNil() ? 0 : RubyNumeric.fix2int(_flags); // TODO - return runtime.newArray( - recv(context, _length), - peeraddr(context)); + return newArray(context, recv(context, _length), peeraddr(context)); } @JRubyMethod @@ -287,7 +262,7 @@ public static IRubyObject socketpair(ThreadContext context, IRubyObject recv, IR RubyUNIXSocket sock2 = (RubyUNIXSocket)(Helpers.invoke(context, UNIXSocket, "allocate")); sock2.init_sock(runtime, sp[1], ""); - return runtime.newArray(sock, sock2); + return newArray(context, sock, sock2); } catch (IOException ioe) { throw runtime.newIOErrorFromException(ioe); diff --git a/core/src/main/java/org/jruby/ext/socket/SocketUtils.java b/core/src/main/java/org/jruby/ext/socket/SocketUtils.java index f6e903ef133..c373d0f22a7 100644 --- a/core/src/main/java/org/jruby/ext/socket/SocketUtils.java +++ b/core/src/main/java/org/jruby/ext/socket/SocketUtils.java @@ -72,8 +72,7 @@ import static jnr.constants.platform.ProtocolFamily.PF_INET6; import static jnr.constants.platform.Sock.SOCK_DGRAM; import static jnr.constants.platform.Sock.SOCK_STREAM; -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.ext.socket.Addrinfo.AI_CANONNAME; @@ -98,15 +97,12 @@ public static IRubyObject gethostname(ThreadContext context) { } public static IRubyObject gethostbyaddr(ThreadContext context, IRubyObject[] args) { - Ruby runtime = context.runtime; - IRubyObject ret0, ret1, ret2, ret3; - - ret0 = newString(context, Sockaddr.addressFromString(runtime, args[0].convertToString().toString()).getCanonicalHostName()); - ret1 = runtime.newArray(); - ret2 = newFixnum(context, 2); // AF_INET - ret3 = args[0]; + var ret0 = newString(context, Sockaddr.addressFromString(context.runtime, args[0].convertToString().toString()).getCanonicalHostName()); + var ret1 = newArray(context); + var ret2 = newFixnum(context, 2); // AF_INET + var ret3 = args[0]; - return RubyArray.newArray(runtime, ret0, ret1, ret2, ret3); + return RubyArray.newArray(context.runtime, ret0, ret1, ret2, ret3); } public static IRubyObject getservbyname(ThreadContext context, IRubyObject[] args) { @@ -146,31 +142,27 @@ public static IRubyObject pack_sockaddr_un(ThreadContext context, IRubyObject fi } public static IRubyObject gethostbyname(ThreadContext context, IRubyObject hostname) { - Ruby runtime = context.runtime; - try { InetAddress addr = getRubyInetAddress(hostname.convertToString().toString()); - IRubyObject ret0, ret1, ret2, ret3; - - ret0 = newString(context, addr.getCanonicalHostName()); - ret1 = runtime.newArray(); - ret2 = runtime.newFixnum(AF_INET); - ret3 = newString(context, new ByteList(addr.getAddress())); - return RubyArray.newArray(runtime, ret0, ret1, ret2, ret3); + return RubyArray.newArray(context.runtime, + newString(context, addr.getCanonicalHostName()), + newArray(context), + newFixnum(context, AF_INET.longValue()), + newString(context, new ByteList(addr.getAddress()))); } catch(UnknownHostException e) { - throw sockerr(runtime, "gethostbyname: name or service not known"); + throw sockerr(context.runtime, "gethostbyname: name or service not known"); } } /** * Ruby definition would look like: - * + *

* def self.getaddrinfo(host, port, family = nil, socktype = nil, protocol = nil, flags = nil, reverse_lookup = nil) */ public static IRubyObject getaddrinfo(final ThreadContext context, IRubyObject[] args) { - final List l = new ArrayList(); + final List list = new ArrayList<>(); buildAddrinfoList(context, args, true, (address, port, sock, reverse, usesCanonical) -> { boolean is_ipv6 = address instanceof Inet6Address; @@ -185,34 +177,30 @@ public static IRubyObject getaddrinfo(final ThreadContext context, IRubyObject[] } } - IRubyObject[] c; - if (sock_dgram) { - c = new IRubyObject[7]; - c[0] = newString(context, is_ipv6 ? "AF_INET6" : "AF_INET"); - c[1] = newFixnum(context, port); - c[2] = newString(context, getHostAddress(context, address, reverse)); - c[3] = newString(context, address.getHostAddress()); - c[4] = newFixnum(context, is_ipv6 ? PF_INET6.longValue() : PF_INET.longValue()); - c[5] = newFixnum(context, SOCK_DGRAM.longValue()); - c[6] = newFixnum(context, IPPROTO_UDP.longValue()); - l.add(RubyArray.newArrayMayCopy(context.runtime, c)); + list.add(RubyArray.newArrayMayCopy(context.runtime, + newString(context, is_ipv6 ? "AF_INET6" : "AF_INET"), + newFixnum(context, port), + newString(context, getHostAddress(context, address, reverse)), + newString(context, address.getHostAddress()), + newFixnum(context, is_ipv6 ? PF_INET6.longValue() : PF_INET.longValue()), + newFixnum(context, SOCK_DGRAM.longValue()), + newFixnum(context, IPPROTO_UDP.longValue()))); } if (sock_stream) { - c = new IRubyObject[7]; - c[0] = newString(context, is_ipv6 ? "AF_INET6" : "AF_INET"); - c[1] = newFixnum(context, port); - c[2] = newString(context, getHostAddress(context, address, reverse)); - c[3] = newString(context, address.getHostAddress()); - c[4] = newFixnum(context, is_ipv6 ? PF_INET6.longValue() : PF_INET.longValue()); - c[5] = newFixnum(context, SOCK_STREAM.longValue()); - c[6] = newFixnum(context, IPPROTO_TCP.longValue()); - l.add(RubyArray.newArrayMayCopy(context.runtime, c)); + list.add(RubyArray.newArrayMayCopy(context.runtime, + newString(context, is_ipv6 ? "AF_INET6" : "AF_INET"), + newFixnum(context, port), + newString(context, getHostAddress(context, address, reverse)), + newString(context, address.getHostAddress()), + newFixnum(context, is_ipv6 ? PF_INET6.longValue() : PF_INET.longValue()), + newFixnum(context, SOCK_STREAM.longValue()), + newFixnum(context, IPPROTO_TCP.longValue()))); } }); - return context.runtime.newArray(l); + return newArray(context, list); } public static List getaddrinfoList(ThreadContext context, IRubyObject[] args) { @@ -392,25 +380,23 @@ public static IRubyObject getnameinfo(ThreadContext context, IRubyObject[] args) port = (flags & NI_NUMERICSERV.intValue()) == 0 ? serv.getName() : Integer.toString(serv.getPort()); } - return context.runtime.newArray(newString(context, host), newString(context, port)); + return newArray(context, newString(context, host), newString(context, port)); } public static IRubyObject ip_address_list(ThreadContext context) { - Ruby runtime = context.runtime; - try { - var list = RubyArray.newArray(runtime); - RubyClass addrInfoCls = runtime.getClass("Addrinfo"); + var list = newArray(context); + RubyClass addrInfoCls = context.runtime.getClass("Addrinfo"); for (Enumeration networkIfcs = NetworkInterface.getNetworkInterfaces(); networkIfcs.hasMoreElements() ; ) { for (Enumeration addresses = networkIfcs.nextElement().getInetAddresses(); addresses.hasMoreElements() ; ) { - list.append(context, new Addrinfo(runtime, addrInfoCls, addresses.nextElement())); + list.append(context, new Addrinfo(context.runtime, addrInfoCls, addresses.nextElement())); } } return list; } catch (SocketException se) { - throw sockerr(runtime, se.getLocalizedMessage()); + throw sockerr(context.runtime, se.getLocalizedMessage()); } } 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 93677cb9667..22b5b6b47f9 100644 --- a/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipReader.java +++ b/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipReader.java @@ -63,8 +63,7 @@ import static org.jruby.RubyIO.PARAGRAPH_SEPARATOR; import static org.jruby.api.Convert.asFixnum; 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.Create.*; import static org.jruby.api.Error.argumentError; import static org.jruby.runtime.Visibility.PRIVATE; @@ -706,7 +705,6 @@ public IRubyObject readlines(ThreadContext context, IRubyObject[] args) { if (argc != 0 && args[0].isNil()) { array.add(read(context, IRubyObject.NULL_ARRAY)); - } else { ByteList sep = ((RubyString) context.runtime.getGlobalVariables().get("$/")).getByteList(); @@ -721,7 +719,7 @@ public IRubyObject readlines(ThreadContext context, IRubyObject[] args) { } } - return getRuntime().newArray(array); + return newArray(context, array); } @JRubyMethod diff --git a/core/src/main/java/org/jruby/ir/interpreter/ExitableInterpreterEngine.java b/core/src/main/java/org/jruby/ir/interpreter/ExitableInterpreterEngine.java index 46c17359923..e0e1b7baeec 100644 --- a/core/src/main/java/org/jruby/ir/interpreter/ExitableInterpreterEngine.java +++ b/core/src/main/java/org/jruby/ir/interpreter/ExitableInterpreterEngine.java @@ -38,6 +38,7 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newArray; import static org.jruby.util.RubyStringBuilder.ids; import static org.jruby.util.RubyStringBuilder.str; @@ -84,7 +85,7 @@ public ExitableReturn interpret(ThreadContext context, Block block, IRubyObject // FIXME: We are forcing a boxing to a Ruby array we probably do not need but did it anyways so it matched the // interface of interpreterengine (re-consider this). return new ExitableReturn( - context.runtime.newArray(interpreterContext.getArgs(context, self, currScope, currDynScope, temp)), + newArray(context, interpreterContext.getArgs(context, self, currScope, currDynScope, temp)), ((CallBase)instrs[ipc]).prepareBlock(context, self, currScope, currDynScope, temp)); } @@ -111,7 +112,7 @@ public ExitableReturn interpret(ThreadContext context, Block block, IRubyObject break; case RET_OP: processReturnOp(context, block, instr, operation, currDynScope, temp, self, currScope); - return new ExitableReturn(context.runtime.newArray(), Block.NULL_BLOCK); + return new ExitableReturn(newArray(context), Block.NULL_BLOCK); case BRANCH_OP: switch (operation) { case JUMP: diff --git a/core/src/main/java/org/jruby/ir/operands/Array.java b/core/src/main/java/org/jruby/ir/operands/Array.java index 55033053650..229b9926a9d 100644 --- a/core/src/main/java/org/jruby/ir/operands/Array.java +++ b/core/src/main/java/org/jruby/ir/operands/Array.java @@ -15,6 +15,9 @@ import java.util.List; import java.util.Map; +import static org.jruby.api.Create.newArray; +import static org.jruby.api.Create.newEmptyArray; + // Represents an array [_, _, .., _] in ruby // // NOTE: This operand is only used in the initial stages of optimization. @@ -123,11 +126,11 @@ public IRubyObject[] retrieveArrayElts(ThreadContext context, IRubyObject self, public Object retrieve(ThreadContext context, IRubyObject self, StaticScope currScope, DynamicScope currDynScope, Object[] temp) { switch (elts.length) { case 0: - return context.runtime.newEmptyArray(); + return newEmptyArray(context); case 1: - return context.runtime.newArray((IRubyObject) elts[0].retrieve(context, self, currScope, currDynScope, temp)); + return newArray(context, (IRubyObject) elts[0].retrieve(context, self, currScope, currDynScope, temp)); case 2: - return context.runtime.newArray((IRubyObject) elts[0].retrieve(context, self, currScope, currDynScope, temp), + return newArray(context, (IRubyObject) elts[0].retrieve(context, self, currScope, currDynScope, temp), (IRubyObject) elts[1].retrieve(context, self, currScope, currDynScope, temp)); default: return RubyArray.newArrayMayCopy(context.runtime, retrieveArrayElts(context, self, currScope, currDynScope, temp)); 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 e882948d9c7..99ee43406ba 100644 --- a/core/src/main/java/org/jruby/ir/runtime/IRRuntimeHelpers.java +++ b/core/src/main/java/org/jruby/ir/runtime/IRRuntimeHelpers.java @@ -28,6 +28,7 @@ import org.jruby.RubyRegexp; import org.jruby.RubyString; import org.jruby.RubySymbol; +import org.jruby.api.Create; import org.jruby.common.IRubyWarnings; import org.jruby.exceptions.RaiseException; import org.jruby.exceptions.Unrescuable; @@ -90,6 +91,7 @@ import org.objectweb.asm.Type; import static org.jruby.api.Convert.*; +import static org.jruby.api.Create.newEmptyArray; import static org.jruby.api.Create.newString; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; @@ -727,7 +729,7 @@ private static IRubyObject receiveSpecificArityRuby2HashKeywords(ThreadContext c return hash; } - return receiverSpecificArityKwargsCommon(context, last, callInfo, isKwarg); + return receiverSpecificArityKwargsCommon(context, last, callInfo, false); } private static IRubyObject receiverSpecificArityKwargsCommon(ThreadContext context, IRubyObject last, int callInfo, boolean isKwarg) { @@ -955,7 +957,7 @@ private static class GatherUnwantedKeywordsVisitor extends RubyHash.VisitorWithS @Override public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, StaticScope scope) { if (!isValidKeyword(scope, key)) { - if (invalidKwargs == null) invalidKwargs = context.runtime.newArray(); + if (invalidKwargs == null) invalidKwargs = newArray(context); invalidKwargs.add(key.inspect()); } } @@ -1266,12 +1268,10 @@ public static RubyBoolean isBlockGiven(ThreadContext context, Object blk) { public static IRubyObject receiveRestArg(ThreadContext context, IRubyObject[] args, IRubyObject keywords, int required, int argIndex) { int argsLength = args.length + (keywords != UNDEFINED ? -1 : 0); - if (required == 0 && argsLength == args.length ) { - return RubyArray.newArray(context.runtime, args); - } - int remainingArguments = argsLength - required; + if (required == 0 && argsLength == args.length ) return RubyArray.newArray(context.runtime, args); - if (remainingArguments <= 0) return context.runtime.newEmptyArray(); + int remainingArguments = argsLength - required; + if (remainingArguments <= 0) return newEmptyArray(context); return RubyArray.newArrayMayCopy(context.runtime, args, argIndex, remainingArguments); } @@ -2017,22 +2017,22 @@ public static RubyRegexp newLiteralRegexp(ThreadContext context, ByteList source @JIT public static RubyArray irSplat(ThreadContext context, IRubyObject ary) { - Ruby runtime = context.runtime; int callInfo = ThreadContext.resetCallInfo(context); - IRubyObject tmp = TypeConverter.convertToTypeWithCheck(context, ary, runtime.getArray(), sites(context).to_a_checked); + IRubyObject tmp = TypeConverter.convertToTypeWithCheck(context, ary, context.runtime.getArray(), sites(context).to_a_checked); + RubyArray result; if (tmp.isNil()) { - tmp = runtime.newArray(ary); + result = newArray(context, ary); context.callInfo = callInfo; } else if (true /**RTEST(flag)**/) { // this logic is only used for bare splat, and MRI dups - tmp = ((RubyArray)tmp).aryDup(); + result = (RubyArray) ((RubyArray)tmp).aryDup(); // We have concat'd an empty keyword rest. This comes from MERGE_KEYWORDS noticing it is empty. - if (((RubyArray) tmp).last() == UNDEFINED) { - ((RubyArray) tmp).pop(context); + if (result.last() == UNDEFINED) { + result.pop(context); context.callInfo |= callInfo | CALL_KEYWORD_EMPTY; } } - return (RubyArray)tmp; + return result; } /** @@ -2042,16 +2042,12 @@ public static RubyArray irSplat(ThreadContext context, IRubyObject ary) { */ @JIT @Interp public static RubyArray splatArray(ThreadContext context, IRubyObject ary, boolean dupArray) { - Ruby runtime = context.runtime; - IRubyObject tmp = TypeConverter.convertToTypeWithCheck(context, ary, runtime.getArray(), sites(context).to_a_checked); + IRubyObject tmp = TypeConverter.convertToTypeWithCheck(context, ary, context.runtime.getArray(), sites(context).to_a_checked); - if (tmp.isNil()) { - tmp = runtime.newArray(ary); - } else if (dupArray) { - tmp = ((RubyArray) tmp).aryDup(); - } + if (tmp.isNil()) return newArray(context, ary); + if (dupArray) return ((RubyArray) tmp).aryDup(); - return (RubyArray) tmp; + return (RubyArray) tmp; } /** @@ -2061,14 +2057,11 @@ public static RubyArray splatArray(ThreadContext context, IRubyObject ary, boole */ @JIT @Interp public static RubyArray splatArray(ThreadContext context, IRubyObject ary) { - Ruby runtime = context.runtime; - IRubyObject tmp = TypeConverter.convertToTypeWithCheck(context, ary, runtime.getArray(), sites(context).to_a_checked); + IRubyObject tmp = TypeConverter.convertToTypeWithCheck(context, ary, context.runtime.getArray(), sites(context).to_a_checked); - if (tmp.isNil()) { - tmp = runtime.newArray(ary); - } + if (tmp.isNil()) return newArray(context, ary); - return (RubyArray) tmp; + return (RubyArray) tmp; } /** @@ -2078,16 +2071,9 @@ public static RubyArray splatArray(ThreadContext context, IRubyObject ary) { */ @JIT @Interp public static RubyArray splatArrayDup(ThreadContext context, IRubyObject ary) { - Ruby runtime = context.runtime; - IRubyObject tmp = TypeConverter.convertToTypeWithCheck(context, ary, runtime.getArray(), sites(context).to_a_checked); - - if (tmp.isNil()) { - tmp = runtime.newArray(ary); - } else { - tmp = ((RubyArray) tmp).aryDup(); - } + IRubyObject tmp = TypeConverter.convertToTypeWithCheck(context, ary, context.runtime.getArray(), sites(context).to_a_checked); - return (RubyArray) tmp; + return tmp.isNil() ? newArray(context, ary) : ((RubyArray) tmp).aryDup(); } public static IRubyObject irToAry(ThreadContext context, IRubyObject value) { @@ -2493,12 +2479,12 @@ public static RubyArray newArray(ThreadContext context) { @JIT public static RubyArray newArray(ThreadContext context, IRubyObject obj) { - return RubyArray.newArray(context.runtime, obj); + return Create.newArray(context, obj); } @JIT public static RubyArray newArray(ThreadContext context, IRubyObject obj0, IRubyObject obj1) { - return RubyArray.newArray(context.runtime, obj0, obj1); + return Create.newArray(context, obj0, obj1); } @JIT @Interp diff --git a/core/src/main/java/org/jruby/java/addons/ArrayJavaAddons.java b/core/src/main/java/org/jruby/java/addons/ArrayJavaAddons.java index a42541fbf89..1e9c3c1147a 100644 --- a/core/src/main/java/org/jruby/java/addons/ArrayJavaAddons.java +++ b/core/src/main/java/org/jruby/java/addons/ArrayJavaAddons.java @@ -9,6 +9,8 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Convert.asInt; +import static org.jruby.api.Create.newEmptyArray; import static org.jruby.api.Create.newFixnum; import static org.jruby.api.Error.typeError; @@ -79,15 +81,13 @@ private static void copyDataToJavaArray(final ThreadContext context, @JRubyMethod public static IRubyObject dimensions(ThreadContext context, IRubyObject rubyArray) { - return dimensions(context, rubyArray, context.runtime.newEmptyArray()); + return dimensions(context, rubyArray, newEmptyArray(context)); } @JRubyMethod public static IRubyObject dimensions(ThreadContext context, IRubyObject rubyArray, IRubyObject dims) { - final Ruby runtime = context.runtime; - if ( ! ( rubyArray instanceof RubyArray ) ) { - return runtime.newEmptyArray(); - } + if (!(rubyArray instanceof RubyArray)) return newEmptyArray(context); + assert dims instanceof RubyArray; return calcDimensions(context, (RubyArray) rubyArray, (RubyArray) dims, 0); @@ -95,15 +95,12 @@ public static IRubyObject dimensions(ThreadContext context, IRubyObject rubyArra @JRubyMethod public static IRubyObject dimensions(ThreadContext context, IRubyObject rubyArray, IRubyObject dims, IRubyObject index) { - final Ruby runtime = context.runtime; - if ( ! ( rubyArray instanceof RubyArray ) ) { - return runtime.newEmptyArray(); - } + if (!(rubyArray instanceof RubyArray)) return newEmptyArray(context); + assert dims instanceof RubyArray; assert index instanceof RubyFixnum; - final int i = (int) ((RubyFixnum) index).getLongValue(); - return calcDimensions(context, (RubyArray) rubyArray, (RubyArray) dims, i); + return calcDimensions(context, (RubyArray) rubyArray, (RubyArray) dims, asInt(context, (RubyFixnum) index)); } private static RubyArray calcDimensions(ThreadContext context, diff --git a/core/src/main/java/org/jruby/java/proxies/ArrayJavaProxy.java b/core/src/main/java/org/jruby/java/proxies/ArrayJavaProxy.java index b0be43e8651..d61f95b27e9 100644 --- a/core/src/main/java/org/jruby/java/proxies/ArrayJavaProxy.java +++ b/core/src/main/java/org/jruby/java/proxies/ArrayJavaProxy.java @@ -5,6 +5,7 @@ import org.jruby.*; import org.jruby.anno.JRubyMethod; +import org.jruby.api.Create; import org.jruby.internal.runtime.methods.DynamicMethod; import org.jruby.java.util.ArrayUtils; import org.jruby.javasupport.Java; @@ -19,6 +20,7 @@ import org.jruby.util.RubyStringBuilder; import static org.jruby.api.Convert.*; +import static org.jruby.api.Create.newFixnum; import static org.jruby.api.Error.typeError; import static org.jruby.javasupport.ext.JavaLang.Character.inspectCharValue; import static org.jruby.RubyEnumerator.enumeratorizeWithSize; @@ -477,12 +479,12 @@ public IRubyObject each_with_index(final ThreadContext context, final Block bloc for ( int i = 0; i < length; i++ ) { IRubyObject element = ArrayUtils.arefDirect(runtime, array, converter, i); - final RubyInteger index = RubyFixnum.newFixnum(runtime, i); + final RubyInteger index = newFixnum(context, i); if (twoArguments) { block.yieldSpecific(context, element, index); } else { - block.yield(context, RubyArray.newArray(runtime, element, index)); + block.yield(context, Create.newArray(context, element, index)); } } return this; diff --git a/core/src/main/java/org/jruby/java/proxies/JavaProxy.java b/core/src/main/java/org/jruby/java/proxies/JavaProxy.java index d5ef785e687..8e2607e9776 100644 --- a/core/src/main/java/org/jruby/java/proxies/JavaProxy.java +++ b/core/src/main/java/org/jruby/java/proxies/JavaProxy.java @@ -59,6 +59,7 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.castAsModule; +import static org.jruby.api.Create.newEmptyArray; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.Helpers.arrayOf; @@ -695,7 +696,7 @@ public static IRubyObject java_send(ThreadContext context, IRubyObject recv, IRu @JRubyMethod(meta = true, visibility = Visibility.PRIVATE) public static IRubyObject java_alias(ThreadContext context, IRubyObject clazz, IRubyObject newName, IRubyObject rubyName) { - return java_alias(context, clazz, newName, rubyName, context.runtime.newEmptyArray()); + return java_alias(context, clazz, newName, rubyName, newEmptyArray(context)); } @JRubyMethod(meta = true, visibility = Visibility.PRIVATE) diff --git a/core/src/main/java/org/jruby/java/proxies/MapJavaProxy.java b/core/src/main/java/org/jruby/java/proxies/MapJavaProxy.java index 38b51210a59..225c0b545a2 100644 --- a/core/src/main/java/org/jruby/java/proxies/MapJavaProxy.java +++ b/core/src/main/java/org/jruby/java/proxies/MapJavaProxy.java @@ -56,8 +56,7 @@ 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.util.Inspector.*; /** @@ -298,40 +297,37 @@ public RubyBoolean compare_by_identity_p(ThreadContext context) { @Override protected RubyBoolean any_p_i(ThreadContext context, Block block) { final Ruby runtime = context.runtime; - for ( Map.Entry entry : entrySet() ) { + for (var entry : entrySet()) { final IRubyObject key = JavaUtil.convertJavaToUsableRubyObject(runtime, entry.getKey()); final IRubyObject val = JavaUtil.convertJavaToUsableRubyObject(runtime, entry.getValue()); - if ( block.yield(context, RubyArray.newArray(runtime, key, val)).isTrue() ) { - return runtime.getTrue(); - } + + if ( block.yield(context, newArray(context, key, val)).isTrue() ) return context.tru; } - return runtime.getFalse(); + return context.fals; } @Override protected RubyBoolean any_p_i_fast(ThreadContext context, Block block) { final Ruby runtime = context.runtime; - for ( Map.Entry entry : entrySet() ) { + for (var entry: entrySet()) { final IRubyObject key = JavaUtil.convertJavaToUsableRubyObject(runtime, entry.getKey()); final IRubyObject val = JavaUtil.convertJavaToUsableRubyObject(runtime, entry.getValue()); - if ( block.yieldArray(context, runtime.newArray(key, val), null).isTrue() ) { - return runtime.getTrue(); - } + + if (block.yieldArray(context, newArray(context, key, val), null).isTrue()) return context.tru; } - return runtime.getFalse(); + return context.fals; } @Override protected RubyBoolean any_p_p(ThreadContext context, IRubyObject pattern) { final Ruby runtime = context.runtime; - for ( Map.Entry entry : entrySet() ) { + for (var entry: entrySet() ) { final IRubyObject key = JavaUtil.convertJavaToUsableRubyObject(runtime, entry.getKey()); final IRubyObject val = JavaUtil.convertJavaToUsableRubyObject(runtime, entry.getValue()); - if ( pattern.callMethod(context, "===", RubyArray.newArray(runtime, key, val)).isTrue() ) { - return runtime.getTrue(); - } + + if ( pattern.callMethod(context, "===", newArray(context, key, val)).isTrue() ) return context.tru; } - return runtime.getFalse(); + return context.fals; } @Override diff --git a/core/src/main/java/org/jruby/javasupport/JavaUtil.java b/core/src/main/java/org/jruby/javasupport/JavaUtil.java index dfb3c5218ee..29dc88afb35 100644 --- a/core/src/main/java/org/jruby/javasupport/JavaUtil.java +++ b/core/src/main/java/org/jruby/javasupport/JavaUtil.java @@ -49,6 +49,7 @@ import static java.lang.Character.isDigit; import static java.lang.Character.toLowerCase; import static java.lang.Character.toUpperCase; +import static org.jruby.api.Create.newArrayNoCopy; import static org.jruby.api.Error.typeError; import java.math.BigDecimal; @@ -129,17 +130,15 @@ public static RubyArray convertJavaArrayToRubyWithNesting(final ThreadContext co final IRubyObject[] rubyElements = new IRubyObject[length]; for ( int i = 0; i < length; i++ ) { final Object element = Array.get(array, i); - if ( element instanceof ArrayJavaProxy ) { - rubyElements[i] = convertJavaArrayToRubyWithNesting(context, ((ArrayJavaProxy) element).getObject()); - } - else if ( element != null && element.getClass().isArray() ) { + if (element instanceof ArrayJavaProxy proxy) { + rubyElements[i] = convertJavaArrayToRubyWithNesting(context, proxy.getObject()); + } else if (element != null && element.getClass().isArray()) { rubyElements[i] = convertJavaArrayToRubyWithNesting(context, element); - } - else { + } else { rubyElements[i] = convertJavaToUsableRubyObject(context.runtime, element); } } - return context.runtime.newArrayNoCopy(rubyElements); + return newArrayNoCopy(context, rubyElements); } public static JavaConverter getJavaConverter(Class clazz) { 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 8ef7be2407a..44fd8d6b1df 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/JavaLang.java +++ b/core/src/main/java/org/jruby/javasupport/ext/JavaLang.java @@ -58,6 +58,7 @@ import static org.jruby.RubyModule.undefinedMethodMessage; import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newString; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; @@ -123,22 +124,21 @@ public static IRubyObject each(final ThreadContext context, final IRubyObject se @JRubyMethod public static IRubyObject each_with_index(final ThreadContext context, final IRubyObject self, final Block block) { - final Ruby runtime = context.runtime; - if ( ! block.isGiven() ) { // ... Enumerator.new(self, :each_with_index) - return enumeratorize(context.runtime, self, "each_with_index"); - } - java.lang.Iterable iterable = unwrapIfJavaObject(self); - java.util.Iterator iterator = iterable.iterator(); + // ... Enumerator.new(self, :each_with_index) + if (!block.isGiven()) return enumeratorize(context.runtime, self, "each_with_index"); + + java.lang.Iterable iterable = unwrapIfJavaObject(self); + java.util.Iterator iterator = iterable.iterator(); final boolean twoArguments = block.getSignature().isTwoArguments(); int i = 0; while ( iterator.hasNext() ) { final RubyInteger index = asFixnum(context, i++); final Object value = iterator.next(); - final IRubyObject rValue = convertJavaToUsableRubyObject(runtime, value); + final IRubyObject rValue = convertJavaToUsableRubyObject(context.runtime, value); if (twoArguments) { block.yieldSpecific(context, rValue, index); } else { - block.yield(context, RubyArray.newArray(runtime, rValue, index)); + block.yield(context, newArray(context, rValue, index)); } } return self; @@ -146,7 +146,7 @@ public static IRubyObject each_with_index(final ThreadContext context, final IRu @JRubyMethod(name = { "to_a", "entries" }) // @override Enumerable#to_a public static IRubyObject to_a(final ThreadContext context, final IRubyObject self, final Block block) { - final var ary = context.runtime.newArray(); + final var ary = newArray(context); java.lang.Iterable iterable = unwrapIfJavaObject(self); for (Object o: iterable) { ary.append(context, convertJavaToUsableRubyObject(context.runtime, o)); @@ -425,12 +425,11 @@ public static IRubyObject nonzero_p(final ThreadContext context, final IRubyObje @JRubyMethod(name = "coerce") public static IRubyObject coerce(final ThreadContext context, final IRubyObject self, final IRubyObject type) { - java.lang.Number val = (java.lang.Number) self.toJava(java.lang.Number.class); + java.lang.Number val = self.toJava(java.lang.Number.class); // NOTE: a basic stub that always coverts Java numbers to Ruby ones (for simplicity) // gist being this is not expected to be used heavily, if so should get special care - final IRubyObject value = convertJavaToUsableRubyObject(context.runtime, val); - return context.runtime.newArray(type, value); + return newArray(context, type, convertJavaToUsableRubyObject(context.runtime, val)); } @JRubyMethod(name = "inspect") @@ -552,40 +551,40 @@ public static IRubyObject declared_annotations_p(final ThreadContext context, fi @JRubyMethod public static IRubyObject java_instance_methods(final ThreadContext context, final IRubyObject self) { - final java.lang.Class klass = unwrapJavaObject(self); - final RubyArray methods = RubyArray.newArray(context.runtime); - for ( java.lang.reflect.Method method : klass.getMethods() ) { - if ( ! Modifier.isStatic(method.getModifiers()) ) methods.add(method); + final java.lang.Class klass = unwrapJavaObject(self); + final var methods = newArray(context); + for (java.lang.reflect.Method method : klass.getMethods()) { + if (!Modifier.isStatic(method.getModifiers())) methods.add(method); } return methods; } @JRubyMethod public static IRubyObject declared_instance_methods(final ThreadContext context, final IRubyObject self) { - final java.lang.Class klass = unwrapJavaObject(self); - final RubyArray methods = RubyArray.newArray(context.runtime); - for ( java.lang.reflect.Method method : klass.getDeclaredMethods() ) { - if ( ! Modifier.isStatic(method.getModifiers()) ) methods.add(method); + final java.lang.Class klass = unwrapJavaObject(self); + final var methods = newArray(context); + for (java.lang.reflect.Method method : klass.getDeclaredMethods()) { + if (!Modifier.isStatic(method.getModifiers())) methods.add(method); } return methods; } @JRubyMethod public static IRubyObject java_class_methods(final ThreadContext context, final IRubyObject self) { - final java.lang.Class klass = unwrapJavaObject(self); - final RubyArray methods = RubyArray.newArray(context.runtime); + final java.lang.Class klass = unwrapJavaObject(self); + final var methods = newArray(context); for ( java.lang.reflect.Method method : klass.getMethods() ) { - if ( Modifier.isStatic(method.getModifiers()) ) methods.add(method); + if (Modifier.isStatic(method.getModifiers())) methods.add(method); } return methods; } @JRubyMethod public static IRubyObject declared_class_methods(final ThreadContext context, final IRubyObject self) { - final java.lang.Class klass = unwrapJavaObject(self); - final RubyArray methods = RubyArray.newArray(context.runtime); - for ( java.lang.reflect.Method method : klass.getDeclaredMethods() ) { - if ( Modifier.isStatic(method.getModifiers()) ) methods.add(method); + final java.lang.Class klass = unwrapJavaObject(self); + final var methods = newArray(context); + for (java.lang.reflect.Method method : klass.getDeclaredMethods()) { + if (Modifier.isStatic(method.getModifiers())) methods.add(method); } return methods; } diff --git a/core/src/main/java/org/jruby/javasupport/ext/JavaMath.java b/core/src/main/java/org/jruby/javasupport/ext/JavaMath.java index eadbd5eaced..ab176fe41b4 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/JavaMath.java +++ b/core/src/main/java/org/jruby/javasupport/ext/JavaMath.java @@ -37,6 +37,7 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newArray; import static org.jruby.javasupport.JavaUtil.unwrapIfJavaObject; /** @@ -75,7 +76,7 @@ public static IRubyObject to_i(ThreadContext context, IRubyObject self) { @JRubyMethod(name = "coerce") // override from java.lang.Number public static IRubyObject coerce(final ThreadContext context, final IRubyObject self, final IRubyObject type) { - return context.runtime.newArray(type, asRubyBigDecimal(context.runtime, unwrapIfJavaObject(self))); + return newArray(context, type, asRubyBigDecimal(context.runtime, unwrapIfJavaObject(self))); } @JRubyMethod(name = "to_r") diff --git a/core/src/main/java/org/jruby/javasupport/ext/JavaUtilRegex.java b/core/src/main/java/org/jruby/javasupport/ext/JavaUtilRegex.java index 8f8fbd60670..aa2a86be33b 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/JavaUtilRegex.java +++ b/core/src/main/java/org/jruby/javasupport/ext/JavaUtilRegex.java @@ -37,6 +37,7 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newString; import static org.jruby.javasupport.JavaUtil.convertJavaToUsableRubyObject; import static org.jruby.javasupport.JavaUtil.unwrapJavaObject; @@ -154,7 +155,7 @@ public static IRubyObject offset(final ThreadContext context, final IRubyObject beg = asFixnum(context, matcher.start(group)); end = asFixnum(context, matcher.end(group)); } - return RubyArray.newArray(context.runtime, beg, end); + return newArray(context, beg, end); } @JRubyMethod(name = { "length", "size" }) diff --git a/core/src/main/java/org/jruby/javasupport/ext/Module.java b/core/src/main/java/org/jruby/javasupport/ext/Module.java index 0cb91894672..c12049df2e4 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/Module.java +++ b/core/src/main/java/org/jruby/javasupport/ext/Module.java @@ -52,6 +52,7 @@ import java.util.Map; import java.util.stream.Collectors; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newString; import static org.jruby.api.Error.argumentError; import static org.jruby.runtime.Visibility.PRIVATE; @@ -87,20 +88,18 @@ public static IRubyObject import_(ThreadContext context, IRubyObject self, IRuby @JRubyMethod(visibility = PRIVATE) public static IRubyObject java_import(ThreadContext context, IRubyObject self, IRubyObject arg, Block block) { - if (arg instanceof RubyArray) { - return java_import(context, self, ((RubyArray) arg).toJavaArrayMaybeUnsafe(), block); - } - return context.runtime.newArray( javaImport(context, (RubyModule) self, arg, block) ); + return arg instanceof RubyArray ? + java_import(context, self, ((RubyArray) arg).toJavaArrayMaybeUnsafe(), block) : + newArray(context, javaImport(context, (RubyModule) self, arg, block) ); } @JRubyMethod(rest = true, visibility = PRIVATE) public static IRubyObject java_import(ThreadContext context, IRubyObject self, IRubyObject[] args, Block block) { - final Ruby runtime = context.runtime; - IRubyObject[] classes = ((RubyArray) RubyArray.newArrayNoCopy(runtime, args).flatten(context)).toJavaArrayMaybeUnsafe(); + IRubyObject[] classes = ((RubyArray) RubyArray.newArrayNoCopy(context.runtime, args).flatten(context)).toJavaArrayMaybeUnsafe(); for (int i = 0; i < classes.length; i++) { classes[i] = javaImport(context, (RubyModule) self, classes[i], block); } - return runtime.newArray(classes); + return newArray(context, classes); } private static IRubyObject javaImport(ThreadContext context, RubyModule target, IRubyObject klass, Block block) { diff --git a/core/src/main/java/org/jruby/parser/Parser.java b/core/src/main/java/org/jruby/parser/Parser.java index 283cdd072cc..c4c21c3f8a1 100644 --- a/core/src/main/java/org/jruby/parser/Parser.java +++ b/core/src/main/java/org/jruby/parser/Parser.java @@ -68,6 +68,7 @@ import org.jruby.util.ByteList; import org.jruby.util.CommonByteLists; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newString; import static org.jruby.parser.ParserType.*; @@ -223,14 +224,14 @@ protected RubyArray getLines(boolean isEvalParse, String file, int length) { IRubyObject scriptLines = runtime.getObject().getConstantAt("SCRIPT_LINES__"); if (!(scriptLines instanceof RubyHash)) return null; - var list = length == -1 ? runtime.newArray() : runtime.newArray(length); - ThreadContext context = runtime.getCurrentContext(); + var context = runtime.getCurrentContext(); + var list = length == -1 ? newArray(context) : newArray(context, length); ((RubyHash) scriptLines).op_aset(context, newString(context, file), list); return list; } public IRubyObject getLineStub(ThreadContext context, ParseResult result, int lineCount) { - var lines = context.runtime.newArray(); + var lines = newArray(context); LineStubVisitor lineVisitor = new LineStubVisitor(context.runtime, lines); lineVisitor.visitRootNode(((RootNode) result)); diff --git a/core/src/main/java/org/jruby/parser/StaticScope.java b/core/src/main/java/org/jruby/parser/StaticScope.java index 822b8ad8279..c24b55b3217 100644 --- a/core/src/main/java/org/jruby/parser/StaticScope.java +++ b/core/src/main/java/org/jruby/parser/StaticScope.java @@ -45,6 +45,7 @@ import org.jruby.RubyBasicObject; import org.jruby.RubyModule; import org.jruby.RubySymbol; +import org.jruby.api.Create; import org.jruby.ast.AssignableNode; import org.jruby.ast.DAsgnNode; import org.jruby.ast.DVarNode; diff --git a/core/src/main/java/org/jruby/runtime/ArgumentDescriptor.java b/core/src/main/java/org/jruby/runtime/ArgumentDescriptor.java index 11c325706fd..c44ee5fe740 100644 --- a/core/src/main/java/org/jruby/runtime/ArgumentDescriptor.java +++ b/core/src/main/java/org/jruby/runtime/ArgumentDescriptor.java @@ -10,6 +10,7 @@ import java.util.Arrays; import static org.jruby.api.Create.newString; +import static org.jruby.api.Create.newSymbol; /** * A description of a single argument in a Ruby argument list. Primarily used in Method.to_proc. @@ -40,9 +41,19 @@ public ArgumentDescriptor(ArgumentType type) { this(type, null); } + /** + * @param runtime + * @param isLambda + * @return "" + * @deprecated Use {@link ArgumentDescriptor#toArrayForm(ThreadContext, boolean)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public final RubyArray toArrayForm(Ruby runtime, boolean isLambda) { - ArgumentType argType = type == ArgumentType.req && !isLambda ? ArgumentType.opt : type; + return toArrayForm(runtime.getCurrentContext(), isLambda); + } + public final RubyArray toArrayForm(ThreadContext context, boolean isLambda) { + ArgumentType argType = type == ArgumentType.req && !isLambda ? ArgumentType.opt : type; RubySymbol name = this.name; // FIXME: When consolidating block and method parameter arg descriptors eliminate this special *,** handling. @@ -52,13 +63,13 @@ public final RubyArray toArrayForm(Ruby runtime, boolean isLambda) { // methods we have no reference to runtime to construct the symbol for `*` or `**`. if (!type.anonymous && name.getBytes().length() == 0) { if (type == ArgumentType.rest) { - name = runtime.newSymbol("*"); + name = newSymbol(context, "*"); } else if (type == ArgumentType.keyrest) { - name = runtime.newSymbol("**"); + name = newSymbol(context, "**"); } } - return argType.toArrayForm(runtime, name); + return argType.toArrayForm(context, name); } public RubyString asParameterName(ThreadContext context) { diff --git a/core/src/main/java/org/jruby/runtime/ArgumentType.java b/core/src/main/java/org/jruby/runtime/ArgumentType.java index c9e0b9c17f4..2460e5bea15 100644 --- a/core/src/main/java/org/jruby/runtime/ArgumentType.java +++ b/core/src/main/java/org/jruby/runtime/ArgumentType.java @@ -5,6 +5,9 @@ import org.jruby.RubySymbol; import org.jruby.internal.runtime.methods.DescriptorInfo; +import static org.jruby.api.Create.newArray; +import static org.jruby.api.Create.newSymbol; + /** * The diffierent types of arguments identified in a method. */ @@ -66,10 +69,21 @@ static char prefixFrom(ArgumentType type) { } } + /** + * @param runtime + * @param name + * @return "" + * @deprecated Use #{@link ArgumentType#toArrayForm(ThreadContext, RubySymbol)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public RubyArray toArrayForm(Ruby runtime, RubySymbol name) { - RubySymbol typeName = runtime.newSymbol(typeId); + return toArrayForm(runtime.getCurrentContext(), name); + } + + public RubyArray toArrayForm(ThreadContext context, RubySymbol name) { + RubySymbol typeName = newSymbol(context, typeId); - return anonymous ? runtime.newArray(typeName) : runtime.newArray(typeName, name); + return anonymous ? newArray(context, typeName) : newArray(context, typeName, name); } public ArgumentType anonymousForm() { diff --git a/core/src/main/java/org/jruby/runtime/Helpers.java b/core/src/main/java/org/jruby/runtime/Helpers.java index dcfcd8601f1..4ad628ddc74 100644 --- a/core/src/main/java/org/jruby/runtime/Helpers.java +++ b/core/src/main/java/org/jruby/runtime/Helpers.java @@ -82,6 +82,7 @@ import static org.jruby.RubyBasicObject.getMetaClass; import static org.jruby.api.Convert.asBoolean; +import static org.jruby.api.Create.*; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.ThreadContext.CALL_KEYWORD_EMPTY; import static org.jruby.runtime.Visibility.*; @@ -424,10 +425,9 @@ public static RubyModule getNthScopeModule(StaticScope scope, int depth) { public static RubyArray viewArgsArray(ThreadContext context, RubyArray rubyArray, int preArgsCount, int postArgsCount) { int n = rubyArray.getLength(); - if (preArgsCount + postArgsCount >= n) { - return RubyArray.newEmptyArray(context.runtime); - } - return (RubyArray)rubyArray.subseq(context.runtime.getArray(), preArgsCount, n - preArgsCount - postArgsCount, true); + return preArgsCount + postArgsCount >= n ? + newEmptyArray(context) : + (RubyArray) rubyArray.subseq(context.runtime.getArray(), preArgsCount, n - preArgsCount - postArgsCount, true); } public static Class[] getStaticMethodParams(Class target, int args) { @@ -1912,45 +1912,52 @@ public static IRubyObject getLastLine(Ruby runtime, ThreadContext context) { } public static RubyArray arrayValue(IRubyObject value) { - Ruby runtime = value.getRuntime(); - return arrayValue(runtime.getCurrentContext(), runtime, value); + return arrayValue(value.getRuntime().getCurrentContext(), value); } + /** + * @param context + * @param runtime + * @param value + * @return "" + * @deprecated Use {@link Helpers#arrayValue(ThreadContext, IRubyObject)} + */ + @Deprecated(since = "10.0") public static RubyArray arrayValue(ThreadContext context, Ruby runtime, IRubyObject value) { + return arrayValue(context, value); + } + + public static RubyArray arrayValue(ThreadContext context, IRubyObject value) { IRubyObject tmp = value.checkArrayType(); if (tmp.isNil()) { if (value.respondsTo("to_a")) { IRubyObject avalue = value.callMethod(context, "to_a"); - if (!(avalue instanceof RubyArray)) { - if (avalue.isNil()) { - return runtime.newArray(value); - } else { - throw typeError(context, "`to_a' did not return Array"); - } - } - return (RubyArray)avalue; + if (avalue instanceof RubyArray ary) return ary; + if (avalue.isNil()) return newArray(context, value); + + throw typeError(context, "`to_a' did not return Array"); } else { CacheEntry entry = value.getMetaClass().searchWithCache("method_missing"); DynamicMethod methodMissing = entry.method; - if (methodMissing.isUndefined() || runtime.isDefaultMethodMissing(methodMissing)) { - return runtime.newArray(value); + if (methodMissing.isUndefined() || context.runtime.isDefaultMethodMissing(methodMissing)) { + return newArray(context, value); } else { - IRubyObject avalue = methodMissing.call(context, value, entry.sourceModule, "to_a", new IRubyObject[] {runtime.newSymbol("to_a")}, Block.NULL_BLOCK); + IRubyObject avalue = methodMissing.call(context, value, entry.sourceModule, "to_a", + new IRubyObject[] {newSymbol(context, "to_a")}, Block.NULL_BLOCK); if (!(avalue instanceof RubyArray)) { if (avalue.isNil()) { - return runtime.newArray(value); + return newArray(context, value); } else { throw typeError(context, "`to_a' did not return Array"); } } - return (RubyArray)avalue; + return (RubyArray)avalue; } } } - RubyArray arr = (RubyArray) tmp; - return arr.aryDup(); + return ((RubyArray) tmp).aryDup(); } // mri: rb_Array @@ -1969,7 +1976,7 @@ public static IRubyObject aryToAry(ThreadContext context, IRubyObject value) { return respondsTo_to_ary(value) ? TypeConverter.convertToTypeUnchecked(context, value, context.runtime.getArray(), "to_ary", false) : - context.runtime.newArray(value); + newArray(context, value); } private static boolean respondsTo_to_ary(IRubyObject value) { @@ -2001,13 +2008,10 @@ public static IRubyObject aValueSplat(IRubyObject value) { return array.getLength() == 1 ? array.first() : array; } - @Deprecated // not used + @Deprecated(since = "9.4-") // not used public static RubyArray splatValue(IRubyObject value) { - if (value.isNil()) { - return value.getRuntime().newArray(value); - } - - return arrayValue(value); + var context = value.getRuntime().getCurrentContext(); + return value.isNil() ? newArray(context, value) : arrayValue(context, value); } @Deprecated // no longer used @@ -2668,15 +2672,26 @@ public static ArgumentDescriptor[] parameterListToArgumentDescriptors(Ruby runti return parms; } - /** Convert a parameter list from ArgumentDescriptor format to "Array of Array" format */ + /** + * @param runtime + * @param argsDesc + * @param isLambda + * @return "" + * @deprecated Use {@link Helpers#argumentDescriptorsToParameters(ThreadContext, ArgumentDescriptor[], boolean)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public static RubyArray argumentDescriptorsToParameters(Ruby runtime, ArgumentDescriptor[] argsDesc, boolean isLambda) { + return argumentDescriptorsToParameters(runtime.getCurrentContext(), argsDesc, isLambda); + } + + /** Convert a parameter list from ArgumentDescriptor format to "Array of Array" format */ + public static RubyArray argumentDescriptorsToParameters(ThreadContext context, ArgumentDescriptor[] argsDesc, boolean isLambda) { if (argsDesc == null) Thread.dumpStack(); - final RubyArray params = RubyArray.newBlankArray(runtime, argsDesc.length); + final var params = newArray(context, argsDesc.length); for (int i = 0; i < argsDesc.length; i++) { - ArgumentDescriptor param = argsDesc[i]; - params.store(i, param.toArrayForm(runtime, isLambda)); + params.store(i, argsDesc[i].toArrayForm(context, isLambda)); } return params; diff --git a/core/src/main/java/org/jruby/runtime/NullBlockBody.java b/core/src/main/java/org/jruby/runtime/NullBlockBody.java index 667affaf214..f32a74f6e3d 100644 --- a/core/src/main/java/org/jruby/runtime/NullBlockBody.java +++ b/core/src/main/java/org/jruby/runtime/NullBlockBody.java @@ -5,6 +5,8 @@ import org.jruby.parser.StaticScope; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newArray; + public class NullBlockBody extends BlockBody { public NullBlockBody() { super(Signature.NO_ARGUMENTS); @@ -33,7 +35,7 @@ public IRubyObject yieldSpecific(ThreadContext context, Block block, IRubyObject } @Override public IRubyObject call(ThreadContext context, Block block, IRubyObject arg0, IRubyObject arg1) { - throw context.runtime.newLocalJumpError(RubyLocalJumpError.Reason.NOREASON, RubyArray.newArray(context.runtime, arg0, arg1), "no block given"); + throw context.runtime.newLocalJumpError(RubyLocalJumpError.Reason.NOREASON, newArray(context, arg0, arg1), "no block given"); } @Override public IRubyObject yieldSpecific(ThreadContext context, Block block, IRubyObject arg0, IRubyObject arg1) { diff --git a/core/src/main/java/org/jruby/runtime/ThreadContext.java b/core/src/main/java/org/jruby/runtime/ThreadContext.java index 7b36ca93c1c..543fac6d783 100644 --- a/core/src/main/java/org/jruby/runtime/ThreadContext.java +++ b/core/src/main/java/org/jruby/runtime/ThreadContext.java @@ -81,6 +81,7 @@ import java.util.stream.Stream; import static org.jruby.RubyBasicObject.NEVER; +import static org.jruby.api.Create.newEmptyArray; import static org.jruby.api.Error.typeError; public final class ThreadContext { @@ -909,9 +910,9 @@ public IRubyObject createCallerLocations(int level, Integer length, Stream loadedFeaturesIndex = new ConcurrentHashMap<>(64); public LibrarySearcher(LoadService loadService) { - Ruby runtime = loadService.runtime; + this.runtime = loadService.runtime; + var context = runtime.getCurrentContext(); - this.runtime = runtime; - this.loadPath = RubyArray.newArray(runtime); + this.loadPath = newArray(context); this.loadService = loadService; - this.cwdPathEntry = new NormalPathEntry(runtime.newString(".")); - this.classloaderPathEntry = new NormalPathEntry(runtime.newString(URLResource.URI_CLASSLOADER)); + this.cwdPathEntry = new NormalPathEntry(newString(context, ".")); + this.classloaderPathEntry = new NormalPathEntry(newString(context, URLResource.URI_CLASSLOADER)); this.nullPathEntry = new NullPathEntry(); this.homePathEntry = new HomePathEntry(); - this.loadedFeaturesSnapshot = runtime.newArray(); + this.loadedFeaturesSnapshot = newArray(context); } public List getExpandedLoadPath() { diff --git a/core/src/main/java/org/jruby/runtime/load/LoadService.java b/core/src/main/java/org/jruby/runtime/load/LoadService.java index 5a6cc775f09..89d238dc419 100644 --- a/core/src/main/java/org/jruby/runtime/load/LoadService.java +++ b/core/src/main/java/org/jruby/runtime/load/LoadService.java @@ -76,8 +76,7 @@ import org.jruby.util.log.Logger; import org.jruby.util.log.LoggerFactory; -import static org.jruby.api.Create.newString; -import static org.jruby.api.Create.newSymbol; +import static org.jruby.api.Create.*; import static org.jruby.util.URLUtil.getPath; /** @@ -207,7 +206,8 @@ public LoadService(Ruby runtime) { * @param prependDirectories */ public void init(List prependDirectories) { - loadPath = RubyArray.newArray(runtime); + var context = runtime.getCurrentContext(); + loadPath = newArray(context); loadPath.getMetaClass().defineAnnotatedMethods(LoadPathMethods.class); String jrubyHome = runtime.getJRubyHome(); @@ -221,10 +221,10 @@ public void init(List prependDirectories) { // add $RUBYLIB paths RubyHash env = (RubyHash) runtime.getObject().getConstant("ENV"); - RubyString env_rubylib = runtime.newString("RUBYLIB"); - ThreadContext currentContext = runtime.getCurrentContext(); - if (env.has_key_p(currentContext, env_rubylib).isTrue()) { - String rubylib = env.op_aref(currentContext, env_rubylib).toString(); + RubyString env_rubylib = newString(context, "RUBYLIB"); + + if (env.has_key_p(context, env_rubylib).isTrue()) { + String rubylib = env.op_aref(context, env_rubylib).toString(); String[] paths = rubylib.split(File.pathSeparator); addPaths(paths); } @@ -248,9 +248,8 @@ public void init(List prependDirectories) { addPath(RbConfigLibrary.getVendorDir(runtime)); } String rubygemsDir = RbConfigLibrary.getRubygemsDir(runtime); - if (rubygemsDir != null) { - addPath(rubygemsDir); - } + if (rubygemsDir != null) addPath(rubygemsDir); + addPath(RbConfigLibrary.getRubyLibDir(runtime)); } @@ -330,7 +329,7 @@ public static IRubyObject resolve_feature_path(ThreadContext context, IRubyObjec name = newString(context, libraryHolder[0].getLoadName()); } - return context.runtime.newArray(ext, name); + return newArray(context, ext, name); } } diff --git a/core/src/main/java/org/jruby/specialized/RubyArrayTwoObject.java b/core/src/main/java/org/jruby/specialized/RubyArrayTwoObject.java index 1b008b80b10..37450584943 100644 --- a/core/src/main/java/org/jruby/specialized/RubyArrayTwoObject.java +++ b/core/src/main/java/org/jruby/specialized/RubyArrayTwoObject.java @@ -7,6 +7,7 @@ import org.jruby.RubyComparable; import org.jruby.RubyFixnum; import org.jruby.RubyString; +import org.jruby.api.Create; import org.jruby.javasupport.JavaUtil; import org.jruby.runtime.Block; import org.jruby.runtime.JavaSites; @@ -242,11 +243,10 @@ protected RubyArray safeReverse() { protected IRubyObject sortInternal(ThreadContext context, Block block) { if (!packed()) return super.sortInternal(context, block); - IRubyObject car = this.car; IRubyObject cdr = this.cdr; - IRubyObject ret = block.yieldArray(context, newArray(context.runtime, car, cdr), null); + IRubyObject ret = block.yieldArray(context, Create.newArray(context, car, cdr), null); //TODO: ary_sort_check should be done here int compare = RubyComparable.cmpint(context, ret, car, cdr); if (compare > 0) reverse_bang(context); @@ -350,28 +350,21 @@ public IRubyObject uniq(ThreadContext context) { @Override public RubyArray collectArray(ThreadContext context, Block block) { if (!packed()) return super.collectArray(context, block); - if (!block.isGiven()) return makeShared(); - Ruby runtime = context.runtime; - IRubyObject newCar = block.yieldNonArray(context, this.car, null); - if (realLength == 2) { - // no size change, yield last elt and return - return new RubyArrayTwoObject( - runtime, - newCar, - block.yieldNonArray(context, cdr, null)); + + if (realLength == 2) { // no size change, yield last elt and return + return new RubyArrayTwoObject(context.runtime, newCar, block.yieldNonArray(context, cdr, null)); } // size has changed, unpack and continue with loop form unpack(context); int currentLength = this.realLength; - IRubyObject[] arr = IRubyObject.array(currentLength); - - if (currentLength == 0) return runtime.newEmptyArray(); + if (currentLength == 0) return Create.newEmptyArray(context); + IRubyObject[] arr = IRubyObject.array(currentLength); arr[0] = newCar; int i = 1; diff --git a/core/src/main/java/org/jruby/util/Pack.java b/core/src/main/java/org/jruby/util/Pack.java index 9a4c758d9bc..aeef83c8763 100644 --- a/core/src/main/java/org/jruby/util/Pack.java +++ b/core/src/main/java/org/jruby/util/Pack.java @@ -960,7 +960,7 @@ public static IRubyObject unpack1WithBlock(ThreadContext context, RubyString enc private static IRubyObject unpackInternal(ThreadContext context, RubyString encoded, ByteList formatString, int mode, long offset, Block block) { final Ruby runtime = context.runtime; - final RubyArray result = (mode == UNPACK_BLOCK) || (mode == UNPACK_1) ? null : runtime.newArray(); + final var result = mode == UNPACK_BLOCK || mode == UNPACK_1 ? null : newArray(context); final ByteList encodedString = encoded.getByteList(); int len = encodedString.realSize(); diff --git a/core/src/main/java/org/jruby/util/StringSupport.java b/core/src/main/java/org/jruby/util/StringSupport.java index 501e1e86edf..a9f31ae0a26 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.Create.newArray; import static org.jruby.api.Error.argumentError; public final class StringSupport { @@ -2171,14 +2172,13 @@ else if (!wantarray) { } if (arg == context.nil) { // rs - if (wantarray) return RubyArray.newArray(runtime, str); - else { - block.yieldSpecific(context, str); - return orig; - } + if (wantarray) return newArray(context, str); + + block.yieldSpecific(context, str); + return orig; } - final RubyArray ary = wantarray ? RubyArray.newArray(runtime) : null; + final var ary = wantarray ? newArray(context) : null; final IRubyObject defaultSep = runtime.getGlobalVariables().get("$/"); RubyString rs = arg.convertToString(); diff --git a/core/src/main/java/org/jruby/util/SunSignalFacade.java b/core/src/main/java/org/jruby/util/SunSignalFacade.java index 2d97e46076e..e0bee3ebcee 100644 --- a/core/src/main/java/org/jruby/util/SunSignalFacade.java +++ b/core/src/main/java/org/jruby/util/SunSignalFacade.java @@ -50,6 +50,7 @@ import java.util.HashMap; import java.util.Map; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newFixnum; /** @@ -196,7 +197,7 @@ private static IRubyObject getSignalResult(final Ruby runtime, final SignalHandl callback = jsHandler.blockCallback; } else { ret = jsHandler.block; - return RubyArray.newArray(runtime, ret, handledBoolean); + return newArray(runtime.getCurrentContext(), ret, handledBoolean); } } diff --git a/core/src/main/java/org/jruby/util/TypeConverter.java b/core/src/main/java/org/jruby/util/TypeConverter.java index 360cc1a98cd..97388584ec3 100644 --- a/core/src/main/java/org/jruby/util/TypeConverter.java +++ b/core/src/main/java/org/jruby/util/TypeConverter.java @@ -51,6 +51,7 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newSymbol; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; @@ -480,9 +481,7 @@ public static RubyArray rb_Array(ThreadContext context, IRubyObject val) { if (tmp == context.nil) { TypeConverterSites sites = sites(context); tmp = convertToTypeWithCheck(context, val, context.runtime.getArray(), sites.to_a_checked); - if (tmp == context.nil) { - return context.runtime.newArray(val); - } + if (tmp == context.nil) return newArray(context, val); } return (RubyArray) tmp; } 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 2061f872c5a..c6945883ac6 100644 --- a/core/src/main/java/org/jruby/util/io/PopenExecutor.java +++ b/core/src/main/java/org/jruby/util/io/PopenExecutor.java @@ -44,8 +44,7 @@ import java.util.Set; 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; /** @@ -379,23 +378,22 @@ 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 = runtime.newArray(); + var env = newArray(context); for (Map.Entry entry : (Set>)hash.directEntrySet()) { IRubyObject key = entry.getKey(); IRubyObject val = entry.getValue(); - RubyString keyString = StringSupport.checkEmbeddedNulls(runtime, key).export(context); + RubyString keyString = StringSupport.checkEmbeddedNulls(context.runtime, key).export(context); String k = keyString.toString(); if (k.indexOf('=') != -1) throw argumentError(context, "environment name contains a equal : " + k); - if (!val.isNil()) val = StringSupport.checkEmbeddedNulls(runtime, val); + if (!val.isNil()) val = StringSupport.checkEmbeddedNulls(context.runtime, val); if (!val.isNil()) val = ((RubyString) val).export(context); if (k.equalsIgnoreCase("PATH")) pathArg.path_env = val; - env.push(runtime.newArray(keyString, val)); + env.push(newArray(context, keyString, val)); } return env; @@ -988,17 +986,17 @@ static int saveRedirectFd(ThreadContext context, int fd, ExecArg sargp, String[] newary = sargp.fd_dup2; if (newary == null) { - newary = context.runtime.newArray(); + newary = newArray(context); sargp.fd_dup2 = newary; } - newary.push(context.runtime.newArray(newFixnum(context, fd), newFixnum(context, save_fd))); + newary.push(newArray(context, newFixnum(context, fd), newFixnum(context, save_fd))); newary = sargp.fd_close; if (newary == null) { - newary = context.runtime.newArray(); + newary = newArray(context); sargp.fd_close = newary; } - newary.push(context.runtime.newArray(newFixnum(context, save_fd), context.nil)); + newary.push(newArray(context, newFixnum(context, save_fd), context.nil)); } return 0; @@ -1336,7 +1334,7 @@ else if (false && // unsupported IRubyObject ary; IRubyObject tmp, softlim, hardlim; if (eargp.rlimit_limits == null) - ary = eargp.rlimit_limits = context.runtime.newArray(); + ary = eargp.rlimit_limits = newArray(context); else ary = eargp.rlimit_limits; tmp = TypeConverter.checkArrayType(context.runtime, val); @@ -1352,7 +1350,7 @@ else if (((RubyArray)tmp).size() == 2) { } else { softlim = hardlim = val.convertToInteger(); } - tmp = RubyArray.newArray(context.runtime, newFixnum(context, rtype), softlim, hardlim); + tmp = newArray(context, newFixnum(context, rtype), softlim, hardlim); ((RubyArray)ary).push(tmp); } else if (id.equals("unsetenv_others")) { @@ -1518,7 +1516,7 @@ else if (flags instanceof RubyString) flags = newFixnum(context, intFlags); perm = ((RubyArray)val).entry(2); perm = perm.isNil() ? newFixnum(context, 0644) : perm.convertToInteger(); - param = RubyArray.newArray(context.runtime, + param = newArray(context, ((RubyString)path).strDup(context.runtime).export(context), flags, perm); @@ -1555,10 +1553,7 @@ else if (flags instanceof RubyString) flags = newFixnum(context, OpenFlags.O_RDONLY.intValue()); } perm = newFixnum(context, 0644); - param = RubyArray.newArray(context.runtime, - ((RubyString)path).strDup(context.runtime).export(context), - flags, - perm); + param = newArray(context, ((RubyString)path).strDup(context.runtime).export(context), flags, perm); eargp.fd_open = checkExecRedirect1(context, eargp.fd_open, key, param); break; @@ -1617,20 +1612,16 @@ else if (id.equals("err")) // MRI: check_exec_redirect1 static RubyArray checkExecRedirect1(ThreadContext context, RubyArray ary, IRubyObject key, IRubyObject param) { - if (ary == null) { - ary = context.runtime.newArray(); - } + if (ary == null) ary = newArray(context); + if (!(key instanceof RubyArray)) { IRubyObject fd = checkExecRedirectFd(context, key, !param.isNil()); - ary.push(context.runtime.newArray(fd, param)); - } - else { - int i, n=0; - for (i = 0 ; i < ((RubyArray)key).size(); i++) { + ary.push(newArray(context, fd, param)); + } else { + for (int i = 0 ; i < ((RubyArray)key).size(); i++) { IRubyObject v = ((RubyArray)key).eltOk(i); IRubyObject fd = checkExecRedirectFd(context, v, !param.isNil()); - ary.push(context.runtime.newArray(fd, param)); - n++; + ary.push(newArray(context, fd, param)); } } return ary; @@ -1655,13 +1646,13 @@ private static RubyString execargInit(ThreadContext context, IRubyObject[] argv, prog = execGetargs(context, argv_p, accept_shell, env_opt); IRubyObject opt = env_opt[1]; RubyHash optHash; - RubySymbol exceptionSym = context.runtime.newSymbol("exception"); + RubySymbol exceptionSym = newSymbol(context, "exception"); if (allow_exc_opt && !opt.isNil() && (optHash = ((RubyHash) opt)).has_key_p(context, exceptionSym).isTrue()) { optHash = optHash.dupFast(context); exception = optHash.delete(context, exceptionSym); } - RubySymbol chdirSym = context.runtime.newSymbol("chdir"); + RubySymbol chdirSym = newSymbol(context, "chdir"); IRubyObject chdir; if (!optForChdir.isNil() && (chdir = ((RubyHash) optForChdir).delete(chdirSym)) != null) { eargp.chdirGiven = true; @@ -1678,7 +1669,6 @@ private static RubyString execargInit(ThreadContext context, IRubyObject[] argv, // rb_exec_getargs private static RubyString execGetargs(ThreadContext context, IRubyObject[][] argv_p, boolean accept_shell, IRubyObject[] env_opt) { - Ruby runtime = context.runtime; IRubyObject hash; RubyString prog; int beg = 0; @@ -1686,14 +1676,14 @@ private static RubyString execGetargs(ThreadContext context, IRubyObject[][] arg // extract environment and options from args if (end >= 1) { - hash = TypeConverter.checkHashType(runtime, argv_p[0][end - 1]); + hash = TypeConverter.checkHashType(context.runtime, argv_p[0][end - 1]); if (!hash.isNil()) { env_opt[1] = hash; end--; } } if (end >= 1) { - hash = TypeConverter.checkHashType(runtime, argv_p[0][0]); + hash = TypeConverter.checkHashType(context.runtime, argv_p[0][0]); if (!hash.isNil()) { env_opt[0] = hash; beg++; @@ -1707,9 +1697,7 @@ private static RubyString execGetargs(ThreadContext context, IRubyObject[][] arg if (prog == null) { // use first arg as program name and clear argv if we can use sh prog = (RubyString)argv_p[0][0]; - if (accept_shell && (end - beg) == 1) { - argv_p[0] = IRubyObject.NULL_ARRAY; - } + if (accept_shell && (end - beg) == 1) argv_p[0] = IRubyObject.NULL_ARRAY; } return prog; diff --git a/core/src/main/java/org/jruby/util/io/SelectExecutor.java b/core/src/main/java/org/jruby/util/io/SelectExecutor.java index f059792fcd3..8fedf846b53 100644 --- a/core/src/main/java/org/jruby/util/io/SelectExecutor.java +++ b/core/src/main/java/org/jruby/util/io/SelectExecutor.java @@ -24,6 +24,7 @@ import java.util.concurrent.Future; import static com.headius.backport9.buffer.Buffers.flipBuffer; +import static org.jruby.api.Create.newArray; /** * Created by headius on 6/3/14. @@ -151,11 +152,11 @@ IRubyObject selectInternal(ThreadContext context) throws IOException { if (n == 0 && pendingReadFDs == null && n == 0 && unselectableReadFDs == null && unselectableWriteFDs == null) return context.nil; /* returns nil on timeout */ - res = RubyArray.newArray(runtime, 3); - res.push(runtime.newArray(Math.min(n, maxReadReadySize()))); - res.push(runtime.newArray(Math.min(n, maxWriteReadySize()))); + res = newArray(context, 3); + res.push(newArray(context, Math.min(n, maxReadReadySize()))); + res.push(newArray(context, Math.min(n, maxWriteReadySize()))); // we never add anything for error since JDK does not provide a way to select for error - res.push(runtime.newArray(0)); + res.push(newArray(context, 0)); if (readKeyList != null) { list = (RubyArray) res.eltOk(0); 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 9748fca2719..83eb7a19006 100644 --- a/core/src/main/java/org/jruby/util/io/Sockaddr.java +++ b/core/src/main/java/org/jruby/util/io/Sockaddr.java @@ -31,8 +31,7 @@ import org.jruby.ext.socket.SocketUtilsIPV6; import org.jruby.runtime.Helpers; -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; @@ -222,7 +221,7 @@ public static RubyArray unpack_sockaddr_in(ThreadContext context, IRubyObject ad throw argumentError(context, "not an AF_INET/AF_INET6 sockaddr"); } - return RubyArray.newArray(context.runtime, addrinfo.ip_port(context), addrinfo.ip_address(context)); + return newArray(context, addrinfo.ip_port(context), addrinfo.ip_address(context)); } return unpack_sockaddr_in(context, addr.convertToString().getByteList()); @@ -257,7 +256,7 @@ public static RubyArray unpack_sockaddr_in(ThreadContext context, ByteList val) ip = newString(context, SocketUtilsIPV6.getIPV6Address(formatAddr.toString())); } - return RubyArray.newArray(context.runtime, newFixnum(context, port), ip); + return newArray(context, newFixnum(context, port), ip); } public static IRubyObject pack_sockaddr_un(ThreadContext context, String unixpath) { diff --git a/core/src/test/java/org/jruby/exceptions/TestRaiseException.java b/core/src/test/java/org/jruby/exceptions/TestRaiseException.java index 3c6bf09e352..690472296d9 100644 --- a/core/src/test/java/org/jruby/exceptions/TestRaiseException.java +++ b/core/src/test/java/org/jruby/exceptions/TestRaiseException.java @@ -21,7 +21,7 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import static org.jruby.api.Create.newString; +import static org.jruby.api.Create.*; public class TestRaiseException extends Base { @@ -73,9 +73,10 @@ public void testToString() { } public void testFromWithBacktrace() { + var context = runtime.getCurrentContext(); final int count = runtime.getExceptionCount(); - final IRubyObject backtrace = runtime.newArray(); + final IRubyObject backtrace = newArray(context); RaiseException ex = RaiseException.from(runtime, runtime.getArgumentError(), "testFromWithBacktrace", backtrace); assertEquals( count + 1, runtime.getExceptionCount() ); @@ -86,10 +87,11 @@ public void testFromWithBacktrace() { } public void testFromLegacyOnlyPreRaisesOnce() { + var context = runtime.getCurrentContext(); final int count = runtime.getExceptionCount(); - final IRubyObject ex = runtime.getRuntimeError().newInstance(runtime.getCurrentContext(), Block.NULL_BLOCK); - RaiseException.from((RubyException) ex, runtime.newArrayLight()); + final IRubyObject ex = runtime.getRuntimeError().newInstance(context, Block.NULL_BLOCK); + RaiseException.from((RubyException) ex, RubyArray.newArrayLight(runtime)); assertEquals( count + 1, runtime.getExceptionCount() ); @@ -448,6 +450,7 @@ public IRubyObject raise_from_nil(ThreadContext context) { public void testNewRaiseException() { Ruby ruby = Ruby.newInstance(); + var context = ruby.getCurrentContext(); try { throw ruby.newRaiseException(ruby.getException(), "blah"); @@ -461,7 +464,7 @@ public void testNewRaiseException() { assertEquals("(Exception) blah", e.getMessage()); } - RubyArray backtrace = ruby.newEmptyArray(); + var backtrace = newEmptyArray(context); try { throw RaiseException.from(ruby, ruby.getException(), "blah", backtrace); } catch (Exception e) { @@ -469,12 +472,12 @@ public void testNewRaiseException() { assertEquals(backtrace, e.getException().backtrace()); } - RubyString message = newString(ruby.getCurrentContext(), "blah"); + RubyString message = newString(context, "blah"); try { throw RaiseException.from(ruby, ruby.getException(), message); } catch (Exception e) { assertEquals("(Exception) blah", e.getMessage()); - assertEquals(message, e.getException().message(ruby.getCurrentContext())); + assertEquals(message, e.getException().message(context)); } try { @@ -494,7 +497,7 @@ public void testNewRaiseException() { throw RaiseException.from(ruby, "Exception", message); } catch (Exception e) { assertEquals("(Exception) blah", e.getMessage()); - assertEquals(message, e.getException().message(ruby.getCurrentContext())); + assertEquals(message, e.getException().message(context)); } } } diff --git a/core/src/test/java/org/jruby/javasupport/JavaEmbedUtilsTest.java b/core/src/test/java/org/jruby/javasupport/JavaEmbedUtilsTest.java index f010d1113ed..7336ca982b4 100644 --- a/core/src/test/java/org/jruby/javasupport/JavaEmbedUtilsTest.java +++ b/core/src/test/java/org/jruby/javasupport/JavaEmbedUtilsTest.java @@ -9,6 +9,7 @@ import java.util.Collections; import java.util.List; +import static org.jruby.api.Create.newEmptyArray; import static org.jruby.api.Create.newFixnum; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -77,6 +78,7 @@ public void testAddClassloaderToLoadPathOnNoneTCCL() throws Exception { @Test public void testAPIUsageTheNonGenericWay() { // before generic signatures were introduced (JRuby <= 9.4.0) final Ruby runtime = Ruby.newInstance(); + var context = runtime.getCurrentContext(); IRubyObject str = runtime.evalScriptlet("'foo'"); Object javaStr = JavaEmbedUtils.rubyToJava(runtime, str, String.class); assertEquals("foo", javaStr); @@ -85,7 +87,7 @@ public void testAPIUsageTheNonGenericWay() { // before generic signatures we javaStr = JavaEmbedUtils.rubyToJava(runtime, str, Object.class); assertEquals("barbarbar", javaStr); - Object val = JavaEmbedUtils.rubyToJava(runtime.newEmptyArray()); + Object val = JavaEmbedUtils.rubyToJava(newEmptyArray(context)); assertEquals("org.jruby.RubyArray", val.getClass().getName()); } diff --git a/core/src/test/java/org/jruby/test/TestArrayFlatten.java b/core/src/test/java/org/jruby/test/TestArrayFlatten.java index 5916ef30d89..5358d09ef7b 100644 --- a/core/src/test/java/org/jruby/test/TestArrayFlatten.java +++ b/core/src/test/java/org/jruby/test/TestArrayFlatten.java @@ -8,26 +8,23 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Create.newFixnum; public class TestArrayFlatten extends TestCase { public void testFlatten() { - Ruby runtime = Ruby.newInstance(); - ThreadContext context = runtime.getCurrentContext(); - RubyArray keys = runtime.newArray(); - RubyArray values = runtime.newArray(); - -// int n = 10; - int n = 10000; - for (int i = 0; i < n; ++i) { - keys.append(newFixnum(context, i)); - values.append(newFixnum(context, i)); + var context = Ruby.newInstance().getCurrentContext(); + var keys = newArray(context); + var values = newArray(context); + + for (int i = 0; i < 10_000; ++i) { + keys.append(context, newFixnum(context, i)); + values.append(context, newFixnum(context, i)); } - RubyArray temp = (RubyArray) keys.zip(context, new IRubyObject[] {values}, Block.NULL_BLOCK); - RubyArray preHash = (RubyArray) temp.flatten(context); - + var preHash = ((RubyArray) keys.zip(context, new IRubyObject[] {values}, Block.NULL_BLOCK)).flatten(context); + assertNotNull("We have a hash back", preHash); } } diff --git a/core/src/test/java/org/jruby/test/TestObjectSpace.java b/core/src/test/java/org/jruby/test/TestObjectSpace.java index 501a40665e8..1f3b695ec6f 100644 --- a/core/src/test/java/org/jruby/test/TestObjectSpace.java +++ b/core/src/test/java/org/jruby/test/TestObjectSpace.java @@ -42,6 +42,9 @@ import org.jruby.runtime.ObjectSpace; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newArray; +import static org.jruby.api.Create.newString; + /** * @author Anders */ @@ -78,10 +81,11 @@ public void testIdentities() { } public void testObjectSpace() { - IRubyObject o1 = runtime.newArray(10); - IRubyObject o2 = runtime.newArray(20); - IRubyObject o3 = runtime.newArray(30); - IRubyObject o4 = runtime.newString("hello"); + var context = runtime.getCurrentContext(); + IRubyObject o1 = newArray(context, 10); + IRubyObject o2 = newArray(context, 20); + IRubyObject o3 = newArray(context, 30); + IRubyObject o4 = newString(context, "hello"); target.add(o1); target.add(o2);