diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27793314754..16ab83d5e05 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: strategy: matrix: target: ['test:jruby:int', 'spec:ruby:fast', 'spec:ji', 'spec:ffi'] - java-version: ['17', '21', '23'] + java-version: ['21', '23'] fail-fast: false name: rake ${{ matrix.target }} (Java ${{ matrix.java-version }}) @@ -24,8 +24,8 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk - name: set up java ${{ matrix.java-version }} uses: actions/setup-java@v3 with: @@ -39,7 +39,7 @@ jobs: - name: rake ${{ matrix.target }} run: bin/jruby -S rake ${{ matrix.target }} - rake-test-17: + rake-test-21: runs-on: ubuntu-latest strategy: @@ -47,18 +47,18 @@ jobs: target: ['test:mri:core:jit', 'test:mri:extra', 'spec:ruby:fast:jit', 'test:mri:stdlib', 'spec:ruby:slow', 'spec:ruby:debug', 'test:jruby:aot', 'test:slow_suites', 'spec:compiler', 'spec:regression', 'spec:jruby', 'spec:jrubyc', 'spec:profiler'] fail-fast: false - name: rake ${{ matrix.target }} (Java 17) + name: rake ${{ matrix.target }} (Java 21) steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk - - name: set up java 17 + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'zulu' - java-version: '17' + java-version: '21' cache: 'maven' - name: bootstrap run: mvn -Pbootstrap clean package @@ -79,13 +79,13 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk - - name: set up java 17 + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: 'maven' - name: bootstrap run: mvn -Pbootstrap clean package @@ -94,13 +94,13 @@ jobs: - name: rake test:jruby run: bin/jruby --dev -S rake test:jruby - rake-test-17-indy: + rake-test-21-indy: runs-on: ubuntu-latest strategy: matrix: target: ['test:mri:core:jit', 'test:jruby:jit', 'spec:compiler', 'spec:ruby:fast:jit', 'spec:ji'] - java-version: ['17', '21', '23'] + java-version: ['21', '23'] fail-fast: false name: rake ${{ matrix.target }} (Java ${{ matrix.java-version }} +indy) @@ -111,8 +111,8 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk - name: set up java ${{ matrix.java-version }} uses: actions/setup-java@v3 with: @@ -132,7 +132,7 @@ jobs: strategy: matrix: package-flags: ['-Pmain', '-Pdist', '-Pcomplete', '-Posgi', '-Ptest', '-Pmain,test -Dinvoker.test=extended'] - java-version: [17, 21, 23] + java-version: [21, 23] fail-fast: false name: mvn ${{ matrix.package-flags }} (Java ${{ matrix.java-version }}) @@ -140,8 +140,8 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk - name: set up java ${{ matrix.java-version }} uses: actions/setup-java@v3 with: @@ -163,7 +163,7 @@ jobs: strategy: matrix: package-flags: ['-Pjruby-jars', '-Pjruby-jars,test -Dinvoker.test=extended', '-Pjruby_complete_jar_extended -Dinvoker.skip=true'] - java-version: [17, 21, 23] + java-version: [21, 23] fail-fast: false @@ -172,8 +172,8 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk - name: set up java ${{ matrix.java-version }} uses: actions/setup-java@v3 with: @@ -201,13 +201,13 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk - - name: set up java 17 + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'zulu' - java-version: 17 + java-version: 21 cache: 'maven' - name: bootstrap run: mvn -Pbootstrap clean package @@ -222,7 +222,7 @@ jobs: strategy: fail-fast: false - name: mvn -Ptest, rake test:jruby (Windows, Java 17) + name: mvn -Ptest, rake test:jruby (Windows, Java 21) env: JAVA_OPTS: "-Djdk.io.File.enableADS=true" @@ -231,11 +231,11 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: set up java 17 + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'zulu' - java-version: 17 + java-version: 21 cache: 'maven' - name: bootstrap run: mvn -Pbootstrap clean package @@ -256,13 +256,13 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk - - name: set up java 17 + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'zulu' - java-version: '17' + java-version: '21' cache: 'maven' - name: dependency convergence run: tool/maven-ci-script.sh @@ -279,13 +279,13 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk - - name: set up java 17 + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'zulu' - java-version: 17 + java-version: 21 cache: 'maven' - name: maven-ci-script.sh run: tool/maven-ci-script.sh @@ -316,13 +316,13 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk - - name: set up java 17 + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: 'maven' - name: bootstrap run: mvn -Pbootstrap clean package @@ -340,13 +340,13 @@ jobs: steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk - - name: set up java 17 + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'temurin' - java-version: 17 + java-version: 21 cache: 'maven' - name: bootstrap run: mvn -Pbootstrap clean package @@ -361,7 +361,7 @@ jobs: # strategy: # matrix: # package-flags: ['-Ptest'] -# # dist, complete, and osgi do not pass on 17 yet +# # dist, complete, and osgi do not pass on 21 yet # java-version: ['11'] # fail-fast: false # @@ -398,7 +398,7 @@ jobs: # - name: Bootstrap build # uses: jruby/jruby-ci-build@fbd2cf981aaff3eae190ac20086fa161be3d9060 # with: -# java-version: 17 +# java-version: 21 # - name: set up java ${{ matrix.java-version }} # uses: actions/setup-java@v3 # with: @@ -410,21 +410,21 @@ jobs: ## run: "bin/jruby -S rake ${{ matrix.target }}" # run: "true" - maven-test-openj9-17: + maven-test-openj9-21: runs-on: ubuntu-latest - name: mvn -Ptest (OpenJ9 Java 17) + name: mvn -Ptest (OpenJ9 Java 21) steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk - name: set up java ${{ matrix.java-version }} uses: actions/setup-java@v3 with: distribution: 'semeru' - java-version: '17' + java-version: '21' cache: 'maven' - name: bootstrap run: mvn -Pbootstrap clean package @@ -435,7 +435,7 @@ jobs: env: PHASE: 'package -Ptest' - rake-test-wip-17: + rake-test-wip-21: runs-on: ubuntu-latest strategy: @@ -443,18 +443,18 @@ jobs: target: ['test:mri:core_wip', 'test:mri:stdlib_wip'] fail-fast: false - name: rake ${{ matrix.target }} (Java 17) + name: rake ${{ matrix.target }} (Java 21) steps: - name: checkout uses: actions/checkout@v3 - - name: remove default java except 17 - run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-21-jdk - - name: set up java 17 + - name: remove default java except 21 + run: sudo apt remove temurin-8-jdk temurin-11-jdk temurin-17-jdk + - name: set up java 21 uses: actions/setup-java@v3 with: distribution: 'zulu' - java-version: '17' + java-version: '21' cache: 'maven' - name: bootstrap run: mvn -Pbootstrap clean package @@ -469,7 +469,7 @@ jobs: permissions: contents: none if: ${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/jruby-9.5' }} - needs: [mvn-test, mvn-test-extended, mvn-test-windows, dependency-check, rake-test, rake-test-17-indy, rake-test-17, test-versions, sequel, concurrent-ruby, jruby-tests-dev, regression-specs-jit] + needs: [mvn-test, mvn-test-extended, mvn-test-windows, dependency-check, rake-test, rake-test-21-indy, rake-test-21, test-versions, sequel, concurrent-ruby, jruby-tests-dev, regression-specs-jit] uses: jruby/jruby/.github/workflows/snapshot-publish.yml@6cd0d4d96d9406635183d81cf91acc82cd78245f secrets: SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} diff --git a/core/src/main/java/org/jruby/Main.java b/core/src/main/java/org/jruby/Main.java index 61d6f7d23fd..609feaa9441 100644 --- a/core/src/main/java/org/jruby/Main.java +++ b/core/src/main/java/org/jruby/Main.java @@ -279,7 +279,7 @@ private Status internalRun() { return doCheckSyntax(runtime, in, filename); } else { // proceed to run the script - doRunFromMain(runtime, in, filename); + runtime.runFromMain(in, filename); } status = new Status(); } finally { @@ -392,12 +392,6 @@ private Status handleMainExit(MainExitException mee) { return new Status(mee.getStatus()); } - private void doRunFromMain(Ruby runtime, InputStream in, String filename) { - doCheckSecurityManager(); - - runtime.runFromMain(in, filename); - } - private Status doCheckSyntax(Ruby runtime, InputStream in, String filename) throws RaiseException { // check primary script boolean status = checkStreamSyntax(runtime, in, filename); @@ -522,13 +516,6 @@ private static void doGCJCheck() { } } - private void doCheckSecurityManager() { - if (Main.class.getClassLoader() == null && System.getSecurityManager() != null) { - System.err.println("Warning: security manager and JRuby running from boot classpath.\n" + - "Run from jruby.jar or set env VERIFY_JRUBY=true to enable security."); - } - } - /** * This is only used from the main(String[]) path, in which case the err for this * run should be System.err. In order to avoid the Ruby err being closed and unable diff --git a/core/src/main/java/org/jruby/Ruby.java b/core/src/main/java/org/jruby/Ruby.java index eb5cf33e9a8..29b0017f6be 100644 --- a/core/src/main/java/org/jruby/Ruby.java +++ b/core/src/main/java/org/jruby/Ruby.java @@ -301,7 +301,7 @@ private Ruby(RubyInstanceConfig config) { RubyInstanceConfig.POOL_MAX, RubyInstanceConfig.POOL_TTL, TimeUnit.SECONDS, - new SynchronousQueue(), + new SynchronousQueue<>(), new DaemonThreadFactory("Ruby-" + getRuntimeNumber() + "-Worker")); fiberExecutor = new ThreadPoolExecutor( @@ -309,7 +309,7 @@ private Ruby(RubyInstanceConfig config) { Integer.MAX_VALUE, RubyInstanceConfig.FIBER_POOL_TTL, TimeUnit.SECONDS, - new SynchronousQueue(), + new SynchronousQueue<>(), new DaemonThreadFactory("Ruby-" + getRuntimeNumber() + "-Fiber")); // initialize the root of the class hierarchy completely @@ -601,7 +601,7 @@ public IRubyObject call(ThreadContext context1, IRubyObject self, RubyModule cla case 2: return RubyKernel.gsub(context1, self, args[0], args[1], block); default: - throw newArgumentError(String.format("wrong number of arguments %d for 1..2", args.length)); + throw argumentError(context1, String.format("wrong number of arguments %d for 1..2", args.length)); } } }); @@ -638,7 +638,7 @@ private JRubyClassLoader initJRubyClassLoader(RubyInstanceConfig config) { private void initDefaultEncodings() { // External should always have a value, but Encoding.external_encoding{,=} will lazily setup String encoding = this.config.getExternalEncoding(); - if (encoding != null && !encoding.equals("")) { + if (encoding != null && !encoding.isEmpty()) { Encoding loadedEncoding = encodingService.loadEncoding(ByteList.create(encoding)); if (loadedEncoding == null) throw new MainExitException(1, "unknown encoding name - " + encoding); setDefaultExternalEncoding(loadedEncoding); @@ -656,7 +656,7 @@ private void initDefaultEncodings() { } encoding = this.config.getInternalEncoding(); - if (encoding != null && !encoding.equals("")) { + if (encoding != null && !encoding.isEmpty()) { Encoding loadedEncoding = encodingService.loadEncoding(ByteList.create(encoding)); if (loadedEncoding == null) throw new MainExitException(1, "unknown encoding name - " + encoding); setDefaultInternalEncoding(loadedEncoding); @@ -1326,6 +1326,7 @@ public Caches getCaches() { /** * @deprecated use #newInstance() */ + @Deprecated(since = "9.4-", forRemoval = true) public static Ruby getDefaultInstance() { return newInstance(); } @@ -2493,16 +2494,10 @@ public void setDefaultRandom(RubyRandom random) { this.defaultRand = random.getRandomType(); } - /** - * @deprecated internal API, to be hidden - */ - public RubyRandom.RandomType getDefaultRand() { - return getDefaultRandom().getRandomType(); - } - /** * @deprecated the modified field is now unused and deprecated and the set is ignored */ + @Deprecated(since = "9.4-", forRemoval = true) public void setDefaultRand(RubyRandom.RandomType defaultRand) { } @@ -3306,7 +3301,7 @@ private void systemTeardown(final ThreadContext context) { // Fetches (and unsets) the SIGEXIT handler, if one exists. IRubyObject trapResult = RubySignal.__jtrap_osdefault_kernel(this.getNil(), this.newString("EXIT")); if (trapResult instanceof RubyArray) { - IRubyObject[] trapResultEntries = ((RubyArray) trapResult).toJavaArray(); + IRubyObject[] trapResultEntries = ((RubyArray) trapResult).toJavaArray(context); IRubyObject exitHandlerProc = trapResultEntries[0]; if (exitHandlerProc instanceof RubyProc) { ((RubyProc) exitHandlerProc).call(context, getSingleNilArray()); @@ -4817,6 +4812,7 @@ public CoverageData getCoverageData() { /** * @deprecated internal API, to be removed */ + @Deprecated(since = "9.4-", forRemoval = true) public Random getRandom() { return random; } diff --git a/core/src/main/java/org/jruby/RubyArgsFile.java b/core/src/main/java/org/jruby/RubyArgsFile.java index c4de1e3d683..313bebe41c2 100644 --- a/core/src/main/java/org/jruby/RubyArgsFile.java +++ b/core/src/main/java/org/jruby/RubyArgsFile.java @@ -45,6 +45,7 @@ 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.Error.argumentError; import static org.jruby.runtime.ThreadContext.CALL_KEYWORD; import static org.jruby.runtime.ThreadContext.resetCallInfo; import static org.jruby.runtime.Visibility.PRIVATE; @@ -129,7 +130,7 @@ public enum Next { Stream, // We are only getting from $stdin SameFile, // We are continuing to interact with the same file NextFile // Time to advance to the next file. - }; + } public static final class ArgsFileData { @@ -238,7 +239,7 @@ private void createNewFile(File file) { private void inplaceEditWindows(ThreadContext context, String filename, String extension) throws RaiseException { File file = new File(filename); - if (extension.length() > 0) { + if (!extension.isEmpty()) { String backup = filename + extension; File backupFile = new File(backup); @@ -261,7 +262,7 @@ private void inplaceEdit(ThreadContext context, String filename, String extensio File file = new File(filename); FileStat stat = runtime.getPosix().stat(filename); - if (extension.length() > 0) { + if (!extension.isEmpty()) { file.renameTo(new File(filename + extension)); } else { file.delete(); @@ -309,7 +310,7 @@ private static IRubyObject setInplaceMode(ThreadContext context, IRubyObject rec data.inPlace = context.fals; } else { test = TypeConverter.convertToType(test, context.runtime.getString(), "to_str", false); - if (test.isNil() || ((RubyString) test).length() == 0) { + if (test.isNil() || ((RubyString) test).isEmpty()) { data.inPlace = context.nil; } else { StringSupport.checkStringSafety(context.runtime, test); @@ -443,10 +444,10 @@ public static IRubyObject readlines(ThreadContext context, IRubyObject recv, IRu if (!(data.currentFile instanceof RubyIO)) return data.currentFile.callMethod(context, "readlines", args); - RubyArray ary = runtime.newArray(); + var ary = runtime.newArray(); IRubyObject line; while(!(line = argf_getline(context, recv, args)).isNil()) { - ary.append(line); + ary.append(context, line); } return ary; } @@ -461,10 +462,10 @@ public static IRubyObject to_a(ThreadContext context, IRubyObject recv, IRubyObj if (!data.next_argv(context)) return runtime.newEmptyArray(); if (!(data.currentFile instanceof RubyIO)) return data.currentFile.callMethod(context, "to_a", args); - RubyArray ary = runtime.newArray(); + var ary = runtime.newArray(); IRubyObject line; while ((line = argf_getline(context, recv, args)) != context.nil) { - ary.append(line); + ary.append(context, line); } return ary; } @@ -928,7 +929,7 @@ public static IRubyObject to_s(IRubyObject recv) { private static RubyIO getCurrentDataFile(ThreadContext context, String errorMessage) { ArgsFileData data = ArgsFileData.getArgsFileData(context.runtime); - if (!data.next_argv(context)) throw context.runtime.newArgumentError(errorMessage); + if (!data.next_argv(context)) throw argumentError(context, errorMessage); return (RubyIO) data.currentFile; } diff --git a/core/src/main/java/org/jruby/RubyArithmeticSequence.java b/core/src/main/java/org/jruby/RubyArithmeticSequence.java index 89e999a1225..ebbcee78750 100644 --- a/core/src/main/java/org/jruby/RubyArithmeticSequence.java +++ b/core/src/main/java/org/jruby/RubyArithmeticSequence.java @@ -53,7 +53,7 @@ import static org.jruby.api.Convert.asFixnum; import static org.jruby.api.Convert.numericToLong; -import static org.jruby.api.Create.newFixnum; +import static org.jruby.api.Create.*; import static org.jruby.api.Error.argumentError; import static org.jruby.runtime.Helpers.hashEnd; import static org.jruby.runtime.Helpers.hashStart; @@ -109,11 +109,12 @@ public RubyArithmeticSequence(Ruby runtime, RubyClass klass, IRubyObject generat this.generatedBy = generatedBy; this.method = method; this.args = args; + ThreadContext context = runtime.getCurrentContext(); setInstanceVariable(OBJECT, generatedBy); - setInstanceVariable(METHOD, RubyString.newString(runtime, method)); + setInstanceVariable(METHOD, newString(context, method)); setInstanceVariable(ARGS, args != null ? RubyArray.newArrayMayCopy(runtime, args) : RubyArray.newEmptyArray(runtime)); - setInstanceVariable(GENERATOR, runtime.getNil()); - setInstanceVariable(LOOKAHEAD, RubyArray.newArray(runtime, 4)); + setInstanceVariable(GENERATOR, context.nil); + setInstanceVariable(LOOKAHEAD, newArray(context, 4)); setInstanceVariable(FEEDVALUE, new RubyEnumerator.FeedValue(runtime)); } @@ -185,14 +186,13 @@ public IRubyObject first(ThreadContext context) { // arith_seq_first @JRubyMethod public IRubyObject first(ThreadContext context, IRubyObject num) { - Ruby runtime = context.runtime; IRubyObject b = begin, e = end, s = step; RubyArray ary; if (num == null) { if (b.isNil()) return context.nil; if (!e.isNil()) { - IRubyObject zero = int2fix(runtime, 0); + IRubyObject zero = newFixnum(context, 0); CallSite op_cmp = sites(context).op_cmp; CallSite op_gt = sites(context).op_gt; CallSite op_lt = sites(context).op_lt; @@ -207,23 +207,23 @@ 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 runtime.newEmptyArray(); + if (n == 0) return context.runtime.newEmptyArray(); boolean x = excludeEnd.isTrue(); if (b instanceof RubyFixnum && e.isNil() && s instanceof RubyFixnum) { long i = fix2long(b); long unit = fix2long(s); - ary = RubyArray.newArray(runtime, n); - while (n > 0 && fixable(runtime, i)) { - ary.append(RubyFixnum.newFixnum(runtime, i)); + ary = newArray(context, n); + while (n > 0 && fixable(context.runtime, i)) { + ary.append(context, newFixnum(context, i)); i += unit; /* FIXABLE + FIXABLE never overflow; */ --n; } if (n > 0) { - b = RubyFixnum.newFixnum(runtime, i); + b = newFixnum(context, i); while (n > 0) { - ary.append(b); + ary.append(context, b); b = ((RubyInteger)b).op_plus(context, s); --n; } @@ -241,9 +241,9 @@ public IRubyObject first(ThreadContext context, IRubyObject num) { len = end - i; if (len < 0) len = 0; - ary = RubyArray.newArray(runtime, (n < len) ? n : len); + ary = newArray(context, Math.min(n, len)); while (n > 0 && i < end) { - ary.append(newFixnum(context, i)); + ary.append(context, newFixnum(context, i)); if (i + unit < i) break; i += unit; --n; @@ -253,9 +253,9 @@ public IRubyObject first(ThreadContext context, IRubyObject num) { len = i - end; if (len < 0) len = 0; - ary = RubyArray.newArray(runtime, (n < len) ? n : len); + ary = newArray(context, Math.min(n, len)); while (n > 0 && i > end) { - ary.append(RubyFixnum.newFixnum(runtime, i)); + ary.append(context, newFixnum(context, i)); if (i + unit > i) break; i += unit; --n; @@ -276,30 +276,30 @@ public IRubyObject first(ThreadContext context, IRubyObject num) { if (Double.isInfinite(unit)) { if (len > 0) { - ary = RubyArray.newArray(runtime, 1); - ary.append(dbl2num(runtime, beg)); + ary = newArray(context, 1); + ary.append(context, newFloat(context, beg)); } else { - ary = runtime.newEmptyArray(); + ary = context.runtime.newEmptyArray(); } } else if (unit == 0) { - IRubyObject val = dbl2num(runtime, beg); - ary = RubyArray.newArray(runtime, n); + IRubyObject val = newFloat(context, beg); + ary = newArray(context, n); for (i = 0; i < len; ++i) { - ary.append(val); + ary.append(context, val); } } else { - ary = RubyArray.newArray(runtime, n); + ary = newArray(context, n); for (i = 0; i < n; ++i) { double d = i * unit + beg; if (unit >= 0 ? end < d : d < end) d = end; - ary.append(dbl2num(runtime, d)); + ary.append(context, newFloat(context, d)); } } return ary; } - return Helpers.invokeSuper(context, this, runtime.getEnumerator(), "first", num, Block.NULL_BLOCK); + return Helpers.invokeSuper(context, this, context.runtime.getEnumerator(), "first", num, Block.NULL_BLOCK); } // arith_seq_eq @@ -382,7 +382,7 @@ public RubyString inspect(ThreadContext context) { if (args[argc - 1] instanceof RubyHash) { boolean allKey = true; - IRubyObject [] keys = ((RubyHash)args[argc - 1]).keys().toJavaArray(); + IRubyObject [] keys = ((RubyHash)args[argc - 1]).keys().toJavaArray(context); for (IRubyObject key : keys) { if (!(key instanceof RubySymbol)) { allKey = false; @@ -403,7 +403,7 @@ public RubyString inspect(ThreadContext context) { } if (!kwds.isNil()) { - IRubyObject [] keys = ((RubyHash)kwds).keys().toJavaArray(); + IRubyObject [] keys = ((RubyHash)kwds).keys().toJavaArray(context); for (IRubyObject key : keys) { IRubyObject value = ((RubyHash)kwds).fastARef(key); str.append(((RubySymbol)key).getBytes()); @@ -452,15 +452,14 @@ public IRubyObject last(ThreadContext context) { // arith_seq_last @JRubyMethod public IRubyObject last(ThreadContext context, IRubyObject num) { - Ruby runtime = context.runtime; IRubyObject b = begin, e = end, s = step, len_1, len; RubyArray ary; boolean last_is_adjusted; - if (e.isNil()) throw runtime.newRangeError("cannot get the last element of endless arithmetic sequence"); + 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 : runtime.newEmptyArray(); + if (Numeric.f_negative_p(context, len_1)) return num == null ? context.nil : context.runtime.newEmptyArray(); 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()) { @@ -472,7 +471,7 @@ public IRubyObject last(ThreadContext context, IRubyObject num) { if (last_is_adjusted) { len = len_1; } else { - len = ((RubyNumeric)len_1).op_plus(context, int2fix(runtime, 1)); + len = ((RubyNumeric)len_1).op_plus(context, newFixnum(context, 1)); } IRubyObject nv = num; @@ -486,11 +485,11 @@ public IRubyObject last(ThreadContext context, IRubyObject num) { long n = numericToLong(context, nv); if (n < 0) throw argumentError(context, "negative array size"); - ary = RubyArray.newArray(runtime, n); + 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); - ary.append(b); + ary.append(context, b); --n; } diff --git a/core/src/main/java/org/jruby/RubyArray.java b/core/src/main/java/org/jruby/RubyArray.java index 4f0f6410689..9d03f0860af 100644 --- a/core/src/main/java/org/jruby/RubyArray.java +++ b/core/src/main/java/org/jruby/RubyArray.java @@ -56,6 +56,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.common.IRubyWarnings.ID; import org.jruby.exceptions.RaiseException; @@ -97,12 +98,7 @@ import static org.jruby.api.Create.newFixnum; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; -import static org.jruby.runtime.Helpers.addBufferLength; -import static org.jruby.runtime.Helpers.arrayOf; -import static org.jruby.runtime.Helpers.calculateBufferLength; -import static org.jruby.runtime.Helpers.hashEnd; -import static org.jruby.runtime.Helpers.murmurCombine; -import static org.jruby.runtime.Helpers.validateBufferLength; +import static org.jruby.runtime.Helpers.*; import static org.jruby.runtime.Visibility.PRIVATE; import static org.jruby.util.Inspector.*; @@ -140,11 +136,11 @@ public ClassIndex getNativeClassIndex() { } protected final void concurrentModification() { - throw concurrentModification(getRuntime(), null); + throw concurrentModification(getRuntime().getCurrentContext(), null); } - private static RuntimeException concurrentModification(Ruby runtime, Exception cause) { - RuntimeException ex = runtime.newConcurrencyError("Detected invalid array contents due to unsynchronized modifications with concurrent users"); + private static RuntimeException concurrentModification(ThreadContext context, Exception cause) { + RuntimeException ex = context.runtime.newConcurrencyError("Detected invalid array contents due to unsynchronized modifications with concurrent users"); // NOTE: probably not useful to be on except for debugging : // if ( cause != null ) ex.initCause(cause); return ex; @@ -167,143 +163,141 @@ public static IRubyObject create(IRubyObject klass, IRubyObject[] args, Block bl return arr; } - /** rb_ary_new2 - * + /** + * Create array with specific allocated size + * @deprecated Use {@link Create#newArray(ThreadContext, long)} instead */ + @Deprecated(since = "10.0", forRemoval = true) public static final RubyArray newArray(final Ruby runtime, final long len) { - checkLength(runtime, len); - return newArray(runtime, (int)len); + return Create.newArray(runtime.getCurrentContext(), len); } - public static final RubyArray newArrayLight(final Ruby runtime, final long len) { - checkLength(runtime, len); + public static final RubyArray newArrayLight(final Ruby runtime, final long len) { + checkLength(runtime.getCurrentContext(), len); return newArrayLight(runtime, (int)len); } - public static final RubyArray newArray(final Ruby runtime, final int len) { + public static final RubyArray newArray(final Ruby runtime, final int len) { IRubyObject[] values = IRubyObject.array(validateBufferLength(runtime, len)); Helpers.fillNil(values, 0, len, runtime); - return new RubyArray(runtime, values, 0, 0); + return new RubyArray<>(runtime, values, 0, 0); } - public static final RubyArray newArrayLight(final Ruby runtime, final int len) { + public static final RubyArray newArrayLight(final Ruby runtime, final int len) { IRubyObject[] values = IRubyObject.array(validateBufferLength(runtime, len)); Helpers.fillNil(values, 0, len, runtime); - return new RubyArray(runtime, runtime.getArray(), values, 0, 0, false); + return new RubyArray<>(runtime, runtime.getArray(), values, 0, 0, false); } /** rb_ary_new * */ - public static final RubyArray newArray(final Ruby runtime) { + public static final RubyArray newArray(final Ruby runtime) { return newArray(runtime, ARRAY_DEFAULT_SIZE); } /** rb_ary_new * */ - public static final RubyArray newArrayLight(final Ruby runtime) { + public static final RubyArray newArrayLight(final Ruby runtime) { /* Ruby arrays default to holding 16 elements, so we create an * ArrayList of the same size if we're not told otherwise */ return newArrayLight(runtime, ARRAY_DEFAULT_SIZE); } - public static RubyArray newArray(Ruby runtime, IRubyObject obj) { - return USE_PACKED_ARRAYS ? new RubyArrayOneObject(runtime, obj) : new RubyArray(runtime, arrayOf(obj)); + public static RubyArray newArray(Ruby runtime, IRubyObject obj) { + return USE_PACKED_ARRAYS ? new RubyArrayOneObject(runtime, obj) : new RubyArray<>(runtime, arrayOf(obj)); } - public static RubyArray newArrayLight(Ruby runtime, IRubyObject obj) { - return USE_PACKED_ARRAYS ? new RubyArrayOneObject(runtime, obj) : new RubyArray(runtime, arrayOf(obj)); + public static RubyArray newArrayLight(Ruby runtime, IRubyObject obj) { + return USE_PACKED_ARRAYS ? new RubyArrayOneObject(runtime, obj) : new RubyArray<>(runtime, arrayOf(obj)); } - public static RubyArray newArrayLight(RubyClass arrayClass, IRubyObject obj) { - return USE_PACKED_ARRAYS ? new RubyArrayOneObject(arrayClass, obj) : new RubyArray(arrayClass, arrayOf(obj), false); + public static RubyArray newArrayLight(RubyClass arrayClass, IRubyObject obj) { + return USE_PACKED_ARRAYS ? new RubyArrayOneObject(arrayClass, obj) : new RubyArray<>(arrayClass, arrayOf(obj), false); } - public static RubyArray newArrayLight(Ruby runtime, IRubyObject car, IRubyObject cdr) { - return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(runtime, car, cdr) : new RubyArray(runtime, arrayOf(car, cdr)); + public static RubyArray newArrayLight(Ruby runtime, IRubyObject car, IRubyObject cdr) { + return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(runtime, car, cdr) : new RubyArray<>(runtime, arrayOf(car, cdr)); } - public static RubyArray newArrayLight(RubyClass arrayClass, IRubyObject car, IRubyObject cdr) { - return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(arrayClass, car, cdr) : new RubyArray(arrayClass, arrayOf(car, cdr), false); + public static RubyArray newArrayLight(RubyClass arrayClass, IRubyObject car, IRubyObject cdr) { + return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(arrayClass, car, cdr) : new RubyArray<>(arrayClass, arrayOf(car, cdr), false); } - public static RubyArray newArrayLight(Ruby runtime, IRubyObject... objs) { - return new RubyArray(runtime, objs, false); + public static RubyArray newArrayLight(Ruby runtime, IRubyObject... objs) { + return new RubyArray<>(runtime, objs, false); } /** rb_assoc_new * */ - public static RubyArray newArray(Ruby runtime, IRubyObject car, IRubyObject cdr) { - return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(runtime, car, cdr) : new RubyArray(runtime, arrayOf(car, cdr)); + public static RubyArray newArray(Ruby runtime, IRubyObject car, IRubyObject cdr) { + return USE_PACKED_ARRAYS ? new RubyArrayTwoObject(runtime, car, cdr) : new RubyArray<>(runtime, arrayOf(car, cdr)); } - public static RubyArray newArray(Ruby runtime, IRubyObject first, IRubyObject second, IRubyObject third) { - return new RubyArray(runtime, arrayOf(first, second, third)); + public static RubyArray newArray(Ruby runtime, IRubyObject first, IRubyObject second, IRubyObject third) { + return new RubyArray<>(runtime, arrayOf(first, second, third)); } - public static RubyArray newArray(Ruby runtime, IRubyObject first, IRubyObject second, IRubyObject third, IRubyObject fourth) { - return new RubyArray(runtime, arrayOf(first, second, third, fourth)); + public static RubyArray newArray(Ruby runtime, IRubyObject first, IRubyObject second, IRubyObject third, IRubyObject fourth) { + return new RubyArray<>(runtime, arrayOf(first, second, third, fourth)); } - public static RubyArray newEmptyArray(Ruby runtime) { - return new RubyArray(runtime, NULL_ARRAY); + public static RubyArray newEmptyArray(Ruby runtime) { + return new RubyArray<>(runtime, NULL_ARRAY); } - public static RubyArray newEmptyArray(Ruby runtime, RubyClass klass) { - return new RubyArray(runtime, klass, NULL_ARRAY); + public static RubyArray newEmptyArray(Ruby runtime, RubyClass klass) { + return new RubyArray<>(runtime, klass, NULL_ARRAY); } /** rb_ary_new4, rb_ary_new3 * */ - public static RubyArray newArray(Ruby runtime, IRubyObject[] args) { + public static RubyArray newArray(Ruby runtime, IRubyObject[] args) { final int size = args.length; if (size == 0) { return newEmptyArray(runtime); } - return isPackedArray(size) ? packedArray(runtime, args) : new RubyArray(runtime, args.clone()); + return isPackedArray(size) ? packedArray(runtime, args) : new RubyArray<>(runtime, args.clone()); } - public static RubyArray newArray(Ruby runtime, Collection collection) { + public static RubyArray newArray(Ruby runtime, Collection collection) { if (collection.isEmpty()) { return newEmptyArray(runtime); } final IRubyObject[] arr = collection.toArray(IRubyObject.NULL_ARRAY); - return isPackedArray(collection) ? packedArray(runtime, arr) : new RubyArray(runtime, arr); + return isPackedArray(collection) ? packedArray(runtime, arr) : new RubyArray<>(runtime, arr); } - public static RubyArray newArray(Ruby runtime, List list) { + public static RubyArray newArray(Ruby runtime, List list) { if (list.isEmpty()) { return newEmptyArray(runtime); } - return isPackedArray(list) ? packedArray(runtime, list) : new RubyArray(runtime, list.toArray(IRubyObject.NULL_ARRAY)); + return isPackedArray(list) ? packedArray(runtime, list) : new RubyArray<>(runtime, list.toArray(IRubyObject.NULL_ARRAY)); } - public static RubyArray newSharedArray(RubyClass arrayClass, IRubyObject[] shared) { - RubyArray sharedArray = new RubyArray(arrayClass, shared, true); + public static RubyArray newSharedArray(RubyClass arrayClass, IRubyObject[] shared) { + var sharedArray = new RubyArray<>(arrayClass, shared, true); sharedArray.isShared = true; return sharedArray; } - private static RubyArray packedArray(final Ruby runtime, final IRubyObject[] args) { - if (args.length == 1) { - return new RubyArrayOneObject(runtime, args[0]); - } else { - return new RubyArrayTwoObject(runtime, args[0], args[1]); - } + private static RubyArray packedArray(final Ruby runtime, final IRubyObject[] args) { + return args.length == 1 ? + new RubyArrayOneObject(runtime, args[0]) : + new RubyArrayTwoObject(runtime, args[0], args[1]); } - private static RubyArray packedArray(final Ruby runtime, final List args) { - if (args.size() == 1) { - return new RubyArrayOneObject(runtime, args.get(0)); - } else { - return new RubyArrayTwoObject(runtime, args.get(0), args.get(1)); - } + private static RubyArray packedArray(final Ruby runtime, final List args) { + return args.size() == 1 ? + new RubyArrayOneObject(runtime, args.get(0)) : + new RubyArrayTwoObject(runtime, args.get(0), args.get(1)); + } private static boolean isPackedArray(final int size) { @@ -411,7 +405,7 @@ private RubyArray(Ruby runtime, IRubyObject[] vals, boolean objectSpace) { /* * plain internal array assignment */ - private RubyArray(Ruby runtime, IRubyObject[] vals, int begin, int length) { + public RubyArray(Ruby runtime, IRubyObject[] vals, int begin, int length) { super(runtime, runtime.getArray()); this.values = vals; this.begin = begin; @@ -475,7 +469,7 @@ public RubyArray(RubyClass klass, IRubyObject[] vals, boolean shared) { /** * Overridden by specialized arrays to fall back to IRubyObject[]. */ - protected void unpack() { + protected void unpack(ThreadContext context) { } private void alloc(int length) { @@ -486,34 +480,41 @@ private void alloc(int length) { begin = 0; } - private void realloc(int newLength, int valuesLength) { - unpack(); + private void realloc(ThreadContext context, int newLength, int valuesLength) { + unpack(context); Ruby runtime = metaClass.runtime; IRubyObject[] reallocated = IRubyObject.array(validateBufferLength(runtime, newLength)); if (newLength > valuesLength) { Helpers.fillNil(reallocated, valuesLength, newLength, runtime); - safeArrayCopy(values, begin, reallocated, 0, valuesLength); // elements and trailing nils + safeArrayCopy(context, values, begin, reallocated, 0, valuesLength); // elements and trailing nils } else { - safeArrayCopy(values, begin, reallocated, 0, newLength); // ??? + safeArrayCopy(context, values, begin, reallocated, 0, newLength); // ??? } begin = 0; values = reallocated; } + /** + * check length of array + * @param runtime the runtime + * @param length the length to check + * @deprecated this has been replaced by {@link RubyArray#checkLength(ThreadContext, long)}. + */ + @Deprecated(since = "10.0", forRemoval = true) protected static final void checkLength(Ruby runtime, long length) { - if (length < 0) { - throw runtime.newArgumentError("negative array size (or size too big)"); - } + checkLength(runtime.getCurrentContext(), length); + } - if (length >= Integer.MAX_VALUE) { - throw runtime.newArgumentError("array size too big"); - } + public static final void checkLength(ThreadContext context, long length) { + if (length < 0) throw argumentError(context, "negative array size (or size too big)"); + if (length >= Integer.MAX_VALUE) throw argumentError(context, "array size too big"); } /** * @deprecated RubyArray implements List, use it directly * @return a read-only copy of this list */ + @Deprecated(since = "9.4-", forRemoval = true) public final List getList() { return Arrays.asList(toJavaArray()); } @@ -522,6 +523,15 @@ public int getLength() { return realLength; } + /** + * @return "" + * @deprecated Use {@link RubyArray#toJavaArray(ThreadContext)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject[] toJavaArray() { + return toJavaArray(getCurrentContext()); + } + /** * Return a Java array copy of the elements contained in this Array. * @@ -529,9 +539,9 @@ public int getLength() { * * @return a Java array with exactly the size and contents of this RubyArray's elements */ - public IRubyObject[] toJavaArray() { + public IRubyObject[] toJavaArray(ThreadContext context) { IRubyObject[] copy = IRubyObject.array(realLength); - copyInto(copy, 0); + copyInto(context, copy, 0); return copy; } @@ -546,7 +556,7 @@ public IRubyObject[] toJavaArray() { */ public IRubyObject[] toJavaArrayUnsafe() { - unpack(); + unpack(getRuntime().getCurrentContext()); return !isShared ? values : toJavaArray(); } @@ -560,7 +570,7 @@ public IRubyObject[] toJavaArrayUnsafe() { * underlying array. */ public IRubyObject[] toJavaArrayMaybeUnsafe() { - unpack(); + unpack(getRuntime().getCurrentContext()); return (!isShared && begin == 0 && values.length == realLength) ? values : toJavaArray(); } @@ -571,9 +581,9 @@ public boolean isSharedJavaArray(RubyArray other) { /** rb_ary_make_shared * */ - protected RubyArray makeShared() { + protected RubyArray makeShared() { // TODO: (CON) Some calls to makeShared could create packed array almost as efficiently - unpack(); + unpack(getRuntime().getCurrentContext()); return makeShared(begin, realLength, getRuntime().getArray()); } @@ -583,7 +593,7 @@ private RubyArray makeShared(int beg, int len, RubyClass klass) { } private final RubyArray makeShared(int beg, int len, RubyArray sharedArray) { - unpack(); + unpack(getRuntime().getCurrentContext()); isShared = true; sharedArray.values = values; sharedArray.isShared = true; @@ -610,21 +620,21 @@ private RubyArray makeSharedFirst(ThreadContext context, IRubyObject num, boolea /** rb_ary_modify_check * */ - protected final void modifyCheck() { + protected final void modifyCheck(ThreadContext context) { if ((flags & TMPLOCK_OR_FROZEN_ARR_F) != 0) { - if ((flags & FROZEN_F) != 0) throw getRuntime().newFrozenError(this); - if ((flags & TMPLOCK_ARR_F) != 0) throw typeError(getRuntime().getCurrentContext(), "can't modify array during iteration"); + if ((flags & FROZEN_F) != 0) throw context.runtime.newFrozenError(this); + if ((flags & TMPLOCK_ARR_F) != 0) throw typeError(context, "can't modify array during iteration"); } } /** rb_ary_modify * */ - protected void modify() { - modifyCheck(); + protected void modify(ThreadContext context) { + modifyCheck(context); if (isShared) { IRubyObject[] vals = IRubyObject.array(realLength); - safeArrayCopy(values, begin, vals, 0, realLength); + safeArrayCopy(context, values, begin, vals, 0, realLength); begin = 0; values = vals; isShared = false; @@ -640,6 +650,7 @@ protected void modify() { * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ + @Deprecated(since = "9.4-", forRemoval = false) public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block) { switch (args.length) { case 0: @@ -659,8 +670,8 @@ public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block b */ @JRubyMethod(visibility = PRIVATE) public IRubyObject initialize(ThreadContext context, Block block) { - modifyCheck(); - unpack(); + modifyCheck(context); + unpack(context); realLength = 0; if (block.isGiven() && context.runtime.isVerbose()) { context.runtime.getWarnings().warn(ID.BLOCK_UNUSED, "given block not used"); @@ -685,7 +696,7 @@ public IRubyObject initialize(ThreadContext context, IRubyObject arg0, IRubyObje } protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0, IRubyObject arg1, Block block) { - unpack(); + unpack(context); if (arg1 == null && !(arg0 instanceof RubyFixnum)) { IRubyObject val = arg0.checkArrayType(); @@ -699,7 +710,7 @@ protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0, if (len < 0) throw argumentError(context, "negative array size"); int ilen = validateBufferLength(context.runtime, len); - modify(); + modify(context); if (ilen > values.length - begin) { values = IRubyObject.array(ilen); @@ -714,12 +725,12 @@ protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0, if (block.getSignature() == Signature.NO_ARGUMENTS) { IRubyObject nil = context.nil; for (int i = 0; i < ilen; i++) { - storeInternal(i, block.yield(context, nil)); + storeInternal(context, i, block.yield(context, nil)); realLength = i + 1; } } else { for (int i = 0; i < ilen; i++) { - storeInternal(i, block.yield(context, newFixnum(context, i))); + storeInternal(context, i, block.yield(context, newFixnum(context, i))); realLength = i + 1; } } @@ -732,7 +743,7 @@ protected IRubyObject initializeCommon(ThreadContext context, IRubyObject arg0, Arrays.fill(values, begin, begin + ilen, arg1); } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + throw concurrentModification(context, ex); } realLength = ilen; } @@ -778,21 +789,30 @@ public RubyArray aryDup() { return dupImpl(runtime, runtime.getArray()); } - /** rb_ary_replace - * + /** + * @param orig + * @return "" + * @deprecated Use {@link RubyArray#replace(ThreadContext, IRubyObject)} instead. */ - @JRubyMethod(name = {"replace"}) + @Deprecated(since = "10.0", forRemoval = true) public IRubyObject replace(IRubyObject orig) { - unpack(); - modifyCheck(); - - if (this == orig) return this; + return replace(getCurrentContext(), orig); + } - RubyArray origArr = orig.convertToArray(); + /** rb_ary_replace + * + */ + @JRubyMethod(name = {"replace"}) + public IRubyObject replace(ThreadContext context, IRubyObject orig) { + unpack(context); + modifyCheck(context); - origArr.unpack(); + if (this == orig) return this; + var origArr = orig.convertToArray(); + origArr.unpack(context); origArr.isShared = true; + isShared = true; values = origArr.values; realLength = origArr.realLength; @@ -867,47 +887,49 @@ private long hashImpl(final ThreadContext context) { //public int hashCode() { // return (int) hashImpl(getRuntime().getCurrentContext()); //} + public IRubyObject store(long index, IRubyObject value) { + return store(metaClass.runtime.getCurrentContext(), index, value); + } /** rb_ary_store * */ - public IRubyObject store(long index, IRubyObject value) { + public IRubyObject store(ThreadContext context, long index, IRubyObject value) { if (index < 0 && (index += realLength) < 0) { - throw metaClass.runtime.newIndexError("index " + (index - realLength) + " out of array"); + throw context.runtime.newIndexError("index " + (index - realLength) + " out of array"); } if (index >= Integer.MAX_VALUE) { - throw metaClass.runtime.newIndexError("index " + index + " too big"); + throw context.runtime.newIndexError("index " + index + " too big"); } - modify(); + modify(context); - storeInternal((int) index, value); + storeInternal(context, (int) index, value); return value; } - protected void storeInternal(final int index, final IRubyObject value) { + protected void storeInternal(ThreadContext context, final int index, final IRubyObject value) { assert index >= 0; if (index >= realLength) { int valuesLength = values.length - begin; - if (index >= valuesLength) storeRealloc(index, valuesLength); + if (index >= valuesLength) storeRealloc(context, index, valuesLength); realLength = index + 1; } - safeArraySet(values, begin + index, value); + safeArraySet(context, values, begin + index, value); } - private void storeRealloc(final int index, final int valuesLength) { + private void storeRealloc(ThreadContext context, final int index, final int valuesLength) { long newLength = valuesLength >> 1; if (newLength < ARRAY_DEFAULT_SIZE) newLength = ARRAY_DEFAULT_SIZE; newLength += index; - if (newLength >= Integer.MAX_VALUE) { - throw getRuntime().newIndexError("index " + index + " too big"); - } - realloc((int) newLength, valuesLength); + if (newLength >= Integer.MAX_VALUE) throw context.runtime.newIndexError("index " + index + " too big"); + + realloc(context, (int) newLength, valuesLength); } /** rb_ary_elt @@ -924,7 +946,7 @@ public T eltOk(long offset) { try { return (T) eltInternal((int)offset); } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(getRuntime(), ex); + throw concurrentModification(getRuntime().getCurrentContext(), ex); } } @@ -936,7 +958,7 @@ public T eltSetOk(int offset, T value) { try { return eltInternalSet(offset, value); } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(getRuntime(), ex); + throw concurrentModification(getRuntime().getCurrentContext(), ex); } } @@ -964,6 +986,7 @@ public T eltInternalSet(int offset, T item) { * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ + @Deprecated(since = "9.4-", forRemoval = false) public IRubyObject fetch(ThreadContext context, IRubyObject[] args, Block block) { switch (args.length) { case 1: @@ -1054,8 +1077,8 @@ private void splice(ThreadContext context, int beg, int len, final RubyArray rpl if (len < 0) throw context.runtime.newIndexError("negative length (" + len + ")"); if (beg < 0 && (beg += realLength) < 0) throw context.runtime.newIndexError("index " + (beg - realLength) + " out of array"); - unpack(); - modify(); + unpack(context); + modify(context); int valuesLength = values.length - begin; if (beg >= realLength) { @@ -1064,7 +1087,7 @@ private void splice(ThreadContext context, int beg, int len, final RubyArray rpl try { Helpers.fillNil(values, begin + realLength, begin + beg, context.runtime); } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(context.runtime, e); + throw concurrentModification(context, e); } realLength = len; } else { @@ -1073,24 +1096,24 @@ private void splice(ThreadContext context, int beg, int len, final RubyArray rpl if (alen >= valuesLength) spliceRealloc(alen, valuesLength); if (len != rlen) { - safeArrayCopy(values, begin + (beg + len), values, begin + beg + rlen, realLength - (beg + len)); + safeArrayCopy(context, values, begin + (beg + len), values, begin + beg + rlen, realLength - (beg + len)); realLength = alen; } } if (rlen > 0) { - rplArr.copyInto(values, begin + beg, rlen); + rplArr.copyInto(context, values, begin + beg, rlen); } } /** rb_ary_splice * */ - private final void spliceOne(long beg, IRubyObject rpl) { - if (beg < 0 && (beg += realLength) < 0) throw getRuntime().newIndexError("index " + (beg - realLength) + " out of array"); + private final void spliceOne(ThreadContext context, long beg, IRubyObject rpl) { + if (beg < 0 && (beg += realLength) < 0) throw context.runtime.newIndexError("index " + (beg - realLength) + " out of array"); - unpack(); - modify(); + unpack(context); + modify(context); int valuesLength = values.length - begin; if (beg >= realLength) { @@ -1104,12 +1127,12 @@ private final void spliceOne(long beg, IRubyObject rpl) { if (alen >= valuesLength) spliceRealloc(alen, valuesLength); if (len == 0) { - safeArrayCopy(values, begin + (int) beg, values, begin + (int) beg + 1, realLength - (int) beg); + safeArrayCopy(context, values, begin + (int) beg, values, begin + (int) beg + 1, realLength - (int) beg); realLength = alen; } } - safeArraySet(values, begin + (int) beg, rpl); + safeArraySet(context, values, begin + (int) beg, rpl); } private void spliceRealloc(int length, int valuesLength) { @@ -1128,7 +1151,7 @@ private void spliceRealloc(int length, int valuesLength) { values = vals; } - private void unshiftRealloc(int valuesLength) { + private void unshiftRealloc(ThreadContext context, int valuesLength) { Ruby runtime = metaClass.runtime; int newLength = valuesLength >> 1; @@ -1137,7 +1160,7 @@ private void unshiftRealloc(int valuesLength) { newLength = addBufferLength(runtime, valuesLength, newLength); IRubyObject[] vals = IRubyObject.array(newLength); - safeArrayCopy(values, begin, vals, 1, valuesLength); + safeArrayCopy(context, values, begin, vals, 1, valuesLength); Helpers.fillNil(vals, valuesLength + 1, newLength, runtime); values = vals; begin = 0; @@ -1147,37 +1170,55 @@ public IRubyObject insert() { throw metaClass.runtime.newArgumentError(0, 1); } + /** + * @param arg + * @return "" + * @deprecated Use #{@link RubyArray#insert(ThreadContext, IRubyObject)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject insert(IRubyObject arg) { + return insert(getCurrentContext(), arg); + } + /** rb_ary_insert * */ @JRubyMethod(name = "insert") - public IRubyObject insert(IRubyObject arg) { - modifyCheck(); - - numericToLong(getRuntime().getCurrentContext(), arg); - + public IRubyObject insert(ThreadContext context, IRubyObject arg) { + modifyCheck(context); + numericToLong(context, arg); return this; } - @JRubyMethod(name = "insert") + /** + * @param arg1 + * @param arg2 + * @return itself + * @deprecated See {@link RubyArray#insert(ThreadContext, IRubyObject, IRubyObject)} + */ + @Deprecated(since = "10.0", forRemoval = true) public IRubyObject insert(IRubyObject arg1, IRubyObject arg2) { - modifyCheck(); + return insert(getCurrentContext(), arg1, arg2); + } - insert(numericToLong(getRuntime().getCurrentContext(), arg1), arg2); + @JRubyMethod(name = "insert") + public IRubyObject insert(ThreadContext context, IRubyObject arg1, IRubyObject arg2) { + modifyCheck(context); + insert(context, numericToLong(context, arg1), arg2); return this; } - private void insert(long pos, IRubyObject val) { + private void insert(ThreadContext context, long pos, IRubyObject val) { if (pos == -1) pos = realLength; else if (pos < 0) { long minpos = -realLength - 1; if (pos < minpos) { - throw getRuntime().newIndexError("index " + pos + " too small for array; minimum: " + minpos); + throw context.runtime.newIndexError("index " + pos + " too small for array; minimum: " + minpos); } pos++; } - spliceOne(pos, val); // rb_ary_new4 + spliceOne(context, pos, val); // rb_ary_new4 } @Deprecated @@ -1191,11 +1232,11 @@ public IRubyObject insert(ThreadContext context, IRubyObject[] args) { int argc = Arity.checkArgumentCount(context, args, 1, -1); - modifyCheck(); + modifyCheck(context); if (argc == 1) return this; - unpack(); + unpack(context); long pos = numericToLong(context, args[0]); @@ -1212,48 +1253,62 @@ public IRubyObject insert(ThreadContext context, IRubyObject[] args) { return this; } + /** + * @return new ary + * @deprecated Use {@link RubyArray#transpose(ThreadContext)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public RubyArray transpose() { + return transpose(getRuntime().getCurrentContext()); + } + /** rb_ary_transpose * */ @JRubyMethod(name = "transpose") - public RubyArray transpose() { - + public RubyArray transpose(ThreadContext context) { int alen = realLength; if (alen == 0) return aryDup(); - - Ruby runtime = metaClass.runtime; - int elen = -1; IRubyObject[] result = null; + for (int i = 0; i < alen; i++) { - RubyArray tmp = elt(i).convertToArray(); + var tmp = elt(i).convertToArray(); if (elen < 0) { elen = tmp.realLength; result = IRubyObject.array(elen); for (int j = 0; j < elen; j++) { - result[j] = newBlankArray(runtime, alen); + result[j] = newBlankArray(context.runtime, alen); } } else if (elen != tmp.realLength) { - throw runtime.newIndexError("element size differs (" + tmp.realLength + throw context.runtime.newIndexError("element size differs (" + tmp.realLength + " should be " + elen + ")"); } for (int j = 0; j < elen; j++) { - ((RubyArray) result[j]).storeInternal(i, tmp.elt(j)); + ((RubyArray) result[j]).storeInternal(context, i, tmp.elt(j)); } } - return new RubyArray(runtime, result); + return new RubyArray<>(context.runtime, result); + } + + /** + * @param args yes + * @return values_at + * @deprecated Use {@link RubyArray#values_at(ThreadContext, IRubyObject[])} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject values_at(IRubyObject[] args) { + return values_at(getRuntime().getCurrentContext(), args); } /** rb_values_at * */ @JRubyMethod(name = "values_at", rest = true) - public IRubyObject values_at(IRubyObject[] args) { - final Ruby runtime = metaClass.runtime; - ThreadContext context = runtime.getCurrentContext(); + public IRubyObject values_at(ThreadContext context, IRubyObject[] args) { final int length = realLength; - RubyArray result = newArray(runtime, args.length); + RubyArray result = Create.newArray(context, args.length); for (int i = 0; i < args.length; i++) { final IRubyObject arg = args[i]; @@ -1280,7 +1335,7 @@ else if ( ( begLen = ((RubyRange) arg).begLenInt(length, 1) ) == null ) { result.append(entry(numericToLong(context, arg))); } - Helpers.fillNil(result.values, result.realLength, result.values.length, runtime); + Helpers.fillNil(result.values, result.realLength, result.values.length, context.runtime); return result; } @@ -1295,7 +1350,6 @@ public IRubyObject subseq(long beg, long len) { * */ public IRubyObject subseq_step(ThreadContext context, RubyArithmeticSequence arg0) { - Ruby runtime = context.runtime; long beg, len, end; long step = getStep(context, arg0); IRubyObject aseqBeg = getBegin(context, arg0); @@ -1319,12 +1373,12 @@ public IRubyObject subseq_step(ThreadContext context, RubyArithmeticSequence arg // e.g. // [1].slice((-101..-1)%2) shoud throw "((-101..-1).%(2)) out of range". // The original exception message is "-1..-1 out of range". - throw runtime.newRangeError(arg0.inspect(context) + " out of range"); + throw context.runtime.newRangeError(arg0.inspect(context) + " out of range"); } else { throw ex; } } - if (ret != null && (ret[0] > len || ret[1] > len)) throw runtime.newRangeError(arg0.inspect(context) + " out of range"); + if (ret != null && (ret[0] > len || ret[1] > len)) throw context.runtime.newRangeError(arg0.inspect(context) + " out of range"); } if (aseqBeg.isNil()) { @@ -1342,7 +1396,7 @@ public IRubyObject subseq_step(ThreadContext context, RubyArithmeticSequence arg if (beg < 0) { beg += len; - if (beg < 0) throw runtime.newRangeError("integer " + beg + " out of range of fixnum"); + if (beg < 0) throw context.runtime.newRangeError("integer " + beg + " out of range of fixnum"); } if (end < 0) { end += len; } @@ -1360,13 +1414,13 @@ public IRubyObject subseq_step(ThreadContext context, RubyArithmeticSequence arg len = alen - beg; } - if (len == 0) return newArray(runtime, 0); - if (step == 0) throw runtime.newRangeError("slice step cannot be zero"); + if (len == 0) return Create.newArray(context, 0); + if (step == 0) throw context.runtime.newRangeError("slice step cannot be zero"); if (step == 1) return subseq(beg, len); long orig_len = len; if (step > 0 && step >= len) { - RubyArray result = newArray(runtime, 1); + RubyArray result = Create.newArray(context, 1); result.append(eltOk(beg)); return result; } else if (step < 0 && (step < -len)) { @@ -1377,7 +1431,7 @@ public IRubyObject subseq_step(ThreadContext context, RubyArithmeticSequence arg len = (len + ustep - 1) / ustep; long j = beg + ((step > 0) ? 0 : (orig_len - 1)); - RubyArray result = newArray(runtime, len); + RubyArray result = Create.newArray(context, len); for(long i = 0; i < len; ++i) { result.append(eltOk(j)); @@ -1441,16 +1495,26 @@ protected static IRubyObject size(ThreadContext context, RubyArray self, IRubyOb return self.length(context); } + /** + * @param item + * @return itself + * @deprecated Use {@link RubyArray#append(ThreadContext, IRubyObject)} + */ + @Deprecated(since = "10.0", forRemoval = true) + public RubyArray append(IRubyObject item) { + return append(getCurrentContext(), item); + } + /** rb_ary_push - specialized rb_ary_store * */ @JRubyMethod(name = "<<") - public RubyArray append(IRubyObject item) { - unpack(); - modify(); + public RubyArray append(ThreadContext context, IRubyObject item) { + unpack(context); + modify(context); int valuesLength = values.length - begin; if (realLength == valuesLength) { - if (realLength == Integer.MAX_VALUE) throw getRuntime().newIndexError("index " + Integer.MAX_VALUE + " too big"); + if (realLength == Integer.MAX_VALUE) throw context.runtime.newIndexError("index " + Integer.MAX_VALUE + " too big"); long newLength = valuesLength + (valuesLength >> 1); if (newLength > Integer.MAX_VALUE) { @@ -1459,10 +1523,10 @@ public RubyArray append(IRubyObject item) { newLength = ARRAY_DEFAULT_SIZE; } - realloc((int) newLength, valuesLength); + realloc(context, (int) newLength, valuesLength); } - safeArraySet(values, begin + realLength++, item); + safeArraySet(context, values, begin + realLength++, item); return this; } @@ -1471,7 +1535,7 @@ public RubyArray append(IRubyObject item) { * */ @Deprecated // not-used - public RubyArray push_m(IRubyObject[] items) { + public RubyArray push_m(IRubyObject[] items) { return push(items); } @@ -1482,11 +1546,21 @@ public RubyArray push(IRubyObject item) { return this; } + /** + * @param items + * @return "" + * @deprecated Use {@link RubyArray@} + */ + @Deprecated(since = "10.0", forRemoval = true) + public RubyArray push(IRubyObject[] items) { + return push(getCurrentContext(), items); + } + @JRubyMethod(name = "push", alias = "append", rest = true) - public RubyArray push(IRubyObject[] items) { - if (items.length == 0) modifyCheck(); - for (int i = 0; i < items.length; i++) { - append(items[i]); + public RubyArray push(ThreadContext context, IRubyObject[] items) { + if (items.length == 0) modifyCheck(context); + for (IRubyObject item : items) { + append(item); } return this; } @@ -1496,23 +1570,23 @@ public RubyArray push(IRubyObject[] items) { */ @JRubyMethod public IRubyObject pop(ThreadContext context) { - unpack(); - modifyCheck(); + unpack(context); + modifyCheck(context); if (realLength == 0) return context.nil; if (isShared) { - return safeArrayRef(context.runtime, values, begin + --realLength); + return safeArrayRef(context, values, begin + --realLength); } else { int index = begin + --realLength; - return safeArrayRefSet(context.runtime, values, index, context.nil); + return safeArrayRefSet(context, values, index, context.nil); } } @JRubyMethod public IRubyObject pop(ThreadContext context, IRubyObject num) { - unpack(); - modifyCheck(); + unpack(context); + modifyCheck(context); RubyArray result = makeSharedFirst(context, num, true, context.runtime.getArray()); realLength -= result.realLength; return result; @@ -1523,12 +1597,12 @@ public IRubyObject pop(ThreadContext context, IRubyObject num) { */ @JRubyMethod(name = "shift") public IRubyObject shift(ThreadContext context) { - unpack(); - modifyCheck(); + unpack(context); + modifyCheck(context); if (realLength == 0) return context.nil; - final IRubyObject obj = safeArrayRefCondSet(context.runtime, values, begin, !isShared, context.nil); + final IRubyObject obj = safeArrayRefCondSet(context, values, begin, !isShared, context.nil); begin++; realLength--; return obj; @@ -1537,8 +1611,8 @@ public IRubyObject shift(ThreadContext context) { @JRubyMethod(name = "shift") public IRubyObject shift(ThreadContext context, IRubyObject num) { - unpack(); - modify(); + unpack(context); + modify(context); RubyArray result = makeSharedFirst(context, num, false, context.runtime.getArray()); @@ -1548,32 +1622,51 @@ public IRubyObject shift(ThreadContext context, IRubyObject num) { return result; } - @JRubyMethod(name = "unshift", alias = "prepend") + /** + * @return "" + * @deprecated Use {@link RubyArray#unshift(ThreadContext)} instead + */ + @Deprecated public IRubyObject unshift() { - modifyCheck(); + return unshift(getCurrentContext()); + } + + @JRubyMethod(name = "unshift", alias = "prepend") + public IRubyObject unshift(ThreadContext context) { + modifyCheck(context); return this; } + /** + * @param item + * @return "" + * @deprecated Use {@link RubyArray#unshift(ThreadContext, IRubyObject)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject unshift(IRubyObject item) { + return unshift(getCurrentContext(), item); + } + /** rb_ary_unshift * */ @JRubyMethod(name = "unshift", alias = "prepend") - public IRubyObject unshift(IRubyObject item) { - unpack(); + public IRubyObject unshift(ThreadContext context, IRubyObject item) { + unpack(context); if (begin == 0 || isShared) { - modify(); + modify(context); final int valuesLength = values.length - begin; if (valuesLength == 0) { alloc(ARRAY_DEFAULT_SIZE); begin = ARRAY_DEFAULT_SIZE - 1; } else if (realLength == valuesLength) { - unshiftRealloc(valuesLength); + unshiftRealloc(context, valuesLength); } else { - safeArrayCopy(values, begin, values, begin + 1, realLength); + safeArrayCopy(context, values, begin, values, begin + 1, realLength); } } else { - modifyCheck(); + modifyCheck(context); begin--; } realLength++; @@ -1581,23 +1674,33 @@ public IRubyObject unshift(IRubyObject item) { return this; } - @JRubyMethod(name = "unshift", alias = "prepend", rest = true) + /** + * @param items + * @return "" + * @deprecated Use {@link RubyArray#unshift(ThreadContext, IRubyObject[])} + */ + @Deprecated(since = "10.0", forRemoval = true) public IRubyObject unshift(IRubyObject[] items) { - unpack(); + return unshift(getCurrentContext(), items); + } + + @JRubyMethod(name = "unshift", alias = "prepend", rest = true) + public IRubyObject unshift(ThreadContext context, IRubyObject[] items) { + unpack(context); if (items.length == 0) { - modifyCheck(); + modifyCheck(context); return this; } final int len = realLength; - store(((long) len) + items.length - 1, metaClass.runtime.getNil()); + store(((long) len) + items.length - 1, context.nil); try { System.arraycopy(values, begin, values, begin + items.length, len); ArraySupport.copy(items, 0, values, begin, items.length); } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(getRuntime(), e); + throw concurrentModification(context, e); } return this; @@ -1686,6 +1789,7 @@ private IRubyObject arefCommon(ThreadContext context, IRubyObject arg0, IRubyObj * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ + @Deprecated(since = "9.4-", forRemoval = false) public IRubyObject aset(IRubyObject[] args) { switch (args.length) { case 2: @@ -1697,14 +1801,23 @@ public IRubyObject aset(IRubyObject[] args) { } } - @JRubyMethod(name = "[]=") + /** + * @param arg0 + * @param arg1 + * @return "" + * @deprecated Use {@link RubyArray#aset(ThreadContext, IRubyObject, IRubyObject)} + */ + @Deprecated(since = "10.0", forRemoval = true) public IRubyObject aset(IRubyObject arg0, IRubyObject arg1) { - ThreadContext context = getRuntime().getCurrentContext(); - modifyCheck(); + return aset(getCurrentContext(), arg0, arg1); + } + + @JRubyMethod(name = "[]=") + public IRubyObject aset(ThreadContext context, IRubyObject arg0, IRubyObject arg1) { + modifyCheck(context); if (arg0 instanceof RubyFixnum) { store(((RubyFixnum) arg0).value, arg1); - } else if (arg0 instanceof RubyRange) { - RubyRange range = (RubyRange) arg0; + } else if (arg0 instanceof RubyRange range) { int beg0 = checkLongForInt(context, range.begLen0(context, realLength)); int beg1 = checkLongForInt(context, range.begLen1(context, realLength, beg0)); splice(context, beg0, beg1, arg1); @@ -1736,22 +1849,43 @@ private void asetFallback(ThreadContext context, IRubyObject arg0, IRubyObject a } } + /** + * @param arg0 + * @param arg1 + * @param arg2 + * @return "" + * @deprecated Use {@link RubyArray#aset(ThreadContext, IRubyObject, IRubyObject, IRubyObject)} instead. + */ + @Deprecated + public IRubyObject aset(IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { + return aset(getCurrentContext(), arg0, arg1, arg2); + } + /** rb_ary_aset * */ @JRubyMethod(name = "[]=") - public IRubyObject aset(IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { - modifyCheck(); - splice(metaClass.runtime.getCurrentContext(), RubyNumeric.num2int(arg0), RubyNumeric.num2int(arg1), arg2); + public IRubyObject aset(ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { + modifyCheck(context); + splice(context, RubyNumeric.num2int(arg0), RubyNumeric.num2int(arg1), arg2); return arg2; } + /** + * @param pos + * @return "" + * @deprecated Use {@link RubyArray#at(ThreadContext, IRubyObject)} instead. + */ + @Deprecated + public IRubyObject at(IRubyObject pos) { + return at(getCurrentContext(), pos); + } + /** rb_ary_at * */ @JRubyMethod(name = "at") - public IRubyObject at(IRubyObject pos) { - ThreadContext context = getRuntime().getCurrentContext(); + public IRubyObject at(ThreadContext context, IRubyObject pos) { return entry(numericToLong(context, pos)); } @@ -1760,20 +1894,29 @@ public IRubyObject at(IRubyObject pos) { */ @JRubyMethod(name = "concat") public RubyArray concat(ThreadContext context, IRubyObject obj) { - modifyCheck(); + modifyCheck(context); - concat(context.runtime, obj.convertToArray()); + concat(context, obj.convertToArray()); return this; } - private void concat(final Ruby runtime, RubyArray obj) { - splice(runtime.getCurrentContext(), realLength, 0, obj, obj.realLength); + private void concat(ThreadContext context, RubyArray obj) { + splice(context, realLength, 0, obj, obj.realLength); } - // MRI: ary_append - public RubyArray aryAppend(RubyArray y) { - if (y.realLength > 0) splice(metaClass.runtime.getCurrentContext(), realLength, 0, y, y.realLength); + /** + * @param y array + * @return array + * @deprecated Use {@link RubyArray#aryAppend(ThreadContext, RubyArray)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public RubyArray aryAppend(RubyArray y) { + return aryAppend(getCurrentContext(), y); + } + // MRI: ary_append + public RubyArray aryAppend(ThreadContext context, RubyArray y) { + if (y.realLength > 0) splice(context, realLength, 0, y, y.realLength); return this; } @@ -1782,17 +1925,16 @@ public RubyArray aryAppend(RubyArray y) { */ @JRubyMethod(name = "concat", rest = true) public RubyArray concat(ThreadContext context, IRubyObject[] objs) { - modifyCheck(); + modifyCheck(context); if (objs.length > 0) { - Ruby runtime = context.runtime; - RubyArray tmp = newArray(runtime, objs.length); + var tmp = Create.newArray(context, objs.length); for (IRubyObject obj : objs) { - tmp.concat(runtime, obj.convertToArray()); + tmp.concat(context, obj.convertToArray()); } - return aryAppend(tmp); + return aryAppend(context, tmp); } return this; @@ -1806,13 +1948,12 @@ public RubyArray concat(IRubyObject obj) { * */ protected IRubyObject inspectAry(ThreadContext context) { - final Ruby runtime = context.runtime; - RubyString str = RubyString.newStringLight(runtime, DEFAULT_INSPECT_STR_SIZE, USASCIIEncoding.INSTANCE); + RubyString str = RubyString.newStringLight(context.runtime, DEFAULT_INSPECT_STR_SIZE, USASCIIEncoding.INSTANCE); str.cat((byte) '['); for (int i = 0; i < realLength; i++) { - RubyString s = inspect(context, safeArrayRef(runtime, values, begin + i)); + RubyString s = inspect(context, safeArrayRef(context, values, begin + i)); if (i > 0) { ByteList bytes = str.getByteList(); bytes.append((byte) ',').append((byte) ' '); @@ -1852,6 +1993,7 @@ public IRubyObject inspect() { * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ + @Deprecated(since = "9.4-", forRemoval = false) public IRubyObject first(IRubyObject[] args) { switch (args.length) { case 0: @@ -1890,7 +2032,7 @@ public IRubyObject first(IRubyObject arg0) { return newArray(context.runtime, eltOk(0), eltOk(1)); } - unpack(); + unpack(context); return makeShared(begin, (int) n, context.runtime.getArray()); } @@ -1898,6 +2040,7 @@ public IRubyObject first(IRubyObject arg0) { * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ + @Deprecated(since = "9.4-", forRemoval = false) public IRubyObject last(IRubyObject[] args) { switch (args.length) { case 0: @@ -1936,7 +2079,7 @@ public IRubyObject last(IRubyObject arg0) { return newArray(metaClass.runtime, eltOk(realLength - 2), eltOk(realLength - 1)); } - unpack(); + unpack(context); return makeShared(begin + realLength - (int) n, (int) n, metaClass.runtime.getArray()); } @@ -1956,7 +2099,7 @@ public IRubyObject each(ThreadContext context, Block block) { } public IRubyObject eachSlice(ThreadContext context, int size, Block block) { - unpack(); + unpack(context); final RubyClass array = context.runtime.getArray(); // local copies of everything @@ -2034,10 +2177,7 @@ public IRubyObject reverse_each(ThreadContext context, Block block) { // MRI: ary_join_0 protected int joinStrings(RubyString sep, int max, RubyString result) { - IRubyObject first; - if (max > 0 && (first = eltOk(0)) instanceof EncodingCapable) { - result.setEncoding(((EncodingCapable) first).getEncoding()); - } + if (max > 0 && eltOk(0) instanceof EncodingCapable ec) result.setEncoding(ec.getEncoding()); int i; try { @@ -2048,7 +2188,7 @@ protected int joinStrings(RubyString sep, int max, RubyString result) { result.append(val); } } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(getRuntime(), e); + throw concurrentModification(getRuntime().getCurrentContext(), e); } return i; @@ -2292,13 +2432,22 @@ public IRubyObject eql(ThreadContext context, IRubyObject obj) { return RecursiveComparator.compare(context, sites(context).eql, this, obj, true); } + /** + * @return "" + * @deprecated Use {@link RubyArray#compact_bang(ThreadContext)} + */ + @Deprecated + public IRubyObject compact_bang() { + return compact_bang(getCurrentContext()); + } + /** rb_ary_compact_bang * */ @JRubyMethod(name = "compact!") - public IRubyObject compact_bang() { - unpack(); - modify(); + public IRubyObject compact_bang(ThreadContext context) { + unpack(context); + modify(context); int p = begin; int t = p; @@ -2313,13 +2462,13 @@ public IRubyObject compact_bang() { } } } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(getRuntime(), e); + throw concurrentModification(context, e); } p -= begin; if (realLength == p) return metaClass.runtime.getNil(); - realloc(p, values.length - begin); + realloc(context, p, values.length - begin); realLength = p; return this; } @@ -2343,12 +2492,21 @@ public IRubyObject empty_p() { return realLength == 0 ? runtime.getTrue() : runtime.getFalse(); } + /** + * @return "" + * @deprecated Use {@link } + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject rb_clear() { + return rb_clear(getCurrentContext()); + } + /** rb_ary_clear * */ @JRubyMethod(name = "clear") - public IRubyObject rb_clear() { - modifyCheck(); + public IRubyObject rb_clear(ThreadContext context) { + modifyCheck(context); if (isShared) { alloc(ARRAY_DEFAULT_SIZE); @@ -2358,9 +2516,9 @@ public IRubyObject rb_clear() { } else { try { begin = 0; - Helpers.fillNil(values, 0, realLength, metaClass.runtime); + Helpers.fillNil(values, 0, realLength, context.runtime); } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(getRuntime(), e); + throw concurrentModification(context, e); } } @@ -2435,8 +2593,8 @@ private long fillLen(ThreadContext context, long beg, IRubyObject arg) { } protected IRubyObject fillCommon(ThreadContext context, int beg, long len, IRubyObject item) { - unpack(); - modify(); + unpack(context); + modify(context); if (len < 0) return this; @@ -2445,7 +2603,7 @@ protected IRubyObject fillCommon(ThreadContext context, int beg, long len, IRuby int end = (int)(beg + len); if (end > realLength) { int valuesLength = values.length - begin; - if (end >= valuesLength) realloc(end, valuesLength); + if (end >= valuesLength) realloc(context, end, valuesLength); realLength = end; } @@ -2453,7 +2611,7 @@ protected IRubyObject fillCommon(ThreadContext context, int beg, long len, IRuby try { Arrays.fill(values, begin + beg, begin + end, item); } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + throw concurrentModification(context, ex); } } @@ -2461,8 +2619,8 @@ protected IRubyObject fillCommon(ThreadContext context, int beg, long len, IRuby } protected IRubyObject fillCommon(ThreadContext context, int beg, long len, Block block) { - unpack(); - modify(); + unpack(context); + modify(context); if (len < 0) return this; @@ -2471,15 +2629,14 @@ protected IRubyObject fillCommon(ThreadContext context, int beg, long len, Block int end = (int)(beg + len); if (end > realLength) { int valuesLength = values.length - begin; - if (end >= valuesLength) realloc(end, valuesLength); + if (end >= valuesLength) realloc(context, end, valuesLength); realLength = end; } - final Ruby runtime = context.runtime; for (int i = beg; i < end; i++) { IRubyObject v = block.yield(context, asFixnum(context, i)); if (i >= realLength) break; - safeArraySet(runtime, values, begin + i, v); + safeArraySet(context, values, begin + i, v); } return this; } @@ -2586,7 +2743,7 @@ private int bsearch_index_internal(ThreadContext context, Block block) { * */ public IRubyObject rindex(ThreadContext context, IRubyObject obj) { - unpack(); + unpack(context); int i = realLength; @@ -2644,19 +2801,28 @@ public IRubyObject indexes(ThreadContext context, IRubyObject[] args) { RubyArray ary = newBlankArrayInternal(runtime, argc); for (int i = 0; i < argc; i++) { - ary.storeInternal(i, aref(context, args[i])); + ary.storeInternal(context, i, aref(context, args[i])); } ary.realLength = argc; return ary; } + /** + * @return "" + * @deprecated Use {@link RubyArray#reverse_bang(ThreadContext)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject reverse_bang() { + return reverse_bang(getCurrentContext()); + } + /** rb_ary_reverse_bang * */ @JRubyMethod(name = "reverse!") - public IRubyObject reverse_bang() { - modify(); + public IRubyObject reverse_bang(ThreadContext context) { + modify(context); try { if (realLength > 1) { @@ -2668,7 +2834,7 @@ public IRubyObject reverse_bang() { } } } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(getRuntime(), e); + throw concurrentModification(context, e); } return this; } @@ -2697,7 +2863,7 @@ protected RubyArray safeReverse() { vals[length - i - 1] = myValues[myBegin + i]; } } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(runtime, e); + throw concurrentModification(runtime.getCurrentContext(), e); } return new RubyArray(runtime, runtime.getArray(), vals); } @@ -2713,14 +2879,10 @@ protected RubyArray safeReverse() { public RubyArray collectArray(ThreadContext context, Block block) { if (!block.isGiven()) return makeShared(); - final Ruby runtime = context.runtime; - - RubyArray ary = RubyArray.newArray(runtime, realLength); + RubyArray ary = Create.newArray(context, realLength); - int i = 0; - for (; i < realLength; i++) { - // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield - // See JRUBY-5434 + for (int i = 0; i < realLength; i++) { + // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield (see JRUBY-5434) ary.store(i, block.yieldNonArray(context, eltOk(i), null)); // arr[i] = ... } @@ -2762,12 +2924,12 @@ public IRubyObject map(ThreadContext context, Block block) { */ public RubyArray collectBang(ThreadContext context, Block block) { if (!block.isGiven()) throw context.runtime.newLocalJumpErrorNoBlock(); - modify(); + modify(context); for (int i = 0; i < realLength; i++) { // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield // See JRUBY-5434 - storeInternal(i, block.yield(context, eltOk(i))); + storeInternal(context, i, block.yield(context, eltOk(i))); } return this; @@ -2817,13 +2979,11 @@ public IRubyObject selectCommon(ThreadContext context, Block block) { } } - RubyArray result = newArray(runtime, realLength); + RubyArray result = Create.newArray(context, realLength); for (int i = 0; i < realLength; i++) { - // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield - // See JRUBY-5434 + // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield (see JRUBY-5434) IRubyObject value = eltOk(i); - if (block.yield(context, value).isTrue()) result.append(value); } @@ -2840,18 +3000,16 @@ public IRubyObject select(ThreadContext context, Block block) { public IRubyObject select_bang(ThreadContext context, Block block) { if (!block.isGiven()) return enumeratorizeWithSize(context, this, "select!", RubyArray::size); - unpack(); - modify(); + unpack(context); + modify(context); boolean modified = false; - final Ruby runtime = context.runtime; - int len0 = 0, len1 = 0; + try { int i1, i2; for (i1 = i2 = 0; i1 < realLength; len0 = ++i1) { - // Do not coarsen the "safe" check, since it will misinterpret - // AIOOBE from the yield (see JRUBY-5434) + // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield (see JRUBY-5434) IRubyObject value = eltOk(i1); if (!block.yield(context, value).isTrue()) { @@ -2866,7 +3024,7 @@ public IRubyObject select_bang(ThreadContext context, Block block) { } finally { if (modified) checkFrozen(); - selectBangEnsure(runtime, len0, len1); + selectBangEnsure(context, len0, len1); } } @@ -2889,15 +3047,13 @@ public IRubyObject deconstruct(ThreadContext context) { */ @JRubyMethod public IRubyObject delete(ThreadContext context, IRubyObject item, Block block) { - unpack(); + unpack(context); int i2 = 0; IRubyObject value = item; - final Ruby runtime = context.runtime; for (int i1 = 0; i1 < realLength; i1++) { - // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from equalInternal - // See JRUBY-5434 - IRubyObject e = safeArrayRef(runtime, values, begin + i1); + // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from equalInternal (see JRUBY-5434) + IRubyObject e = safeArrayRef(context, values, begin + i1); if (equalInternal(context, e, item)) { value = e; continue; @@ -2906,13 +3062,9 @@ public IRubyObject delete(ThreadContext context, IRubyObject item, Block block) i2++; } - if (realLength == i2) { - if (block.isGiven()) return block.yield(context, item); - - return context.nil; - } + if (realLength == i2) return block.isGiven() ? block.yield(context, item) : context.nil; - modify(); + modify(context); final int myRealLength = this.realLength; final int myBegin = this.begin; @@ -2922,50 +3074,57 @@ public IRubyObject delete(ThreadContext context, IRubyObject item, Block block) Helpers.fillNil(myValues, myBegin + i2, myBegin + myRealLength, context.runtime); this.realLength = i2; int valuesLength = myValues.length - myBegin; - if (i2 << 1 < valuesLength && valuesLength > ARRAY_DEFAULT_SIZE) realloc(i2 << 1, valuesLength); + if (i2 << 1 < valuesLength && valuesLength > ARRAY_DEFAULT_SIZE) realloc(context, i2 << 1, valuesLength); } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + throw concurrentModification(context, ex); } return value; } + /** + * @param pos + * @return "" + * @deprecated Use {@link RubyArray#delete_at(ThreadContext, int)} + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject delete_at(int pos) { + return delete_at(getCurrentContext(), pos); + } + /** rb_ary_delete_at * */ - public IRubyObject delete_at(int pos) { + public IRubyObject delete_at(ThreadContext context, int pos) { int len = realLength; - if (pos >= len || (pos < 0 && (pos += len) < 0)) return metaClass.runtime.getNil(); + if (pos >= len || (pos < 0 && (pos += len) < 0)) return context.nil; - unpack(); - modify(); - - IRubyObject nil = metaClass.runtime.getNil(); - IRubyObject obj; + unpack(context); + modify(context); try { - obj = values[begin + pos]; + IRubyObject obj = values[begin + pos]; // fast paths for head and tail if (pos == 0) { - values[begin] = nil; + values[begin] = context.nil; begin++; realLength--; return obj; } else if (pos == realLength - 1) { - values[begin + realLength - 1] = nil; + values[begin + realLength - 1] = context.nil; realLength--; return obj; } System.arraycopy(values, begin + pos + 1, values, begin + pos, len - (pos + 1)); - values[begin + len - 1] = nil; + values[begin + len - 1] = context.nil; + realLength--; + + return obj; } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(getRuntime(), e); + throw concurrentModification(context, e); } - realLength--; - - return obj; } /** rb_ary_delete_at_m @@ -2999,12 +3158,10 @@ public IRubyObject reject(ThreadContext context, Block block) { // MRI: ary_reject_bang and reject_bang_i public IRubyObject rejectBang(ThreadContext context, Block block) { - unpack(); - modify(); + unpack(context); + modify(context); - final Ruby runtime = context.runtime; final int beg = begin; - boolean modified = false; int len0 = 0, len1 = 0; @@ -3012,31 +3169,28 @@ public IRubyObject rejectBang(ThreadContext context, Block block) { int i1, i2; for (i1 = i2 = 0; i1 < realLength; len0 = ++i1) { final IRubyObject[] values = this.values; - // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield - // See JRUBY-5434 - IRubyObject value = safeArrayRef(runtime, values, beg + i1); + // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield (see JRUBY-5434) + IRubyObject value = safeArrayRef(context, values, beg + i1); if (block.yield(context, value).isTrue()) { modified = true; continue; } - if (i1 != i2) { - safeArraySet(runtime, values, beg + i2, value); - } + if (i1 != i2) safeArraySet(context, values, beg + i2, value); + len1 = ++i2; } return (i1 == i2) ? context.nil : this; - } - finally { + } finally { if (modified) checkFrozen(); - selectBangEnsure(runtime, len0, len1); + selectBangEnsure(context, len0, len1); } } // MRI: select_bang_ensure - private void selectBangEnsure(final Ruby runtime, int i1, int i2) { + private void selectBangEnsure(ThreadContext context, int i1, int i2) { int len = realLength; if (i2 < len && i2 < i1) { @@ -3044,14 +3198,14 @@ private void selectBangEnsure(final Ruby runtime, int i1, int i2) { int beg = begin; if (i1 < len) { tail = len - i1; - safeArrayCopy(runtime, values, beg + i1, values, beg + i2, tail); + safeArrayCopy(context, values, beg + i1, values, beg + i2, tail); } else if (realLength > 0) { // nil out left-overs to avoid leaks (MRI doesn't) try { - Helpers.fillNil(values, beg + i2, beg + i1, runtime); + Helpers.fillNil(values, beg + i2, beg + i1, context.runtime); } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(runtime, ex); + throw concurrentModification(context, ex); } } realLength = i2 + tail; @@ -3147,7 +3301,7 @@ private IRubyObject zipCommon(ThreadContext context, IRubyObject[] args, Block b result[i] = newArrayMayCopy(runtime, tmp); } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(runtime, ex); + throw concurrentModification(context, ex); } return newArrayMayCopy(runtime, result); } @@ -3206,6 +3360,7 @@ private IRubyObject cmpCommon(ThreadContext context, Ruby runtime, RubyArray ary * Variable arity version for compatibility. Not bound to a Ruby method. * @deprecated Use the versions with zero, one, or two args. */ + @Deprecated(since = "9.4-", forRemoval = false) public IRubyObject slice_bang(IRubyObject[] args) { switch (args.length) { case 1: @@ -3235,7 +3390,7 @@ private IRubyObject slice_internal(ThreadContext context, int pos, int len) { return context.runtime.newEmptyArray(); } - unpack(); + unpack(context); RubyArray result = makeShared(begin + pos, len, context.runtime.getArray()); splice(context, pos, len, null, 0); @@ -3243,20 +3398,25 @@ private IRubyObject slice_internal(ThreadContext context, int pos, int len) { return result; } - /** rb_ary_slice_bang - * + /** + * @param arg0 + * @return "" + * @deprecated Use {@link RubyArray#slice_bang(ThreadContext, IRubyObject)} */ - @JRubyMethod(name = "slice!") + @Deprecated(since = "10.0", forRemoval = true) public IRubyObject slice_bang(IRubyObject arg0) { - modifyCheck(); - Ruby runtime = metaClass.runtime; - ThreadContext context = runtime.getCurrentContext(); + return slice_bang(getCurrentContext(), arg0); + } - if (arg0 instanceof RubyRange) { - RubyRange range = (RubyRange) arg0; - if (!range.checkBegin(context, realLength)) { - return runtime.getNil(); - } + /** rb_ary_slice_bang + * + */ + @JRubyMethod(name = "slice!") + public IRubyObject slice_bang(ThreadContext context, IRubyObject arg0) { + modifyCheck(context); + + if (arg0 instanceof RubyRange range) { + if (!range.checkBegin(context, realLength)) return context.nil; int pos = checkInt(context, range.begLen0(context, realLength)); int len = checkInt(context, range.begLen1(context, realLength, pos)); @@ -3265,14 +3425,25 @@ public IRubyObject slice_bang(IRubyObject arg0) { return delete_at(RubyNumeric.num2int(arg0)); } + /** + * @param arg0 + * @param arg1 + * @return "" + * @deprecated Use {@link RubyArray#slice_bang(ThreadContext, IRubyObject, IRubyObject)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject slice_bang(IRubyObject arg0, IRubyObject arg1) { + return slice_bang(getCurrentContext(), arg0, arg1); + } + /** rb_ary_slice_bang * */ @JRubyMethod(name = "slice!") - public IRubyObject slice_bang(IRubyObject arg0, IRubyObject arg1) { - modifyCheck(); + public IRubyObject slice_bang(ThreadContext context, IRubyObject arg0, IRubyObject arg1) { + modifyCheck(context); - return slice_internal(metaClass.runtime.getCurrentContext(), RubyNumeric.num2int(arg0), RubyNumeric.num2int(arg1)); + return slice_internal(context, RubyNumeric.num2int(arg0), RubyNumeric.num2int(arg1)); } /** rb_ary_assoc @@ -3312,18 +3483,17 @@ public IRubyObject rassoc(ThreadContext context, IRubyObject value) { // MRI array.c flatten protected boolean flatten(ThreadContext context, final int level, final RubyArray result) { // TODO: (CON) We can flatten packed versions efficiently if length does not change (e.g. [[1,2],[]]) - unpack(); - final Ruby runtime = context.runtime; + unpack(context); IRubyObject tmp = null; int i = 0; for (; i < realLength; i++) { IRubyObject elt = eltOk(i); - tmp = TypeConverter.checkArrayType(runtime, elt); + tmp = TypeConverter.checkArrayType(context.runtime, elt); if (!tmp.isNil()) break; } - safeArrayCopy(values, begin, result.values, result.begin, i); + safeArrayCopy(context, values, begin, result.values, result.begin, i); result.realLength = i; if (i == realLength) return false; @@ -3374,7 +3544,7 @@ protected boolean flatten(ThreadContext context, final int level, final RubyArra ary = (RubyArray) stack.pop(); } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + throw concurrentModification(context, ex); } return stack != null; @@ -3382,12 +3552,12 @@ protected boolean flatten(ThreadContext context, final int level, final RubyArra @JRubyMethod(name = "flatten!") public IRubyObject flatten_bang(ThreadContext context) { - unpack(); - modifyCheck(); + unpack(context); + modifyCheck(context); RubyArray result = new RubyArray(context.runtime, getType(), realLength); if (flatten(context, -1, result)) { - modifyCheck(); + modifyCheck(context); isShared = false; begin = 0; realLength = result.realLength; @@ -3399,8 +3569,8 @@ public IRubyObject flatten_bang(ThreadContext context) { @JRubyMethod(name = "flatten!") public IRubyObject flatten_bang(ThreadContext context, IRubyObject arg) { - unpack(); - modifyCheck(); + unpack(context); + modifyCheck(context); int level = RubyNumeric.num2int(arg); if (level == 0) return context.nil; @@ -3418,9 +3588,7 @@ public IRubyObject flatten_bang(ThreadContext context, IRubyObject arg) { @JRubyMethod(name = "flatten") public IRubyObject flatten(ThreadContext context) { - Ruby runtime = context.runtime; - - RubyArray result = new RubyArray(runtime, runtime.getArray(), realLength); + var result = new RubyArray(context.runtime, context.runtime.getArray(), realLength); flatten(context, -1, result); return result; } @@ -3479,35 +3647,44 @@ public IRubyObject nitems() { return nitems(getCurrentContext()); } + /** + * @param obj to be plussed + * @return object + * @deprecated Use {@link RubyArray#op_plus(ThreadContext, IRubyObject)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject op_plus(IRubyObject obj) { + return op_plus(getCurrentContext(), obj); + } + /** rb_ary_plus * */ @JRubyMethod(name = "+") - public IRubyObject op_plus(IRubyObject obj) { - Ruby runtime = metaClass.runtime; + public IRubyObject op_plus(ThreadContext context, IRubyObject obj) { RubyArray y = obj.convertToArray(); int len = realLength + y.realLength; switch (len) { case 1: - return new RubyArrayOneObject(runtime, realLength == 1 ? eltInternal(0) : y.eltInternal(0)); + return new RubyArrayOneObject(context.runtime, realLength == 1 ? eltInternal(0) : y.eltInternal(0)); case 2: switch (realLength) { case 0: - return newArray(runtime, y.eltInternal(0), y.eltInternal(1)); + return newArray(context.runtime, y.eltInternal(0), y.eltInternal(1)); case 1: - return newArray(runtime, eltInternal(0), y.eltInternal(0)); + return newArray(context.runtime, eltInternal(0), y.eltInternal(0)); case 2: - return newArray(runtime, eltInternal(0), eltInternal(1)); + return newArray(context.runtime, eltInternal(0), eltInternal(1)); } } - RubyArray z = newArray(runtime, len); + RubyArray z = Create.newArray(context, len); try { - copyInto(z.values, 0); - y.copyInto(z.values, realLength); + copyInto(context, z.values, 0); + y.copyInto(context, z.values, realLength); } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(runtime, e); + throw concurrentModification(context, e); } z.realLength = len; return z; @@ -3523,23 +3700,21 @@ public IRubyObject op_times(ThreadContext context, IRubyObject times) { if (!tmp.isNil()) return join(context, tmp); long len = numericToLong(context, times); - Ruby runtime = context.runtime; - if (len == 0) return RubyArray.newEmptyArray(runtime); + if (len == 0) return RubyArray.newEmptyArray(context.runtime); if (len < 0) throw argumentError(context, "negative argument"); if (Long.MAX_VALUE / len < realLength) throw argumentError(context, "argument too big"); len *= realLength; - checkLength(runtime, len); - RubyArray ary2 = new RubyArray(runtime, (int)len); + RubyArray ary2 = Create.newArray(context, len); ary2.realLength = ary2.values.length; try { for (int i = 0; i < len; i += realLength) { - copyInto(ary2.values, i); + copyInto(context, ary2.values, i); } } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(runtime, e); + throw concurrentModification(context, e); } return ary2; @@ -3577,7 +3752,7 @@ private void setValuesFrom(ThreadContext context, RubyHash hash) { try { hash.visitAll(context, RubyHash.SetValueVisitor, this); } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + throw concurrentModification(context, ex); } } @@ -3585,7 +3760,7 @@ private void clearValues(final int from, final int to) { try { Helpers.fillNil(values, begin + from, begin + to, metaClass.runtime); } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(getRuntime(), ex); + throw concurrentModification(getRuntime().getCurrentContext(), ex); } } @@ -3597,8 +3772,8 @@ public IRubyObject uniq_bang(ThreadContext context) { final int newLength = hash.size; if (realLength == newLength) return context.nil; - modify(); // in case array isShared - unpack(); + modify(context); // in case array isShared + unpack(context); setValuesFrom(context, hash); clearValues(newLength, realLength); @@ -3609,7 +3784,7 @@ public IRubyObject uniq_bang(ThreadContext context) { @JRubyMethod(name = "uniq!") public IRubyObject uniq_bang(ThreadContext context, Block block) { - modifyCheck(); + modifyCheck(context); if (!block.isGiven()) return uniq_bang(context); @@ -3618,8 +3793,8 @@ public IRubyObject uniq_bang(ThreadContext context, Block block) { if (realLength == newLength) return context.nil; // after evaluating the block, a new modify check is needed - modify(); // in case array isShared - unpack(); + modify(context); // in case array isShared + unpack(context); setValuesFrom(context, hash); clearValues(newLength, realLength); @@ -3657,30 +3832,37 @@ public IRubyObject uniq(ThreadContext context, Block block) { return result; } + /** + * @param other + * @return "" + * @deprecated Use {@link RubyArray#op_diff(ThreadContext, IRubyObject)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject op_diff(IRubyObject other) { + return op_diff(getCurrentContext(), other); + } /** rb_ary_diff * */ @JRubyMethod(name = "-") - public IRubyObject op_diff(IRubyObject other) { - final Ruby runtime = metaClass.runtime; - + public IRubyObject op_diff(ThreadContext context, IRubyObject other) { final int len = realLength; - RubyArray res = newBlankArrayInternal(runtime, len); + RubyArray res = newBlankArrayInternal(context.runtime, len); int index = 0; - RubyHash hash = other.convertToArray().makeHash(runtime); + RubyHash hash = other.convertToArray().makeHash(context.runtime); for (int i = 0; i < len; i++) { IRubyObject val = eltOk(i); - if (hash.fastARef(val) == null) res.storeInternal(index++, val); + if (hash.fastARef(val) == null) res.storeInternal(context, index++, val); } // if index is 1 and we made a size 2 array, repack - if (index == 0) return newEmptyArray(runtime); - if (index == 1 && len == 2) return newArray(runtime, res.eltInternal(0)); + if (index == 0) return newEmptyArray(context.runtime); + if (index == 1 && len == 2) return newArray(context.runtime, res.eltInternal(0)); assert index == res.realLength; if (!(res instanceof RubyArraySpecialized)) { - Helpers.fillNil(res.values, index, res.values.length, runtime); + Helpers.fillNil(res.values, index, res.values.length, context.runtime); } return res; @@ -3765,42 +3947,50 @@ public IRubyObject intersect_p(ThreadContext context, IRubyObject other) { return context.fals; } + /** + * @param other + * @return "" + * @deprecated Use {@link RubyArray#op_and(ThreadContext, IRubyObject)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public IRubyObject op_and(IRubyObject other) { + return op_and(getCurrentContext(), other); + } + /** MRI: rb_ary_and * */ @JRubyMethod(name = "&") - public IRubyObject op_and(IRubyObject other) { - final Ruby runtime = metaClass.runtime; - - RubyArray ary2 = other.convertToArray(); + public IRubyObject op_and(ThreadContext context, IRubyObject other) { + RubyArray ary2 = other.convertToArray(); final int len = realLength; int maxSize = len < ary2.realLength ? len : ary2.realLength; RubyArray res; switch (maxSize) { case 0: - return newEmptyArray(runtime); + return newEmptyArray(context.runtime); case 1: - if (len == 0 || ary2.realLength == 0) return newEmptyArray(runtime); + if (len == 0 || ary2.realLength == 0) return newEmptyArray(context.runtime); default: - res = newBlankArrayInternal(runtime, maxSize); + res = newBlankArrayInternal(context.runtime, maxSize); break; } int index = 0; - RubyHash hash = ary2.makeHash(runtime); + RubyHash hash = ary2.makeHash(context.runtime); for (int i = 0; i < len; i++) { IRubyObject val = elt(i); - if (hash.fastDelete(val)) res.storeInternal(index++, val); + if (hash.fastDelete(val)) res.storeInternal(context, index++, val); } // if index is 1 and we made a size 2 array, repack - if (index == 0) return newEmptyArray(runtime); - if (index == 1 && maxSize == 2) return newArray(runtime, res.eltInternal(0)); + if (index == 0) return newEmptyArray(context.runtime); + if (index == 1 && maxSize == 2) return newArray(context.runtime, res.eltInternal(0)); assert index == res.realLength; if (!(res instanceof RubyArraySpecialized)) { - Helpers.fillNil(res.values, index, res.values.length, runtime); + Helpers.fillNil(res.values, index, res.values.length, context.runtime); } return res; @@ -3894,7 +4084,7 @@ public RubyArray sort(ThreadContext context, Block block) { */ @JRubyMethod(name = "sort!") public IRubyObject sort_bang(ThreadContext context, Block block) { - modify(); + modify(context); if (realLength > 1) { return block.isGiven() ? sortInternal(context, block) : sortInternal(context, true); } @@ -3906,13 +4096,12 @@ protected IRubyObject sortInternal(final ThreadContext context, final boolean ho Arrays.sort(values, begin, begin + realLength, new DefaultComparator(context, honorOverride) { protected int compareGeneric(IRubyObject o1, IRubyObject o2) { int result = super.compareGeneric(o1, o2); - modifyCheck(); + modifyCheck(context); return result; } }); - } - catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + } catch (ArrayIndexOutOfBoundsException ex) { + throw concurrentModification(context, ex); } return this; } @@ -4034,18 +4223,18 @@ protected final ThreadContext context() { protected IRubyObject sortInternal(final ThreadContext context, final Block block) { // block code can modify, so we need to iterate - unpack(); + unpack(context); IRubyObject[] newValues = IRubyObject.array(realLength); int length = realLength; - copyInto(newValues, 0); + copyInto(context, newValues, 0); CallSite gt = sites(context).op_gt_sort; CallSite lt = sites(context).op_lt_sort; Arrays.sort(newValues, 0, length, new BlockComparator(context, block, gt, lt) { @Override public int compare(IRubyObject obj1, IRubyObject obj2) { int result = super.compare(obj1, obj2); - modifyCheck(); + modifyCheck(context); return result; } }); @@ -4063,7 +4252,7 @@ public int compare(IRubyObject obj1, IRubyObject obj2) { public IRubyObject sort_by_bang(ThreadContext context, Block block) { if (!block.isGiven()) return enumeratorizeWithSize(context, this, "sort_by!", RubyArray::size); - modifyCheck(); + modifyCheck(context); RubyArray sorted = sites(context).sort_by.call(context, this, this, block).convertToArray(); @@ -4481,7 +4670,7 @@ private IRubyObject permutationCommon(ThreadContext context, int r, boolean repe block.yield(context, newArray(context.runtime, eltOk(i))); } } else if (r >= 0) { - unpack(); + unpack(context); int n = realLength; if (repeat) { rpermute(context, n, r, @@ -4528,14 +4717,6 @@ private static IRubyObject descendingFactorial(ThreadContext context, long from, return cnt; } - @Deprecated - public IRubyObject choice(ThreadContext context) { - if (realLength == 0) { - return context.nil; - } - return eltOk((int) (context.runtime.getDefaultRand().genrandReal() * realLength)); - } - @JRubyMethod(name = "shuffle!") public IRubyObject shuffle_bang(ThreadContext context) { return shuffleBang(context, context.runtime.getRandomClass()); @@ -4561,9 +4742,7 @@ public IRubyObject shuffle_bang(ThreadContext context, IRubyObject opts) { } private IRubyObject shuffleBang(ThreadContext context, IRubyObject randgen) { - Ruby runtime = context.runtime; - - modify(); + modify(context); int i = realLength; int len = i; @@ -4571,14 +4750,14 @@ private IRubyObject shuffleBang(ThreadContext context, IRubyObject randgen) { while (i > 0) { int r = (int) RubyRandom.randomLongLimited(context, randgen, i - 1); if (len != realLength) { // || ptr != RARRAY_CONST_PTR(ary) - throw runtime.newRuntimeError("modified during shuffle"); + throw context.runtime.newRuntimeError("modified during shuffle"); } T tmp = eltOk(--i); eltSetOk(i, eltOk(r)); eltSetOk(r, tmp); } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(runtime, ex); + throw concurrentModification(context, ex); } return this; @@ -4723,12 +4902,12 @@ private IRubyObject sampleCommon(ThreadContext context, IRubyObject sample, IRub result[j] = result[i]; result[i] = tmp; } - RubyArray ary = newArrayNoCopy(runtime, result); + RubyArray ary = newArrayNoCopy(runtime, result); ary.realLength = n; return ary; } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + throw concurrentModification(context, ex); } } @@ -4741,7 +4920,7 @@ private static void aryReverse(IRubyObject[] _p1, int p1, IRubyObject[] _p2, int } protected IRubyObject internalRotateBang(ThreadContext context, int cnt) { - modify(); + modify(context); try { if(cnt != 0) { @@ -4757,7 +4936,7 @@ protected IRubyObject internalRotateBang(ThreadContext context, int cnt) { } } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + throw concurrentModification(context, ex); } return context.nil; @@ -4770,7 +4949,7 @@ private static int rotateCount(int cnt, int len) { protected IRubyObject internalRotate(ThreadContext context, int cnt) { int len = realLength; RubyArray rotated = aryDup(); - rotated.modify(); + rotated.modify(context); try { if(len > 0) { @@ -4782,7 +4961,7 @@ protected IRubyObject internalRotate(ThreadContext context, int cnt) { System.arraycopy(ptr, begin, ptr2, len, cnt); } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(context.runtime, ex); + throw concurrentModification(context, ex); } return rotated; @@ -5262,7 +5441,7 @@ public static void marshalTo(RubyArray array, MarshalStream output) throws IOExc output.dumpObject(array.eltInternal(i)); } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(array.getRuntime(), ex); + throw concurrentModification(array.getRuntime().getCurrentContext(), ex); } } @@ -5277,19 +5456,20 @@ public static void marshalTo(RubyArray array, NewMarshal output, ThreadContext c output.dumpObject(context, out, array.eltInternal(i)); } } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(array.getRuntime(), ex); + throw concurrentModification(array.getRuntime().getCurrentContext(), ex); } } public static RubyArray unmarshalFrom(UnmarshalStream input) throws IOException { int size = input.unmarshalInt(); + var context = input.getRuntime().getCurrentContext(); // 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(input.getRuntime(), size)); + RubyArray result = (RubyArray) input.entry(newArray(context.runtime, size)); for (int i = 0; i < size; i++) { - result.storeInternal(i, input.unmarshalObject()); + result.storeInternal(context, i, input.unmarshalObject()); } return result; @@ -5355,7 +5535,7 @@ public RubyString pack(ThreadContext context, IRubyObject obj) { RubyString buffer = context.runtime.newString(); return Pack.pack(context, this, format, buffer); } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(context.runtime, e); + throw concurrentModification(context, e); } } @@ -5555,22 +5735,43 @@ public Class getJavaClass() { return List.class; } + /** + * @param target + * @param start + * @deprecated Use {@link RubyArray#copyInto(ThreadContext, IRubyObject[], int)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public void copyInto(IRubyObject[] target, int start) { + copyInto(getCurrentContext(), target, start); + } + /** * Copy the values contained in this array into the target array at the specified offset. * It is expected that the target array is large enough to hold all necessary values. */ - public void copyInto(IRubyObject[] target, int start) { + public void copyInto(ThreadContext context, IRubyObject[] target, int start) { assert target.length - start >= realLength; - safeArrayCopy(values, begin, target, start, realLength); + safeArrayCopy(context, values, begin, target, start, realLength); + } + + /** + * @param target + * @param start + * @param len + * @deprecated Use {@link RubyArray#copyInto(ThreadContext, IRubyObject[], int, int)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) + public void copyInto(IRubyObject[] target, int start, int len) { + copyInto(getCurrentContext(), target, start, len); } /** * Copy the specified number of values contained in this array into the target array at the specified offset. * It is expected that the target array is large enough to hold all necessary values. */ - public void copyInto(IRubyObject[] target, int start, int len) { + public void copyInto(ThreadContext context, IRubyObject[] target, int start, int len) { assert target.length - start >= len; - safeArrayCopy(values, begin, target, start, len); + safeArrayCopy(context, values, begin, target, start, len); } // Satisfy java.util.List interface (for Java integration) @@ -5618,7 +5819,7 @@ public T toJava(Class target) { try { ArrayUtils.copyDataToJavaArrayDirect(this, rawJavaArray); } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(getRuntime(), ex); + throw concurrentModification(getRuntime().getCurrentContext(), ex); } return target.cast(rawJavaArray); } else { @@ -5632,9 +5833,9 @@ public boolean add(Object element) { } public boolean remove(Object element) { - unpack(); final Ruby runtime = metaClass.runtime; ThreadContext context = runtime.getCurrentContext(); + unpack(context); IRubyObject item = JavaUtil.convertJavaToUsableRubyObject(runtime, element); boolean listchanged = false; @@ -5712,7 +5913,7 @@ public Object set(int index, Object element) { } public void add(int index, Object element) { - insert(index, JavaUtil.convertJavaToUsableRubyObject(metaClass.runtime, element)); + insert(metaClass.runtime.getCurrentContext(), index, JavaUtil.convertJavaToUsableRubyObject(metaClass.runtime, element)); } public Object remove(int index) { @@ -5876,55 +6077,47 @@ public boolean equals(Object other) { return false; } - private static IRubyObject safeArrayRef(Ruby runtime, IRubyObject[] values, int i) { + private static IRubyObject safeArrayRef(ThreadContext context, IRubyObject[] values, int i) { try { return values[i]; } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(runtime, ex); + throw concurrentModification(context, ex); } } - private IRubyObject safeArraySet(IRubyObject[] values, int i, IRubyObject value) { - return safeArraySet(metaClass.runtime, values, i, value); - } - - protected static IRubyObject safeArraySet(Ruby runtime, IRubyObject[] values, int i, IRubyObject value) { + protected static IRubyObject safeArraySet(ThreadContext context, IRubyObject[] values, int i, IRubyObject value) { try { return values[i] = value; } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(runtime, ex); + throw concurrentModification(context, ex); } } - private static IRubyObject safeArrayRefSet(Ruby runtime, IRubyObject[] values, int i, IRubyObject value) { + private static IRubyObject safeArrayRefSet(ThreadContext context, IRubyObject[] values, int i, IRubyObject value) { try { IRubyObject tmp = values[i]; values[i] = value; return tmp; } catch (ArrayIndexOutOfBoundsException e) { - throw concurrentModification(runtime, e); + throw concurrentModification(context, e); } } - private static IRubyObject safeArrayRefCondSet(Ruby runtime, IRubyObject[] values, int i, boolean doSet, IRubyObject value) { + private static IRubyObject safeArrayRefCondSet(ThreadContext context, IRubyObject[] values, int i, boolean doSet, IRubyObject value) { try { IRubyObject tmp = values[i]; if (doSet) values[i] = value; return tmp; } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(runtime, ex); + throw concurrentModification(context, ex); } } - - private void safeArrayCopy(IRubyObject[] source, int sourceStart, IRubyObject[] target, int targetStart, int length) { - safeArrayCopy(metaClass.runtime, source, sourceStart, target, targetStart, length); - } - - private static void safeArrayCopy(Ruby runtime, IRubyObject[] source, int sourceStart, IRubyObject[] target, int targetStart, int length) { + + private static void safeArrayCopy(ThreadContext context, IRubyObject[] source, int sourceStart, IRubyObject[] target, int targetStart, int length) { try { System.arraycopy(source, sourceStart, target, targetStart, length); } catch (ArrayIndexOutOfBoundsException ex) { - throw concurrentModification(runtime, ex); + throw concurrentModification(context, ex); } } @@ -5938,7 +6131,7 @@ private static ArraySites sites(ThreadContext context) { */ @Deprecated public void ensureCapacity(int minCapacity) { - unpack(); + unpack(getCurrentContext()); if ( isShared || (values.length - begin) < minCapacity ) { final int len = this.realLength; int newCapacity = minCapacity > len ? minCapacity : len; diff --git a/core/src/main/java/org/jruby/RubyBasicObject.java b/core/src/main/java/org/jruby/RubyBasicObject.java index 03e5a0120fb..1edeaa50f79 100644 --- a/core/src/main/java/org/jruby/RubyBasicObject.java +++ b/core/src/main/java/org/jruby/RubyBasicObject.java @@ -68,6 +68,8 @@ 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.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.ir.runtime.IRRuntimeHelpers.dupIfKeywordRestAtCallsite; @@ -2828,9 +2830,8 @@ public IRubyObject remove_instance_variable(ThreadContext context, IRubyObject n * Fred.new.instance_variables #=> [:"{@literal @}iv"] */ public RubyArray instance_variables(ThreadContext context) { - Ruby runtime = context.runtime; - RubyArray array = RubyArray.newArray(runtime, getMetaClass().getVariableAccessorsForRead().size()); - forEachInstanceVariableName(name -> array.append(runtime.newSymbol(name))); + var array = newArray(context, getMetaClass().getVariableAccessorsForRead().size()); + forEachInstanceVariableName(name -> array.append(context, newSymbol(context, name))); return array; } diff --git a/core/src/main/java/org/jruby/RubyBignum.java b/core/src/main/java/org/jruby/RubyBignum.java index 8838a007d4d..b3bc481351c 100644 --- a/core/src/main/java/org/jruby/RubyBignum.java +++ b/core/src/main/java/org/jruby/RubyBignum.java @@ -53,6 +53,7 @@ import static org.jruby.RubyFixnum.zero; import static org.jruby.api.Convert.*; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; @@ -352,11 +353,11 @@ public RubyArray digits(ThreadContext context, IRubyObject base) { if (self.signum() == 0) { return RubyArray.newArray(context.runtime, zero(context.runtime)); } else { - RubyArray res = RubyArray.newArray(context.runtime, 0); + RubyArray res = newArray(context, 0); while (self.signum() > 0) { BigInteger q = self.mod(bigBase); - res.append(RubyBignum.newBignum(context.runtime, q)); + res.append(context, RubyBignum.newBignum(context.runtime, q)); self = self.divide(bigBase); } diff --git a/core/src/main/java/org/jruby/RubyBinding.java b/core/src/main/java/org/jruby/RubyBinding.java index 68b4a726348..9280fa0e23c 100644 --- a/core/src/main/java/org/jruby/RubyBinding.java +++ b/core/src/main/java/org/jruby/RubyBinding.java @@ -189,9 +189,7 @@ private String checkLocalId(ThreadContext context, IRubyObject obj) { } @JRubyMethod public IRubyObject local_variables(ThreadContext context) { - Ruby runtime = context.runtime; - - return binding.getEvalScope(runtime).getStaticScope().getLocalVariables(runtime); + return binding.getEvalScope(context.runtime).getStaticScope().getLocalVariables(context); } @JRubyMethod(name = "receiver") diff --git a/core/src/main/java/org/jruby/RubyClass.java b/core/src/main/java/org/jruby/RubyClass.java index 8366d99a573..4963b1831bc 100644 --- a/core/src/main/java/org/jruby/RubyClass.java +++ b/core/src/main/java/org/jruby/RubyClass.java @@ -37,8 +37,6 @@ import static org.jruby.util.CodegenUtils.ci; import static org.jruby.util.CodegenUtils.p; import static org.jruby.util.CodegenUtils.sig; -import static org.jruby.util.RubyStringBuilder.str; -import static org.jruby.util.RubyStringBuilder.types; import static org.objectweb.asm.Opcodes.ACC_BRIDGE; import static org.objectweb.asm.Opcodes.ACC_FINAL; import static org.objectweb.asm.Opcodes.ACC_PRIVATE; @@ -1015,7 +1013,7 @@ protected void setModuleSuperClass(RubyClass superClass) { @JRubyMethod public IRubyObject subclasses(ThreadContext context) { - RubyArray subs = RubyArray.newArray(context.runtime); + var subs = RubyArray.newArray(context.runtime); concreteSubclasses(subs); @@ -1241,7 +1239,7 @@ public static void checkInheritable(IRubyObject superClass) { checkInheritable(superClass.getRuntime().getCurrentContext(), superClass); } - private static void checkInheritable(ThreadContext context, IRubyObject superClass) { + public static void checkInheritable(ThreadContext context, IRubyObject superClass) { if (!(superClass instanceof RubyClass)) { throw typeError(context, "superclass must be a Class (" + superClass.getMetaClass() + " given)"); } @@ -2785,6 +2783,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, int methodInd * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, CallType callType, Block block) { CacheEntry entry = searchWithCache(name); @@ -2805,6 +2804,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-") public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject[] args, CallType callType, Block block) { assert args != null; @@ -2826,6 +2826,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-") public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg, CallType callType, Block block) { CacheEntry entry = searchWithCache(name); @@ -2846,6 +2847,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, CallType callType, Block block) { CacheEntry entry = searchWithCache(name); @@ -2866,6 +2868,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, CallType callType, Block block) { CacheEntry entry = searchWithCache(name); @@ -2886,6 +2889,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, CallType callType) { CacheEntry entry = searchWithCache(name); @@ -2906,6 +2910,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject[] args, CallType callType) { assert args != null; @@ -2927,6 +2932,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg, CallType callType) { CacheEntry entry = searchWithCache(name); @@ -2947,6 +2953,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, CallType callType) { CacheEntry entry = searchWithCache(name); @@ -2967,6 +2974,7 @@ public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, CallType callType) { CacheEntry entry = searchWithCache(name); diff --git a/core/src/main/java/org/jruby/RubyClassPathVariable.java b/core/src/main/java/org/jruby/RubyClassPathVariable.java index 043139e000e..876bf9c58d9 100644 --- a/core/src/main/java/org/jruby/RubyClassPathVariable.java +++ b/core/src/main/java/org/jruby/RubyClassPathVariable.java @@ -66,7 +66,7 @@ public IRubyObject append(IRubyObject obj) { public IRubyObject append(ThreadContext context, IRubyObject obj) { IRubyObject[] paths; if (obj.respondsTo("to_a")) { - paths = ((RubyArray) obj.callMethod(context, "to_a")).toJavaArrayMaybeUnsafe(); + paths = ((RubyArray) obj.callMethod(context, "to_a")).toJavaArrayMaybeUnsafe(); } else { paths = new IRubyObject[] { obj }; } @@ -107,15 +107,15 @@ public IRubyObject size(ThreadContext context) { return asFixnum(context, context.runtime.getJRubyClassLoader().getURLs().length); } public IRubyObject size() { - return size(getCurrentContext()); + return size(getRuntime().getCurrentContext()); } @JRubyMethod public IRubyObject each(Block block) { final ThreadContext context = getRuntime().getCurrentContext(); URL[] urls = context.runtime.getJRubyClassLoader().getURLs(); - for(int i=0,j=urls.length;i f.equals(".") || f.equals("..")); final int len = file.length(); @@ -402,7 +403,7 @@ private static RubyArray newEntryArray(Ruby runtime, String[] files, Encoding en if (len == 2 && file.charAt(0) == '.' && file.charAt(1) == '.') continue; } - result.append(newExternalStringWithEncoding(runtime, file, encoding)); + result.append(context, newExternalStringWithEncoding(context.runtime, file, encoding)); } return result; } @@ -928,7 +929,7 @@ public static IRubyObject empty_p(ThreadContext context, IRubyObject recv, IRuby Ruby runtime = context.runtime; RubyString path = StringSupport.checkEmbeddedNulls(runtime, RubyFile.get_path(context, arg)); RubyFileStat fileStat = runtime.newFileStat(path.asJavaString(), false); - boolean isDirectory = fileStat.directory_p().isTrue(); + boolean isDirectory = fileStat.directory_p(context).isTrue(); return asBoolean(context, isDirectory && entries(context, recv, arg).getLength() <= 2); } @@ -940,7 +941,7 @@ public static IRubyObject exist(ThreadContext context, IRubyObject recv, IRubyOb RubyString path = StringSupport.checkEmbeddedNulls(runtime, RubyFile.get_path(context, arg)); try { - return runtime.newFileStat(path.asJavaString(), false).directory_p(); + return runtime.newFileStat(path.asJavaString(), false).directory_p(context); } catch (Exception e) { // Restore $! runtime.getGlobalVariables().set("$!", exception); @@ -1046,6 +1047,7 @@ private static String[] list(FileResource directory) { /** * @deprecated no longer used */ + @Deprecated(since = "9.4-") protected static List getContents(FileResource directory) { final String[] contents = directory.list(); @@ -1064,6 +1066,7 @@ protected static List getContents(FileResource directory) { /** * @deprecated no longer used */ + @Deprecated(since = "9.4-") protected static List getContents(FileResource directory, Ruby runtime) { final String[] contents = directory.list(); diff --git a/core/src/main/java/org/jruby/RubyEncoding.java b/core/src/main/java/org/jruby/RubyEncoding.java index 3e234dde7bb..8d98301971e 100755 --- a/core/src/main/java/org/jruby/RubyEncoding.java +++ b/core/src/main/java/org/jruby/RubyEncoding.java @@ -59,6 +59,8 @@ import static com.headius.backport9.buffer.Buffers.clearBuffer; import static com.headius.backport9.buffer.Buffers.flipBuffer; import static org.jruby.api.Convert.asBoolean; +import static org.jruby.api.Create.newArray; +import static org.jruby.api.Create.newString; @JRubyClass(name="Encoding") public class RubyEncoding extends RubyObject implements Constantizable { @@ -492,28 +494,27 @@ public static IRubyObject locale_charmap(ThreadContext context, IRubyObject recv @SuppressWarnings("unchecked") @JRubyMethod(name = "name_list", meta = true) public static IRubyObject name_list(ThreadContext context, IRubyObject recv) { - Ruby runtime = context.runtime; - EncodingService service = runtime.getEncodingService(); + EncodingService service = context.runtime.getEncodingService(); - RubyArray result = runtime.newArray(service.getEncodings().size() + service.getAliases().size()); + var result = newArray(context, service.getEncodings().size() + service.getAliases().size()); HashEntryIterator i; i = service.getEncodings().entryIterator(); while (i.hasNext()) { CaseInsensitiveBytesHash.CaseInsensitiveBytesHashEntry e = ((CaseInsensitiveBytesHash.CaseInsensitiveBytesHashEntry)i.next()); - result.append(RubyString.newUsAsciiStringShared(runtime, e.bytes, e.p, e.end - e.p).freeze(context)); + result.append(context, RubyString.newUsAsciiStringShared(context.runtime, e.bytes, e.p, e.end - e.p).freeze(context)); } i = service.getAliases().entryIterator(); while (i.hasNext()) { CaseInsensitiveBytesHash.CaseInsensitiveBytesHashEntry e = ((CaseInsensitiveBytesHash.CaseInsensitiveBytesHashEntry)i.next()); - result.append(RubyString.newUsAsciiStringShared(runtime, e.bytes, e.p, e.end - e.p).freeze(context)); + result.append(context, RubyString.newUsAsciiStringShared(context.runtime, e.bytes, e.p, e.end - e.p).freeze(context)); } - result.append(runtime.newString(EXTERNAL)); - result.append(runtime.newString(FILESYSTEM)); - result.append(runtime.newString(INTERNAL)); - result.append(runtime.newString(LOCALE)); + result.append(context, newString(context, EXTERNAL)); + result.append(context, newString(context, FILESYSTEM)); + result.append(context, newString(context, INTERNAL)); + result.append(context, newString(context, LOCALE)); return result; } @@ -589,18 +590,16 @@ public IRubyObject inspect(ThreadContext context) { @SuppressWarnings("unchecked") @JRubyMethod(name = "names") public IRubyObject names(ThreadContext context) { - Ruby runtime = context.runtime; - EncodingService service = runtime.getEncodingService(); + EncodingService service = context.runtime.getEncodingService(); Entry entry = service.findEncodingOrAliasEntry(name); - - RubyArray result = runtime.newArray(); + var result = context.runtime.newArray(); HashEntryIterator i; i = service.getEncodings().entryIterator(); while (i.hasNext()) { CaseInsensitiveBytesHash.CaseInsensitiveBytesHashEntry e = ((CaseInsensitiveBytesHash.CaseInsensitiveBytesHashEntry)i.next()); if (e.value == entry) { - result.append(RubyString.newUsAsciiStringShared(runtime, e.bytes, e.p, e.end - e.p).freeze(context)); + result.append(context, RubyString.newUsAsciiStringShared(context.runtime, e.bytes, e.p, e.end - e.p).freeze(context)); } } i = service.getAliases().entryIterator(); @@ -608,11 +607,11 @@ public IRubyObject names(ThreadContext context) { CaseInsensitiveBytesHash.CaseInsensitiveBytesHashEntry e = ((CaseInsensitiveBytesHash.CaseInsensitiveBytesHashEntry)i.next()); if (e.value == entry) { - result.append(RubyString.newUsAsciiStringShared(runtime, e.bytes, e.p, e.end - e.p).freeze(context)); + result.append(context, RubyString.newUsAsciiStringShared(context.runtime, e.bytes, e.p, e.end - e.p).freeze(context)); } } - result.append(runtime.newString(EXTERNAL)); - result.append(runtime.newString(LOCALE)); + result.append(context, newString(context, EXTERNAL)); + result.append(context, newString(context, LOCALE)); return result; } diff --git a/core/src/main/java/org/jruby/RubyEnumerable.java b/core/src/main/java/org/jruby/RubyEnumerable.java index c4d9f8f0da9..aeef05da6f1 100644 --- a/core/src/main/java/org/jruby/RubyEnumerable.java +++ b/core/src/main/java/org/jruby/RubyEnumerable.java @@ -69,6 +69,7 @@ import static org.jruby.RubyObject.equalInternal; import static org.jruby.api.Convert.asFixnum; import static org.jruby.api.Convert.numericToLong; +import static org.jruby.api.Create.newArray; import static org.jruby.api.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.Helpers.arrayOf; @@ -285,7 +286,7 @@ public IRubyObject yield(ThreadContext context1, IRubyObject[] args) { @Override public IRubyObject yield(ThreadContext context1, IRubyObject value) { synchronized (result) { - result.append(value); + result.append(context, value); if (--i == 0) throw JumpException.SPECIAL_JUMP; } return context1.nil; @@ -315,7 +316,7 @@ public static IRubyObject take_while(ThreadContext context, IRubyObject self, fi } IRubyObject val = ary ? block.yieldArray(ctx, larg, null) : block.yield(ctx, larg); if ( ! val.isTrue() ) throw JumpException.SPECIAL_JUMP; - synchronized (result) { result.append(larg); } + synchronized (result) { result.append(context, larg); } return ctx.nil; }); } catch (JumpException.SpecialJump sj) {} @@ -343,7 +344,7 @@ public IRubyObject yield(ThreadContext context1, IRubyObject[] args) { public IRubyObject yield(ThreadContext context1, IRubyObject value) { synchronized (result) { if (i == 0) { - result.append(value); + result.append(context, value); } else { --i; } @@ -375,7 +376,7 @@ public IRubyObject yield(ThreadContext context1, IRubyObject[] args) { @Override public IRubyObject yield(ThreadContext context1, IRubyObject value) { if (!memo && !block.yield(context1, value).isTrue()) memo = true; - if (memo) synchronized (result) { result.append(value); } + if (memo) synchronized (result) { result.append(context, value); } return context1.nil; } }); @@ -407,15 +408,14 @@ public IRubyObject yield(ThreadContext context1, IRubyObject value) { @JRubyMethod(name = "first") public static IRubyObject first(ThreadContext context, IRubyObject self, final IRubyObject num) { - final Ruby runtime = context.runtime; final long firstCount = numericToLong(context, num); - if (firstCount == 0) return runtime.newEmptyArray(); + if (firstCount == 0) return context.runtime.newEmptyArray(); if (firstCount < 0) throw argumentError(context, "attempt to take negative size"); - final RubyArray result = RubyArray.newArray(runtime, firstCount); + final RubyArray result = newArray(context, firstCount); try { - each(context, eachSite(context), self, new JavaInternalBlockBody(runtime, context, "Enumerable#first", Signature.OPTIONAL) { + each(context, eachSite(context), self, new JavaInternalBlockBody(context.runtime, context, "Enumerable#first", Signature.OPTIONAL) { private long iter = firstCount; @Override public IRubyObject yield(ThreadContext context1, IRubyObject[] args) { @@ -423,7 +423,7 @@ public IRubyObject yield(ThreadContext context1, IRubyObject[] args) { } @Override public IRubyObject yield(ThreadContext context1, IRubyObject value) { - result.append(value); + result.append(context, value); if (iter-- == 1) throw JumpException.SPECIAL_JUMP; return context1.nil; } @@ -558,7 +558,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] args, Block unused) { public IRubyObject call(ThreadContext ctx, IRubyObject arg, Block unused) { if (site.call(ctx, pattern, pattern, arg).isTrue() == isPresent) { // pattern === arg IRubyObject value = block.yield(ctx, arg); - synchronized (result) { result.append(value); } + synchronized (result) { result.append(context, value); } } return ctx.nil; } @@ -573,7 +573,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject arg, Block unused) { IRubyObject converted = arg instanceof RubySymbol ? arg : TypeConverter.checkStringType(ctx.runtime, arg); if (((RubyRegexp) pattern).match_p(ctx, converted).isTrue() == isPresent) { - synchronized (result) { result.append(arg); } + synchronized (result) { result.append(context, arg); } } return ctx.nil; } @@ -588,7 +588,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] args, Block unused) { @Override public IRubyObject call(ThreadContext ctx, IRubyObject arg, Block unused) { if (site.call(ctx, pattern, pattern, arg).isTrue() == isPresent) { // pattern === arg - synchronized (result) { result.append(arg); } + synchronized (result) { result.append(ctx, arg); } } return ctx.nil; } @@ -756,7 +756,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { @Override public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { if (block.yield(ctx, larg).isTrue()) { - synchronized (result) { result.append(larg); } + synchronized (result) { result.append(ctx, larg); } } return ctx.nil; } @@ -790,14 +790,14 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { @Override public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { if ( ! block.yield(ctx, larg).isTrue() ) { - synchronized (result) { result.append(larg); } + synchronized (result) { result.append(ctx, larg); } } return ctx.nil; } @Override public IRubyObject call(ThreadContext ctx, IRubyObject larg) { if ( ! block.yield(ctx, larg).isTrue() ) { - synchronized (result) { result.append(larg); } + synchronized (result) { result.append(ctx, larg); } } return ctx.nil; } @@ -831,14 +831,14 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { } IRubyObject val = ary ? block.yieldArray(ctx, larg, null) : block.yield(ctx, larg); - synchronized (result) { result.append(val); } + 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(val); } + synchronized (result) { result.append(ctx, val); } return ctx.nil; } }, context)); @@ -866,7 +866,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { IRubyObject val = ary ? block.yieldArray(ctx, larg, null) : block.yield(ctx, larg); if (val.isTrue()) { - synchronized (result) { result.append(val); } + synchronized (result) { result.append(ctx, val); } } return ctx.nil; } @@ -875,7 +875,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { IRubyObject val = block.yield(ctx, larg); if (val.isTrue()) { - synchronized (result) { result.append(val); } + synchronized (result) { result.append(ctx, val); } } return ctx.nil; } @@ -911,7 +911,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { IRubyObject tmp = i.checkArrayType(); synchronized(ary) { if (tmp.isNil()) { - ary.append(i); + ary.append(ctx, i); } else { ary.concat(ctx, tmp); } @@ -1124,11 +1124,11 @@ public static IRubyObject partition(ThreadContext context, IRubyObject self, fin IRubyObject larg = packEnumValues(ctx, largs); if (block.yield(ctx, larg).isTrue()) { synchronized (arr_true) { - arr_true.append(larg); + arr_true.append(ctx, larg); } } else { synchronized (arr_false) { - arr_false.append(larg); + arr_false.append(ctx, larg); } } @@ -1264,7 +1264,7 @@ static IRubyObject each_sliceCommon(ThreadContext context, IRubyObject self, fin final SingleObject result = new SingleObject<>(runtime.newArray(size)); callEach(context, eachSite(context), self, Signature.OPTIONAL, (ctx, largs, blk) -> { - result.object.append(packEnumValues(ctx, largs)); + result.object.append(context, packEnumValues(ctx, largs)); if (result.object.size() == size) { block.yield(ctx, result.object); result.object = runtime.newArray(size); @@ -1310,7 +1310,7 @@ static IRubyObject each_consCommon(ThreadContext context, IRubyObject self, fina callEach(context, eachSite(context), self, Signature.OPTIONAL, (ctx, largs, blk) -> { if (result.size() == size) result.shift(ctx); - result.append(packEnumValues(ctx, largs)); + result.append(context, packEnumValues(ctx, largs)); if (result.size() == size) block.yield(ctx, result.aryDup()); return ctx.nil; }); @@ -1993,7 +1993,7 @@ public static IRubyObject zipCommon(ThreadContext context, IRubyObject self, array.eltInternalSet(i + 1, nextElement.apply(context, args[i], myIx)); } array.realLength = len; - synchronized (zip) { zip.append(array); } + synchronized (zip) { zip.append(context, array); } return ctx.nil; }); return zip; @@ -2020,7 +2020,7 @@ public static IRubyObject zipCommon(ThreadContext context, IRubyObject self, 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)); - synchronized (zip) { zip.append(array); } + synchronized (zip) { zip.append(ctx, array); } return ctx.nil; }); return zip; @@ -2045,12 +2045,12 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { } @Override public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { - array.append(larg); + array.append(ctx, larg); return larg; } @Override public IRubyObject call(ThreadContext ctx, IRubyObject larg) { - array.append(larg); + array.append(ctx, larg); return larg; } }); @@ -2093,7 +2093,7 @@ public static IRubyObject group_by(ThreadContext context, IRubyObject self, fina curr = runtime.newArray(); result.fastASet(key, curr); } - curr.append(larg); + curr.append(context, larg); } return ctx.nil; }); @@ -2177,7 +2177,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) { } @Override public IRubyObject call(ThreadContext ctx, IRubyObject obj, Block blk) { - if (!obj.isNil()) array.append(obj); + if (!obj.isNil()) array.append(ctx, obj); return obj; } }); @@ -2265,7 +2265,7 @@ else if ( (v instanceof RubySymbol) && v.toString().charAt(0) == '_' ) { } else { if ( arg.prev_value.equals(v) ) { - ((RubyArray) arg.prev_elts).append(larg); + ((RubyArray) arg.prev_elts).append(context, larg); } else { chunk_op_lshift.call(ctx, yielder, yielder, runtime.newArray(arg.prev_value, arg.prev_elts)); @@ -2300,14 +2300,14 @@ public AppendBlockCallback(Ruby runtime, RubyArray result) { public IRubyObject call(ThreadContext context, IRubyObject[] args, Block block) { ThreadContext.resetCallInfo(context); - result.append(packEnumValues(context, args)); + result.append(context, packEnumValues(context, args)); return context.nil; } @Override public IRubyObject call(ThreadContext context, IRubyObject arg, Block block) { ThreadContext.resetCallInfo(context); - result.append(arg); + result.append(context, arg); return context.nil; } diff --git a/core/src/main/java/org/jruby/RubyFile.java b/core/src/main/java/org/jruby/RubyFile.java index 65e249c35cf..14bca32694e 100644 --- a/core/src/main/java/org/jruby/RubyFile.java +++ b/core/src/main/java/org/jruby/RubyFile.java @@ -414,7 +414,7 @@ public IRubyObject atime(ThreadContext context) { @JRubyMethod(name = "ctime") public IRubyObject ctime(ThreadContext context) { checkClosed(context); - return context.runtime.newFileStat(getPath(), false).ctime(); + return context.runtime.newFileStat(getPath(), false).ctime(context); } @JRubyMethod(name = "birthtime") @@ -1037,9 +1037,8 @@ private static boolean dir_fnmatch(ByteList pattern, ByteList path, int flags) { @JRubyMethod(name = "ftype", meta = true) public static IRubyObject ftype(ThreadContext context, IRubyObject recv, IRubyObject filename) { - Ruby runtime = context.runtime; - RubyString path = StringSupport.checkEmbeddedNulls(runtime, get_path(context, filename)); - return runtime.newFileStat(path.toString(), true).ftype(); + RubyString path = StringSupport.checkEmbeddedNulls(context.runtime, get_path(context, filename)); + return context.runtime.newFileStat(path.toString(), true).ftype(context); } @JRubyMethod(rest = true, meta = true) @@ -1065,7 +1064,7 @@ public static IRubyObject stat(ThreadContext context, IRubyObject recv, IRubyObj public static IRubyObject atime(ThreadContext context, IRubyObject recv, IRubyObject filename) { Ruby runtime = context.runtime; String f = StringSupport.checkEmbeddedNulls(runtime, get_path(context, filename)).toString(); - return runtime.newFileStat(f, false).atime(); + return runtime.newFileStat(f, false).atime(context); } @JRubyMethod(name = "ctime", meta = true) @@ -1077,9 +1076,8 @@ public static IRubyObject ctime(ThreadContext context, IRubyObject recv, IRubyOb @JRubyMethod(name = "birthtime", meta = true) public static IRubyObject birthtime(ThreadContext context, IRubyObject recv, IRubyObject filename) { - Ruby runtime = context.runtime; - String f = StringSupport.checkEmbeddedNulls(runtime, get_path(context, filename)).toString(); - return runtime.newFileStat(f, false).birthtime(); + String f = StringSupport.checkEmbeddedNulls(context.runtime, get_path(context, filename)).toString(); + return context.runtime.newFileStat(f, false).birthtime(context); } @JRubyMethod(required = 1, rest = true, checkArity = false, meta = true) @@ -1158,7 +1156,7 @@ public static IRubyObject rename(ThreadContext context, IRubyObject recv, IRubyO JRubyFile oldFile = JRubyFile.create(runtime.getCurrentDirectory(), oldNameJavaString); JRubyFile newFile = JRubyFile.create(runtime.getCurrentDirectory(), newNameJavaString); - boolean isOldSymlink = RubyFileTest.symlink_p(recv, oldNameString).isTrue(); + boolean isOldSymlink = RubyFileTest.symlink_p(context, recv, oldNameString).isTrue(); // Broken symlinks considered by exists() as non-existing, // so we need to check for symlinks explicitly. if (!(oldFile.exists() || isOldSymlink) || !newFile.getParentFile().exists()) { @@ -1597,7 +1595,7 @@ public static FileResource fileResource(ThreadContext context, IRubyObject pathO * * @param pathOrFile the string or IO to use for the path */ - @Deprecated + @Deprecated(since = "9.4-", forRemoval = true) public static FileResource fileResource(IRubyObject pathOrFile) { return fileResource(((RubyBasicObject)pathOrFile).getCurrentContext(), pathOrFile); } @@ -1772,8 +1770,8 @@ private static long[] extractTimespec(ThreadContext context, IRubyObject value) } else { time = (RubyTime) TypeConverter.convertToType(context, value, context.runtime.getTime(), sites(context).to_time_checked, true); } - timespec[0] = Platform.IS_32_BIT ? RubyNumeric.num2int(time.to_i()) : numericToLong(context, time.to_i()); - timespec[1] = Platform.IS_32_BIT ? RubyNumeric.num2int(time.nsec()) : numericToLong(context, time.nsec()); + timespec[0] = Platform.IS_32_BIT ? asInt(context, time.to_i(context)) : numericToLong(context, time.to_i(context)); + timespec[1] = Platform.IS_32_BIT ? asInt(context, time.nsec(context)) : numericToLong(context, time.nsec(context)); } return timespec; @@ -1990,7 +1988,7 @@ public static String expandPath(ThreadContext context, String relativePath, Enco cwd = adjustRootPathOnWindows(runtime, cwd, null); boolean startsWithSlashNotOnWindows = (cwd != null) - && !Platform.IS_WINDOWS && cwd.length() > 0 + && !Platform.IS_WINDOWS && !cwd.isEmpty() && cwd.charAt(0) == '/'; // TODO: better detection when path is absolute or not. @@ -2035,7 +2033,7 @@ public static String expandPath(ThreadContext context, String relativePath, Enco if (uriParts != null) { padSlashes = uriParts[0]; } else if (!Platform.IS_WINDOWS) { - if (relativePath.length() > 0 && relativePath.charAt(0) == '/') { + if (!relativePath.isEmpty() && relativePath.charAt(0) == '/') { padSlashes = countSlashes(relativePath); } else { padSlashes = countSlashes(cwd); @@ -2043,7 +2041,7 @@ public static String expandPath(ThreadContext context, String relativePath, Enco } JRubyFile pathFile; - if (relativePath.length() == 0) { + if (relativePath.isEmpty()) { pathFile = JRubyFile.create(relativePath, cwd); } else { relativePath = adjustRootPathOnWindows(runtime, relativePath, cwd); @@ -2459,24 +2457,13 @@ private static IRubyObject truncateCommon(ThreadContext context, IRubyObject rec RubyString filename = arg1.convertToString(); // TODO: SafeStringValue here Ruby runtime = context.runtime; RubyInteger newLength = arg2.convertToInteger(); - - File testFile ; File childFile = new File(filename.toString()); String filenameString = Helpers.decodeByteList(runtime, filename.getByteList()); - if ( childFile.isAbsolute() ) { - testFile = childFile ; - } else { - testFile = new File(runtime.getCurrentDirectory(), filenameString); - } + File testFile = childFile.isAbsolute() ? childFile : new File(runtime.getCurrentDirectory(), filenameString); - if (!testFile.exists()) { - throw runtime.newErrnoENOENTError(filenameString); - } - - if (newLength.getLongValue() < 0) { - throw runtime.newErrnoEINVALError(filenameString); - } + if (!testFile.exists()) throw runtime.newErrnoENOENTError(filenameString); + if (newLength.getLongValue() < 0) throw runtime.newErrnoEINVALError(filenameString); IRubyObject[] args = new IRubyObject[] { filename, newString(context, "r+") }; RubyFile file = (RubyFile) open(context, recv, args, Block.NULL_BLOCK); @@ -2512,38 +2499,29 @@ private static FileSites sites(ThreadContext context) { @Deprecated public static IRubyObject dirname(ThreadContext context, IRubyObject recv, IRubyObject [] args) { - switch (args.length) { - case 1: - return dirname(context, recv, args[0]); - case 2: - return dirname(context, recv, args[0], args[1]); - default: - throw argumentError(context, args.length, 1, 2); - } + return switch (args.length) { + case 1 -> dirname(context, recv, args[0]); + case 2 -> dirname(context, recv, args[0], args[1]); + default -> throw argumentError(context, args.length, 1, 2); + }; } @Deprecated public static IRubyObject expand_path(ThreadContext context, IRubyObject recv, IRubyObject... args) { - switch (args.length) { - case 1: - return expand_path(context, recv, args[0]); - case 2: - return expand_path(context, recv, args[0], args[1]); - default: - throw argumentError(context, args.length, 1, 2); - } + return switch (args.length) { + case 1 -> expand_path(context, recv, args[0]); + case 2 -> expand_path(context, recv, args[0], args[1]); + default -> throw argumentError(context, args.length, 1, 2); + }; } @Deprecated private static RubyString expandPathInternal(ThreadContext context, IRubyObject[] args, boolean expandUser, boolean canonicalize) { - switch (args.length) { - case 1: - return expandPathInternal(context, args[0], null, expandUser, canonicalize); - case 2: - return expandPathInternal(context, args[0], args[1], expandUser, canonicalize); - default: - throw argumentError(context, args.length, 1, 2); - } + return switch (args.length) { + case 1 -> expandPathInternal(context, args[0], null, expandUser, canonicalize); + case 2 -> expandPathInternal(context, args[0], args[1], expandUser, canonicalize); + default -> throw argumentError(context, args.length, 1, 2); + }; } @Deprecated @@ -2581,13 +2559,10 @@ public static IRubyObject realpath(ThreadContext context, IRubyObject recv, IRub @Deprecated public static IRubyObject fnmatch(ThreadContext context, IRubyObject recv, IRubyObject[] args) { - switch (args.length) { - case 2: - return fnmatch(context, recv, args[0], args[1]); - case 3: - return fnmatch(context, recv, args[0], args[1], args[2]); - default: - throw argumentError(context, args.length, 2, 3); - } + return switch (args.length) { + case 2 -> fnmatch(context, recv, args[0], args[1]); + case 3 -> fnmatch(context, recv, args[0], args[1], args[2]); + default -> throw argumentError(context, args.length, 2, 3); + }; } } diff --git a/core/src/main/java/org/jruby/RubyFileTest.java b/core/src/main/java/org/jruby/RubyFileTest.java index 550921f753f..d53a6c56680 100644 --- a/core/src/main/java/org/jruby/RubyFileTest.java +++ b/core/src/main/java/org/jruby/RubyFileTest.java @@ -70,9 +70,9 @@ public static IRubyObject blockdev_p(ThreadContext context, IRubyObject recv, IR return asBoolean(context, stat != null && stat.isBlockDev()); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject blockdev_p(IRubyObject recv, IRubyObject filename) { - return blockdev_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return blockdev_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "chardev?", module = true) @@ -82,17 +82,17 @@ public static IRubyObject chardev_p(ThreadContext context, IRubyObject recv, IRu return asBoolean(context, stat != null && stat.isCharDev()); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject chardev_p(IRubyObject recv, IRubyObject filename) { - return chardev_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return chardev_p(recv.getRuntime().getCurrentContext(), recv, filename); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject directory_p(IRubyObject recv, IRubyObject filename) { - return directory_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return directory_p(recv.getRuntime().getCurrentContext(), recv, filename); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject directory_p(Ruby ruby, IRubyObject filename) { return directory_p(ruby.getCurrentContext(), filename); } @@ -115,9 +115,9 @@ public static IRubyObject executable_p(ThreadContext context, IRubyObject recv, return asBoolean(context, fileResource(context, filename).canExecute()); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject executable_p(IRubyObject recv, IRubyObject filename) { - return executable_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return executable_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "executable_real?", module = true) @@ -130,14 +130,14 @@ public static IRubyObject executable_real_p(ThreadContext context, IRubyObject r } } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject executable_real_p(IRubyObject recv, IRubyObject filename) { - return executable_real_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return executable_real_p(recv.getRuntime().getCurrentContext(), recv, filename); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject exist_p(IRubyObject recv, IRubyObject filename) { - return exist_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return exist_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "exist?", module = true) @@ -154,9 +154,9 @@ static boolean exist(ThreadContext context, RubyString path) { return existsOnClasspath(context, pathStr); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static RubyBoolean file_p(IRubyObject recv, IRubyObject filename) { - return file_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return file_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "file?", module = true) @@ -174,8 +174,9 @@ public static IRubyObject grpowned_p(ThreadContext context, IRubyObject recv, IR return asBoolean(context, stat != null && stat.isGroupOwned()); } + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject grpowned_p(IRubyObject recv, IRubyObject filename) { - return grpowned_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return grpowned_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "identical?", module = true) @@ -224,14 +225,14 @@ public static IRubyObject pipe_p(ThreadContext context, IRubyObject recv, IRubyO return asBoolean(context, stat != null && stat.isNamedPipe()); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject pipe_p(IRubyObject recv, IRubyObject filename) { - return pipe_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return pipe_p(recv.getRuntime().getCurrentContext(), recv, filename); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject readable_p(IRubyObject recv, IRubyObject filename) { - return readable_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return readable_p(recv.getRuntime().getCurrentContext(), recv, filename); } // We use file test since it is faster than a stat; also euid == uid in Java always @@ -252,9 +253,9 @@ public static IRubyObject rowned_p(ThreadContext context, IRubyObject recv, IRub return asBoolean(context, stat != null && stat.isROwned()); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject rowned_p(IRubyObject recv, IRubyObject filename) { - return rowned_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return rowned_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "setgid?", module = true) @@ -264,9 +265,9 @@ public static IRubyObject setgid_p(ThreadContext context, IRubyObject recv, IRub return asBoolean(context, stat != null && stat.isSetgid()); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject setgid_p(IRubyObject recv, IRubyObject filename) { - return setgid_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return setgid_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "setuid?", module = true) @@ -276,14 +277,14 @@ public static IRubyObject setuid_p(ThreadContext context, IRubyObject recv, IRub return asBoolean(context, stat != null && stat.isSetuid()); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject setuid_p(IRubyObject recv, IRubyObject filename) { - return setuid_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return setuid_p(recv.getRuntime().getCurrentContext(), recv, filename); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject size(IRubyObject recv, IRubyObject filename) { - return size(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return size(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "size", module = true) @@ -509,19 +510,20 @@ public static IRubyObject readable_p(ThreadContext context, IRubyObject recv, IR public static IRubyObject setgid_p(ThreadContext context, IRubyObject recv, IRubyObject filename) { return RubyFileTest.setgid_p(context, recv, filename); } - + + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject setgid_p(IRubyObject recv, IRubyObject filename) { - return setgid_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return setgid_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "setuid?") public static IRubyObject setuid_p(ThreadContext context, IRubyObject recv, IRubyObject filename) { return RubyFileTest.setuid_p(context, recv, filename); } - - @Deprecated + + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject setuid_p(IRubyObject recv, IRubyObject filename) { - return setuid_p(((RubyBasicObject) recv).getCurrentContext(), recv, filename); + return setuid_p(recv.getRuntime().getCurrentContext(), recv, filename); } @JRubyMethod(name = "size") diff --git a/core/src/main/java/org/jruby/RubyFixnum.java b/core/src/main/java/org/jruby/RubyFixnum.java index bfa0f1771da..7c3a0962690 100644 --- a/core/src/main/java/org/jruby/RubyFixnum.java +++ b/core/src/main/java/org/jruby/RubyFixnum.java @@ -388,7 +388,7 @@ public RubyArray digits(ThreadContext context, IRubyObject base) { RubyArray res = RubyArray.newArray(context.runtime, 0); while (value > 0) { - res.append(newFixnum(context.runtime, value % longBase)); + res.append(context, newFixnum(context.runtime, value % longBase)); value /= longBase; } diff --git a/core/src/main/java/org/jruby/RubyGlobal.java b/core/src/main/java/org/jruby/RubyGlobal.java index 9fff0fdf5b2..e4bbe3454b1 100644 --- a/core/src/main/java/org/jruby/RubyGlobal.java +++ b/core/src/main/java/org/jruby/RubyGlobal.java @@ -97,16 +97,17 @@ */ public class RubyGlobal { public static void initARGV(Ruby runtime) { + var context = runtime.getCurrentContext(); // define ARGV and $* for this runtime - RubyArray argvArray = runtime.newArray(); + var argvArray = runtime.newArray(); String[] argv = runtime.getInstanceConfig().getArgv(); for (String arg : argv) { - argvArray.append(RubyString.newInternalFromJavaExternal(runtime, arg)); + argvArray.append(context, RubyString.newInternalFromJavaExternal(runtime, arg)); } if (runtime.getObject().getConstantNoConstMissing("ARGV") != null) { - ((RubyArray)runtime.getObject().getConstant("ARGV")).replace(argvArray); + ((RubyArray)runtime.getObject().getConstant("ARGV")).replace(context, argvArray); } else { runtime.getObject().setConstantQuiet("ARGV", argvArray); runtime.getGlobalVariables().define("$*", new ValueAccessor(argvArray), GLOBAL); @@ -461,13 +462,13 @@ public IRubyObject assoc(final ThreadContext context, IRubyObject obj) { @JRubyMethod(name = "fetch", required = 1, optional = 2) public IRubyObject fetch(ThreadContext context, IRubyObject[] args, Block block) { EnvStringValidation.ensureValidEnvString(context.runtime, args[0], "key"); - - switch(args.length) { - case 1: return super.fetch(context, args[0], block); - case 2: return super.fetch(context, args[0], args[1], block); - } - return null; + return switch (args.length) { + case 1 -> super.fetch(context, args[0], block); + case 2 -> super.fetch(context, args[0], args[1], block); + default -> null; + }; + } @JRubyMethod(name = "fetch", required = 1) @@ -497,11 +498,11 @@ public IRubyObject each(final ThreadContext context, final Block block) { return this; } - private static final VisitorWithState EachVisitor = new VisitorWithState() { + private static final VisitorWithState> EachVisitor = new VisitorWithState<>() { @Override - public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, RubyArray ary) { - ary.append(newString(context, key)); - ary.append(newName(context, key, value)); + public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, RubyArray ary) { + ary.append(context, newString(context, key)); + ary.append(context, newName(context, key, value)); } }; @@ -553,7 +554,7 @@ public RubyArray keys(final ThreadContext context) { private static final VisitorWithState StoreKeyVisitor = new VisitorWithState() { @Override public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, RubyArray keys) { - keys.storeInternal(index, newString(context, key)); + keys.storeInternal(context, index, newString(context, key)); } }; diff --git a/core/src/main/java/org/jruby/RubyHash.java b/core/src/main/java/org/jruby/RubyHash.java index 15587d4b150..b75e6114050 100644 --- a/core/src/main/java/org/jruby/RubyHash.java +++ b/core/src/main/java/org/jruby/RubyHash.java @@ -167,7 +167,7 @@ public static IRubyObject create(ThreadContext context, IRubyObject recv, IRubyO tmp = TypeConverter.convertToTypeWithCheck(args[0], runtime.getArray(), "to_ary"); if (tmp != nil) { RubyHash hash = (RubyHash) ((RubyClass) recv).allocate(); - RubyArray arr = (RubyArray) tmp; + var arr = (RubyArray) tmp; for (int i = 0, j = arr.getLength(); i) v).getLength()) { default: - throw argumentError(context, "invalid number of elements (" + ((RubyArray) v).getLength() + " for 1..2)"); + throw argumentError(context, "invalid number of elements (" + ((RubyArray) v).getLength() + " for 1..2)"); case 2: - val = ((RubyArray) v).entry(1); + val = ((RubyArray) v).entry(1); case 1: - key = ((RubyArray) v).entry(0); + key = ((RubyArray) v).entry(0); hash.fastASetCheckString(runtime, key, val); } } @@ -1008,7 +1008,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(index, RubyArray.newArray(context.runtime, key, value)); + result.storeInternal(context, index, RubyArray.newArray(context.runtime, key, value)); } }; @@ -1856,7 +1856,7 @@ public final RubyArray keys() { private static final VisitorWithState StoreKeyVisitor = new VisitorWithState() { @Override public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, RubyArray keys) { - keys.storeInternal(index, key); + keys.storeInternal(context, index, key); } }; @@ -1884,7 +1884,7 @@ public final RubyArray rb_values(ThreadContext context) { public static final VisitorWithState StoreValueVisitor = new VisitorWithState() { @Override public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyObject value, int index, RubyArray values) { - values.storeInternal(index, value); + values.storeInternal(context, index, value); } }; @@ -2191,7 +2191,7 @@ public void visit(ThreadContext context, RubyHash self, IRubyObject key, IRubyOb public RubyArray values_at(ThreadContext context, IRubyObject[] args) { RubyArray result = RubyArray.newBlankArrayInternal(context.runtime, args.length); for (int i = 0; i < args.length; i++) { - result.storeInternal(i, op_aref(context, args[i])); + result.storeInternal(context, i, op_aref(context, args[i])); } return result; } @@ -2200,7 +2200,7 @@ public RubyArray values_at(ThreadContext context, IRubyObject[] args) { public RubyArray fetch_values(ThreadContext context, IRubyObject[] args, Block block) { RubyArray result = RubyArray.newBlankArrayInternal(context.runtime, args.length); for (int i = 0; i < args.length; i++) { - result.storeInternal(i, fetch(context, args[i], block)); + result.storeInternal(context, i, fetch(context, args[i], block)); } return result; } @@ -2943,6 +2943,7 @@ public int hashCode() { * Note: this is included as a compatibility measure for AR-JDBC * @deprecated use RubyHash.op_aset instead */ + @Deprecated(forRemoval = true) public IRubyObject aset(IRubyObject key, IRubyObject value) { return op_aset(metaClass.runtime.getCurrentContext(), key, value); } @@ -2951,6 +2952,7 @@ public IRubyObject aset(IRubyObject key, IRubyObject value) { * Note: this is included as a compatibility measure for Mongrel+JRuby * @deprecated use RubyHash.op_aref instead */ + @Deprecated(forRemoval = true) public IRubyObject aref(IRubyObject key) { return op_aref(metaClass.runtime.getCurrentContext(), key); } diff --git a/core/src/main/java/org/jruby/RubyIO.java b/core/src/main/java/org/jruby/RubyIO.java index 3314516d50b..0127cb37133 100644 --- a/core/src/main/java/org/jruby/RubyIO.java +++ b/core/src/main/java/org/jruby/RubyIO.java @@ -2667,11 +2667,11 @@ 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) { - RubyArray ary = context.runtime.newArray(); + var ary = context.runtime.newArray(); IRubyObject line; while ((line = self.getlineImpl(context, rs, limit, chomp)) != context.nil) { - ary.append(line); + ary.append(context, line); } return ary; @@ -4502,7 +4502,7 @@ private static final class RubyPOpen { final IRubyObject[] cmdPlusArgs; final RubyHash env; - RubyPOpen(Ruby runtime, IRubyObject[] args) { + RubyPOpen(ThreadContext context, IRubyObject[] args) { IRubyObject[] _cmdPlusArgs; IRubyObject _env; IRubyObject _cmd; @@ -4510,8 +4510,8 @@ private static final class RubyPOpen { int firstArg = 0; int argc = args.length; - if (argc > 0 && !(_env = TypeConverter.checkHashType(runtime, args[0])).isNil()) { - if (argc < 2) throw runtime.newArgumentError(1, 2); + if (argc > 0 && !(_env = TypeConverter.checkHashType(context.runtime, args[0])).isNil()) { + if (argc < 2) throw context.runtime.newArgumentError(1, 2); firstArg++; argc--; } else { @@ -4521,39 +4521,39 @@ private static final class RubyPOpen { IRubyObject arg0 = args[firstArg].checkArrayType(); if (arg0.isNil()) { - if ((arg0 = TypeConverter.checkStringType(runtime, args[firstArg])).isNil()) { - throw typeError(runtime.getCurrentContext(), args[firstArg], "String"); + if ((arg0 = TypeConverter.checkStringType(context.runtime, args[firstArg])).isNil()) { + throw typeError(context, args[firstArg], "String"); } _cmdPlusArgs = null; _cmd = arg0; } else { RubyArray arg0Ary = (RubyArray) arg0; - if (arg0Ary.isEmpty()) throw runtime.newArgumentError("wrong number of arguments"); + if (arg0Ary.isEmpty()) throw argumentError(context, "wrong number of arguments"); if (arg0Ary.eltOk(0) instanceof RubyHash) { // leading hash, use for env - _env = arg0Ary.delete_at(0); + _env = arg0Ary.delete_at(context,0); } - if (arg0Ary.isEmpty()) throw runtime.newArgumentError("wrong number of arguments"); + if (arg0Ary.isEmpty()) throw argumentError(context, "wrong number of arguments"); if (arg0Ary.size() > 1 && arg0Ary.eltOk(arg0Ary.size() - 1) instanceof RubyHash) { // trailing hash, use for opts _env = arg0Ary.eltOk(arg0Ary.size() - 1); } - _cmdPlusArgs = arg0Ary.toJavaArray(); + _cmdPlusArgs = arg0Ary.toJavaArray(context); _cmd = _cmdPlusArgs[0]; } if (Platform.IS_WINDOWS) { String commandString = _cmd.convertToString().toString().replace('/', '\\'); - _cmd = runtime.newString(commandString); + _cmd = newString(context, commandString); if (_cmdPlusArgs != null) _cmdPlusArgs[0] = _cmd; } else { _cmd = _cmd.convertToString(); if (_cmdPlusArgs != null) _cmdPlusArgs[0] = _cmd; } - this.cmd = (RubyString)_cmd; + this.cmd = (RubyString) _cmd; this.cmdPlusArgs = _cmdPlusArgs; - this.env = (RubyHash)_env; + this.env = (RubyHash) _env; } } @@ -4606,7 +4606,7 @@ public static IRubyObject popen(ThreadContext context, IRubyObject recv, IRubyOb args = ArraySupport.newCopy(args, 0, argc - 1); } - RubyPOpen pOpen = new RubyPOpen(runtime, args); + RubyPOpen pOpen = new RubyPOpen(context, args); if (isDash(pOpen.cmd)) { throw runtime.newNotImplementedError("popen(\"-\") is unimplemented"); diff --git a/core/src/main/java/org/jruby/RubyKernel.java b/core/src/main/java/org/jruby/RubyKernel.java index 4768c7a7d8f..07bebefc9da 100644 --- a/core/src/main/java/org/jruby/RubyKernel.java +++ b/core/src/main/java/org/jruby/RubyKernel.java @@ -950,11 +950,10 @@ 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) { - Ruby runtime = context.runtime; - RubyArray globalVariables = runtime.newArray(); + RubyArray globalVariables = context.runtime.newArray(); - for (String globalVariableName : runtime.getGlobalVariables().getNames()) { - globalVariables.append(runtime.newSymbol(globalVariableName)); + for (String globalVariableName : context.runtime.getGlobalVariables().getNames()) { + globalVariables.append(context, newSymbol(context, globalVariableName)); } return globalVariables; @@ -967,7 +966,7 @@ public static RubyArray global_variables(ThreadContext context, IRubyObject recv */ @JRubyMethod(name = "local_variables", module = true, visibility = PRIVATE, reads = SCOPE) public static RubyArray local_variables(ThreadContext context, IRubyObject recv) { - return context.getCurrentStaticScope().getLocalVariables(context.runtime); + return context.getCurrentStaticScope().getLocalVariables(context); } @JRubyMethod(name = "binding", module = true, visibility = PRIVATE, @@ -1705,13 +1704,13 @@ private static IRubyObject testCommon(ThreadContext context, IRubyObject recv, i switch (cmd) { case 'A': // ?A | Time | Last access time for file1 - return context.runtime.newFileStat(fileResource(arg1).path(), false).atime(context); + return context.runtime.newFileStat(fileResource(context, arg1).path(), false).atime(context); case 'b': // ?b | boolean | True if file1 is a block device return RubyFileTest.blockdev_p(context, recv, arg1); case 'c': // ?c | boolean | True if file1 is a character device return RubyFileTest.chardev_p(context, recv, arg1); case 'C': // ?C | Time | Last change time for file1 - return context.runtime.newFileStat(fileResource(arg1).path(), false).ctime(context); + return context.runtime.newFileStat(fileResource(context, arg1).path(), false).ctime(context); case 'd': // ?d | boolean | True if file1 exists and is a directory return RubyFileTest.directory_p(context, recv, arg1); case 'e': // ?e | boolean | True if file1 exists @@ -1725,7 +1724,7 @@ private static IRubyObject testCommon(ThreadContext context, IRubyObject recv, i case 'k': // ?k | boolean | True if file1 exists and has the sticky bit set return RubyFileTest.sticky_p(context, recv, arg1); case 'M': // ?M | Time | Last modification time for file1 - return context.runtime.newFileStat(fileResource(arg1).path(), false).mtime(context); + return context.runtime.newFileStat(fileResource(context, arg1).path(), false).mtime(context); case 'l': // ?l | boolean | True if file1 exists and is a symbolic link return RubyFileTest.symlink_p(context, recv, arg1); case 'o': // ?o | boolean | True if file1 exists and is owned by the caller's effective uid @@ -1961,11 +1960,11 @@ public static IRubyObject _exec_internal(ThreadContext context, IRubyObject recv IRubyObject env = args[0]; IRubyObject prog = args[1]; IRubyObject options = args[2]; - RubyArray cmdArgs = (RubyArray) args[3]; + var cmdArgs = (RubyArray) args[3]; if (options instanceof RubyHash) checkExecOptions(context, (RubyHash) options); - return execCommon(context, env, prog, options, cmdArgs.toJavaArray()); + return execCommon(context, env, prog, options, cmdArgs.toJavaArray(context)); } static void checkExecOptions(ThreadContext context, RubyHash opts) { diff --git a/core/src/main/java/org/jruby/RubyMatchData.java b/core/src/main/java/org/jruby/RubyMatchData.java index 5ba271df616..d442444d062 100644 --- a/core/src/main/java/org/jruby/RubyMatchData.java +++ b/core/src/main/java/org/jruby/RubyMatchData.java @@ -307,7 +307,7 @@ private RubyRegexp getRegexp() { return this.regexp = RubyRegexp.newRegexp(metaClass.runtime, (ByteList) pattern.getUserObject(), pattern); } - private RubyArray match_array(ThreadContext context, int start) { + private RubyArray match_array(ThreadContext context, int start) { Ruby runtime = context.runtime; check(); @@ -321,10 +321,10 @@ private RubyArray match_array(ThreadContext context, int start) { } } else { int count = regs.getNumRegs() - start; - RubyArray arr = RubyArray.newBlankArray(runtime, count); + var arr = RubyArray.newBlankArray(runtime, count); for (int i=0; i < count; i++) { int beg = regs.getBeg(i+start); - arr.storeInternal(i, beg == -1 ? + arr.storeInternal(context, i, beg == -1 ? context.nil : str.makeSharedString(runtime, beg, regs.getEnd(i+start) - beg)); } @@ -456,11 +456,11 @@ public IRubyObject values_at(ThreadContext context, IRubyObject[] args) { for (IRubyObject arg : args) { if (arg instanceof RubyFixnum) { - result.append(RubyRegexp.nth_match(arg.convertToInteger().getIntValue(), this)); + result.append(context, RubyRegexp.nth_match(arg.convertToInteger().getIntValue(), this)); } else { int num = namevToBackrefNumber(context, arg); if (num >= 0) { - result.append(RubyRegexp.nth_match(num, this)); + result.append(context, RubyRegexp.nth_match(num, this)); } else { matchAryAref(context, arg, result); } @@ -560,13 +560,13 @@ private IRubyObject matchArySubseq(ThreadContext context, int beg, int len, Ruby if (len == 0) return result; for (j = beg; j < end; j++) { - result.append(RubyRegexp.nth_match(j, this)); + result.append(context, RubyRegexp.nth_match(j, this)); } // if not enough groups, force length to be as wide as desired by setting last value to nil if (wantedEnd > j) { int newLength = result.size() + wantedEnd - j; - result.storeInternal(newLength - 1, context.nil); + result.storeInternal(context, newLength - 1, context.nil); } return result; @@ -941,7 +941,7 @@ public IRubyObject deconstruct_keys(ThreadContext context, IRubyObject what) { Iterable iterable = () -> arr.rubyStream().iterator(); for (IRubyObject obj : iterable) { if (!(obj instanceof RubySymbol)) { - throw runtime.newTypeError(str(runtime, "wrong argument type ", obj.getMetaClass(), " (expected Symbol)")); + throw typeError(context, str(runtime, "wrong argument type ", obj.getMetaClass(), " (expected Symbol)")); } RubySymbol requestedKey = (RubySymbol) obj; @@ -954,7 +954,7 @@ public IRubyObject deconstruct_keys(ThreadContext context, IRubyObject what) { hash.op_aset(context, requestedKey, value); } } else { - throw context.runtime.newTypeError(str(runtime, "wrong argument type ", what.getMetaClass(), " (expected Array)")); + throw typeError(context, str(runtime, "wrong argument type ", what.getMetaClass(), " (expected Array)")); } return hash; } diff --git a/core/src/main/java/org/jruby/RubyMethod.java b/core/src/main/java/org/jruby/RubyMethod.java index be2c131caa3..01dbf95ff82 100644 --- a/core/src/main/java/org/jruby/RubyMethod.java +++ b/core/src/main/java/org/jruby/RubyMethod.java @@ -36,13 +36,11 @@ import org.jruby.anno.JRubyClass; import org.jruby.api.Convert; import org.jruby.internal.runtime.methods.AliasMethod; -import org.jruby.internal.runtime.methods.DelegatingDynamicMethod; import org.jruby.internal.runtime.methods.DynamicMethod; import org.jruby.internal.runtime.methods.IRMethodArgs; import org.jruby.internal.runtime.methods.PartialDelegatingMethod; import org.jruby.internal.runtime.methods.ProcMethod; import org.jruby.runtime.ArgumentDescriptor; -import org.jruby.runtime.ArgumentType; import org.jruby.runtime.Block; import org.jruby.runtime.ClassIndex; import org.jruby.runtime.Helpers; @@ -56,6 +54,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.ir.runtime.IRRuntimeHelpers.dupIfKeywordRestAtCallsite; /** @@ -153,8 +152,8 @@ public IRubyObject call(ThreadContext context, IRubyObject[] args, Block block) * @return the number of arguments of a method. */ @JRubyMethod - public RubyFixnum arity() { - return RubyFixnum.newFixnum(getRuntime(), method.getSignature().arityValue()); + public RubyFixnum arity(ThreadContext context) { + return newFixnum(context, method.getSignature().arityValue()); } @JRubyMethod(name = "eql?") diff --git a/core/src/main/java/org/jruby/RubyModule.java b/core/src/main/java/org/jruby/RubyModule.java index 5ea2b120abd..8fa861b9411 100644 --- a/core/src/main/java/org/jruby/RubyModule.java +++ b/core/src/main/java/org/jruby/RubyModule.java @@ -140,7 +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.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; @@ -1604,19 +1606,6 @@ public final void addMethodInternal(String name, DynamicMethod method) { } } - /** - * This method is not intended for use by normal users; it is a fast-path - * method that skips synchronization and hierarchy invalidation to speed - * boot-time method definition. - * - * @param id The name to which to bind the method - * @param method The method to bind - * @deprecated No longer used, internal API! - */ - public final void addMethodAtBootTimeOnly(String id, DynamicMethod method) { - putMethod(getRuntime(), id, method); - } - public void removeMethod(ThreadContext context, String id) { testFrozen("class/module"); @@ -2404,7 +2393,7 @@ private void methodRemoved(ThreadContext context, RubySymbol name) { */ public void setMethodVisibility(IRubyObject[] methods, Visibility visibility) { if (methods.length == 1 && methods[0] instanceof RubyArray) { - setMethodVisibility(((RubyArray) methods[0]).toJavaArray(), visibility); + setMethodVisibility(((RubyArray) methods[0]).toJavaArray(getRuntime().getCurrentContext()), visibility); return; } @@ -2765,7 +2754,7 @@ public RubyArray included_modules(ThreadContext context) { for (RubyModule p = getSuperClass(); p != null; p = p.getSuperClass()) { if (p.isIncluded()) { - ary.append(p.getDelegate().getOrigin()); + ary.append(context, p.getDelegate().getOrigin()); } } @@ -3239,27 +3228,40 @@ final void populateInstanceMethodNames(final Set seen, final RubyArray a } } + /** + * @param runtime + * @param seen + * @param ary + * @param not + * @param visibility + * @deprecated Use {@link RubyModule#addMethodSymbols(ThreadContext, Set, RubyArray, boolean, Visibility)} instead + */ + @Deprecated(since = "10.0", forRemoval = true) protected void addMethodSymbols(Ruby runtime, Set seen, RubyArray ary, boolean not, Visibility visibility) { + addMethodSymbols(getCurrentContext(), seen, ary, not, visibility); + } + + protected void addMethodSymbols(ThreadContext context, Set seen, RubyArray ary, boolean not, Visibility visibility) { getMethods().forEach((id, method) -> { if (method instanceof RefinedMarker) return; if (seen.add(id)) { // false - not added (already seen) if ((!not && method.getVisibility() == visibility || (not && method.getVisibility() != visibility)) && !method.isUndefined()) { - ary.append(runtime.newSymbol(id)); + ary.append(context, newSymbol(context, id)); } } }); } @Deprecated - public RubyArray instance_methods19(IRubyObject[] args) { + public RubyArray instance_methods19(IRubyObject[] args) { return instance_methods(args); } @Deprecated - public RubyArray instance_methods(IRubyObject[] args) { - return instance_methods(getRuntime().getCurrentContext(), args); + public RubyArray instance_methods(IRubyObject[] args) { + return instance_methods(getCurrentContext(), args); } @JRubyMethod(name = "instance_methods", optional = 1, checkArity = false) @@ -3270,13 +3272,13 @@ public RubyArray instance_methods(ThreadContext context, IRubyObject[] args) { } @Deprecated - public RubyArray public_instance_methods19(IRubyObject[] args) { + public RubyArray public_instance_methods19(IRubyObject[] args) { return public_instance_methods(args); } @Deprecated - public RubyArray public_instance_methods(IRubyObject[] args) { - return public_instance_methods(getRuntime().getCurrentContext(), args); + public RubyArray public_instance_methods(IRubyObject[] args) { + return public_instance_methods(getCurrentContext(), args); } @JRubyMethod(name = "public_instance_methods", optional = 1, checkArity = false) @@ -3332,11 +3334,11 @@ public RubyArray private_instance_methods(ThreadContext context, IRubyObject[] a @JRubyMethod(name = "undefined_instance_methods") public IRubyObject undefined_instance_method(ThreadContext context) { - RubyArray list = context.runtime.newArray(); + var list = context.runtime.newArray(); getMethods().forEach((id, method) -> { if (method instanceof RefinedMarker) return; - if (method.isUndefined()) list.append(context.runtime.newSymbol(id)); + if (method.isUndefined()) list.append(context, newSymbol(context, id)); }); return list; @@ -3843,13 +3845,12 @@ public static RubyModule unmarshalFrom(UnmarshalStream input) throws java.io.IOE */ @JRubyMethod(name = "nesting", reads = SCOPE, meta = true) public static RubyArray nesting(ThreadContext context, IRubyObject recv, Block block) { - Ruby runtime = context.runtime; - RubyModule object = runtime.getObject(); + RubyModule object = context.runtime.getObject(); StaticScope scope = context.getCurrentStaticScope(); - RubyArray result = runtime.newArray(); + var result = context.runtime.newArray(); for (StaticScope current = scope; current.getModule() != object; current = current.getPreviousCRefScope()) { - result.append(current.getModule()); + result.append(context, current.getModule()); } return result; @@ -4457,15 +4458,13 @@ public RubyArray constants(ThreadContext context, IRubyObject allConstants) { return constantsCommon(context, false, allConstants.isTrue()); } - private RubyArray constantsCommon(ThreadContext context, boolean replaceModule, boolean allConstants) { - Ruby runtime = context.runtime; - - Collection constantNames = constantsCommon(runtime, replaceModule, allConstants, false); - RubyArray array = RubyArray.newBlankArrayInternal(runtime, constantNames.size()); + private RubyArray constantsCommon(ThreadContext context, boolean replaceModule, boolean allConstants) { + Collection constantNames = constantsCommon(context.runtime, replaceModule, allConstants, false); + var array = RubyArray.newBlankArrayInternal(context.runtime, constantNames.size()); int i = 0; for (String name : constantNames) { - array.storeInternal(i++, runtime.newSymbol(name)); + array.storeInternal(context, i++, newSymbol(context, name)); } array.realLength = i; return array; @@ -4610,10 +4609,10 @@ public final void setConstantVisibility(Ruby runtime, String name, boolean hidde @JRubyMethod(name = "refinements") public IRubyObject refinements(ThreadContext context) { - RubyArray refinementModules = context.runtime.newArray(); + RubyArray refinementModules = newArray(context); refinements.forEach((key, value) -> { - refinementModules.append(value); + refinementModules.append(context, value); }); return refinementModules; } diff --git a/core/src/main/java/org/jruby/RubyNoMatchingPatternKeyError.java b/core/src/main/java/org/jruby/RubyNoMatchingPatternKeyError.java index d0fb65a8296..0079d59494a 100644 --- a/core/src/main/java/org/jruby/RubyNoMatchingPatternKeyError.java +++ b/core/src/main/java/org/jruby/RubyNoMatchingPatternKeyError.java @@ -37,6 +37,7 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.runtime.ThreadContext.resetCallInfo; import static org.jruby.runtime.Visibility.PRIVATE; import static org.jruby.runtime.Visibility.PUBLIC; @@ -81,7 +82,7 @@ private void setValues(ThreadContext context, IRubyObject message, IRubyObject k @JRubyMethod(visibility = PRIVATE, optional = 2, keywords = true) public IRubyObject initialize(ThreadContext context, IRubyObject[] args, Block block) { - int callInfo = context.resetCallInfo(); + int callInfo = resetCallInfo(context); switch (args.length) { case 0: diff --git a/core/src/main/java/org/jruby/RubyNumeric.java b/core/src/main/java/org/jruby/RubyNumeric.java index 59fe74247d9..d4d97c3301e 100644 --- a/core/src/main/java/org/jruby/RubyNumeric.java +++ b/core/src/main/java/org/jruby/RubyNumeric.java @@ -169,7 +169,7 @@ public static RubyNumeric newNumeric(Ruby runtime) { */ /** rb_num2int, NUM2INT - * + * if you know it is Integer use {@link org.jruby.api.Convert#asInt(ThreadContext, RubyInteger)}. */ public static int num2int(IRubyObject arg) { long num = num2long(arg); diff --git a/core/src/main/java/org/jruby/RubyProc.java b/core/src/main/java/org/jruby/RubyProc.java index 08955c11e2f..a584654bb1d 100644 --- a/core/src/main/java/org/jruby/RubyProc.java +++ b/core/src/main/java/org/jruby/RubyProc.java @@ -61,6 +61,7 @@ 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.runtime.ThreadContext.resetCallInfo; import static org.jruby.util.RubyStringBuilder.types; /** @@ -433,7 +434,7 @@ public IRubyObject parameters(ThreadContext context) { @JRubyMethod(keywords = true) public IRubyObject parameters(ThreadContext context, IRubyObject opts) { - int callInfo = context.resetCallInfo(); + int callInfo = resetCallInfo(context); boolean isLambda = (callInfo & ThreadContext.CALL_KEYWORD) != 0 ? ArgsUtil.extractKeywordArg(context, (RubyHash) opts, "lambda").isTrue() : isLambda(); diff --git a/core/src/main/java/org/jruby/RubyProcess.java b/core/src/main/java/org/jruby/RubyProcess.java index 1b8f5abb36a..927508136e9 100644 --- a/core/src/main/java/org/jruby/RubyProcess.java +++ b/core/src/main/java/org/jruby/RubyProcess.java @@ -138,7 +138,7 @@ public static RubyModule createProcessModule(Ruby runtime) { process.defineConstant("CLOCK_REALTIME", newSymbol(context, CLOCK_REALTIME)); process.defineConstant("CLOCK_MONOTONIC", newSymbol(context, CLOCK_MONOTONIC)); - RubyClass tmsStruct = RubyStruct.newInstance( + RubyClass tmsStruct = RubyStruct.newInstance(context, runtime.getStructClass(), new IRubyObject[]{ newString(context, "Tms"), @@ -603,7 +603,7 @@ public static IRubyObject eid(ThreadContext context, IRubyObject self) { return eid(context.runtime); } public static IRubyObject eid(Ruby runtime) { - return egid(runtime); + return egid(runtime.getCurrentContext(), null); } @Deprecated @@ -679,7 +679,7 @@ public static IRubyObject switch_rb(ThreadContext context, IRubyObject self, Blo public static class Sys { @Deprecated public static IRubyObject getegid(IRubyObject self) { - return egid(self.getRuntime()); + return egid(self.getRuntime().getCurrentContext(), null); } @JRubyMethod(name = "getegid", module = true, visibility = PRIVATE) public static IRubyObject getegid(ThreadContext context, IRubyObject self) { @@ -742,11 +742,11 @@ public static IRubyObject setgid(ThreadContext context, IRubyObject recv, IRubyO @Deprecated public static IRubyObject setuid(IRubyObject recv, IRubyObject arg) { - return uid_set(recv.getRuntime(), arg); + return uid_set(recv.getRuntime().getCurrentContext(), null, arg); } @JRubyMethod(name = "setuid", module = true, visibility = PRIVATE) public static IRubyObject setuid(ThreadContext context, IRubyObject recv, IRubyObject arg) { - return uid_set(context.runtime, arg); + return uid_set(context, null, arg); } } @@ -757,7 +757,7 @@ public static IRubyObject abort(ThreadContext context, IRubyObject recv, IRubyOb @JRubyMethod(name = "exit!", optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject exit_bang(IRubyObject recv, IRubyObject[] args) { - return RubyKernel.exit_bang(recv, args); + return RubyKernel.exit_bang(recv.getRuntime().getCurrentContext(), recv, args); } @JRubyMethod(name = "groups", module = true, visibility = PRIVATE) @@ -1226,15 +1226,16 @@ public static IRubyObject waitall(ThreadContext context, IRubyObject recv) { } public static IRubyObject waitall(Ruby runtime) { POSIX posix = runtime.getPosix(); - RubyArray results = runtime.newArray(); + var results = runtime.newArray(); int[] status = new int[1]; - ThreadContext context = runtime.getCurrentContext(); + var context = runtime.getCurrentContext(); int result = pthreadKillable(context, ctx -> posix.wait(status)); while (result != -1) { - results.append(runtime.newArray(asFixnum(context, result), RubyProcess.RubyStatus.newProcessStatus(runtime, status[0], result))); + results.append(context, runtime.newArray(asFixnum(context, result), + RubyProcess.RubyStatus.newProcessStatus(runtime, status[0], result))); result = pthreadKillable(context, ctx -> posix.wait(status)); } @@ -1309,7 +1310,7 @@ public static IRubyObject euid(Ruby runtime) { @Deprecated public static IRubyObject uid_set(IRubyObject recv, IRubyObject arg) { - return uid_set(recv.getRuntime(), arg); + return uid_set(recv.getRuntime().getCurrentContext(), null, arg); } @JRubyMethod(name = "uid=", module = true, visibility = PRIVATE) public static IRubyObject uid_set(ThreadContext context, IRubyObject recv, IRubyObject arg) { @@ -1537,7 +1538,7 @@ public static IRubyObject getrlimit(Ruby runtime, IRubyObject arg) { @Deprecated public static IRubyObject egid(IRubyObject recv) { - return egid(recv.getRuntime()); + return egid(recv.getRuntime().getCurrentContext(), recv); } @JRubyMethod(name = "egid", module = true, visibility = PRIVATE) public static IRubyObject egid(ThreadContext context, IRubyObject recv) { @@ -1895,7 +1896,7 @@ public static RubyFixnum spawn(ThreadContext context, IRubyObject recv, IRubyObj @JRubyMethod(name = "exit", optional = 1, checkArity = false, module = true, visibility = PRIVATE) public static IRubyObject exit(IRubyObject recv, IRubyObject[] args) { - return RubyKernel.exit(recv, args); + return RubyKernel.exit(recv.getRuntime().getCurrentContext(), recv, args); } @JRubyMethod(name = "setproctitle", module = true, visibility = PRIVATE) diff --git a/core/src/main/java/org/jruby/RubyRange.java b/core/src/main/java/org/jruby/RubyRange.java index e737b84785f..eb4d1c5a2a4 100644 --- a/core/src/main/java/org/jruby/RubyRange.java +++ b/core/src/main/java/org/jruby/RubyRange.java @@ -61,7 +61,8 @@ import static org.jruby.RubyEnumerator.enumeratorizeWithSize; import static org.jruby.RubyNumeric.*; 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.hashEnd; import static org.jruby.runtime.Helpers.hashStart; @@ -1172,7 +1173,7 @@ public IRubyObject call(ThreadContext ctx, IRubyObject larg, Block blk) { if (n-- <= 0) { throw JumpException.SPECIAL_JUMP; } - result.append(larg); + result.append(context, larg); return ctx.nil; } }); @@ -1225,7 +1226,7 @@ && getMetaClass().checkMethodBasicDefinition("each")) { // MRI rb_int_range_last private RubyArray intRangeLast(ThreadContext context, IRubyObject arg) { - IRubyObject one = RubyInteger.int2fix(context.runtime, 1); + IRubyObject one = newFixnum(context, 1); IRubyObject len1, len, nv, b; len1 = ((RubyInteger)end).op_minus(context, begin); @@ -1242,15 +1243,15 @@ private RubyArray intRangeLast(ThreadContext context, IRubyObject arg) { } long n = numericToLong(context, arg); - if (n < 0) throw context.runtime.newArgumentError("negative array size"); + if (n < 0) throw argumentError(context, "negative array size"); - nv = RubyInteger.int2fix(context.runtime, n); + nv = newFixnum(context, n); if (Numeric.f_gt_p(context, nv, len)) { nv = len; n = numericToLong(context, nv); } - RubyArray array = RubyArray.newArray(context.runtime, n); + RubyArray array = newArray(context, n); b = ((RubyInteger)end).op_minus(context, nv); while (n > 0) { b = ((RubyInteger)b).op_plus(context, one); diff --git a/core/src/main/java/org/jruby/RubyRegexp.java b/core/src/main/java/org/jruby/RubyRegexp.java index 6fc388dc62c..846e56ff2c0 100755 --- a/core/src/main/java/org/jruby/RubyRegexp.java +++ b/core/src/main/java/org/jruby/RubyRegexp.java @@ -789,9 +789,9 @@ public static IRubyObject last_match_s(ThreadContext context, IRubyObject recv, public static IRubyObject union(ThreadContext context, IRubyObject recv, IRubyObject[] args) { IRubyObject obj; if (args.length == 1 && !(obj = args[0].checkArrayType()).isNil()) { - RubyArray ary = (RubyArray)obj; + var ary = (RubyArray) obj; IRubyObject[] tmp = new IRubyObject[ary.size()]; - ary.copyInto(tmp, 0); + ary.copyInto(context, tmp, 0); args = tmp; } @@ -1547,7 +1547,7 @@ public IRubyObject names(ThreadContext context) { 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()); - ary.storeInternal(index++, name); + ary.storeInternal(context, index++, name); } return ary; } @@ -1568,7 +1568,7 @@ public IRubyObject named_captures(ThreadContext context) { RubyArray ary = RubyArray.newBlankArrayInternal(runtime, backrefs.length); for (int idx = 0; idx 0 && (limit || len > beg || lim < 0)) result.append(makeSharedString(runtime, beg, len - beg)); + if (len > 0 && (limit || len > beg || lim < 0)) result.append(context, makeSharedString(runtime, beg, len - beg)); return result; } @@ -4861,7 +4861,7 @@ private RubyArray awkSplit(final ThreadContext context, boolean limit, int lim) } else { // MRI uses rb_isspace if (ASCII.isSpace(c)) { - result.append(makeSharedString(context.runtime, b, e - b)); + result.append(context, makeSharedString(context.runtime, b, e - b)); skip = true; b = p - ptr; if (limit) i++; @@ -4871,7 +4871,7 @@ private RubyArray awkSplit(final ThreadContext context, boolean limit, int lim) } } - if (len > 0 && (limit || len > b || lim < 0)) result.append(makeSharedString(context.runtime, b, len - b)); + if (len > 0 && (limit || len > b || lim < 0)) result.append(context, makeSharedString(context.runtime, b, len - b)); return result; } @@ -4891,16 +4891,16 @@ private RubyArray asciiStringSplitOne(ThreadContext context, byte pat, boolean l for (; index < realSize; index++) { if (bytes[begin + index] == pat) { - result.append(makeSharedString(runtime, startSegment, index - startSegment)); + result.append(context, makeSharedString(runtime, startSegment, index - startSegment)); startSegment = index + 1; if (limit && lim <= ++i) break; } } if (limit) { - result.append(makeSharedString(runtime, startSegment, realSize - startSegment)); + result.append(context, makeSharedString(runtime, startSegment, realSize - startSegment)); } else if (index > startSegment || lim < 0) { - result.append(makeSharedString(runtime, startSegment, index - startSegment)); + result.append(context, makeSharedString(runtime, startSegment, index - startSegment)); } return result; @@ -4924,13 +4924,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(makeSharedString(runtime, p, e - p)); + result.append(context, makeSharedString(runtime, p, e - p)); p = e + pattern.getRealSize(); if (limit && lim <= ++i) break; } if (realSize > 0 && (limit || realSize > p || lim < 0)) { - result.append(makeSharedString(runtime, p, realSize - p)); + result.append(context, makeSharedString(runtime, p, realSize - p)); } return result; @@ -4962,13 +4962,13 @@ private RubyArray stringSplit(ThreadContext context, RubyString spat, boolean li p = t; continue; } - result.append(makeSharedString(runtime, p, e - p)); + result.append(context, makeSharedString(runtime, p, e - p)); p = e + pattern.getRealSize(); if (limit && lim <= ++i) break; } if (realSize > 0 && (limit || realSize > p || lim < 0)) { - result.append(makeSharedString(runtime, p, realSize - p)); + result.append(context, makeSharedString(runtime, p, realSize - p)); } return result; @@ -5097,7 +5097,7 @@ public IRubyObject scan(ThreadContext context, IRubyObject pat, Block block) { last = prev; prev = startp[0]; if (ary == null) ary = context.runtime.newArray(4); - ary.append(result); + ary.append(context, result); } if (last >= 0) patternSearch(context, pat, str, last); return ary == null ? context.runtime.newEmptyArray() : ary; @@ -6418,7 +6418,7 @@ else if (!wantarray) { while (ptr < end) { int c = codePoint(context, enc, ptrBytes, ptr, end); int n = codeLength(enc, c); - if (wantarray) ary.append(newFixnum(context, c)); + if (wantarray) ary.append(context, newFixnum(context, c)); else block.yield(context, newFixnum(context, c)); ptr += n; } @@ -6520,7 +6520,7 @@ else if (!wantarray) { int len = matcher.match(ptr, end, Option.DEFAULT); if (len <= 0) break; RubyString result = newStringShared(runtime, ptrBytes, ptr, len, enc); - if (wantarray) ary.append(result); + if (wantarray) ary.append(context, result); else block.yield(context, result); ptr += len; } diff --git a/core/src/main/java/org/jruby/RubyStruct.java b/core/src/main/java/org/jruby/RubyStruct.java index 6d2816f5fb8..571b826a81c 100644 --- a/core/src/main/java/org/jruby/RubyStruct.java +++ b/core/src/main/java/org/jruby/RubyStruct.java @@ -59,9 +59,10 @@ import org.jruby.util.RecursiveComparator; import static org.jruby.RubyEnumerator.enumeratorizeWithSize; -import static org.jruby.api.Convert.asFixnum; -import static org.jruby.api.Convert.numericToLong; +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.Error.argumentError; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.Helpers.invokedynamic; import static org.jruby.runtime.ThreadContext.hasKeywords; @@ -85,8 +86,8 @@ public class RubyStruct extends RubyObject { /** * Constructor for RubyStruct. - * @param runtime - * @param rubyClass + * @param runtime the runtime + * @param rubyClass the class */ private RubyStruct(Ruby runtime, RubyClass rubyClass) { super(runtime, rubyClass); @@ -216,12 +217,12 @@ private IRubyObject getByName(String name) { private static IRubyObject extractKeywordArg(final ThreadContext context, final RubyHash options, String validKey) { if (options.isEmpty()) return null; - final RubySymbol testKey = context.runtime.newSymbol(validKey); + final RubySymbol testKey = newSymbol(context, validKey); IRubyObject ret = options.fastARef(testKey); if (ret == null || options.size() > 1) { // other (unknown) keys in options options.visitAll(context, (ctxt, self, key, value, index) -> { - if (!key.equals(testKey)) throw ctxt.runtime.newTypeError("unknown keyword: " + key.inspect()); + if (!key.equals(testKey)) throw typeError(ctxt, "unknown keyword: " + key.inspect()); }); } @@ -243,13 +244,12 @@ 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; - RubyArray member = runtime.newArray(); - IRubyObject keywordInitValue = runtime.getNil(); + var member = runtime.newArray(); + IRubyObject keywordInitValue = context.nil; if (argc > 0) { IRubyObject firstArgAsString = args[0].checkStringType(); @@ -274,20 +274,17 @@ public static RubyClass newInstance(ThreadContext context, IRubyObject recv, IRu for (int i = (name == null && !nilName) ? 0 : 1; i < argc; i++) { IRubyObject arg = args[i]; RubySymbol sym; - if (arg instanceof RubySymbol) { - sym = (RubySymbol) arg; + if (arg instanceof RubySymbol sym1) { + sym = sym1; } else if (arg instanceof RubyString) { sym = runtime.newSymbol(arg.convertToString().getByteList()); } else { - sym = runtime.newSymbol(arg.asJavaString()); - } - if (tmpMemberSet.contains(sym)) { - throw runtime.newArgumentError("duplicate member: " + sym); - } else { - tmpMemberSet.add(sym); + sym = newSymbol(context, arg.asJavaString()); } + if (tmpMemberSet.contains(sym)) throw argumentError(context, "duplicate member: " + sym); - member.append(sym); + tmpMemberSet.add(sym); + member.append(context, sym); } RubyClass newStruct; @@ -585,7 +582,7 @@ public IRubyObject select(ThreadContext context, Block block) { for (int i = 0; i < values.length; i++) { if (block.yield(context, values[i]).isTrue()) { - array.append(values[i]); + array.append(context, values[i]); } } @@ -849,30 +846,31 @@ private IRubyObject aset(int idx, IRubyObject value) { @JRubyMethod(rest = true) public IRubyObject values_at(IRubyObject[] args) { final Ruby runtime = metaClass.runtime; + var context = runtime.getCurrentContext(); final int olen = values.length; RubyArray result = getRuntime().newArray(args.length); for (int i = 0; i < args.length; i++) { final IRubyObject arg = args[i]; - if (arg instanceof RubyFixnum ) { - result.append( aref(arg) ); + if (arg instanceof RubyFixnum) { + result.append(context, aref(arg)); continue; } final int [] begLen = new int[2]; if (arg instanceof RubyRange && - RubyRange.rangeBeginLength(runtime.getCurrentContext(),(RubyRange) args[i], olen, begLen, 1).isTrue()) { + RubyRange.rangeBeginLength(runtime.getCurrentContext(), args[i], olen, begLen, 1).isTrue()) { final int beg = begLen[0]; final int len = begLen[1]; - int end = olen < beg + len ? olen : beg + len; + int end = Math.min(olen, beg + len); int j; for (j = beg; j < end; j++) { result.push(aref(j)); } if ( beg + len > j ) { IRubyObject [] tmp = new IRubyObject[beg + len - j]; - Helpers.fillNil(tmp, getRuntime()); - result.push(tmp); + Helpers.fillNil(tmp, runtime); + result.push(context, tmp); } continue; } diff --git a/core/src/main/java/org/jruby/RubySymbol.java b/core/src/main/java/org/jruby/RubySymbol.java index 85409b5cb92..5a8d4c2ef91 100644 --- a/core/src/main/java/org/jruby/RubySymbol.java +++ b/core/src/main/java/org/jruby/RubySymbol.java @@ -931,11 +931,12 @@ private static boolean isSymbolLocal(final String str, final char first, final i @JRubyMethod(meta = true) public static IRubyObject all_symbols(ThreadContext context, IRubyObject recv) { - return context.runtime.getSymbolTable().all_symbols(); + return context.runtime.getSymbolTable().all_symbols(context); } @Deprecated public static IRubyObject all_symbols(IRubyObject recv) { - return recv.getRuntime().getSymbolTable().all_symbols(); + var runtime = recv.getRuntime(); + return runtime.getSymbolTable().all_symbols(runtime.getCurrentContext()); } public static RubySymbol unmarshalFrom(UnmarshalStream input, UnmarshalStream.MarshalState state) throws java.io.IOException { @@ -1404,15 +1405,23 @@ public RubySymbol lookup(long id) { return null; } + /** + * @return "" + * @deprecated Use {@link RubySymbol#all_symbols(ThreadContext, IRubyObject)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public RubyArray all_symbols() { + return all_symbols(runtime.getCurrentContext()); + } + + public RubyArray all_symbols(ThreadContext context) { SymbolEntry[] table = this.symbolTable; RubyArray array = runtime.newArray(this.size); - RubySymbol symbol; for (int i = table.length; --i >= 0; ) { for (SymbolEntry e = table[i]; e != null; e = e.next) { - symbol = e.symbol.get(); - if (symbol != null) array.append(symbol); + var symbol = e.symbol.get(); + if (symbol != null) array.append(context, symbol); } } return array; @@ -1594,9 +1603,7 @@ public static IRubyObject prepareID(ThreadContext context, IRubyObject object) { IRubyObject tmp = TypeConverter.checkStringType(context, sites(context).to_str_checked, object); - if (tmp.isNil()) { - throw runtime.newTypeError(str(runtime, "", object, " is not a symbol nor a string")); - } + if (tmp.isNil()) throw typeError(context, str(runtime, "", object, " is not a symbol nor a string")); return tmp; } @@ -1631,7 +1638,7 @@ private IRubyObject yieldInner(ThreadContext context, RubyArray array, Block blo } final IRubyObject self = array.shift(context); - return site.call(context, symbol, self, array.toJavaArray(), blockArg); + return site.call(context, symbol, self, array.toJavaArray(context), blockArg); } @Override diff --git a/core/src/main/java/org/jruby/RubyThread.java b/core/src/main/java/org/jruby/RubyThread.java index e50f0075b84..632fc92f3c4 100644 --- a/core/src/main/java/org/jruby/RubyThread.java +++ b/core/src/main/java/org/jruby/RubyThread.java @@ -368,13 +368,9 @@ private int pendingInterruptCheckMask(ThreadContext context, IRubyObject err) { while (--idx >= 0) { RubyHash mask = interruptMaskStack.get(idx); - for (int j = 0; j < ancestorsLen; j++) { - IRubyObject klass = ancestors.get(j); - IRubyObject sym; - - if (!(sym = mask.op_aref(context, klass)).isNil()) { - return checkInterruptMask(context, sym); - } + for (IRubyObject klass: ancestors) { + IRubyObject sym = mask.op_aref(context, klass); + if (!sym.isNil()) return checkInterruptMask(context, sym); } } return INTERRUPT_NONE; @@ -1854,6 +1850,7 @@ public interface ReadWrite extends Unblocker { /** * @deprecated Prefer version that receives ByteBuffer rather than recreating every time. */ + @Deprecated(since = "9.4-") public default int run(ThreadContext context, Data data, byte[] bytes, int start, int length) throws InterruptedException { return run(context, data, ByteBuffer.wrap(bytes), start, length); } @@ -1863,16 +1860,15 @@ public default int run(ThreadContext context, Data data, byte[] bytes, int start /** * Execute an interruptible regexp operation with the given function and bytess. - * - * @param context the current context - * @param data a data object - * @param bytes the bytes to write - * @param start start range of bytes to write - * @param length length of bytes to write - * @param task the write task - * @param the type of the data object - * @return the number of bytes written - * @throws InterruptedException + * @param context + * @param matcher + * @param start + * @param range + * @param option + * @param task + * @return "" + * @param + * @throws InterruptedException when interrupted */ public int executeRegexp( ThreadContext context, diff --git a/core/src/main/java/org/jruby/RubyThreadGroup.java b/core/src/main/java/org/jruby/RubyThreadGroup.java index 764995adab8..fe3978078a0 100644 --- a/core/src/main/java/org/jruby/RubyThreadGroup.java +++ b/core/src/main/java/org/jruby/RubyThreadGroup.java @@ -133,14 +133,22 @@ public IRubyObject enclosed_p(Block block) { return enclosed_p(getRuntime().getCurrentContext(), block); } - @JRubyMethod + /** + * @param block + * @return "" + * @deprecated Use {@link RubyThreadGroup#list(ThreadContext, Block)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public IRubyObject list(Block block) { - RubyArray ary = RubyArray.newArray(getRuntime()); + return list(getCurrentContext(), block); + } + + @JRubyMethod + public IRubyObject list(ThreadContext context, Block block) { + var ary = RubyArray.newArray(context.runtime); synchronized (rubyThreadList) { for (RubyThread thread : rubyThreadList) { - if (thread != null) { - ary.append(thread); - } + if (thread != null) ary.append(context, thread); } } return ary; diff --git a/core/src/main/java/org/jruby/RubyTime.java b/core/src/main/java/org/jruby/RubyTime.java index 67e1ad5100d..8637d1f9a22 100644 --- a/core/src/main/java/org/jruby/RubyTime.java +++ b/core/src/main/java/org/jruby/RubyTime.java @@ -62,11 +62,9 @@ import org.jruby.runtime.builtin.IRubyObject; import org.jruby.runtime.callsite.CachingCallSite; import org.jruby.util.ByteList; -import org.jruby.util.ConvertBytes; import org.jruby.util.RubyDateFormatter; import org.jruby.util.RubyTimeParser; import org.jruby.util.Sprintf; -import org.jruby.util.TypeConverter; import org.jruby.util.time.TimeArgs; import java.io.Serializable; @@ -83,7 +81,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static java.lang.Integer.parseInt; import static org.jruby.RubyComparable.invcmp; import static org.jruby.api.Convert.*; import static org.jruby.api.Create.newString; @@ -94,7 +91,6 @@ import static org.jruby.runtime.Visibility.PRIVATE; import static org.jruby.runtime.invokedynamic.MethodNames.OP_CMP; import static org.jruby.util.RubyStringBuilder.str; -import static org.jruby.util.RubyStringBuilder.types; import static org.jruby.util.TypeConverter.typeAsString; /** The Time class. @@ -156,7 +152,7 @@ public static String getEnvTimeZone(Ruby runtime) { if (entry.key != tz) runtime.tzVar = (RubyString) entry.key; - return (entry.value instanceof RubyString) ? ((RubyString) entry.value).asJavaString() : null; + return (entry.value instanceof RubyString) ? entry.value.asJavaString() : null; } public static DateTimeZone getLocalTimeZone(Ruby runtime) { @@ -940,7 +936,7 @@ public RubyInteger to_i(ThreadContext context) { return asFixnum(context, Math.floorDiv(getTimeInMillis(), (long) 1000)); } - @Deprecated + @Deprecated(since = "9.4-", forRemoval = true) public RubyInteger to_i() { return to_i(getCurrentContext()); } @@ -958,7 +954,7 @@ public RubyInteger nsec(ThreadContext context) { return asFixnum(context, getNanos()); } - @Deprecated + @Deprecated(since = "9.4-", forRemoval = true) public RubyInteger nsec() { return nsec(getCurrentContext()); } @@ -1015,11 +1011,13 @@ public void setMicros(int micros) { /** * @deprecated use {@link #setMicros(int)} instead */ + @Deprecated(since = "9.4-", forRemoval = true) public void setMicroseconds(long micros) { setMicros((int) micros); } /** * @deprecated use {@link #getMicros()} instead */ + @Deprecated(since = "9.4-", forRemoval = true) public long microseconds() { return getMicros(); } @@ -1179,6 +1177,7 @@ public RubyInteger gmt_offset(ThreadContext context) { return asFixnum(context, offset / 1000); } + @Deprecated(since = "9.4-", forRemoval = true) public RubyInteger gmt_offset() { return gmt_offset(getCurrentContext()); } diff --git a/core/src/main/java/org/jruby/TopSelfFactory.java b/core/src/main/java/org/jruby/TopSelfFactory.java index 748e331d86f..89dd185921f 100644 --- a/core/src/main/java/org/jruby/TopSelfFactory.java +++ b/core/src/main/java/org/jruby/TopSelfFactory.java @@ -73,7 +73,7 @@ public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule claz singletonClass.addMethod("include", new JavaMethod.JavaMethodN(singletonClass, Visibility.PRIVATE, "include") { @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { - return context.runtime.getObject().include(args); + return context.runtime.getObject().include(context, args); } }); diff --git a/core/src/main/java/org/jruby/api/Create.java b/core/src/main/java/org/jruby/api/Create.java index e766e525e25..1e191b11936 100644 --- a/core/src/main/java/org/jruby/api/Create.java +++ b/core/src/main/java/org/jruby/api/Create.java @@ -2,10 +2,43 @@ import org.jcodings.Encoding; import org.jruby.*; +import org.jruby.runtime.Helpers; import org.jruby.runtime.ThreadContext; +import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; +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. + * + * @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); + } + + /** + * 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. + * + * @param context the current thread context + * @param length the size to allocate for the array + * @return the new array + */ + // mri: rb_ary_new2 + public static RubyArray newArray(ThreadContext context, long length) { + checkLength(context, length); + return RubyArray.newArray(context.runtime, (int)length); + } + /** * Creates a new RubyString from the provided int. * diff --git a/core/src/main/java/org/jruby/ext/date/RubyDate.java b/core/src/main/java/org/jruby/ext/date/RubyDate.java index 6ec61626dec..5c679caf4fd 100644 --- a/core/src/main/java/org/jruby/ext/date/RubyDate.java +++ b/core/src/main/java/org/jruby/ext/date/RubyDate.java @@ -209,9 +209,10 @@ RubyDate newInstance(final ThreadContext context, final DateTime dt, int off, lo *

Note: since Date.new is a civil alias, this won't ever get used

* @deprecated kept due AR-JDBC (uses RubyClass.newInstance(...) to 'fast' allocate a Date instance) */ + @Deprecated(since = "9.4-") @JRubyMethod(visibility = Visibility.PRIVATE) public RubyDate initialize(ThreadContext context, IRubyObject dt) { - this.dt = (DateTime) JavaUtil.unwrapJavaValue(dt); + this.dt = JavaUtil.unwrapJavaValue(dt); return this; } @@ -297,50 +298,49 @@ public IRubyObject initialize_copy(IRubyObject original) { * @deprecated internal Date.new! */ @JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE) + @Deprecated(since = "9.4-") public static RubyDate new_(ThreadContext context, IRubyObject self) { - if (isDateTime(context.runtime, self)) { - return new RubyDateTime(context.runtime, 0, CHRONO_ITALY_UTC); - } - return new RubyDate(context.runtime, 0, CHRONO_ITALY_UTC); + return isDateTime(context.runtime, self) ? + new RubyDateTime(context.runtime, 0, CHRONO_ITALY_UTC) : + new RubyDate(context.runtime, 0, CHRONO_ITALY_UTC); } /** * @deprecated internal Date.new! */ + @Deprecated(since = "9.4-") @JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE) public static RubyDate new_(ThreadContext context, IRubyObject self, IRubyObject ajd) { if (ajd instanceof JavaProxy) { // backwards - compatibility with JRuby's date.rb - if (isDateTime(context.runtime, self)) { - return new RubyDateTime(context.runtime, (RubyClass) self, JavaUtil.unwrapJavaValue(ajd)); - } - return new RubyDate(context.runtime, (RubyClass) self, JavaUtil.unwrapJavaValue(ajd)); - } - if (isDateTime(context.runtime, self)) { - return new RubyDateTime(context, (RubyClass) self, ajd, CHRONO_ITALY_UTC, 0); + return isDateTime(context.runtime, self) ? + new RubyDateTime(context.runtime, (RubyClass) self, JavaUtil.unwrapJavaValue(ajd)) : + new RubyDate(context.runtime, (RubyClass) self, JavaUtil.unwrapJavaValue(ajd)); } - return new RubyDate(context, (RubyClass) self, ajd, CHRONO_ITALY_UTC, 0); + return isDateTime(context.runtime, self) ? + new RubyDateTime(context, (RubyClass) self, ajd, CHRONO_ITALY_UTC, 0) : + new RubyDate(context, (RubyClass) self, ajd, CHRONO_ITALY_UTC, 0); } /** * @deprecated internal Date.new! */ + @Deprecated(since = "9.4-") @JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE) public static RubyDate new_(ThreadContext context, IRubyObject self, IRubyObject ajd, IRubyObject of) { - if (isDateTime(context.runtime, self)) { - return new RubyDateTime(context.runtime, (RubyClass) self).initialize(context, ajd, of); - } - return new RubyDate(context.runtime, (RubyClass) self).initialize(context, ajd, of); + return isDateTime(context.runtime, self) ? + new RubyDateTime(context.runtime, (RubyClass) self).initialize(context, ajd, of) : + new RubyDate(context.runtime, (RubyClass) self).initialize(context, ajd, of); } /** * @deprecated internal Date.new! */ + @Deprecated(since = "9.4-") @JRubyMethod(name = "new!", meta = true, visibility = Visibility.PRIVATE) public static RubyDate new_(ThreadContext context, IRubyObject self, IRubyObject ajd, IRubyObject of, IRubyObject sg) { - if (isDateTime(context.runtime, self)) { - return new RubyDateTime(context.runtime, (RubyClass) self).initialize(context, ajd, of, sg); - } - return new RubyDate(context.runtime, (RubyClass) self).initialize(context, ajd, of, sg); + return isDateTime(context.runtime, self) ? + new RubyDateTime(context.runtime, (RubyClass) self).initialize(context, ajd, of, sg) : + new RubyDate(context.runtime, (RubyClass) self).initialize(context, ajd, of, sg); } /** diff --git a/core/src/main/java/org/jruby/ext/digest/RubyDigest.java b/core/src/main/java/org/jruby/ext/digest/RubyDigest.java index 209dbe16325..debbc2b5d88 100644 --- a/core/src/main/java/org/jruby/ext/digest/RubyDigest.java +++ b/core/src/main/java/org/jruby/ext/digest/RubyDigest.java @@ -69,7 +69,7 @@ @JRubyModule(name="Digest") public class RubyDigest { - private static final Map CLONEABLE_DIGESTS = new HashMap(8, 1); + private static final Map CLONEABLE_DIGESTS = new HashMap<>(8, 1); static { // standard digests from JCA specification; if we can retrieve and clone, save them for (String name : new String[] {"MD2", "MD5", "SHA-1", "SHA-256", "SHA-384", "SHA-512"}) { @@ -150,21 +150,32 @@ private static MessageDigest createMessageDigest(final String name) throws NoSuc private static ByteList toHex(byte[] val) { ByteList byteList = new ByteList(val.length * 2); - for (int i = 0, j = val.length; i < j; i++) { - int b = val[i] & 0xFF; + for (byte value: val) { + int b = value & 0xFF; byteList.append(digits[b >> 4]); byteList.append(digits[b & 0xF]); } return byteList; } - private static RubyString toHexString(Ruby runtime, byte[] val) { - return RubyString.newStringNoCopy(runtime, new ByteList(ByteList.plain(toHex(val)), USASCIIEncoding.INSTANCE)); + private static RubyString toHexString(ThreadContext context, byte[] val) { + return RubyString.newStringNoCopy(context.runtime, new ByteList(ByteList.plain(toHex(val)), USASCIIEncoding.INSTANCE)); } - @JRubyMethod(name = "hexencode", meta = true) + /** + * @param self + * @param arg + * @return "" + * @deprecated Use {@link RubyDigest#hexencode(ThreadContext, IRubyObject, IRubyObject)} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public static RubyString hexencode(IRubyObject self, IRubyObject arg) { - return toHexString(self.getRuntime(), arg.convertToString().getBytes()); + return hexencode(self.getRuntime().getCurrentContext(), self, arg); + } + + @JRubyMethod(name = "hexencode", meta = true) + public static RubyString hexencode(ThreadContext context, IRubyObject self, IRubyObject arg) { + return toHexString(context, arg.convertToString().getBytes()); } @JRubyMethod(name = "bubblebabble", meta = true) @@ -173,23 +184,7 @@ public static RubyString bubblebabble(IRubyObject recv, IRubyObject arg) { return RubyString.newString(recv.getRuntime(), BubbleBabble.bubblebabble(bytes.unsafeBytes(), bytes.begin(), bytes.length())); } - private static class Metadata { - - private final String name; - private final int blockLength; - - Metadata(String name, int blockLength) { - this.name = name; - this.blockLength = blockLength; - } - - String getName() { - return name; - } - - int getBlockLength() { - return blockLength; - } + private record Metadata(String name, int blockLength) { } @@ -264,34 +259,34 @@ public static void createDigestBubbleBabble(Ruby runtime) { @JRubyModule(name = "Digest::Instance") public static class DigestInstance { - private static IRubyObject throwUnimplError(IRubyObject self, String name) { - throw self.getRuntime().newRuntimeError(String.format("%s does not implement %s()", self.getMetaClass().getRealClass().getName(), name)); + private static IRubyObject throwUnimplError(ThreadContext context, IRubyObject self, String name) { + throw context.runtime.newRuntimeError(String.format("%s does not implement %s()", self.getMetaClass().getRealClass().getName(), name)); } /* instance methods that should be overridden */ @JRubyMethod(name = {"update", "<<"}) public static IRubyObject update(ThreadContext context, IRubyObject self, IRubyObject arg) { - return throwUnimplError(self, "update"); + return throwUnimplError(context, self, "update"); } @JRubyMethod() public static IRubyObject finish(ThreadContext context, IRubyObject self) { - return throwUnimplError(self, "finish"); + return throwUnimplError(context, self, "finish"); } @JRubyMethod() public static IRubyObject reset(ThreadContext context, IRubyObject self) { - return throwUnimplError(self, "reset"); + return throwUnimplError(context, self, "reset"); } @JRubyMethod() public static IRubyObject digest_length(ThreadContext context, IRubyObject self) { - return digest(context, self, IRubyObject.NULL_ARRAY).convertToString().bytesize(); + return digest(context, self, IRubyObject.NULL_ARRAY).convertToString().bytesize(context); } @JRubyMethod() public static IRubyObject block_length(ThreadContext context, IRubyObject self) { - return throwUnimplError(self, "block_length"); + return throwUnimplError(context, self, "block_length"); } /* instance methods that may be overridden */ @@ -308,13 +303,13 @@ public static IRubyObject op_equal(ThreadContext context, IRubyObject self, IRub str1 = to_s(context, self).convertToString(); str2 = oth.convertToString(); } - boolean ret = str1.bytesize().eql(str2.bytesize()) && (str1.eql(str2)); + boolean ret = str1.bytesize(context).eql(str2.bytesize(context)) && (str1.eql(str2)); return ret ? context.tru : context.fals; } @JRubyMethod() public static IRubyObject inspect(ThreadContext context, IRubyObject self) { - return RubyString.newStringNoCopy(self.getRuntime(), ByteList.plain("#<" + self.getMetaClass().getRealClass().getName() + ": " + hexdigest(context, self, IRubyObject.NULL_ARRAY) + ">")); + return RubyString.newStringNoCopy(context.runtime, ByteList.plain("#<" + self.getMetaClass().getRealClass().getName() + ": " + hexdigest(context, self, IRubyObject.NULL_ARRAY) + ">")); } /* instance methods that need not usually be overridden */ @@ -325,10 +320,7 @@ public static IRubyObject newObject(ThreadContext context, IRubyObject self) { @JRubyMethod public static IRubyObject digest(ThreadContext context, IRubyObject self) { - IRubyObject clone = self.rbClone(); - IRubyObject value = clone.callMethod(context, "finish"); - clone.callMethod(context, "reset"); - return value; + return digest_bang(context, self.rbClone()); } @JRubyMethod @@ -350,17 +342,17 @@ public static IRubyObject digest_bang(ThreadContext context, IRubyObject self) { @JRubyMethod public static IRubyObject hexdigest(ThreadContext context, IRubyObject self) { - return toHexString(context.runtime, digest(context, self).convertToString().getBytes()); + return toHexString(context, digest(context, self).convertToString().getBytes()); } @JRubyMethod public static IRubyObject hexdigest(ThreadContext context, IRubyObject self, IRubyObject arg0) { - return toHexString(context.runtime, digest(context, self, arg0).convertToString().getBytes()); + return toHexString(context, digest(context, self, arg0).convertToString().getBytes()); } @JRubyMethod(name = "hexdigest!") public static IRubyObject hexdigest_bang(ThreadContext context, IRubyObject self) { - return toHexString(context.runtime, digest_bang(context, self).convertToString().getBytes()); + return toHexString(context, digest_bang(context, self).convertToString().getBytes()); } @JRubyMethod(name = "bubblebabble", meta = true) @@ -399,7 +391,7 @@ public static IRubyObject digest(ThreadContext context, IRubyObject self, IRubyO @Deprecated public static IRubyObject hexdigest(ThreadContext context, IRubyObject self, IRubyObject[] args) { - return toHexString(context.runtime, digest(context, self, args).convertToString().getBytes()); + return toHexString(context, digest(context, self, args).convertToString().getBytes()); } @Deprecated @@ -469,23 +461,20 @@ public static IRubyObject s_digest(ThreadContext context, IRubyObject recv, IRub @JRubyMethod(name = "hexdigest", required = 1, optional = 1, checkArity = false, meta = true) public static IRubyObject s_hexdigest(ThreadContext context, IRubyObject recv, IRubyObject[] args) { - Ruby runtime = recv.getRuntime(); byte[] digest = recv.callMethod(context, "digest", args, Block.NULL_BLOCK).convertToString().getBytes(); - return RubyDigest.toHexString(runtime, digest); + return RubyDigest.toHexString(context, digest); } @JRubyMethod(name = "hexdigest", meta = true) public static IRubyObject s_hexdigest(ThreadContext context, IRubyObject recv, IRubyObject arg0) { - Ruby runtime = recv.getRuntime(); byte[] digest = sites(context).digest.call(context, recv, recv, arg0).convertToString().getBytes(); - return RubyDigest.toHexString(runtime, digest); + return RubyDigest.toHexString(context, digest); } @JRubyMethod(name = "hexdigest", meta = true) public static IRubyObject s_hexdigest(ThreadContext context, IRubyObject recv, IRubyObject arg0, IRubyObject arg1) { - Ruby runtime = recv.getRuntime(); byte[] digest = sites(context).digest.call(context, recv, recv, arg0, arg1).convertToString().getBytes(); - return RubyDigest.toHexString(runtime, digest); + return RubyDigest.toHexString(context, digest); } @JRubyMethod(name = "bubblebabble", meta = true) @@ -600,8 +589,8 @@ public IRubyObject bubblebabble(ThreadContext context) { } private void setAlgorithm(Metadata metadata) throws NoSuchAlgorithmException { - this.algo = createMessageDigest(metadata.getName()); - this.blockLength = metadata.getBlockLength(); + this.algo = createMessageDigest(metadata.name()); + this.blockLength = metadata.blockLength(); } } diff --git a/core/src/main/java/org/jruby/ext/etc/RubyEtc.java b/core/src/main/java/org/jruby/ext/etc/RubyEtc.java index 90c5cda29fc..9ca8ddb3608 100644 --- a/core/src/main/java/org/jruby/ext/etc/RubyEtc.java +++ b/core/src/main/java/org/jruby/ext/etc/RubyEtc.java @@ -110,7 +110,7 @@ private static void definePasswdStruct(Ruby runtime) { runtime.newSymbol("expire") }; - runtime.setPasswdStruct(RubyStruct.newInstance(runtime.getStructClass(), args, Block.NULL_BLOCK)); + runtime.setPasswdStruct(RubyStruct.newInstance(runtime.getCurrentContext(), runtime.getStructClass(), args, Block.NULL_BLOCK)); runtime.getEtc().defineConstant("Passwd", runtime.getPasswdStruct()); } @@ -123,7 +123,7 @@ private static void defineGroupStruct(Ruby runtime) { runtime.newSymbol("mem") }; - runtime.setGroupStruct(RubyStruct.newInstance(runtime.getStructClass(), args, Block.NULL_BLOCK)); + runtime.setGroupStruct(RubyStruct.newInstance(runtime.getCurrentContext(), runtime.getStructClass(), args, Block.NULL_BLOCK)); runtime.getEtc().defineConstant("Group", runtime.getGroupStruct()); } 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 8e4554a9a48..1c107d5dee5 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,6 @@ import org.jruby.util.ByteList; import static org.jruby.api.Convert.asFixnum; -import static org.jruby.api.Convert.castAsArray; import static org.jruby.api.Create.newFixnum; import static org.jruby.api.Error.typeError; import static org.jruby.runtime.Visibility.*; @@ -176,11 +175,10 @@ private StructLayout(ThreadContext context, RubyClass klass, Collection paramTypes)) { throw typeError(context, "Invalid parameter array ", rbParameterTypes, " (expected Array)"); } @@ -112,13 +112,12 @@ public static VariadicInvoker newInstance(ThreadContext context, IRubyObject kla CallingConvention callConvention = "stdcall".equals(convention) ? CallingConvention.STDCALL : CallingConvention.DEFAULT; - RubyArray paramTypes = (RubyArray) rbParameterTypes; - RubyArray fixed = RubyArray.newArray(context.runtime); + var fixed = RubyArray.newArray(context.runtime); int fixedParamCount = 0; for (int i = 0; i < paramTypes.getLength(); ++i) { Type type = (Type)paramTypes.entry(i); if (type.getNativeType() != org.jruby.ext.ffi.NativeType.VARARGS) { - fixed.append(type); + fixed.append(context, type); fixedParamCount++; } } 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 738daf320b5..a16d1715cbe 100644 --- a/core/src/main/java/org/jruby/ext/jruby/JRubyLibrary.java +++ b/core/src/main/java/org/jruby/ext/jruby/JRubyLibrary.java @@ -336,12 +336,8 @@ public IRubyObject yield(ThreadContext context, IRubyObject[] args) { @Override protected IRubyObject doYield(ThreadContext context, Block block, IRubyObject value) { if (klass != value) { - if (recurseAll) { - return subclasses.append(value); - } - if (((RubyClass) value).superclass(context) == klass) { - return subclasses.append(value); - } + if (recurseAll) return subclasses.append(context, value); + if (((RubyClass) value).superclass(context) == klass) return subclasses.append(context, value); } return context.nil; } diff --git a/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java b/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java index 00e04440a01..f127fc6ca3a 100644 --- a/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java +++ b/core/src/main/java/org/jruby/ext/jruby/JRubyUtilLibrary.java @@ -51,6 +51,7 @@ import static org.jruby.api.Convert.asBoolean; import static org.jruby.api.Convert.asFixnum; import static org.jruby.api.Create.newString; +import static org.jruby.api.Create.newSymbol; import static org.jruby.api.Error.argumentError; import static org.jruby.util.URLUtil.getPath; @@ -131,12 +132,9 @@ public static IRubyObject load_java_class(ThreadContext context, IRubyObject rec @JRubyMethod(module = true, name = "class_loader_resources", alias = "classloader_resources", required = 1, optional = 1, checkArity = false) public static IRubyObject class_loader_resources(ThreadContext context, IRubyObject recv, IRubyObject... args) { int argc = Arity.checkArgumentCount(context, args, 1, 2); - - final Ruby runtime = context.runtime; - - final ClassLoader loader = runtime.getJRubyClassLoader(); + final ClassLoader loader = context.runtime.getJRubyClassLoader(); final String name = args[0].convertToString().asJavaString(); - final RubyArray resources = RubyArray.newArray(runtime); + final var resources = RubyArray.newArray(context.runtime); boolean raw = false, path = false; if (argc > 1 && args[1] instanceof RubyHash) { @@ -150,11 +148,11 @@ public static IRubyObject class_loader_resources(ThreadContext context, IRubyObj while (e.hasMoreElements()) { final URL entry = e.nextElement(); if (path) { - resources.append( newString(context, getPath(entry)) ); + resources.append(context, newString(context, getPath(entry))); } else if (raw) { - resources.append( Java.getInstance(runtime, entry) ); + resources.append(context, Java.getInstance(context.runtime, entry)); } else { - resources.append( newString(context, entry.toString()) ); // toExternalForm + resources.append(context, newString(context, entry.toString())); // toExternalForm } } } catch (IOException ex) { @@ -409,16 +407,14 @@ public static IRubyObject unseeded_hash(ThreadContext context, IRubyObject recv) /** * Provide stats on how many method and constant invalidations have occurred globally. - * * This was added for Pry in https://github.com/jruby/jruby/issues/4384 */ @JRubyMethod(name = "cache_stats", module = true) public static IRubyObject cache_stats(ThreadContext context, IRubyObject self) { - Ruby runtime = context.runtime; - - RubyHash stat = RubyHash.newHash(runtime); - stat.op_aset(context, runtime.newSymbol("method_invalidation_count"), asFixnum(context, runtime.getCaches().getMethodInvalidationCount())); - stat.op_aset(context, runtime.newSymbol("constant_invalidation_count"), asFixnum(context, runtime.getCaches().getConstantInvalidationCount())); + RubyHash stat = RubyHash.newHash(context.runtime); + var caches = context.runtime.getCaches(); + stat.op_aset(context, newSymbol(context, "method_invalidation_count"), asFixnum(context, caches.getMethodInvalidationCount())); + stat.op_aset(context, newSymbol(context, "constant_invalidation_count"), asFixnum(context, caches.getConstantInvalidationCount())); return stat; } 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 fb6d8e3ebbb..f5db1948858 100644 --- a/core/src/main/java/org/jruby/ext/ripper/RipperParserBase.java +++ b/core/src/main/java/org/jruby/ext/ripper/RipperParserBase.java @@ -362,7 +362,8 @@ protected IRubyObject assignable(ByteList name, IRubyObject value) { } protected IRubyObject backref_error(IRubyObject ref, IRubyObject expr) { - RubyString str = getRuntime().newString("Can't set variable "); + var runtime = ref.getRuntime(); + RubyString str = runtime.newString("Can't set variable "); str = str.append(ref); return dispatch("on_assign_error", str, expr); @@ -385,14 +386,10 @@ public IRubyObject method_optarg(IRubyObject method, IRubyObject arg) { } public IRubyObject keyword_arg(IRubyObject key, IRubyObject value) { - RubyArray array = RubyArray.newArray(context.runtime, 2); + var array = RubyArray.newArray(context.runtime, 2); - array.append(key); - if (value != null) { - array.append(value); - } else { - array.append(context.nil); - } + array.append(context, key); + array.append(context, value != null ? value : context.nil); return array; } @@ -680,15 +677,15 @@ private boolean isNumParamId(String id) { } public IRubyObject new_array_pattern(int _line, IRubyObject constant, IRubyObject preArg, RubyArray arrayPattern) { - RubyArray preArgs = (RubyArray) arrayPattern.eltOk(0); + var preArgs = (RubyArray) arrayPattern.eltOk(0); IRubyObject restArg = arrayPattern.eltOk(1); IRubyObject postArgs = arrayPattern.eltOk(2); if (preArg != null) { if (preArgs != null) { - preArgs.unshift(preArg); + preArgs.unshift(context, preArg); } else { - preArgs = RubyArray.newArray(getRuntime()); + preArgs = RubyArray.newArray(context.runtime); preArgs.add(preArg); } } 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 9ca660335f8..88a7ad336fd 100644 --- a/core/src/main/java/org/jruby/ext/set/RubySet.java +++ b/core/src/main/java/org/jruby/ext/set/RubySet.java @@ -604,7 +604,7 @@ public RubySet add(final ThreadContext context, IRubyObject obj) { return this; } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) protected void addImpl(final Ruby runtime, final IRubyObject obj) { addImpl(runtime.getCurrentContext(), obj); } @@ -955,11 +955,11 @@ private IRubyObject divideTSort(ThreadContext context, final Block block) { } */ for ( IRubyObject u : elementsOrdered() ) { - RubyArray a; - dig.fastASet(u, a = runtime.newArray()); + var a = runtime.newArray(); + dig.fastASet(u, a); for ( IRubyObject v : elementsOrdered() ) { IRubyObject ret = block.call(context, u, v); - if ( ret.isTrue() ) a.append(v); + if ( ret.isTrue() ) a.append(context, v); } } diff --git a/core/src/main/java/org/jruby/ext/set/RubySortedSet.java b/core/src/main/java/org/jruby/ext/set/RubySortedSet.java index e567f68fcf6..5b1d4057e5c 100644 --- a/core/src/main/java/org/jruby/ext/set/RubySortedSet.java +++ b/core/src/main/java/org/jruby/ext/set/RubySortedSet.java @@ -98,19 +98,17 @@ void unmarshal() { @JRubyMethod(name = "[]", rest = true, meta = true) // re-def Set[] for SortedSet public static RubySortedSet create(final ThreadContext context, IRubyObject self, IRubyObject... ary) { - final Ruby runtime = context.runtime; - - RubySortedSet set = new RubySortedSet(runtime, (RubyClass) self); + RubySortedSet set = new RubySortedSet(context.runtime, (RubyClass) self); return (RubySortedSet) set.initSet(context, ary, 0, ary.length); } @Override - protected void addImpl(final Ruby runtime, final IRubyObject obj) { + protected void addImpl(ThreadContext context, final IRubyObject obj) { // NOTE: we're able to function without the check - comparator will raise ArgumentError //if ( ! obj.respondsTo("<=>") ) { // throw runtime.newArgumentError("value must respond to <=>"); //} - super.addImpl(runtime, obj); // @hash[obj] = true + super.addImpl(context, obj); // @hash[obj] = true order.add(obj); } @@ -122,8 +120,9 @@ protected void addImplSet(final ThreadContext context, final RubySet set) { @Override protected boolean deleteImpl(final IRubyObject obj) { - if ( super.deleteImpl(obj) ) { - order.remove(obj); return true; + if (super.deleteImpl(obj)) { + order.remove(obj); + return true; } return false; } 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 0179a556274..2dd5f2057e7 100644 --- a/core/src/main/java/org/jruby/ext/socket/Addrinfo.java +++ b/core/src/main/java/org/jruby/ext/socket/Addrinfo.java @@ -10,7 +10,6 @@ import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyBignum; -import org.jruby.RubyBoolean; import org.jruby.RubyClass; import org.jruby.RubyInteger; import org.jruby.RubyObject; @@ -50,6 +49,7 @@ import static jnr.constants.platform.Sock.*; 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.ext.socket.SocketUtils.IP_V4_MAPPED_ADDRESS_PREFIX; import static org.jruby.ext.socket.SocketUtils.sockerr; @@ -497,9 +497,9 @@ public IRubyObject ip_p(ThreadContext context) { @JRubyMethod public IRubyObject ip_unpack(ThreadContext context) { - RubyArray ary = RubyArray.newArray(context.runtime, 2); - ary.append(ip_address(context)); - ary.append(ip_port(context)); + var ary = newArray(context, 2); + ary.append(context, ip_address(context)); + ary.append(context, ip_port(context)); return ary; } 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 75b73b677bf..4383103850a 100644 --- a/core/src/main/java/org/jruby/ext/socket/RubySocket.java +++ b/core/src/main/java/org/jruby/ext/socket/RubySocket.java @@ -268,9 +268,9 @@ public static IRubyObject getifaddrs(ThreadContext context, IRubyObject recv) { while (en.hasMoreElements()) { NetworkInterface iface = en.nextElement(); // create interface link layer ifaddr - list.append(new Ifaddr(context.runtime, Ifaddr, iface)); + list.append(context, new Ifaddr(context.runtime, Ifaddr, iface)); for ( InterfaceAddress iaddr : iface.getInterfaceAddresses() ) { - list.append(new Ifaddr(context.runtime, Ifaddr, iface, iaddr)); + list.append(context, new Ifaddr(context.runtime, Ifaddr, iface, iaddr)); } } } 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 d91d6cea3c0..f6e903ef133 100644 --- a/core/src/main/java/org/jruby/ext/socket/SocketUtils.java +++ b/core/src/main/java/org/jruby/ext/socket/SocketUtils.java @@ -399,12 +399,12 @@ public static IRubyObject ip_address_list(ThreadContext context) { Ruby runtime = context.runtime; try { - RubyArray list = RubyArray.newArray(runtime); + var list = RubyArray.newArray(runtime); RubyClass addrInfoCls = runtime.getClass("Addrinfo"); for (Enumeration networkIfcs = NetworkInterface.getNetworkInterfaces(); networkIfcs.hasMoreElements() ; ) { for (Enumeration addresses = networkIfcs.nextElement().getInetAddresses(); addresses.hasMoreElements() ; ) { - list.append(new Addrinfo(runtime, addrInfoCls, addresses.nextElement())); + list.append(context, new Addrinfo(runtime, addrInfoCls, addresses.nextElement())); } } diff --git a/core/src/main/java/org/jruby/ext/zlib/JZlibDeflate.java b/core/src/main/java/org/jruby/ext/zlib/JZlibDeflate.java index 1df2f354860..d4e42875ba1 100644 --- a/core/src/main/java/org/jruby/ext/zlib/JZlibDeflate.java +++ b/core/src/main/java/org/jruby/ext/zlib/JZlibDeflate.java @@ -58,31 +58,27 @@ public class JZlibDeflate extends ZStream { private com.jcraft.jzlib.Deflater flater = null; private int flush = JZlib.Z_NO_FLUSH; - @Deprecated + @Deprecated(since = "9.4", forRemoval = true) public static IRubyObject s_deflate(IRubyObject recv, IRubyObject[] args) { return s_deflate(recv.getRuntime().getCurrentContext(), recv, args); } @JRubyMethod(name = "deflate", required = 1, optional = 1, checkArity = false, meta = true) public static IRubyObject s_deflate(ThreadContext context, IRubyObject recv, IRubyObject[] args) { - Ruby runtime = context.runtime; args = Arity.scanArgs(context, args, 1, 1); int level = JZlib.Z_DEFAULT_COMPRESSION; - if (!args[1].isNil()) { - level = RubyNumeric.fix2int(args[1]); - checkLevel(runtime, level); - } + if (!args[1].isNil()) level = checkLevel(context, RubyNumeric.fix2int(args[1])); - RubyClass klass = (RubyClass)(recv.isClass() ? recv : runtime.getClassFromPath("Zlib::Deflate")); + RubyClass klass = (RubyClass)(recv.isClass() ? recv : context.runtime.getClassFromPath("Zlib::Deflate")); JZlibDeflate deflate = (JZlibDeflate) klass.allocate(); - deflate.init(level, JZlib.DEF_WBITS, 8, JZlib.Z_DEFAULT_STRATEGY); + deflate.init(context, level, JZlib.DEF_WBITS, 8, JZlib.Z_DEFAULT_STRATEGY); try { IRubyObject result = deflate.deflate(args[0].convertToString().getByteList(), JZlib.Z_FINISH); deflate.close(); return result; } catch (IOException ioe) { - throw runtime.newIOErrorFromException(ioe); + throw context.runtime.newIOErrorFromException(ioe); } } @@ -98,30 +94,16 @@ public IRubyObject _initialize(IRubyObject[] args) { @JRubyMethod(name = "initialize", optional = 4, checkArity = false, visibility = PRIVATE) public IRubyObject _initialize(ThreadContext context, IRubyObject[] args) { args = Arity.scanArgs(context, args, 0, 4); - level = -1; - windowBits = JZlib.MAX_WBITS; - int memlevel = 8; - strategy = 0; - if (!args[0].isNil()) { - level = RubyNumeric.fix2int(args[0]); - checkLevel(getRuntime(), level); - } - if (!args[1].isNil()) { - windowBits = RubyNumeric.fix2int(args[1]); - checkWindowBits(getRuntime(), windowBits, false); - } - if (!args[2].isNil()) { - memlevel = RubyNumeric.fix2int(args[2]); - // We accepts any memlevel and ignores it. Memory setting means nothing on Java platform. - } - if (!args[3].isNil()) { - strategy = RubyNumeric.fix2int(args[3]); - } - init(level, windowBits, memlevel, strategy); + level = !args[0].isNil() ? checkLevel(context, RubyNumeric.fix2int(args[0])) : -1; + windowBits = !args[1].isNil() ? checkWindowBits(context, RubyNumeric.fix2int(args[1]), false) : JZlib.MAX_WBITS; + int memlevel = !args[2].isNil() ? RubyNumeric.fix2int(args[2]) : 8; // ignored. Memory setting means nothing on Java. + strategy = !args[3].isNil() ? RubyNumeric.fix2int(args[3]) : 0; + + init(context, level, windowBits, memlevel, strategy); return this; } - private void init(int level, int windowBits, int memlevel, int strategy) { + private void init(ThreadContext context, int level, int windowBits, int memlevel, int strategy) { flush = JZlib.Z_NO_FLUSH; flater = new com.jcraft.jzlib.Deflater(); @@ -129,11 +111,11 @@ private void init(int level, int windowBits, int memlevel, int strategy) { // Then we should remove checkLevel, checkWindowsBits and checkStrategy. int err = flater.init(level, windowBits, memlevel); if (err == com.jcraft.jzlib.JZlib.Z_STREAM_ERROR) { - throw RubyZlib.newStreamError(getRuntime(), "stream error"); + throw RubyZlib.newStreamError(context.runtime, "stream error"); } err = flater.params(level, strategy); if (err == com.jcraft.jzlib.JZlib.Z_STREAM_ERROR) { - throw RubyZlib.newStreamError(getRuntime(), "stream error"); + throw RubyZlib.newStreamError(context.runtime, "stream error"); } collected = new byte[BASE_SIZE]; @@ -184,7 +166,7 @@ public IRubyObject append(IRubyObject arg) { @JRubyMethod(name = "params") public IRubyObject params(ThreadContext context, IRubyObject level, IRubyObject strategy) { int l = RubyNumeric.fix2int(level); - checkLevel(getRuntime(), l); + checkLevel(context, l); int s = RubyNumeric.fix2int(strategy); checkStrategy(getRuntime(), s); @@ -277,7 +259,7 @@ protected boolean internalStreamEndP() { @Override protected void internalReset() { - init(level, windowBits, 8, strategy); + init(getRuntime().getCurrentContext(), level, windowBits, 8, strategy); } @Override diff --git a/core/src/main/java/org/jruby/ext/zlib/JZlibInflate.java b/core/src/main/java/org/jruby/ext/zlib/JZlibInflate.java index 0dc9c04cb26..12661340af8 100644 --- a/core/src/main/java/org/jruby/ext/zlib/JZlibInflate.java +++ b/core/src/main/java/org/jruby/ext/zlib/JZlibInflate.java @@ -76,12 +76,8 @@ public IRubyObject _initialize(IRubyObject[] args) { public IRubyObject _initialize(ThreadContext context, IRubyObject[] args) { int argc = Arity.checkArgumentCount(context, args, 0, 1); - windowBits = JZlib.DEF_WBITS; - - if (args.length > 0 && !args[0].isNil()) { - windowBits = RubyNumeric.fix2int(args[0]); - checkWindowBits(context.runtime, windowBits, true); - } + windowBits = argc > 0 && !args[0].isNil() ? + checkWindowBits(context, RubyNumeric.fix2int(args[0]), true) : JZlib.DEF_WBITS; init(windowBits); return this; 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 4e40e5512fb..93677cb9667 100644 --- a/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipReader.java +++ b/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipReader.java @@ -593,7 +593,7 @@ public IRubyObject unused() { @Override @JRubyMethod - public IRubyObject crc() { + public IRubyObject crc(ThreadContext context) { long crc = 0; try { @@ -601,17 +601,17 @@ public IRubyObject crc() { } catch (GZIPException e) { } - return getRuntime().newFixnum(crc); + return newFixnum(context, crc); } @Override @JRubyMethod - public IRubyObject os_code() { + public IRubyObject os_code(ThreadContext context) { int os = io.getOS(); if (os == 255) os = (byte) 0x0b; // NTFS filesystem (NT), because CRuby's test_zlib expect it. - return RubyFixnum.newFixnum(getRuntime(), os & 0xff); + return newFixnum(context, os & 0xff); } @Override diff --git a/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipWriter.java b/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipWriter.java index fa5c27f7573..e762fcccc34 100644 --- a/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipWriter.java +++ b/core/src/main/java/org/jruby/ext/zlib/JZlibRubyGzipWriter.java @@ -341,7 +341,7 @@ public IRubyObject set_mtime(IRubyObject arg) { this.mtime = RubyTime.newTime(runtime, RubyNumeric.fix2long(arg) * 1000); } try { - io.setModifiedTime(this.mtime.to_i().getLongValue()); + io.setModifiedTime(this.mtime.to_i(runtime.getCurrentContext()).getLongValue()); } catch (GZIPException e) { throw RubyZlib.newGzipFileError(runtime, "header is already written"); } @@ -351,7 +351,7 @@ public IRubyObject set_mtime(IRubyObject arg) { @Override @JRubyMethod(name = "crc") - public IRubyObject crc() { + public IRubyObject crc(ThreadContext context) { long crc = 0L; try { diff --git a/core/src/main/java/org/jruby/ext/zlib/RubyZlib.java b/core/src/main/java/org/jruby/ext/zlib/RubyZlib.java index 79a8e368aef..e79476d66cb 100644 --- a/core/src/main/java/org/jruby/ext/zlib/RubyZlib.java +++ b/core/src/main/java/org/jruby/ext/zlib/RubyZlib.java @@ -56,6 +56,7 @@ 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.newFixnum; import static org.jruby.runtime.Visibility.*; import org.jruby.runtime.builtin.IRubyObject; @@ -245,17 +246,28 @@ public static IRubyObject inflate(ThreadContext context, IRubyObject recv, IRuby return JZlibInflate.s_inflate(context, recv, string); } - @JRubyMethod(required = 1, optional = 1, checkArity = false, module = true) + /** + * @param recv + * @param args + * @return "" + * @deprecated Use {@link RubyZlib#deflate(ThreadContext, IRubyObject, IRubyObject[])} instead. + */ + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject deflate(IRubyObject recv, IRubyObject[] args) { - return JZlibDeflate.s_deflate(recv, args); + return deflate(((RubyBasicObject) recv).getRuntime().getCurrentContext(), recv, args); + } + + @JRubyMethod(required = 1, optional = 1, checkArity = false, module = true) + public static IRubyObject deflate(ThreadContext context, IRubyObject recv, IRubyObject[] args) { + return JZlibDeflate.s_deflate(context, recv, args); } @JRubyMethod(name = "crc_table", module = true, visibility = PRIVATE) public static IRubyObject crc_table(ThreadContext context, IRubyObject recv) { int[] table = com.jcraft.jzlib.CRC32.getCRC32Table(); - RubyArray array = context.runtime.newArray(table.length); - for (int i = 0; i < table.length; i++) { - array.append(asFixnum(context, table[i] & 0xffffffffL)); + var array = newArray(context, table.length); + for (int j : table) { + array.append(context, asFixnum(context, j & 0xffffffffL)); } return array; } diff --git a/core/src/main/java/org/jruby/ext/zlib/ZStream.java b/core/src/main/java/org/jruby/ext/zlib/ZStream.java index 946683612be..0d303f8e241 100644 --- a/core/src/main/java/org/jruby/ext/zlib/ZStream.java +++ b/core/src/main/java/org/jruby/ext/zlib/ZStream.java @@ -29,7 +29,6 @@ import com.jcraft.jzlib.JZlib; import org.jruby.Ruby; -import org.jruby.RubyBoolean; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyObject; @@ -192,10 +191,11 @@ void checkClosed() { } // TODO: remove when JZlib checks the given level - static void checkLevel(Ruby runtime, int level) { + static int checkLevel(ThreadContext context, int level) { if ((level < 0 || level > 9) && level != JZlib.Z_DEFAULT_COMPRESSION) { - throw RubyZlib.newStreamError(runtime, "stream error: invalid level"); + throw RubyZlib.newStreamError(context.runtime, "stream error: invalid level"); } + return level; } /** @@ -205,21 +205,23 @@ static void checkLevel(Ruby runtime, int level) { * decompression) and MAX_WBITS + 32(automatic detection of gzip and LZ77). */ // TODO: remove when JZlib checks the given windowBits - static void checkWindowBits(Ruby runtime, int wbits, boolean forInflate) { - wbits = Math.abs(wbits); + static int checkWindowBits(ThreadContext context, int value, boolean forInflate) { + int wbits = Math.abs(value); if ((wbits & 0xf) < 8) { - throw RubyZlib.newStreamError(runtime, "stream error: invalid window bits"); + throw RubyZlib.newStreamError(context.runtime, "stream error: invalid window bits"); } if ((wbits & 0xf) != 0xf) { // windowBits < 15 for reducing memory is meaningless on Java platform. - runtime.getWarnings().warn("windowBits < 15 is ignored on this platform"); + context.runtime.getWarnings().warn("windowBits < 15 is ignored on this platform"); // continue } if (forInflate && wbits > JZlib.MAX_WBITS + 32) { - throw RubyZlib.newStreamError(runtime, "stream error: invalid window bits"); + throw RubyZlib.newStreamError(context.runtime, "stream error: invalid window bits"); } else if (!forInflate && wbits > JZlib.MAX_WBITS + 16) { - throw RubyZlib.newStreamError(runtime, "stream error: invalid window bits"); + throw RubyZlib.newStreamError(context.runtime, "stream error: invalid window bits"); } + + return value; } // TODO: remove when JZlib checks the given strategy 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 db34a30f743..e882948d9c7 100644 --- a/core/src/main/java/org/jruby/ir/runtime/IRRuntimeHelpers.java +++ b/core/src/main/java/org/jruby/ir/runtime/IRRuntimeHelpers.java @@ -511,7 +511,7 @@ public static IRubyObject[] convertValueIntoArgArray(ThreadContext context, IRub switch (signature.arityValue()) { case -1: return signature.opt() > 1 && value instanceof RubyArray ? - ((RubyArray) value).toJavaArray() : + ((RubyArray) value).toJavaArray(context) : new IRubyObject[] { value }; case 0: case 1: @@ -527,7 +527,7 @@ public static IRubyObject[] convertValueIntoArgArray(ThreadContext context, IRub public static IRubyObject[] convertValueIntoArgArray(ThreadContext context, RubyArray array, org.jruby.runtime.Signature signature) { switch (signature.arityValue()) { case -1: - return array.toJavaArray(); + return array.toJavaArray(context); case 0: case 1: return signature.rest() == org.jruby.runtime.Signature.Rest.ANON ? @@ -1788,7 +1788,7 @@ public static RubyModule newRubyClassFromIR(ThreadContext context, String id, St if (superClass == UNDEFINED) { sc = null; } else { - RubyClass.checkInheritable((IRubyObject) superClass); + RubyClass.checkInheritable(context, (IRubyObject) superClass); sc = (RubyClass) superClass; } @@ -2188,7 +2188,7 @@ public static IRubyObject[] toAry(ThreadContext context, IRubyObject[] args) { IRubyObject ary; if (args.length == 1 && (ary = Helpers.aryOrToAry(context, args[0])) != context.nil) { if (!(ary instanceof RubyArray)) throw typeError(context, "", args[0], "#to_ary should return Array"); - args = ((RubyArray) ary).toJavaArray(); + args = ((RubyArray) ary).toJavaArray(context); } return args; } @@ -2407,7 +2407,7 @@ public static RubyProc newSymbolProc(ThreadContext context, RubySymbol symbol) { @JIT public static IRubyObject[] singleBlockArgToArray(IRubyObject value) { return value instanceof RubyArray ? - ((RubyArray) value).toJavaArray() : + ((RubyArray) value).toJavaArray(value.getRuntime().getCurrentContext()) : new IRubyObject[] { value }; } @@ -2577,9 +2577,7 @@ public static void putConst(ThreadContext context, IRubyObject self, IRubyObject } private static void putConst(ThreadContext context, IRubyObject self, IRubyObject module, String id, IRubyObject value, String filename, int line) { - if (!(module instanceof RubyModule)) { - throw context.getRuntime().newTypeError("" + module.inspect() + " is not a class/module"); - } + if (!(module instanceof RubyModule)) throw typeError(context, module.inspect() + " is not a class/module"); warnSetConstInRefinement(context, self); 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 98264b036b0..a42541fbf89 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,7 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; +import static org.jruby.api.Create.newFixnum; import static org.jruby.api.Error.typeError; public class ArrayJavaAddons { @@ -89,7 +90,7 @@ public static IRubyObject dimensions(ThreadContext context, IRubyObject rubyArra } assert dims instanceof RubyArray; - return calcDimensions(runtime, (RubyArray) rubyArray, (RubyArray) dims, 0); + return calcDimensions(context, (RubyArray) rubyArray, (RubyArray) dims, 0); } @JRubyMethod @@ -102,25 +103,25 @@ public static IRubyObject dimensions(ThreadContext context, IRubyObject rubyArra assert index instanceof RubyFixnum; final int i = (int) ((RubyFixnum) index).getLongValue(); - return calcDimensions(runtime, (RubyArray) rubyArray, (RubyArray) dims, i); + return calcDimensions(context, (RubyArray) rubyArray, (RubyArray) dims, i); } - private static RubyArray calcDimensions(final Ruby runtime, - final RubyArray array, final RubyArray dims, final int index) { + private static RubyArray calcDimensions(ThreadContext context, + final RubyArray array, final RubyArray dims, final int index) { while ( dims.size() <= index ) { - dims.append( RubyFixnum.zero(runtime) ); + dims.append(context, RubyFixnum.zero(context.runtime) ); } final long dim = ((RubyFixnum) dims.eltInternal(index)).getLongValue(); if ( array.size() > dim ) { - dims.eltInternalSet(index, RubyFixnum.newFixnum(runtime, array.size())); + dims.eltInternalSet(index, newFixnum(context, array.size())); } for ( int i = 0; i < array.size(); i++ ) { final IRubyObject element = array.eltInternal(i); if ( element instanceof RubyArray ) { - calcDimensions(runtime, (RubyArray) element, dims, 1); + calcDimensions(context, (RubyArray) element, dims, 1); } } diff --git a/core/src/main/java/org/jruby/java/proxies/JavaInterfaceTemplate.java b/core/src/main/java/org/jruby/java/proxies/JavaInterfaceTemplate.java index 287a137d1e7..16b4f52c461 100644 --- a/core/src/main/java/org/jruby/java/proxies/JavaInterfaceTemplate.java +++ b/core/src/main/java/org/jruby/java/proxies/JavaInterfaceTemplate.java @@ -147,7 +147,7 @@ private static void appendFeaturesToClass(ThreadContext context, final IRubyObje // to the list of intentions unless we're past the point of no return or // already intend to implement the given interface if ( ! ( javaInterfaces.isFrozen() || javaInterfaces.includes(context, javaClass) ) ) { - javaInterfaces.append(javaClass); + javaInterfaces.append(context, javaClass); } } } @@ -331,9 +331,9 @@ private static void appendFeaturesToModule(ThreadContext context, final IRubyObj } else { // already set up append_features, just add the interface if we haven't already - final RubyArray interfaceModules = getInterfaceModules(module); + final var interfaceModules = getInterfaceModules(module); if ( ! interfaceModules.includes(context, self) ) { - interfaceModules.append(self); + interfaceModules.append(context, self); } } } @@ -346,7 +346,7 @@ private static class AppendFeatures extends JavaMethodOneBlock { @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg, Block block) { RubyModule target = castAsModule(context, arg, "append_features called with non-module"); - target.include( getInterfaceModules(self).toJavaArrayMaybeUnsafe() ); + target.include(context, getInterfaceModules(self).toJavaArrayMaybeUnsafe() ); return Helpers.invokeAs(context, clazz.getSuperClass(), self, name, arg, block); } diff --git a/core/src/main/java/org/jruby/javasupport/Java.java b/core/src/main/java/org/jruby/javasupport/Java.java index 0d5bdb0e222..c95164c37aa 100644 --- a/core/src/main/java/org/jruby/javasupport/Java.java +++ b/core/src/main/java/org/jruby/javasupport/Java.java @@ -1361,23 +1361,37 @@ public static IRubyObject java_to_primitive(IRubyObject recv, IRubyObject object return JavaUtil.java_to_primitive(recv, object, unusedBlock); } - // TODO: Formalize conversion mechanisms between Java and Ruby - @JRubyMethod(required = 2, module = true, visibility = PRIVATE) + /** + * @param recv + * @param wrapper + * @param interfaces + * @param block + * @return "" + * @deprecated Use + */ + @Deprecated(since = "10.0", forRemoval = true) public static IRubyObject new_proxy_instance2(IRubyObject recv, final IRubyObject wrapper, final IRubyObject interfaces, Block block) { - IRubyObject[] javaClasses = ((RubyArray) interfaces).toJavaArray(); + return new_proxy_instance2(recv.getRuntime().getCurrentContext(), recv, wrapper, interfaces, block); + } + + // TODO: Formalize conversion mechanisms between Java and Ruby + @JRubyMethod(required = 2, module = true, visibility = PRIVATE) + public static IRubyObject new_proxy_instance2(ThreadContext context, IRubyObject recv, final IRubyObject wrapper, + final IRubyObject interfaces, Block block) { + IRubyObject[] javaClasses = ((RubyArray) interfaces).toJavaArray(context); // Create list of interface names to proxy (and make sure they really are interfaces) Class[] unwrapped = new Class[javaClasses.length]; for (int i = 0; i < javaClasses.length; i++) { final Class klass = JavaUtil.unwrapJava(javaClasses[i]); // TypeError if not a Java wrapper - if (!klass.isInterface()) { - throw recv.getRuntime().newArgumentError("Java interface expected, got: " + klass); - } + + if (!klass.isInterface()) throw argumentError(context, "Java interface expected, got: " + klass); + unwrapped[i] = klass; } - return getInstance(recv.getRuntime(), newInterfaceImpl(wrapper, unwrapped)); + return getInstance(context.runtime, newInterfaceImpl(wrapper, unwrapped)); } public static Object newInterfaceImpl(final IRubyObject wrapper, Class[] interfaces) { diff --git a/core/src/main/java/org/jruby/javasupport/JavaArray.java b/core/src/main/java/org/jruby/javasupport/JavaArray.java index f438b0a6ae4..f577a8886b6 100644 --- a/core/src/main/java/org/jruby/javasupport/JavaArray.java +++ b/core/src/main/java/org/jruby/javasupport/JavaArray.java @@ -39,8 +39,6 @@ import org.jruby.java.util.ArrayUtils; import org.jruby.runtime.builtin.IRubyObject; -import static org.jruby.api.Convert.castAsInteger; -import static org.jruby.api.Error.typeError; import static org.jruby.javasupport.Java.castToJavaObject; /** diff --git a/core/src/main/java/org/jruby/javasupport/JavaEmbedUtils.java b/core/src/main/java/org/jruby/javasupport/JavaEmbedUtils.java index 9afc7cdf0cc..8bd64d0db45 100644 --- a/core/src/main/java/org/jruby/javasupport/JavaEmbedUtils.java +++ b/core/src/main/java/org/jruby/javasupport/JavaEmbedUtils.java @@ -100,7 +100,7 @@ public IRubyObject setInstanceVariable(IRubyObject obj, String variableName, IRu } public IRubyObject[] convertToJavaArray(IRubyObject array) { - return ((RubyArray) array).toJavaArray(); + return ((RubyArray) array).toJavaArray(array.getRuntime().getCurrentContext()); } public RubyInteger convertToRubyInteger(IRubyObject obj) { 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 3efe6f34769..8ef7be2407a 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/JavaLang.java +++ b/core/src/main/java/org/jruby/javasupport/ext/JavaLang.java @@ -146,13 +146,10 @@ 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 Ruby runtime = context.runtime; - final RubyArray ary = runtime.newArray(); - java.lang.Iterable iterable = unwrapIfJavaObject(self); - java.util.Iterator iterator = iterable.iterator(); - while ( iterator.hasNext() ) { - final Object value = iterator.next(); - ary.append( convertJavaToUsableRubyObject(runtime, value) ); + final var ary = context.runtime.newArray(); + java.lang.Iterable iterable = unwrapIfJavaObject(self); + for (Object o: iterable) { + ary.append(context, convertJavaToUsableRubyObject(context.runtime, o)); } return ary; } @@ -908,7 +905,7 @@ public IRubyObject call(final ThreadContext context, final IRubyObject self, fin // <#Java::JavaLang::Thread:760 [foo] bar TIMED_WAITING> RubyString buf = inspectPrefix(context, self.getMetaClass()); - RubyStringBuilder.cat(context.runtime, buf, Long.toString(thread.getId())); + RubyStringBuilder.cat(context.runtime, buf, Long.toString(thread.threadId())); RubyStringBuilder.cat(context.runtime, buf, ' '); RubyStringBuilder.cat(context.runtime, buf, thread.getName()); RubyStringBuilder.cat(context.runtime, buf, ' '); diff --git a/core/src/main/java/org/jruby/javasupport/ext/JavaLangReflect.java b/core/src/main/java/org/jruby/javasupport/ext/JavaLangReflect.java index cfe5bb4344d..dbc9e29089b 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/JavaLangReflect.java +++ b/core/src/main/java/org/jruby/javasupport/ext/JavaLangReflect.java @@ -96,14 +96,14 @@ public static IRubyObject return_type(final ThreadContext context, final IRubyOb @JRubyMethod // alias argument_types parameter_types public static IRubyObject argument_types(final ThreadContext context, final IRubyObject self) { - final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); + final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); return convertJavaToUsableRubyObject(context.runtime, thiz.getParameterTypes()); } // NOTE: (legacy) JavaConstructor compat - converting arguments @JRubyMethod(name = {"newInstance", "new_instance"}, rest = true) public static IRubyObject new_instance(final ThreadContext context, final IRubyObject self, final IRubyObject[] args) { - final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); + final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); final Object[] javaArgs; if (args.length == 0) { javaArgs = NO_ARGS; @@ -122,18 +122,18 @@ public static IRubyObject new_instance(final ThreadContext context, final IRubyO @JRubyMethod(name = "public?") public static IRubyObject public_p(ThreadContext context, final IRubyObject self) { - final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); + final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); return isPublic(context, self, thiz.getModifiers()); } - @Deprecated + @Deprecated(since = "9.4", forRemoval = true) public static IRubyObject public_p(final IRubyObject self) { - return public_p(((RubyBasicObject) self).getCurrentContext(), self); + return public_p(self.getRuntime().getCurrentContext(), self); } @JRubyMethod(name = "protected?") public static IRubyObject protected_p(ThreadContext context, final IRubyObject self) { - final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); + final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); return isProtected(context, self, thiz.getModifiers()); } @@ -144,7 +144,7 @@ public static IRubyObject protected_p(final IRubyObject self) { @JRubyMethod(name = "private?") public static IRubyObject private_p(ThreadContext context, final IRubyObject self) { - final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); + final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); return isPrivate(context, self, thiz.getModifiers()); } @@ -155,7 +155,7 @@ public static IRubyObject private_p(final IRubyObject self) { @JRubyMethod(name = "final?") public static IRubyObject final_p(ThreadContext context, final IRubyObject self) { - final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); + final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); return isFinal(context, self, thiz.getModifiers()); } @@ -166,7 +166,7 @@ public static IRubyObject final_p(final IRubyObject self) { @JRubyMethod(name = "static?") public static IRubyObject static_p(ThreadContext context, final IRubyObject self) { - final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); + final java.lang.reflect.Constructor thiz = JavaUtil.unwrapJavaObject(self); return isStatic(context, self, thiz.getModifiers()); } @@ -298,7 +298,7 @@ public static IRubyObject static_p(ThreadContext context, final IRubyObject self } public static IRubyObject static_p(final IRubyObject self) { - return static_p(((RubyBasicObject) self).getCurrentContext(), self); + return static_p(self.getRuntime().getCurrentContext(), self); } } 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 ffbf7711921..eadbd5eaced 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/JavaMath.java +++ b/core/src/main/java/org/jruby/javasupport/ext/JavaMath.java @@ -65,7 +65,7 @@ public static IRubyObject to_d(ThreadContext context, IRubyObject self) { @JRubyMethod(name = "to_f") // override from java.lang.Number public static IRubyObject to_f(ThreadContext context, IRubyObject self) { - return asRubyBigDecimal(context.runtime, unwrapIfJavaObject(self)).to_f(); + return asRubyBigDecimal(context.runtime, unwrapIfJavaObject(self)).to_f(context); } @JRubyMethod(name = { "to_i", "to_int" }) // override from java.lang.Number diff --git a/core/src/main/java/org/jruby/javasupport/ext/JavaUtil.java b/core/src/main/java/org/jruby/javasupport/ext/JavaUtil.java index 4e45a93a967..41832d67d64 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/JavaUtil.java +++ b/core/src/main/java/org/jruby/javasupport/ext/JavaUtil.java @@ -46,8 +46,7 @@ import static org.jruby.RubyEnumerator.enumeratorize; import static org.jruby.api.Convert.asBoolean; -import static org.jruby.api.Create.newFixnum; -import static org.jruby.api.Create.newString; +import static org.jruby.api.Create.*; import static org.jruby.javasupport.JavaUtil.convertJavaArrayToRuby; import static org.jruby.javasupport.JavaUtil.convertJavaToUsableRubyObject; import static org.jruby.javasupport.JavaUtil.inspectObject; @@ -161,14 +160,13 @@ public static IRubyObject first(final ThreadContext context, final IRubyObject s @JRubyMethod(name = { "first", "ruby_first" }) // re-def Enumerable#first(n) public static IRubyObject first(final ThreadContext context, final IRubyObject self, final IRubyObject count) { - final java.util.Collection coll = unwrapIfJavaObject(self); + final java.util.Collection coll = unwrapIfJavaObject(self); int len = count.convertToInteger().getIntValue(); int size = coll.size(); if ( len > size ) len = size; - final Ruby runtime = context.runtime; - if ( len == 0 ) return RubyArray.newEmptyArray(runtime); - final RubyArray arr = RubyArray.newArray(runtime, len); - int i = 0; for ( java.util.Iterator it = coll.iterator(); i < len; i++ ) { - arr.append( convertJavaToUsableRubyObject(runtime, it.next() ) ); + if ( len == 0 ) return RubyArray.newEmptyArray(context.runtime); + final var arr = newArray(context, len); + int i = 0; for ( java.util.Iterator it = coll.iterator(); i < len; i++ ) { + arr.append(context, convertJavaToUsableRubyObject(context.runtime, it.next())); } return arr; } 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 fb94e650742..8f8fbd60670 100644 --- a/core/src/main/java/org/jruby/javasupport/ext/JavaUtilRegex.java +++ b/core/src/main/java/org/jruby/javasupport/ext/JavaUtilRegex.java @@ -231,7 +231,7 @@ public static IRubyObject aref(final ThreadContext context, final IRubyObject se @JRubyMethod(rest = true) public static IRubyObject values_at(final ThreadContext context, final IRubyObject self, final IRubyObject[] args) { - return to_a(context, self).values_at(args); + return to_a(context, self).values_at(context, args); } } diff --git a/core/src/main/java/org/jruby/lexer/ByteListLexerSource.java b/core/src/main/java/org/jruby/lexer/ByteListLexerSource.java index 8bf8d6270b0..6410db570d9 100644 --- a/core/src/main/java/org/jruby/lexer/ByteListLexerSource.java +++ b/core/src/main/java/org/jruby/lexer/ByteListLexerSource.java @@ -7,7 +7,6 @@ import org.jcodings.Encoding; import org.jruby.RubyArray; import org.jruby.RubyIO; -import org.jruby.RubyString; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; import org.jruby.util.io.ChannelHelper; @@ -15,6 +14,8 @@ import java.io.ByteArrayInputStream; import java.nio.channels.Channel; +import static org.jruby.api.Create.newString; + /** * Lexer source for ripper when we have all bytes available to us. */ @@ -57,7 +58,11 @@ public ByteList gets() { ByteList line = completeSource.makeShared(offset, end - offset); offset = end; - if (scriptLines != null) scriptLines.append(RubyString.newString(scriptLines.getRuntime(), line)); + + if (scriptLines != null) { + var context = scriptLines.getRuntime().getCurrentContext(); + scriptLines.append(context, newString(context, line)); + } return line; } diff --git a/core/src/main/java/org/jruby/lexer/GetsLexerSource.java b/core/src/main/java/org/jruby/lexer/GetsLexerSource.java index bc250915286..9b233daf308 100644 --- a/core/src/main/java/org/jruby/lexer/GetsLexerSource.java +++ b/core/src/main/java/org/jruby/lexer/GetsLexerSource.java @@ -17,6 +17,8 @@ import java.nio.channels.Channel; import java.nio.channels.Channels; +import static org.jruby.api.Create.newString; + /** * Lexer source from ripper getting a line at a time via 'gets' calls. */ @@ -65,7 +67,8 @@ public void setEncoding(Encoding encoding) { @Override public ByteList gets() { - IRubyObject result = io.callMethod(io.getRuntime().getCurrentContext(), "gets"); + var context = io.getRuntime().getCurrentContext(); + IRubyObject result = io.callMethod(context, "gets"); if (result.isNil()) return null; @@ -73,7 +76,7 @@ public ByteList gets() { offset += bytelist.getRealSize(); bytelist.setEncoding(encoding); - if (scriptLines != null) scriptLines.append(RubyString.newString(scriptLines.getRuntime(), bytelist)); + if (scriptLines != null) scriptLines.append(context, newString(context, bytelist)); return bytelist; } diff --git a/core/src/main/java/org/jruby/management/BeanManagerImpl.java b/core/src/main/java/org/jruby/management/BeanManagerImpl.java index 65936c22d99..0f48b451d72 100644 --- a/core/src/main/java/org/jruby/management/BeanManagerImpl.java +++ b/core/src/main/java/org/jruby/management/BeanManagerImpl.java @@ -2,7 +2,6 @@ import java.lang.management.ManagementFactory; import java.lang.reflect.Method; -import java.security.AccessControlException; import java.text.SimpleDateFormat; import java.util.Date; @@ -84,7 +83,7 @@ public void unregisterInlineStats() { public boolean tryShutdownAgent() { try { - Class agent = Class.forName("sun.management.Agent"); + Class agent = Class.forName("sun.management.Agent"); Method shutdown = agent.getDeclaredMethod("stopRemoteManagementAgent"); Java.trySetAccessible(shutdown); shutdown.invoke(null); @@ -96,7 +95,7 @@ public boolean tryShutdownAgent() { public boolean tryRestartAgent() { try { - Class agent = Class.forName("sun.management.Agent"); + Class agent = Class.forName("sun.management.Agent"); Method start = agent.getMethod("startAgent"); Java.trySetAccessible(start); start.invoke(null); @@ -114,17 +113,9 @@ private void register(String name, Object bean) { mbs.registerMBean(bean, beanName); } catch (InstanceAlreadyExistsException ex) { LOG.warn("mbean already registered: {}", name); - } catch (MBeanRegistrationException ex) { + } catch (MBeanRegistrationException | NotCompliantMBeanException | MalformedObjectNameException | + NullPointerException ex) { LOG.error(ex); - } catch (NotCompliantMBeanException ex) { - LOG.error(ex); - } catch (MalformedObjectNameException ex) { - LOG.error(ex); - } catch (NullPointerException ex) { - LOG.error(ex); - } catch (AccessControlException ex) { - // ignore...bean doesn't get registered - // TODO: Why does that bother me? } catch (SecurityException ex) { // ignore...bean doesn't get registered // TODO: Why does that bother me? @@ -142,15 +133,8 @@ private void unregister(String name) { ObjectName beanName = new ObjectName(name); mbs.unregisterMBean(beanName); } catch (InstanceNotFoundException ex) { - } catch (MBeanRegistrationException ex) { + } catch (MBeanRegistrationException | NullPointerException | MalformedObjectNameException ex) { LOG.error(ex); - } catch (MalformedObjectNameException ex) { - LOG.error(ex); - } catch (NullPointerException ex) { - LOG.error(ex); - } catch (AccessControlException ex) { - // ignore...bean doesn't get registered - // TODO: Why does that bother me? } catch (SecurityException ex) { // ignore...bean doesn't get registered // TODO: Why does that bother me? diff --git a/core/src/main/java/org/jruby/parser/Parser.java b/core/src/main/java/org/jruby/parser/Parser.java index 96aafb2c855..283cdd072cc 100644 --- a/core/src/main/java/org/jruby/parser/Parser.java +++ b/core/src/main/java/org/jruby/parser/Parser.java @@ -88,7 +88,7 @@ public ParseResult parse(String fileName, int lineNumber, ByteList content, Dyna protected ParseResult parse(String fileName, int lineNumber, InputStream in, Encoding encoding, DynamicScope existingScope, ParserType type) { - RubyArray list = getLines(type == EVAL, fileName, -1); + var list = getLines(type == EVAL, fileName, -1); if (in instanceof LoadServiceResourceInputStream) { ByteList source = new ByteList(((LoadServiceResourceInputStream) in).getBytes(), encoding); @@ -138,7 +138,7 @@ private ParseResult parse(LexerSource lexerSource, DynamicScope existingScope, P public Node parse(String file, ByteList content, DynamicScope blockScope, ParserConfiguration configuration) { configuration.setDefaultEncoding(content.getEncoding()); - RubyArray list = getLines(configuration.isEvalParse(), file, -1); + var list = getLines(configuration.isEvalParse(), file, -1); LexerSource lexerSource = new ByteListLexerSource(file, configuration.getLineNumber(), content, list); return parse(file, lexerSource, blockScope, configuration); } @@ -146,7 +146,7 @@ public Node parse(String file, ByteList content, DynamicScope blockScope, @Deprecated public Node parse(String file, byte[] content, DynamicScope blockScope, ParserConfiguration configuration) { - RubyArray list = getLines(configuration.isEvalParse(), file, -1); + var list = getLines(configuration.isEvalParse(), file, -1); ByteList in = new ByteList(content, configuration.getDefaultEncoding()); LexerSource lexerSource = new ByteListLexerSource(file, configuration.getLineNumber(), in, list); return parse(file, lexerSource, blockScope, configuration); @@ -158,7 +158,7 @@ public Node parse(String file, InputStream content, DynamicScope blockScope, if (content instanceof LoadServiceResourceInputStream) { return parse(file, ((LoadServiceResourceInputStream) content).getBytes(), blockScope, configuration); } else { - RubyArray list = getLines(configuration.isEvalParse(), file, -1); + var list = getLines(configuration.isEvalParse(), file, -1); boolean requiresClosing = false; RubyIO io; if (content instanceof FileInputStream) { @@ -217,25 +217,25 @@ public Node parse(String file, LexerSource lexerSource, DynamicScope blockScope, return result.getAST(); } - protected RubyArray getLines(boolean isEvalParse, String file, int length) { + protected RubyArray getLines(boolean isEvalParse, String file, int length) { if (isEvalParse && !runtime.getCoverageData().isEvalCovered()) return null; IRubyObject scriptLines = runtime.getObject().getConstantAt("SCRIPT_LINES__"); - if (scriptLines == null || !(scriptLines instanceof RubyHash)) return null; + if (!(scriptLines instanceof RubyHash)) return null; - RubyArray list = length == -1 ? runtime.newArray() : runtime.newArray(length); + var list = length == -1 ? runtime.newArray() : runtime.newArray(length); ThreadContext context = runtime.getCurrentContext(); ((RubyHash) scriptLines).op_aset(context, newString(context, file), list); return list; } public IRubyObject getLineStub(ThreadContext context, ParseResult result, int lineCount) { - RubyArray lines = context.runtime.newArray(); + var lines = context.runtime.newArray(); LineStubVisitor lineVisitor = new LineStubVisitor(context.runtime, lines); lineVisitor.visitRootNode(((RootNode) result)); for (int i = 0; i <= lineCount - lines.size(); i++) { - lines.append(context.nil); + lines.append(context, context.nil); } return lines; } diff --git a/core/src/main/java/org/jruby/parser/StaticScope.java b/core/src/main/java/org/jruby/parser/StaticScope.java index ac438fc465a..822b8ad8279 100644 --- a/core/src/main/java/org/jruby/parser/StaticScope.java +++ b/core/src/main/java/org/jruby/parser/StaticScope.java @@ -65,6 +65,8 @@ import org.jruby.runtime.scope.DynamicScopeGenerator; import org.jruby.runtime.scope.ManyVarsDynamicScope; +import static org.jruby.api.Create.newSymbol; + /** * StaticScope represents lexical scoping of variables and module/class constants. * @@ -457,18 +459,28 @@ public T collectVariables(IntFunction collectionFactory, BiConsumer { - RubySymbol symbol = runtime.newSymbol(id); - if (symbol.validLocalVariableName()) array.append(symbol); + RubySymbol symbol = newSymbol(context, id); + if (symbol.validLocalVariableName()) array.append(context, symbol); }); } diff --git a/core/src/main/java/org/jruby/runtime/Helpers.java b/core/src/main/java/org/jruby/runtime/Helpers.java index d3a34d88db3..dcfcd8601f1 100644 --- a/core/src/main/java/org/jruby/runtime/Helpers.java +++ b/core/src/main/java/org/jruby/runtime/Helpers.java @@ -2019,31 +2019,31 @@ public static IRubyObject[] splatToArguments(IRubyObject value) { IRubyObject tmp = value.checkArrayType(); if (tmp.isNil()) { - return convertSplatToJavaArray(value.getRuntime(), value); + return convertSplatToJavaArray(value.getRuntime().getCurrentContext(), value); } return ((RubyArray)tmp).toJavaArrayMaybeUnsafe(); } - private static IRubyObject[] convertSplatToJavaArray(Ruby runtime, IRubyObject value) { + private static IRubyObject[] convertSplatToJavaArray(ThreadContext context, IRubyObject value) { // Object#to_a is obsolete. We match Ruby's hack until to_a goes away. Then we can // remove this hack too. RubyClass metaClass = value.getMetaClass(); CacheEntry entry = metaClass.searchWithCache("to_a"); DynamicMethod method = entry.method; - if (method.isUndefined() || method.isImplementedBy(runtime.getKernel())) { + if (method.isUndefined() || method.isImplementedBy(context.runtime.getKernel())) { return new IRubyObject[] {value}; } - IRubyObject avalue = method.call(runtime.getCurrentContext(), value, entry.sourceModule, "to_a"); + IRubyObject avalue = method.call(context, value, entry.sourceModule, "to_a"); if (!(avalue instanceof RubyArray)) { if (avalue.isNil()) { return new IRubyObject[] {value}; } else { - throw typeError(runtime.getCurrentContext(), "`to_a' did not return Array"); + throw typeError(context, "`to_a' did not return Array"); } } - return ((RubyArray)avalue).toJavaArray(); + return ((RubyArray)avalue).toJavaArray(context); } @SuppressWarnings("deprecation") @Deprecated // no longer used @@ -2532,7 +2532,7 @@ public static int[] decodeCaptureOffsets(String encoded) { @Deprecated public static RubyArray argsPush(ThreadContext context, RubyArray first, IRubyObject second) { - return ((RubyArray)first.dup()).append(second); + return ((RubyArray)first.dup()).append(context, second); } @JIT @Interp @@ -2545,7 +2545,7 @@ public static RubyArray argsPush(ThreadContext context, IRubyObject first, IRuby return array; } - return ((RubyArray)first.dup()).append(second); + return ((RubyArray)first.dup()).append(context, second); } public static RubyArray argsCat(ThreadContext context, IRubyObject first, IRubyObject second) { @@ -3122,6 +3122,7 @@ public static String javaStringFromPath(Ruby runtime, IRubyObject loadPathEntry) * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject[] args, CallType callType, Block block) { return self.getMetaClass().invoke(context, self, name, args, callType, block); } @@ -3134,6 +3135,7 @@ public static IRubyObject invoke(ThreadContext context, IRubyObject self, String * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, IRubyObject arg, CallType callType, Block block) { return self.getMetaClass().invoke(context, self, name, arg, callType, block); } @@ -3146,6 +3148,7 @@ public static IRubyObject invoke(ThreadContext context, IRubyObject self, String * * @deprecated Use finvoke if you do not want visibility-checking or invokeFrom if you do. */ + @Deprecated(since = "9.4-", forRemoval = true) public static IRubyObject invoke(ThreadContext context, IRubyObject self, String name, CallType callType) { return Helpers.invoke(context, self, name, IRubyObject.NULL_ARRAY, callType, Block.NULL_BLOCK); } diff --git a/core/src/main/java/org/jruby/runtime/IRBlockBody.java b/core/src/main/java/org/jruby/runtime/IRBlockBody.java index 52e3404aa4c..0d400a8d758 100644 --- a/core/src/main/java/org/jruby/runtime/IRBlockBody.java +++ b/core/src/main/java/org/jruby/runtime/IRBlockBody.java @@ -83,15 +83,15 @@ public IRubyObject yieldSpecific(ThreadContext context, Block block) { public IRubyObject yieldSpecific(ThreadContext context, Block block, IRubyObject arg0) { IRubyObject[] args; if (canCallDirect()) { - if (arg0 instanceof RubyArray) { // Unwrap the array arg - args = IRRuntimeHelpers.convertValueIntoArgArray(context, (RubyArray) arg0, signature); + if (arg0 instanceof RubyArray ary) { // Unwrap the array arg + args = IRRuntimeHelpers.convertValueIntoArgArray(context, ary, signature); } else { args = new IRubyObject[] { arg0 }; } return yieldDirect(context, block, args, null); } else { - if (arg0 instanceof RubyArray) { // Unwrap the array arg - args = IRRuntimeHelpers.convertValueIntoArgArray(context, (RubyArray) arg0, signature); + if (arg0 instanceof RubyArray ary) { // Unwrap the array arg + args = IRRuntimeHelpers.convertValueIntoArgArray(context, ary, signature); // FIXME: arity error is against new args but actual error shows arity of original args. if (block.type == Block.Type.LAMBDA) signature.checkArity(context.runtime, args); @@ -131,7 +131,7 @@ public IRubyObject yieldSpecific(ThreadContext context, Block block, IRubyObject public static IRubyObject[] toAry(ThreadContext context, IRubyObject value) { final IRubyObject ary = Helpers.aryToAry(context, value); - if (ary instanceof RubyArray) return ((RubyArray) ary).toJavaArray(); + if (ary instanceof RubyArray array) return array.toJavaArray(context); if (ary == context.nil) return new IRubyObject[] { value }; throw typeError(context, "", value, "#to_ary should return Array"); diff --git a/core/src/main/java/org/jruby/runtime/backtrace/TraceType.java b/core/src/main/java/org/jruby/runtime/backtrace/TraceType.java index bf5b862b2a0..9d5029ffe98 100644 --- a/core/src/main/java/org/jruby/runtime/backtrace/TraceType.java +++ b/core/src/main/java/org/jruby/runtime/backtrace/TraceType.java @@ -94,6 +94,7 @@ public static void logException(RubyException exception) { /** * @deprecated use {@link #logException(org.jruby.RubyException)} */ + @Deprecated(since = "9.4-", forRemoval = true) public static void dumpException(RubyException exception) { logException(exception); } @@ -119,6 +120,7 @@ public static void logCaller(RubyArray trace) { /** * @deprecated use {@link #logCaller(org.jruby.RubyArray)} */ + @Deprecated(since = "9.4-", forRemoval = true) public static void dumpCaller(RubyArray trace) { logCaller(trace); } @@ -142,6 +144,7 @@ private static StringBuilder formatWithMRIBacktrace(final String message, RubySt /** * @deprecated use {@link #logCaller(org.jruby.runtime.backtrace.RubyStackTraceElement[]) } */ + @Deprecated(since = "9.4-", forRemoval = true) public static void dumpCaller(RubyStackTraceElement[] trace) { logCaller(trace); } @@ -155,6 +158,7 @@ public static void logWarning(RubyStackTraceElement[] trace) { /** * @deprecated use {@link #logWarning(org.jruby.runtime.backtrace.RubyStackTraceElement[])} */ + @Deprecated(since = "9.4-", forRemoval = true) public static void dumpWarning(RubyStackTraceElement[] trace) { logWarning(trace); } diff --git a/core/src/main/java/org/jruby/runtime/callsite/AsetCallSite.java b/core/src/main/java/org/jruby/runtime/callsite/AsetCallSite.java index 71d68f83710..93c9ffdec21 100644 --- a/core/src/main/java/org/jruby/runtime/callsite/AsetCallSite.java +++ b/core/src/main/java/org/jruby/runtime/callsite/AsetCallSite.java @@ -13,9 +13,7 @@ public AsetCallSite() { @Override public IRubyObject call(ThreadContext context, IRubyObject caller, IRubyObject self, IRubyObject arg0, IRubyObject arg1) { - if (getMetaClass(self) == context.runtime.getArray()) { - return ((RubyArray) self).aset(arg0, arg1); - } - return super.call(context, caller, self, arg0, arg1); + return getMetaClass(self) == context.runtime.getArray() ? + ((RubyArray) self).aset(context, arg0, arg1) : super.call(context, caller, self, arg0, arg1); } } diff --git a/core/src/main/java/org/jruby/runtime/callsite/NormalCachingCallSite.java b/core/src/main/java/org/jruby/runtime/callsite/NormalCachingCallSite.java index 5b3bbebeef3..0298788aa39 100644 --- a/core/src/main/java/org/jruby/runtime/callsite/NormalCachingCallSite.java +++ b/core/src/main/java/org/jruby/runtime/callsite/NormalCachingCallSite.java @@ -5,6 +5,7 @@ /** * @deprecated replaced with {@link MonomorphicCallSite} */ +@Deprecated(since = "9.4-") public class NormalCachingCallSite extends CachingCallSite { public NormalCachingCallSite(String methodName) { diff --git a/core/src/main/java/org/jruby/runtime/ivars/VariableTableManager.java b/core/src/main/java/org/jruby/runtime/ivars/VariableTableManager.java index 8c50497e11f..757c741450f 100644 --- a/core/src/main/java/org/jruby/runtime/ivars/VariableTableManager.java +++ b/core/src/main/java/org/jruby/runtime/ivars/VariableTableManager.java @@ -683,6 +683,7 @@ synchronized final VariableAccessor allocateVariableAccessors(String name, Funct * @return the lazy accessor for object_id * @deprecated Use {@link #getObjectIdAccessorForRead()} or {@link #getObjectIdAccessorForWrite()} */ + @Deprecated(since = "9.4-", forRemoval = true) public VariableAccessorField getObjectIdAccessorField() { return objectIdVariableAccessorField; } @@ -693,6 +694,7 @@ public VariableAccessorField getObjectIdAccessorField() { * @return the lazy accessor for FFI handle * @deprecated Use {@link #getFFIHandleAccessorForRead()} or {@link #getFFIHandleAccessorForWrite()} */ + @Deprecated(since = "9.4-", forRemoval = true) public VariableAccessorField getFFIHandleAccessorField() { return ffiHandleVariableAccessorField; } @@ -703,6 +705,7 @@ public VariableAccessorField getFFIHandleAccessorField() { * @return the lazy accessor for object group * @deprecated Use {@link #getObjectGroupAccessorForRead()} or {@link #getObjectGroupAccessorForWrite()} */ + @Deprecated(since = "9.4-", forRemoval = true) public VariableAccessorField getObjectGroupAccessorField() { return objectGroupVariableAccessorField; } diff --git a/core/src/main/java/org/jruby/runtime/load/LibrarySearcher.java b/core/src/main/java/org/jruby/runtime/load/LibrarySearcher.java index 96500bb034a..44f8ea1ad6a 100644 --- a/core/src/main/java/org/jruby/runtime/load/LibrarySearcher.java +++ b/core/src/main/java/org/jruby/runtime/load/LibrarySearcher.java @@ -407,7 +407,7 @@ protected synchronized void provideFeature(RubyString name) { name.setFrozen(true); - loadedFeatures.append(name); + loadedFeatures.append(runtime.getCurrentContext(), name); snapshotLoadedFeatures(); @@ -415,7 +415,7 @@ protected synchronized void provideFeature(RubyString name) { } protected synchronized RubyArray snapshotLoadedFeatures() { - return (RubyArray) loadedFeaturesSnapshot.replace(this.loadService.loadedFeatures); + return (RubyArray) loadedFeaturesSnapshot.replace(runtime.getCurrentContext(), this.loadService.loadedFeatures); } protected synchronized void addFeatureToIndex(String name, IRubyObject featurePath) { 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 f35ee7e2ae2..5a6cc775f09 100644 --- a/core/src/main/java/org/jruby/runtime/load/LoadService.java +++ b/core/src/main/java/org/jruby/runtime/load/LoadService.java @@ -37,7 +37,6 @@ import java.io.File; import java.io.IOException; import java.net.URL; -import java.security.AccessControlException; import java.util.EnumSet; import java.util.HashMap; import java.util.List; @@ -62,10 +61,8 @@ import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.CatchThrow; import org.jruby.exceptions.JumpException; -import org.jruby.exceptions.LoadError; import org.jruby.exceptions.MainExitException; import org.jruby.exceptions.RaiseException; -import org.jruby.exceptions.StandardError; import org.jruby.exceptions.Unrescuable; import org.jruby.ext.rbconfig.RbConfigLibrary; import org.jruby.platform.Platform; @@ -147,7 +144,6 @@ public class LoadService { static final Logger LOG = LoggerFactory.getLogger(LoadService.class); private final LoadTimer loadTimer; - private boolean canGetAbsolutePath = true; public enum SuffixType { Source(LibrarySearcher.Suffix.SOURCES), @@ -291,13 +287,14 @@ public void provide(String name) { protected void addPath(String path) { // Empty paths do not need to be added - if (path == null || path.length() == 0) return; - final RubyArray loadPath = this.loadPath; + if (path == null || path.isEmpty()) return; + var loadPath = this.loadPath; synchronized(loadPath) { final RubyString pathToAdd = runtime.newString(path.replace('\\', '/')); + var context = runtime.getCurrentContext(); // Do not add duplicated paths - if (loadPath.includes(runtime.getCurrentContext(), pathToAdd)) return; - loadPath.append(pathToAdd); + if (loadPath.includes(context, pathToAdd)) return; + loadPath.append(context, pathToAdd); } } @@ -964,20 +961,9 @@ && isRequireable(loc)) { } protected String resolveLoadName(LoadServiceResource foundResource, String previousPath) { - if (canGetAbsolutePath) { - try { - String path = foundResource.getAbsolutePath(); - if (Platform.IS_WINDOWS) { - path = path.replace('\\', '/'); - } - return path; - } catch (AccessControlException ace) { - // can't get absolute path in this security context, so we give up forever - runtime.getWarnings().warn("can't canonicalize loaded names due to security restrictions; disabling"); - canGetAbsolutePath = false; - } - } - return resolveLoadName(foundResource, previousPath); + String path = foundResource.getAbsolutePath(); + if (Platform.IS_WINDOWS) path = path.replace('\\', '/'); + return path; } public String getMainScript() { diff --git a/core/src/main/java/org/jruby/specialized/RubyArrayOneObject.java b/core/src/main/java/org/jruby/specialized/RubyArrayOneObject.java index 05c2ccc609a..ce4b3634037 100644 --- a/core/src/main/java/org/jruby/specialized/RubyArrayOneObject.java +++ b/core/src/main/java/org/jruby/specialized/RubyArrayOneObject.java @@ -61,16 +61,16 @@ protected void finishUnpack(IRubyObject nil) { } @Override - public RubyArray aryDup() { + public RubyArray aryDup() { if (!packed()) return super.aryDup(); return new RubyArrayOneObject(getRuntime().getArray(), this); } @Override - public IRubyObject rb_clear() { - if (!packed()) return super.rb_clear(); + public IRubyObject rb_clear(ThreadContext context) { + if (!packed()) return super.rb_clear(context); - modifyCheck(); + modifyCheck(context); // fail packing, but defer [] creation in case it is never needed value = null; @@ -81,41 +81,37 @@ public IRubyObject rb_clear() { } @Override - public void copyInto(IRubyObject[] target, int start) { + public void copyInto(ThreadContext context, IRubyObject[] target, int start) { if (!packed()) { - super.copyInto(target, start); + super.copyInto(context, target, start); return; } target[start] = value; } @Override - public void copyInto(IRubyObject[] target, int start, int len) { + public void copyInto(ThreadContext context, IRubyObject[] target, int start, int len) { if (!packed()) { - super.copyInto(target, start, len); + super.copyInto(context, target, start, len); return; } if (len != 1) { - unpack(); - super.copyInto(target, start, len); + unpack(context); + super.copyInto(context, target, start, len); return; } target[start] = value; } @Override - protected RubyArray dupImpl(Ruby runtime, RubyClass metaClass) { + protected RubyArray dupImpl(Ruby runtime, RubyClass metaClass) { if (!packed()) return super.dupImpl(runtime, metaClass); return new RubyArrayOneObject(metaClass, this); } @Override public boolean includes(ThreadContext context, IRubyObject item) { - if (!packed()) return super.includes(context, item); - - if (equalInternal(context, value, item)) return true; - - return false; + return !packed() ? super.includes(context, item) : equalInternal(context, value, item); } @Override @@ -158,26 +154,26 @@ protected IRubyObject internalRotate(ThreadContext context, int cnt) { protected IRubyObject internalRotateBang(ThreadContext context, int cnt) { if (!packed()) return super.internalRotateBang(context, cnt); - modifyCheck(); + modifyCheck(context); return context.nil; } @Override - public IRubyObject op_plus(IRubyObject obj) { - if (!packed()) return super.op_plus(obj); - RubyArray y = obj.convertToArray(); - if (y.size() == 0) return new RubyArrayOneObject(this); - return super.op_plus(y); + public IRubyObject op_plus(ThreadContext context, IRubyObject obj) { + if (!packed()) return super.op_plus(context, obj); + var y = obj.convertToArray(); + if (y.isEmpty()) return new RubyArrayOneObject(this); + return super.op_plus(context, y); } @Override - public IRubyObject replace(IRubyObject orig) { - if (!packed()) return super.replace(orig); + public IRubyObject replace(ThreadContext context, IRubyObject orig) { + if (!packed()) return super.replace(context, orig); - modifyCheck(); + modifyCheck(context); - RubyArray origArr = orig.convertToArray(); + var origArr = orig.convertToArray(); if (this == orig) return this; @@ -186,20 +182,19 @@ public IRubyObject replace(IRubyObject orig) { return this; } - unpack(); + unpack(context); - return super.replace(origArr); + return super.replace(context, origArr); } @Override - public IRubyObject reverse_bang() { - if (!packed()) return super.reverse_bang(); - + public IRubyObject reverse_bang(ThreadContext context) { + if (!packed()) return super.reverse_bang(context); return this; } @Override - protected RubyArray safeReverse() { + protected RubyArray safeReverse() { if (!packed()) return super.safeReverse(); return new RubyArrayOneObject(this); @@ -220,14 +215,14 @@ protected IRubyObject sortInternal(final ThreadContext context, boolean honorOve } @Override - protected void storeInternal(final int index, final IRubyObject value) { + protected void storeInternal(ThreadContext context, final int index, final IRubyObject value) { if (index == 0 && packed()) { this.value = value; return; } - if (packed()) unpack(); // index > 0 - super.storeInternal(index, value); + if (packed()) unpack(context); // index > 0 + super.storeInternal(context, index, value); } @Override @@ -237,7 +232,7 @@ public IRubyObject subseq(RubyClass metaClass, long beg, long len, boolean light if (len == 0) return newEmptyArray(metaClass.getClassRuntime()); if (beg != 0 || len != 1) { - unpack(); + unpack(metaClass.getRuntime().getCurrentContext()); return super.subseq(metaClass, beg, len, light); } @@ -245,8 +240,8 @@ public IRubyObject subseq(RubyClass metaClass, long beg, long len, boolean light } @Override - public IRubyObject[] toJavaArray() { - if (!packed()) return super.toJavaArray(); + public IRubyObject[] toJavaArray(ThreadContext context) { + if (!packed()) return super.toJavaArray(context); return arrayOf(value); } @@ -259,7 +254,7 @@ public IRubyObject uniq(ThreadContext context) { } @Override - public RubyArray collectArray(ThreadContext context, Block block) { + public RubyArray collectArray(ThreadContext context, Block block) { if (!packed()) return super.collectArray(context, block); if (!block.isGiven()) return makeShared(); @@ -268,7 +263,7 @@ public RubyArray collectArray(ThreadContext context, Block block) { } @Override - protected RubyArray makeShared() { + protected RubyArray makeShared() { if (!packed()) return super.makeShared(); return new RubyArrayOneObject(this); diff --git a/core/src/main/java/org/jruby/specialized/RubyArraySpecialized.java b/core/src/main/java/org/jruby/specialized/RubyArraySpecialized.java index 849bf0db2b6..f4cd3467d7c 100644 --- a/core/src/main/java/org/jruby/specialized/RubyArraySpecialized.java +++ b/core/src/main/java/org/jruby/specialized/RubyArraySpecialized.java @@ -3,43 +3,43 @@ import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyClass; -import org.jruby.runtime.Constants; import org.jruby.runtime.Helpers; +import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; /** * This is the base class for all specialized RubyArray. - * + *

* Specialized RubyArray use fields rather than an IRubyObject[] to hold their values. When they need * to grow or shrink, they unpack those values to a proper IRubyObject[] and fall back on RubyArray * logic. - * + *

* Subclasses should override all methods that would access the array directly to use the fields, * with guards for the packed flag and access outside packed range. This includes the following * methods (at the time of this writing...this list will evolve): - * + *

* RubyArray{@link #eltInternal(int)} * RubyArray{@link #eltInternalSet(int index, IRubyObject value)} * RubyArraySpecialized{@link #finishUnpack(IRubyObject nil)} * RubyArray{@link #aryDup()} - * RubyArray{@link #rb_clear()} + * RubyArray{@link #rb_clear(org.jruby.runtime.ThreadContext)} * RubyArray{@link #collect(org.jruby.runtime.ThreadContext, org.jruby.runtime.Block)} - * RubyArray{@link #copyInto(IRubyObject[], int)} - * RubyArray{@link #copyInto(IRubyObject[], int, int)} + * RubyArray{@link #copyInto(org.jruby.runtime.ThreadContext,IRubyObject[], int)} + * RubyArray{@link #copyInto(org.jruby.runtime.ThreadContext,IRubyObject[], int, int)} * RubyArray{@link #dupImpl(Ruby, RubyClass)} * RubyArray{@link #includes(org.jruby.runtime.ThreadContext, IRubyObject)} * RubyArray{@link #indexOf(Object)} * RubyArray{@link #inspectAry(org.jruby.runtime.ThreadContext)} * RubyArray{@link #internalRotate(org.jruby.runtime.ThreadContext, int)} * RubyArray{@link #internalRotateBang(org.jruby.runtime.ThreadContext, int)} - * RubyArray{@link #op_plus(IRubyObject)} - * RubyArray{@link #reverse_bang()} + * RubyArray{@link #op_plus(org.jruby.runtime.ThreadContext, IRubyObject)} + * RubyArray{@link #reverse_bang(org.jruby.runtime.ThreadContext)} * RubyArray{@link #safeReverse()} * RubyArray{@link #sortInternal(org.jruby.runtime.ThreadContext, org.jruby.runtime.Block)} * RubyArray{@link #sortInternal(org.jruby.runtime.ThreadContext, boolean)} - * RubyArray{@link #storeInternal(int, IRubyObject)} + * RubyArray{@link #storeInternal(org.jruby.runtime.ThreadContext, int, IRubyObject)} * RubyArray{@link #subseq(RubyClass, long, long, boolean)} - * RubyArray{@link #toJavaArray()} + * RubyArray{@link #toJavaArray(ThreadContext)} * RubyArray{@link #uniq(org.jruby.runtime.ThreadContext)} */ public abstract class RubyArraySpecialized extends RubyArray { @@ -57,19 +57,18 @@ public RubyArraySpecialized(RubyClass otherClass) { super(otherClass.getClassRuntime(), otherClass); } - protected final void unpack() { + protected final void unpack(ThreadContext context) { if (!packed()) return; // CON: I believe most of the time we'll unpack because we need to grow, so give a bit of extra room. // For example, <<, unshift, and push will all just add one to front or back. - Ruby runtime = getRuntime(); IRubyObject[] values = new IRubyObject[realLength + 2]; - Helpers.fillNil(values, runtime); - copyInto(values, 1); + Helpers.fillNil(values, context.runtime); + copyInto(context, values, 1); this.values = values; this.begin = 1; - finishUnpack(runtime.getNil()); + finishUnpack(context.nil); } protected abstract void finishUnpack(IRubyObject nil); diff --git a/core/src/main/java/org/jruby/specialized/RubyArrayTwoObject.java b/core/src/main/java/org/jruby/specialized/RubyArrayTwoObject.java index f2f20301bbf..1b008b80b10 100644 --- a/core/src/main/java/org/jruby/specialized/RubyArrayTwoObject.java +++ b/core/src/main/java/org/jruby/specialized/RubyArrayTwoObject.java @@ -72,20 +72,19 @@ protected void finishUnpack(IRubyObject nil) { } @Override - public RubyArray aryDup() { + public RubyArray aryDup() { if (!packed()) return super.aryDup(); return new RubyArrayTwoObject(getRuntime().getArray(), this); } @Override - public IRubyObject rb_clear() { - if (!packed()) return super.rb_clear(); + public IRubyObject rb_clear(ThreadContext context) { + if (!packed()) return super.rb_clear(context); - modifyCheck(); + modifyCheck(context); // fail packing, but defer [] creation in case it is never needed - IRubyObject nil = getRuntime().getNil(); - car = cdr = nil; + car = cdr = context.nil; values = IRubyObject.NULL_ARRAY; realLength = 0; @@ -93,9 +92,9 @@ public IRubyObject rb_clear() { } @Override - public void copyInto(IRubyObject[] target, int start) { + public void copyInto(ThreadContext context, IRubyObject[] target, int start) { if (!packed()) { - super.copyInto(target, start); + super.copyInto(context, target, start); return; } target[start] = car; @@ -103,14 +102,14 @@ public void copyInto(IRubyObject[] target, int start) { } @Override - public void copyInto(IRubyObject[] target, int start, int len) { + public void copyInto(ThreadContext context, IRubyObject[] target, int start, int len) { if (!packed()) { - super.copyInto(target, start, len); + super.copyInto(context, target, start, len); return; } if (len != 2) { - unpack(); - super.copyInto(target, start, len); + unpack(context); + super.copyInto(context, target, start, len); return; } target[start] = car; @@ -118,7 +117,7 @@ public void copyInto(IRubyObject[] target, int start, int len) { } @Override - protected RubyArray dupImpl(Ruby runtime, RubyClass metaClass) { + protected RubyArray dupImpl(Ruby runtime, RubyClass metaClass) { if (!packed()) return super.dupImpl(runtime, metaClass); return new RubyArrayTwoObject(metaClass, this); } @@ -181,7 +180,7 @@ protected IRubyObject internalRotate(ThreadContext context, int cnt) { protected IRubyObject internalRotateBang(ThreadContext context, int cnt) { if (!packed()) return super.internalRotateBang(context, cnt); - modifyCheck(); + modifyCheck(context); if (cnt % 2 == 1) { IRubyObject tmp = car; @@ -193,20 +192,20 @@ protected IRubyObject internalRotateBang(ThreadContext context, int cnt) { } @Override - public IRubyObject op_plus(IRubyObject obj) { - if (!packed()) return super.op_plus(obj); - RubyArray y = obj.convertToArray(); - if (y.size() == 0) return new RubyArrayTwoObject(this); - return super.op_plus(y); + public IRubyObject op_plus(ThreadContext context, IRubyObject obj) { + if (!packed()) return super.op_plus(context, obj); + var y = obj.convertToArray(); + if (y.isEmpty()) return new RubyArrayTwoObject(this); + return super.op_plus(context, y); } @Override - public IRubyObject replace(IRubyObject orig) { - if (!packed()) return super.replace(orig); + public IRubyObject replace(ThreadContext context, IRubyObject orig) { + if (!packed()) return super.replace(context, orig); - modifyCheck(); + modifyCheck(context); - RubyArray origArr = orig.convertToArray(); + var origArr = orig.convertToArray(); if (this == orig) return this; @@ -216,14 +215,14 @@ public IRubyObject replace(IRubyObject orig) { return this; } - unpack(); + unpack(context); - return super.replace(origArr); + return super.replace(context, origArr); } @Override - public IRubyObject reverse_bang() { - if (!packed()) return super.reverse_bang(); + public IRubyObject reverse_bang(ThreadContext context) { + if (!packed()) return super.reverse_bang(context); IRubyObject tmp = car; car = cdr; @@ -233,7 +232,7 @@ public IRubyObject reverse_bang() { } @Override - protected RubyArray safeReverse() { + protected RubyArray safeReverse() { if (!packed()) return super.safeReverse(); return new RubyArrayTwoObject(getMetaClass(), cdr, car); @@ -250,7 +249,7 @@ protected IRubyObject sortInternal(ThreadContext context, Block block) { IRubyObject ret = block.yieldArray(context, newArray(context.runtime, car, cdr), null); //TODO: ary_sort_check should be done here int compare = RubyComparable.cmpint(context, ret, car, cdr); - if (compare > 0) reverse_bang(); + if (compare > 0) reverse_bang(context); return this; } @@ -275,7 +274,7 @@ protected IRubyObject sortInternal(final ThreadContext context, boolean honorOve compare = compareOthers(context, o1, o2); } - if (compare > 0) reverse_bang(); + if (compare > 0) reverse_bang(context); return this; } @@ -288,17 +287,22 @@ private boolean isFixnumBypass(Ruby runtime, JavaSites.Array2Sites sites, boolea return !honorOverride || sites.op_cmp_fixnum.isBuiltin(runtime.getFixnum()); } - @Override + @Deprecated protected void storeInternal(final int index, final IRubyObject value) { + storeInternal(getCurrentContext(), index, value); + } + + @Override + protected void storeInternal(ThreadContext context, final int index, final IRubyObject value) { if (packed()) { switch (index) { case 0: car = value; return; case 1: cdr = value; return; } - unpack(); + unpack(context); } - super.storeInternal(index, value); + super.storeInternal(context, index, value); } @Override @@ -309,7 +313,7 @@ public IRubyObject subseq(RubyClass metaClass, long beg, long len, boolean light if (beg > 2 || beg < 0 || len < 0) return runtime.getNil(); - if (len == 0 || beg == 2) return new RubyArray(runtime, metaClass, IRubyObject.NULL_ARRAY); + if (len == 0 || beg == 2) return new RubyArray<>(runtime, metaClass, IRubyObject.NULL_ARRAY); if (beg == 0) { if (len == 1) return new RubyArrayOneObject(metaClass, car); @@ -321,8 +325,8 @@ public IRubyObject subseq(RubyClass metaClass, long beg, long len, boolean light } @Override - public IRubyObject[] toJavaArray() { - if (!packed()) return super.toJavaArray(); + public IRubyObject[] toJavaArray(ThreadContext context) { + if (!packed()) return super.toJavaArray(context); return arrayOf(car, cdr); } @@ -344,7 +348,7 @@ public IRubyObject uniq(ThreadContext context) { } @Override - public RubyArray collectArray(ThreadContext context, Block block) { + public RubyArray collectArray(ThreadContext context, Block block) { if (!packed()) return super.collectArray(context, block); if (!block.isGiven()) return makeShared(); @@ -361,7 +365,7 @@ public RubyArray collectArray(ThreadContext context, Block block) { } // size has changed, unpack and continue with loop form - unpack(); + unpack(context); int currentLength = this.realLength; IRubyObject[] arr = IRubyObject.array(currentLength); @@ -374,7 +378,7 @@ public RubyArray collectArray(ThreadContext context, Block block) { for (; i < this.realLength; i++) { // Do not coarsen the "safe" check, since it will misinterpret AIOOBE from the yield // See JRUBY-5434 - safeArraySet(runtime, arr, i, block.yieldNonArray(context, eltOk(i), null)); // arr[i] = ... + safeArraySet(context, arr, i, block.yieldNonArray(context, eltOk(i), null)); // arr[i] = ... } // use iteration count as new size in case something was deleted along the way @@ -382,7 +386,7 @@ public RubyArray collectArray(ThreadContext context, Block block) { } @Override - protected RubyArray makeShared() { + protected RubyArray makeShared() { if (!packed()) return super.makeShared(); return new RubyArrayTwoObject(this); diff --git a/core/src/main/java/org/jruby/util/ByteListHelper.java b/core/src/main/java/org/jruby/util/ByteListHelper.java index e7030f21448..ffcdba771f1 100644 --- a/core/src/main/java/org/jruby/util/ByteListHelper.java +++ b/core/src/main/java/org/jruby/util/ByteListHelper.java @@ -115,6 +115,7 @@ private static int eachMBCCodePointWhile(ByteList bytelist, int offset, CodePoin * @return last T from headVisitor * @deprecated This was only used by Module#const_defined, but was difficult to match MRI's equivalent in this form */ + @Deprecated(since = "9.4-", forRemoval = true) public static T split(ByteList value, ByteList pattern, Visit bodyVisitor, Visit headVisitor) { if (headVisitor == null) headVisitor = bodyVisitor; diff --git a/core/src/main/java/org/jruby/util/FileResource.java b/core/src/main/java/org/jruby/util/FileResource.java index 15efa933cb4..9567bc9a7d9 100644 --- a/core/src/main/java/org/jruby/util/FileResource.java +++ b/core/src/main/java/org/jruby/util/FileResource.java @@ -83,6 +83,7 @@ default JRubyFile hackyGetJRubyFile() { * @return just opened InputStream * @throws ResourceException is the file does not exists or if the resource is a directory */ + @Deprecated(since = "9.4-") default InputStream inputStream() throws ResourceException { if (!exists()) { throw new ResourceException.NotFound(absolutePath()); @@ -117,6 +118,7 @@ default InputStream inputStream() throws ResourceException { * @return channel * @throws ResourceException */ + @Deprecated(since = "9.4-") default Channel openChannel(ModeFlags flags, int perm) throws ResourceException { try { return openChannel(flags.getFlags(), perm); diff --git a/core/src/main/java/org/jruby/util/JarCache.java b/core/src/main/java/org/jruby/util/JarCache.java index 3408b3a3f10..e74d40f7b46 100644 --- a/core/src/main/java/org/jruby/util/JarCache.java +++ b/core/src/main/java/org/jruby/util/JarCache.java @@ -5,7 +5,6 @@ import java.io.InputStream; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; -import java.security.AccessControlException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; @@ -185,9 +184,6 @@ public JarIndex getIndex(String jarPath) { indexCache.put(cacheKey, new SoftJarIndex(cacheKey, index)); } catch (IOException ioe) { return null; - } catch (AccessControlException ace) { - // No permissions to index the given path, bail out - return null; } } diff --git a/core/src/main/java/org/jruby/util/Pack.java b/core/src/main/java/org/jruby/util/Pack.java index db55c00529f..9a4c758d9bc 100644 --- a/core/src/main/java/org/jruby/util/Pack.java +++ b/core/src/main/java/org/jruby/util/Pack.java @@ -1599,7 +1599,7 @@ private static void appendOrYield(ThreadContext context, Block block, RubyArray if (mode == UNPACK_BLOCK) { block.yield(context, item); } else if (mode == UNPACK_ARRAY) { - result.append(item); + result.append(context, item); } } diff --git a/core/src/main/java/org/jruby/util/RubyStringBuilder.java b/core/src/main/java/org/jruby/util/RubyStringBuilder.java index ff2b74c34a4..df7ea2935df 100644 --- a/core/src/main/java/org/jruby/util/RubyStringBuilder.java +++ b/core/src/main/java/org/jruby/util/RubyStringBuilder.java @@ -109,7 +109,7 @@ public static RubyString inspectIdentifierByteList(final Ruby runtime, ByteList (c == '#' && p < end && MBCLEN_CHARFOUND_P(StringSupport.preciseLength(enc, bytes, p, end)) && - ((cc = codePoint(runtime, enc, bytes, p, end)) == '$' || + ((cc = codePoint(runtime.getCurrentContext(), enc, bytes, p, end)) == '$' || cc == '@' || cc == '{') ) )) { diff --git a/core/src/main/java/org/jruby/util/ShellLauncher.java b/core/src/main/java/org/jruby/util/ShellLauncher.java index 93e9fd32c06..e7a202304ca 100644 --- a/core/src/main/java/org/jruby/util/ShellLauncher.java +++ b/core/src/main/java/org/jruby/util/ShellLauncher.java @@ -518,7 +518,7 @@ public static long runExternal(Ruby runtime, IRubyObject env, IRubyObject prog, env = null; } - IRubyObject[] rawArgs = args.convertToArray().toJavaArray(); + IRubyObject[] rawArgs = args.convertToArray().toJavaArray(runtime.getCurrentContext()); OutputStream output = runtime.getOutputStream(); OutputStream error = runtime.getErrorStream(); diff --git a/core/src/main/java/org/jruby/util/Sprintf.java b/core/src/main/java/org/jruby/util/Sprintf.java index 36ffd597830..b484939ac8a 100644 --- a/core/src/main/java/org/jruby/util/Sprintf.java +++ b/core/src/main/java/org/jruby/util/Sprintf.java @@ -613,7 +613,7 @@ private static void rubySprintfToBuffer(final ByteList buf, final CharSequence c n = 0; } else { ByteList bl = ((RubyString) tmp).getByteList(); - c = StringSupport.codePoint(runtime, encoding, bl.unsafeBytes(), bl.begin(), bl.begin() + bl.realSize()); + c = StringSupport.codePoint(context, encoding, bl.unsafeBytes(), bl.begin(), bl.begin() + bl.realSize()); n = StringSupport.codeLength(bl.getEncoding(), c); } } else { diff --git a/core/src/main/java/org/jruby/util/StringSupport.java b/core/src/main/java/org/jruby/util/StringSupport.java index 28715098c39..501e1e86edf 100644 --- a/core/src/main/java/org/jruby/util/StringSupport.java +++ b/core/src/main/java/org/jruby/util/StringSupport.java @@ -577,10 +577,11 @@ public static int codePoint(Encoding enc, byte[] bytes, int p, int end) { return enc.mbcToCode(bytes, p, end); } - @Deprecated + @Deprecated(since = "10.0", forRemoval = true) public static int codePoint(Ruby runtime, Encoding enc, byte[] bytes, int p, int end) { return codePoint(runtime.getCurrentContext(), enc, bytes, p, end); } + public static int codePoint(ThreadContext context, Encoding enc, byte[] bytes, int p, int end) { try { return codePoint(enc, bytes, p, end); @@ -2230,7 +2231,7 @@ else if (!wantarray) { } } line = str.substr(runtime, subptr - ptr, subend - subptr); - if (wantarray) ary.append(line); + if (wantarray) ary.append(context, line); else { block.yieldSpecific(context, line); str.modifyCheck(strBytes, len); @@ -2248,7 +2249,7 @@ else if (!wantarray) { } } line = str.substr(runtime, subptr - ptr, pend - subptr); - if (wantarray) ary.append(line); + if (wantarray) ary.append(context, line); else block.yieldSpecific(context, line); } @@ -2282,7 +2283,7 @@ private static void rbStrEnumerateLinesEmptySep(RubyString str, if (subptr == NULL_POINTER) break; RubyString line = str.makeSharedString(context.runtime, subptr - ptr, subend - subptr + (chomp ? 0 : rslen)); - if (ary != null) ary.append(line); // wantarray + if (ary != null) ary.append(context, line); // wantarray else { block.yield(context, line); str.modifyCheck(strBytes, len); diff --git a/core/src/main/java/org/jruby/util/collections/StringArraySet.java b/core/src/main/java/org/jruby/util/collections/StringArraySet.java index 56faa42c9fc..37f392c9b69 100644 --- a/core/src/main/java/org/jruby/util/collections/StringArraySet.java +++ b/core/src/main/java/org/jruby/util/collections/StringArraySet.java @@ -57,21 +57,21 @@ public StringArraySet(Ruby runtime) { public final void appendString(Ruby runtime, String element) { final RubyString item = runtime.newString(element); synchronized (this) { - super.append(item); + super.append(runtime.getCurrentContext(), item); set.add(element); } } @Override - public synchronized RubyArray append(IRubyObject item) { - RubyArray result = super.append(item); + public synchronized RubyArray append(ThreadContext context, IRubyObject item) { + RubyArray result = super.append(context, item); set.add(convertToString(item)); return result; } @Override - public synchronized IRubyObject rb_clear() { - IRubyObject res = super.rb_clear(); + public synchronized IRubyObject rb_clear(ThreadContext context) { + IRubyObject res = super.rb_clear(context); set.clear(); return res; } @@ -104,29 +104,29 @@ public final RubyBoolean include_p(ThreadContext context, IRubyObject item) { } @Override - public synchronized IRubyObject replace(IRubyObject orig) { - IRubyObject result = super.replace(orig); + public synchronized IRubyObject replace(ThreadContext context, IRubyObject orig) { + IRubyObject result = super.replace(context, orig); rehash(); return result; } @Override - public synchronized IRubyObject aset(IRubyObject arg0, IRubyObject arg1) { - IRubyObject result = super.aset(arg0, arg1); + public synchronized IRubyObject aset(ThreadContext context, IRubyObject arg0, IRubyObject arg1) { + IRubyObject result = super.aset(context, arg0, arg1); rehash(); return result; } @Override - public synchronized IRubyObject aset(IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { - IRubyObject result = super.aset(arg0, arg1, arg2); + public synchronized IRubyObject aset(ThreadContext context, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { + IRubyObject result = super.aset(context, arg0, arg1, arg2); rehash(); return result; } @Override public synchronized RubyArray collectBang(ThreadContext context, Block block) { - RubyArray result = super.collectBang(context, block); + var result = super.collectBang(context, block); rehash(); return result; } @@ -148,8 +148,8 @@ public synchronized RubyArray collectBang(ThreadContext context, Block block) { //} @Override - public synchronized IRubyObject compact_bang() { - IRubyObject result = super.compact_bang(); + public synchronized IRubyObject compact_bang(ThreadContext context) { + IRubyObject result = super.compact_bang(context); rehash(); return result; } @@ -190,22 +190,22 @@ public synchronized IRubyObject insert() { } @Override - public synchronized IRubyObject insert(IRubyObject arg) { - IRubyObject result = super.insert(arg); + public synchronized IRubyObject insert(ThreadContext context, IRubyObject arg) { + IRubyObject result = super.insert(context, arg); rehash(); return result; } @Override - public synchronized IRubyObject insert(IRubyObject arg1, IRubyObject arg2) { - IRubyObject result = super.insert(arg1, arg2); + public synchronized IRubyObject insert(ThreadContext context, IRubyObject arg1, IRubyObject arg2) { + IRubyObject result = super.insert(context, arg1, arg2); rehash(); return result; } @Override - public synchronized IRubyObject insert(IRubyObject[] args) { - IRubyObject result = super.insert(args); + public synchronized IRubyObject insert(ThreadContext context, IRubyObject[] args) { + IRubyObject result = super.insert(context, args); rehash(); return result; } @@ -226,14 +226,14 @@ public synchronized IRubyObject pop(ThreadContext context, IRubyObject num) { @Override public synchronized RubyArray push(IRubyObject item) { - RubyArray result = super.push(item); + var result = super.push(item); add(item); return result; } @Override - public synchronized RubyArray push(IRubyObject[] items) { - RubyArray result = super.push(items); + public synchronized RubyArray push(ThreadContext context, IRubyObject[] items) { + var result = super.push(context, items); addAll(items); return result; } @@ -275,36 +275,36 @@ public synchronized IRubyObject shift(ThreadContext context, IRubyObject num) { } @Override - public synchronized IRubyObject slice_bang(IRubyObject arg0) { - IRubyObject result = super.slice_bang(arg0); + public synchronized IRubyObject slice_bang(ThreadContext context, IRubyObject arg0) { + IRubyObject result = super.slice_bang(context, arg0); rehash(); return result; } @Override - public synchronized IRubyObject slice_bang(IRubyObject arg0, IRubyObject arg1) { - IRubyObject result = super.slice_bang(arg0, arg1); + public synchronized IRubyObject slice_bang(ThreadContext context, IRubyObject arg0, IRubyObject arg1) { + IRubyObject result = super.slice_bang(context, arg0, arg1); rehash(); return result; } @Override - public synchronized IRubyObject unshift() { - IRubyObject result = super.unshift(); + public synchronized IRubyObject unshift(ThreadContext context) { + IRubyObject result = super.unshift(context); // rehash(); return result; } @Override - public synchronized IRubyObject unshift(IRubyObject item) { - IRubyObject result = super.unshift(item); + public synchronized IRubyObject unshift(ThreadContext context, IRubyObject item) { + IRubyObject result = super.unshift(context, item); add(item); return result; } @Override - public synchronized IRubyObject unshift(IRubyObject[] items) { - IRubyObject result = super.unshift(items); + public synchronized IRubyObject unshift(ThreadContext context, IRubyObject[] items) { + IRubyObject result = super.unshift(context, items); addAll(items); return result; } diff --git a/core/src/main/java/org/jruby/util/io/Getline.java b/core/src/main/java/org/jruby/util/io/Getline.java index 322db2c4d94..6f8888ef0ca 100644 --- a/core/src/main/java/org/jruby/util/io/Getline.java +++ b/core/src/main/java/org/jruby/util/io/Getline.java @@ -12,7 +12,7 @@ import org.jruby.util.TypeConverter; import static org.jruby.api.Error.argumentError; -import static org.jruby.runtime.ThreadContext.resetCallInfo; +import static org.jruby.api.Error.typeError; /** * Encapsulation of the prepare_getline_args logic from MRI, used by StringIO and IO. @@ -192,11 +192,9 @@ public static Return getlineCall(ThreadContex if (optArg instanceof RubyHash && !keywords) { // We get args from multiple sources so we are form-fitting this as if we are processing it from // the original method. We should not be doing this processing this deep into this IO processing. - if (argc == 3) { - throw argumentError(context, argc, 0, 2); - } else { - throw runtime.newTypeError("no implicit conversion of Hash into Integer"); - } + if (argc == 3) throw argumentError(context, argc, 0, 2); + + throw typeError(context, "no implicit conversion of Hash into Integer"); } opt = ArgsUtil.getOptionsArg(runtime, optArg); 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 72088bbb2bf..2061f872c5a 100644 --- a/core/src/main/java/org/jruby/util/io/PopenExecutor.java +++ b/core/src/main/java/org/jruby/util/io/PopenExecutor.java @@ -116,7 +116,7 @@ public IRubyObject systemInternal(ThreadContext context, IRubyObject[] argv, Str // #if defined(HAVE_FORK) || defined(HAVE_SPAWNV) if (pid > 0) { long ret; - ret = RubyProcess.waitpid(runtime, pid, 0); + ret = RubyProcess.waitpid(context, pid, 0); if (ret == -1) throw runtime.newErrnoFromInt(runtime.getPosix().errno(), "Another thread waited the process started by system()."); } @@ -339,7 +339,7 @@ public static IRubyObject popen(ThreadContext context, IRubyObject[] argv, RubyC // #endif tmp = ((RubyArray)tmp).aryDup(); // RBASIC_CLEAR_CLASS(tmp); - eargp = execargNew(context, ((RubyArray)tmp).toJavaArray(), opt, false, false); + eargp = execargNew(context, ((RubyArray)tmp).toJavaArray(context), opt, false, false); ((RubyArray)tmp).clear(); } else { pname = pname.convertToString(); diff --git a/core/src/main/java/org/jruby/util/log/LoggerFactory.java b/core/src/main/java/org/jruby/util/log/LoggerFactory.java index 42f5acd51a1..00f7778da31 100644 --- a/core/src/main/java/org/jruby/util/log/LoggerFactory.java +++ b/core/src/main/java/org/jruby/util/log/LoggerFactory.java @@ -95,11 +95,11 @@ public static Logger getLogger(Class loggerClass) { /** * @deprecated prefer using {@link #getLogger(java.lang.Class)} if possible */ + @Deprecated(since = "9.4-") public static Logger getLogger(String loggerName) { try { return LOGGER_OLD.newInstance(loggerName); - } - catch (Exception ex) { + } catch (Exception ex) { return getLoggerFallback(loggerName, ex); } } diff --git a/core/src/main/java/org/jruby/util/unsafe/UnsafeHolder.java b/core/src/main/java/org/jruby/util/unsafe/UnsafeHolder.java index c8a5ff90d06..6a484e42c16 100644 --- a/core/src/main/java/org/jruby/util/unsafe/UnsafeHolder.java +++ b/core/src/main/java/org/jruby/util/unsafe/UnsafeHolder.java @@ -42,7 +42,7 @@ private UnsafeHolder(){} private static sun.misc.Unsafe loadUnsafe() { try { - Class unsafeClass = Class.forName("sun.misc.Unsafe"); + Class unsafeClass = Class.forName("sun.misc.Unsafe"); Field f = unsafeClass.getDeclaredField("theUnsafe"); Java.trySetAccessible(f); return (sun.misc.Unsafe) f.get(null); diff --git a/core/src/test/java/org/jruby/test/TestAdoptedThreading.java b/core/src/test/java/org/jruby/test/TestAdoptedThreading.java index 971e90058a0..32f785ce752 100644 --- a/core/src/test/java/org/jruby/test/TestAdoptedThreading.java +++ b/core/src/test/java/org/jruby/test/TestAdoptedThreading.java @@ -121,7 +121,7 @@ public void testThreadsStayAdopted() throws Exception { RubyThreadGroup rtg = (RubyThreadGroup)container.runScriptlet("ThreadGroup::Default"); - int initialCount = ((RubyArray)rtg.list(Block.NULL_BLOCK)).getLength(); + int initialCount = ((RubyArray)rtg.list(container.getProvider().getRuntime().getCurrentContext(), Block.NULL_BLOCK)).getLength(); Thread pausyThread = new Thread() { public void run() {