Update plugin versions and support Java 21 build

Update spotbugs and add necessary exclusions
  Fix one small thing in Context that was making it upset
Update other plugins
Make spotless work -- currently only runs on Java 11

Set time zone in Mozilla tests

Move many tests into modules for better modularity

Add publication info for JARs

The "rhino" module will include an all-in-one JAR for backward
compatibility, but most new code should combine the four modular JARs
instead.

Enable some tests that work now because of Java 11 minimum

Get Gradle to stop trying to download Java versions.
This commit is contained in:
Greg Brail 2024-05-03 22:05:59 -07:00
Родитель be1673f363
Коммит d8ff66bcb5
133 изменённых файлов: 463 добавлений и 120 удалений

2
.github/workflows/gradle.yml поставляемый
Просмотреть файл

@ -15,7 +15,7 @@ jobs:
# Some tests require more CPU, and all can use multiple CPUs # Some tests require more CPU, and all can use multiple CPUs
max-parallel: 1 max-parallel: 1
matrix: matrix:
java: [ '11', '17' ] java: [ '11', '17', '21' ]
name: Rhino Java ${{ matrix.java }} name: Rhino Java ${{ matrix.java }}
steps: steps:
- name: Checkout - name: Checkout

Просмотреть файл

@ -46,26 +46,53 @@ JavaDoc for all the APIs:
[https://javadoc.io/doc/org.mozilla/rhino](https://javadoc.io/doc/org.mozilla/rhino) [https://javadoc.io/doc/org.mozilla/rhino](https://javadoc.io/doc/org.mozilla/rhino)
## Code Structure
Rhino 1.7.15 and before were primarily used in a single JAR called "rhino.jar".
Newer releases now organize the code using Java modules. There are four primary modules:
* **rhino-runtime**: The primary codebase necessary and sufficient to run JavaScript code. Required by everything that uses Rhino.
* **rhino-tools**: Contains the shell, debugger, and the "Global" object, which many tests and other Rhino-based tools sometimes use. Note that adding Global gives Rhino the ability to print to stdout, open files, and do other things that may be considered dangerous in a shared environment.
* **rhino-xml**: Adds the implementation of the E4X XML standard. Only required if you are using that.
* **rhino-engine**: Adds the Rhino implementation of the standard Java *ScriptEngine* interface. Some projects use this to be able to switch between script execution engines, but for anything even moderately complex it is almost always easier and always more flexible to use Rhino's API directly.
The release contains the following other modules, which are used while building and
testing but which are not published to Maven Central:
* **rhino**: This creates an "all-in-one" JAR that includes *rhino-runtime*, *rhino-tools*, and *rhino-xml*. This is what's used if you want to run Rhino using "java jar".
* **tests**: The tests that depend on all of Rhino and also the external tests, including the Mozilla legacy test scripts and the test262 tests.
* **benchmarks**: Runs benchmarks using JMH.
* **examples**: Surprisingly, this contains example code.
## Building ## Building
### Requirements
Rhino requires Java 11 to build. It will (currently) build with Java versions up to at least
Java 21. However, not all tools work with Java 11, such as "spotless", so Java 11 is required for
regular developers.
### How to Build ### How to Build
Rhino builds with `Gradle`. Here are some useful tasks: For normal development, you can build the code, run the static checks, and run all the tests like this:
```
./gradlew jar git submodule init
``` git submodule update
Build and create `Rhino` jar in the `buildGradle/libs` directory. ./gradlew check
```
git submodule init To just run the Rhino shell, you can do this from the top-level directory:
git submodule update
./gradlew test ./gradlew run -q --console=plain
```
Build and run all the tests, including the official [ECMAScript Test Suite](https://github.com/tc39/test262). Alternately, you can build an all-in-one JAR and run that:
See [Running tests](testsrc/README.md) for more detailed info about running tests.
``` ./gradlew shadowJar
./gradlew testBenchmark java -jar rhino/build/libs/rhino-1.7.16-SNAPSHOT.jar
```
Build and run benchmark tests. You can also run the benchmarks:
./gradlew jmh
## Releasing and publishing new version ## Releasing and publishing new version
@ -86,30 +113,19 @@ mavenReleaseRepo=
5. Increase version and add `-SNAPSHOT` to it in `gradle.properties` in project root folder. 5. Increase version and add `-SNAPSHOT` to it in `gradle.properties` in project root folder.
6. Push `gradle.properties` to `GitHub` 6. Push `gradle.properties` to `GitHub`
## Running
Rhino can run as a stand-alone interpreter from the command line:
```
java -jar buildGradle/libs/rhino-1.7.12.jar -debug -version 200
Rhino 1.7.9 2018 03 15
js> print('Hello, World!');
Hello, World!
js>
```
There is also a "rhino" package for many Linux distributions as well as Homebrew for the Mac.
You can also embed it, as most people do. See below for more docs.
### Java 16 and later ### Java 16 and later
If you are using a modular JDK that disallows the reflective access to If you are using a modular JDK that disallows the reflective access to
non-public fields (16 and later), you may need to configure the JVM with the non-public fields (16 and later), you *may* need to configure the JVM with the
[`--add-opens`](https://docs.oracle.com/en/java/javase/17/migrate/migrating-jdk-8-later-jdk-releases.html#GUID-12F945EB-71D6-46AF-8C3D-D354FD0B1781) [`--add-opens`](https://docs.oracle.com/en/java/javase/17/migrate/migrating-jdk-8-later-jdk-releases.html#GUID-12F945EB-71D6-46AF-8C3D-D354FD0B1781)
option to authorize the packages that your scripts shall use, for example: option to authorize the packages that your scripts shall use, for example:
``` ```
--add-opens java.desktop/javax.swing.table=ALL-UNNAMED --add-opens java.desktop/javax.swing.table=ALL-UNNAMED
``` ```
This is not necessary just to build Rhino -- it may be necessary when embedding it
depending on what your project does.
## Issues ## Issues
Most issues are managed on GitHub: Most issues are managed on GitHub:
@ -143,22 +159,12 @@ hundreds of lines of changes to, please try to put the reformatting changes
alone into a single Git commit so that we can separate reformatting changes alone into a single Git commit so that we can separate reformatting changes
from more substantive changes. from more substantive changes.
> **Warning:** If you build with Java 16 or later, you need to apply a Currently, you must be building on Java 11 for Spotless to run. We recommend that you
> workaround for a "spotless" issue. Otherwise, the task will be disabled have that ready. (We have not been able to figure out a version of Spotless and the
> and your PR may fail. Google formatting plugin that it uses that works on many Java versions.)
>
> The following must be added to your `gradle.properties`.
> ```
> org.gradle.jvmargs=--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \
> --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED \
> --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED \
> --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED \
> --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
> ```
> For more details, see https://github.com/diffplug/spotless/issues/834#issuecomment-819118761
## More Help ## More Help
The Google group is the best place to go with questions: GitHub is the best place to go with questions. For example, we use "GitHub discussions":
[https://groups.google.com/forum/#!forum/mozilla-rhino](https://groups.google.com/forum/#!forum/mozilla-rhino) [https://github.com/mozilla/rhino/discussions](https://github.com/mozilla/rhino/discussions)

Просмотреть файл

@ -7,6 +7,6 @@ repositories {
} }
dependencies { dependencies {
implementation 'com.diffplug.spotless:spotless-plugin-gradle:6.20.0' implementation 'com.diffplug.spotless:spotless-plugin-gradle:6.25.0'
implementation 'com.github.spotbugs.snom:spotbugs-gradle-plugin:5.0.14' implementation 'com.github.spotbugs.snom:spotbugs-gradle-plugin:6.0.15'
} }

Просмотреть файл

@ -9,18 +9,14 @@ repositories {
dependencies { dependencies {
testImplementation "junit:junit:4.13.2" testImplementation "junit:junit:4.13.2"
testImplementation "org.yaml:snakeyaml:1.28" testImplementation "org.yaml:snakeyaml:1.33"
testImplementation "javax.xml.soap:javax.xml.soap-api:1.4.0" testImplementation "javax.xml.soap:javax.xml.soap-api:1.4.0"
} }
java {
toolchain {
languageVersion = JavaLanguageVersion.of(11)
}
}
compileJava { compileJava {
options.compilerArgs = ['-Xlint:deprecation,unchecked'] options.compilerArgs = [
'-Xlint:deprecation,unchecked'
]
} }
test { test {
@ -28,8 +24,14 @@ test {
} }
spotless { spotless {
java { // There is no version of googleJavaFormat that works for Java 11 and 17,
// Newer versions of GoogleJavaFormat seem to require JDK 15+ // and different versions format differently. For now, only run spotless on Java 11.
googleJavaFormat('1.10.0').aosp() // This will have to be changed when Java 11 support is removed.
if (JavaVersion.current() == JavaVersion.VERSION_11) {
java {
googleJavaFormat('1.10.0').aosp()
}
} else {
System.out.println("Not running Spotless: Java language version is " + JavaVersion.current())
} }
} }

Просмотреть файл

@ -1,8 +1,13 @@
plugins { plugins {
id 'rhino.java-conventions' id 'rhino.java-conventions'
id 'com.github.spotbugs' id 'com.github.spotbugs'
id 'maven-publish'
id 'checkstyle'
} }
import com.github.spotbugs.snom.Confidence
import com.github.spotbugs.snom.Effort
version = project.version version = project.version
tasks.named('compileJava') { tasks.named('compileJava') {
@ -21,9 +26,9 @@ tasks.withType(Jar).configureEach {
} }
spotbugs { spotbugs {
effort = "less" effort = Effort.valueOf('LESS')
reportLevel = "medium" reportLevel = Confidence.valueOf('MEDIUM')
excludeFilter = file("${projectDir}/../spotbugs-exclude.xml") excludeFilter = file("${projectDir}/../config/spotbugs/spotbugs-exclude.xml")
} }
spotbugsMain { spotbugsMain {
@ -35,3 +40,22 @@ spotbugsMain {
} }
} }
} }
task javadocJar(type: Jar) {
archiveClassifier = 'javadoc'
from javadoc
}
task sourceJar(type: Jar) {
from sourceSets.main.allJava
archiveClassifier = 'sources'
from ('LICENSE.txt') {
into 'META-INF'
}
from ('NOTICE.txt') {
into 'META-INF'
}
from ('NOTICE-tools.txt') {
into 'META-INF'
}
}

Просмотреть файл

@ -39,6 +39,10 @@
<property name="basedir" value="${basedir}"/> <property name="basedir" value="${basedir}"/>
--> -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- <property name="fileExtensions" value="java, properties, xml"/> --> <!-- <property name="fileExtensions" value="java, properties, xml"/> -->
<!-- Checks that a package-info.java file exists for each package. --> <!-- Checks that a package-info.java file exists for each package. -->
@ -106,7 +110,9 @@
<!-- Checks for imports --> <!-- Checks for imports -->
<!-- See http://checkstyle.sf.net/config_import.html --> <!-- See http://checkstyle.sf.net/config_import.html -->
<module name="AvoidStarImport"/> <module name="AvoidStarImport">
<property name="excludes" value="org.junit,org.junit.Assert"/>
</module>
<module name="IllegalImport"/> <module name="IllegalImport"/>
<!-- defaults to sun.* packages --> <!-- defaults to sun.* packages -->
<module name="RedundantImport"/> <module name="RedundantImport"/>

Просмотреть файл

@ -1,6 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" ?>
<FindBugsFilter> <FindBugsFilter>
<!-- Don't bother with our tests -->
<Match>
<Class name="~org\.mozilla\.javascript\.tests.*"/>
</Match>
<Match>
<Class name="~org\.mozilla\.javascript\.SlotMapTest"/>
</Match>
<!-- Things below are legit exemptions --> <!-- Things below are legit exemptions -->
<Match> <Match>
<!-- Existing "Token" constants have values to 255 --> <!-- Existing "Token" constants have values to 255 -->
@ -92,6 +99,19 @@
<Class name="org.mozilla.javascript.optimizer.OptRuntime$GeneratorState"/> <Class name="org.mozilla.javascript.optimizer.OptRuntime$GeneratorState"/>
<Bug pattern="URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"/> <Bug pattern="URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"/>
</Match> </Match>
<Match>
<!-- Don't want to break decades of other code -->
<Class name="org.mozilla.javascript.ContextFactory"/>
<Bug pattern="SING_SINGLETON_HAS_NONPRIVATE_CONSTRUCTOR"/>
</Match>
<Match>
<!-- Lots of constructors in Rhino throw exceptions. -->
<Bug pattern="CT_CONSTRUCTOR_THROW"/>
</Match>
<Match>
<!-- Our serialization calls lots and lots of methods -->
<Bug pattern="MC_OVERRIDABLE_METHOD_CALL_IN_READ_OBJECT"/>
</Match>
<!-- Things below are things that we aspire to fix! --> <!-- Things below are things that we aspire to fix! -->
<Match> <Match>

Просмотреть файл

@ -53,6 +53,7 @@ public class File extends ScriptableObject {
/** */ /** */
private static final long serialVersionUID = 2549960399774237828L; private static final long serialVersionUID = 2549960399774237828L;
/** /**
* The zero-parameter constructor. * The zero-parameter constructor.
* *

Просмотреть файл

@ -4,4 +4,6 @@ version=1.7.16-SNAPSHOT
mavenSnapshotRepo=https://oss.sonatype.org/content/repositories/snapshots mavenSnapshotRepo=https://oss.sonatype.org/content/repositories/snapshots
mavenReleaseRepo=https://oss.sonatype.org/service/local/staging/deploy/maven2/ mavenReleaseRepo=https://oss.sonatype.org/service/local/staging/deploy/maven2/
org.gradle.caching=true org.gradle.caching=true
org.gradle.configuration-cache=true
org.gradle.configuration-cache.problems=warn
org.gradle.parallel=true org.gradle.parallel=true

Двоичные данные
gradle/wrapper/gradle-wrapper.jar поставляемый

Двоичный файл не отображается.

4
gradle/wrapper/gradle-wrapper.properties поставляемый
Просмотреть файл

@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

30
gradlew поставляемый
Просмотреть файл

@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@ -80,13 +80,10 @@ do
esac esac
done done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # This is normally unused
# shellcheck disable=SC2034
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@ -133,22 +130,29 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
case $MAX_FD in #( case $MAX_FD in #(
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@ -193,6 +197,10 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command; # Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in # shell script including quotes and variable substitutions, so put them in
@ -205,6 +213,12 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \ org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args. # Use "xargs" to parse quoted args.
# #
# With -n1 it outputs one arg per line, with the quotes and backslashes removed. # With -n1 it outputs one arg per line, with the quotes and backslashes removed.

15
gradlew.bat поставляемый
Просмотреть файл

@ -14,7 +14,7 @@
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@ -25,7 +25,8 @@
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal

Просмотреть файл

@ -5,3 +5,31 @@ plugins {
dependencies { dependencies {
implementation project(':rhino-runtime') implementation project(':rhino-runtime')
} }
publishing {
publications {
rhinoengine(MavenPublication) {
from components.java
artifacts = [jar, sourceJar, javadocJar]
pom {
description = "Rhino ScriptEngine implementation"
url = "https://mozilla.github.io/rhino/"
licenses {
license {
name = "Mozilla Public License, Version 2.0"
url = "http://www.mozilla.org/MPL/2.0/index.txt"
}
}
scm {
connection = "scm:git:git@github.com:mozilla/rhino.git"
developerConnection = "scm:git:git@github.com:mozilla/rhino.git"
url = "git@github.com:mozilla/rhino.git"
}
organization {
name = "The Mozilla Foundation"
url = "http://www.mozilla.org"
}
}
}
}
}

Просмотреть файл

@ -64,7 +64,7 @@ public class InvocableTest {
@Test @Test
public void invokeMethodTest() throws Exception { public void invokeMethodTest() throws Exception {
try (FileReader reader = new FileReader("testsrc/assert.js")) { try (FileReader reader = new FileReader("../tests/testsrc/assert.js")) {
engine.eval(reader); engine.eval(reader);
engine.eval( engine.eval(
"function FooObj() { this.x = 0; }\n" "function FooObj() { this.x = 0; }\n"
@ -85,7 +85,7 @@ public class InvocableTest {
@Test @Test
public void interfaceFunctionTest() throws Exception { public void interfaceFunctionTest() throws Exception {
try (FileReader reader = new FileReader("testsrc/assert.js")) { try (FileReader reader = new FileReader("../tests/testsrc/assert.js")) {
engine.eval(reader); engine.eval(reader);
engine.eval( engine.eval(
@ -103,7 +103,7 @@ public class InvocableTest {
@Test @Test
public void interfaceMethodTest() throws Exception { public void interfaceMethodTest() throws Exception {
try (FileReader reader = new FileReader("testsrc/assert.js")) { try (FileReader reader = new FileReader("../tests/testsrc/assert.js")) {
engine.eval(reader); engine.eval(reader);
Object foo = Object foo =

Просмотреть файл

@ -86,7 +86,7 @@ public class ScriptEngineTest {
engine.put("actuallyNull", null); engine.put("actuallyNull", null);
// Ensure that stuff we just stuck in bindings made it to a global // Ensure that stuff we just stuck in bindings made it to a global
engine.eval(new FileReader("testsrc/assert.js")); engine.eval(new FileReader("../tests/testsrc/assert.js"));
engine.eval( engine.eval(
"assertEquals(string, 'Hello');\n" "assertEquals(string, 'Hello');\n"
+ "assertEquals(integer, 123);\n" + "assertEquals(integer, 123);\n"
@ -117,7 +117,7 @@ public class ScriptEngineTest {
public void engineScope() throws IOException, ScriptException { public void engineScope() throws IOException, ScriptException {
engine.put("string", "Hello"); engine.put("string", "Hello");
engine.put("integer", 123); engine.put("integer", 123);
engine.eval(new FileReader("testsrc/assert.js")); engine.eval(new FileReader("../tests/testsrc/assert.js"));
engine.eval("assertEquals(string, 'Hello');" + "assertEquals(integer, 123);"); engine.eval("assertEquals(string, 'Hello');" + "assertEquals(integer, 123);");
// Additional things added to the context but old stuff still there // Additional things added to the context but old stuff still there
@ -145,7 +145,7 @@ public class ScriptEngineTest {
gb.put("global", Boolean.TRUE); gb.put("global", Boolean.TRUE);
gb.put("level", 0); gb.put("level", 0);
engine.eval(new FileReader("testsrc/assert.js"), sc); engine.eval(new FileReader("../tests/testsrc/assert.js"), sc);
engine.eval("assertTrue(engine);" + "assertTrue(global);" + "assertEquals(level, 2);", sc); engine.eval("assertTrue(engine);" + "assertTrue(global);" + "assertEquals(level, 2);", sc);
} }
@ -163,7 +163,7 @@ public class ScriptEngineTest {
@Test @Test
public void compiled() throws ScriptException, IOException { public void compiled() throws ScriptException, IOException {
CompiledScript asserts = cEngine.compile(new FileReader("testsrc/assert.js")); CompiledScript asserts = cEngine.compile(new FileReader("../tests/testsrc/assert.js"));
CompiledScript tests = cEngine.compile("assertEquals(compiled, true);"); CompiledScript tests = cEngine.compile("assertEquals(compiled, true);");
// Fails because asserts have not been loaded // Fails because asserts have not been loaded
@ -179,7 +179,7 @@ public class ScriptEngineTest {
@Test @Test
public void compiled2() throws ScriptException, IOException { public void compiled2() throws ScriptException, IOException {
CompiledScript asserts = cEngine.compile(new FileReader("testsrc/assert.js")); CompiledScript asserts = cEngine.compile(new FileReader("../tests/testsrc/assert.js"));
CompiledScript init = cEngine.compile("value = 0;"); CompiledScript init = cEngine.compile("value = 0;");
CompiledScript tests = CompiledScript tests =
cEngine.compile("assertEquals(value, expectedValue);" + "value += 1;"); cEngine.compile("assertEquals(value, expectedValue);" + "value += 1;");

Просмотреть файл

@ -1,3 +1,32 @@
plugins { plugins {
id 'rhino.library-conventions' id 'rhino.library-conventions'
} }
publishing {
publications {
rhinoruntime(MavenPublication) {
from components.java
artifacts = [jar, sourceJar, javadocJar]
pom {
description = "Rhino JavaScript runtime jar, excludes XML, tools ScriptEngine wrapper"
url = "https://mozilla.github.io/rhino/"
licenses {
license {
name = "Mozilla Public License, Version 2.0"
url = "http://www.mozilla.org/MPL/2.0/index.txt"
}
}
scm {
connection = "scm:git:git@github.com:mozilla/rhino.git"
developerConnection = "scm:git:git@github.com:mozilla/rhino.git"
url = "git@github.com:mozilla/rhino.git"
}
organization {
name = "The Mozilla Foundation"
url = "http://www.mozilla.org"
}
}
}
}
}

Просмотреть файл

@ -35,6 +35,7 @@ public class ClassCache implements Serializable {
static class CacheKey { static class CacheKey {
final Class<?> cls; final Class<?> cls;
final Object sec; final Object sec;
/** Constructor. */ /** Constructor. */
public CacheKey(Class<?> cls, Object securityContext) { public CacheKey(Class<?> cls, Object securityContext) {
this.cls = cls; this.cls = cls;

Просмотреть файл

@ -41,7 +41,7 @@ public class CompilerEnvirons {
activationNames = cx.activationNames; activationNames = cx.activationNames;
// Observer code generation in compiled code : // Observer code generation in compiled code :
generateObserverCount = cx.generateObserverCount; generateObserverCount = cx.isGenerateObserverCount();
} }
public final ErrorReporter getErrorReporter() { public final ErrorReporter getErrorReporter() {

Просмотреть файл

@ -2278,6 +2278,11 @@ public class Context implements Closeable {
this.generateObserverCount = generateObserverCount; this.generateObserverCount = generateObserverCount;
} }
/** Determine if observer counts should be generated. */
public boolean isGenerateObserverCount() {
return this.generateObserverCount;
}
/** /**
* Allow application to monitor counter of executed script instructions in Context subclasses. * Allow application to monitor counter of executed script instructions in Context subclasses.
* Run-time calls this when instruction counting is enabled and the counter reaches limit set by * Run-time calls this when instruction counting is enabled and the counter reaches limit set by
@ -2711,7 +2716,7 @@ public class Context implements Closeable {
Scriptable scratchScriptable; Scriptable scratchScriptable;
// Generate an observer count on compiled code // Generate an observer count on compiled code
public boolean generateObserverCount = false; boolean generateObserverCount = false;
boolean isTopLevelStrict; boolean isTopLevelStrict;
} }

Просмотреть файл

@ -24,8 +24,10 @@ public class LambdaConstructor extends LambdaFunction {
/** If this flag is set, the constructor may be invoked as an ordinary function */ /** If this flag is set, the constructor may be invoked as an ordinary function */
public static final int CONSTRUCTOR_FUNCTION = 1; public static final int CONSTRUCTOR_FUNCTION = 1;
/** If this flag is set, the constructor may be invoked using "new" */ /** If this flag is set, the constructor may be invoked using "new" */
public static final int CONSTRUCTOR_NEW = 1 << 1; public static final int CONSTRUCTOR_NEW = 1 << 1;
/** By default, the constructor may be invoked either way */ /** By default, the constructor may be invoked either way */
public static final int CONSTRUCTOR_DEFAULT = CONSTRUCTOR_FUNCTION | CONSTRUCTOR_NEW; public static final int CONSTRUCTOR_DEFAULT = CONSTRUCTOR_FUNCTION | CONSTRUCTOR_NEW;

Просмотреть файл

@ -447,6 +447,7 @@ public class NativeJavaMethod extends BaseFunction {
private static final int PREFERENCE_FIRST_ARG = 1; private static final int PREFERENCE_FIRST_ARG = 1;
private static final int PREFERENCE_SECOND_ARG = 2; private static final int PREFERENCE_SECOND_ARG = 2;
/** No clear "easy" conversion */ /** No clear "easy" conversion */
private static final int PREFERENCE_AMBIGUOUS = 3; private static final int PREFERENCE_AMBIGUOUS = 3;

Просмотреть файл

@ -76,6 +76,7 @@ public class ScriptRuntime {
this.noSuchMethodMethod = noSuchMethodMethod; this.noSuchMethodMethod = noSuchMethodMethod;
this.methodName = methodName; this.methodName = methodName;
} }
/** /**
* Perform the call. * Perform the call.
* *
@ -94,6 +95,7 @@ public class ScriptRuntime {
return noSuchMethodMethod.call(cx, scope, thisObj, nestedArgs); return noSuchMethodMethod.call(cx, scope, thisObj, nestedArgs);
} }
} }
/* /*
* There's such a huge space (and some time) waste for the Foo.class * There's such a huge space (and some time) waste for the Foo.class
* syntax: the compiler sticks in a test of a static field in the * syntax: the compiler sticks in a test of a static field in the
@ -2536,6 +2538,7 @@ public class ScriptRuntime {
} }
return true; return true;
} }
/** /**
* Prepare for calling name(...): return function corresponding to name and make current top * Prepare for calling name(...): return function corresponding to name and make current top
* scope available as ScriptRuntime.lastStoredScriptable() for consumption as thisObj. The * scope available as ScriptRuntime.lastStoredScriptable() for consumption as thisObj. The

Просмотреть файл

@ -100,6 +100,7 @@ public abstract class ScriptableObject
public static final int UNINITIALIZED_CONST = 0x08; public static final int UNINITIALIZED_CONST = 0x08;
public static final int CONST = PERMANENT | READONLY | UNINITIALIZED_CONST; public static final int CONST = PERMANENT | READONLY | UNINITIALIZED_CONST;
/** The prototype of this object. */ /** The prototype of this object. */
private Scriptable prototypeObject; private Scriptable prototypeObject;

Просмотреть файл

@ -134,6 +134,7 @@ public abstract class AstNode extends Node implements Comparable<AstNode> {
public static class PositionComparator implements Comparator<AstNode>, Serializable { public static class PositionComparator implements Comparator<AstNode>, Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
* Sorts nodes by (relative) start position. The start positions are relative to their * Sorts nodes by (relative) start position. The start positions are relative to their
* parent, so this comparator is only meaningful for comparing siblings. * parent, so this comparator is only meaningful for comparing siblings.

Просмотреть файл

@ -27,6 +27,7 @@ public interface DebugFrame {
* @param args the array of arguments * @param args the array of arguments
*/ */
public void onEnter(Context cx, Scriptable activation, Scriptable thisObj, Object[] args); public void onEnter(Context cx, Scriptable activation, Scriptable thisObj, Object[] args);
/** /**
* Called when executed code reaches new line in the source. * Called when executed code reaches new line in the source.
* *

Просмотреть файл

@ -26,8 +26,10 @@ public abstract class NativeArrayBufferView extends IdScriptableObject {
/** Many view objects can share the same backing array */ /** Many view objects can share the same backing array */
protected final NativeArrayBuffer arrayBuffer; protected final NativeArrayBuffer arrayBuffer;
/** The offset, in bytes, from the start of the backing array */ /** The offset, in bytes, from the start of the backing array */
protected final int offset; protected final int offset;
/** The length, in bytes, of the portion of the backing array that we use */ /** The length, in bytes, of the portion of the backing array that we use */
protected final int byteLength; protected final int byteLength;

Просмотреть файл

@ -11,7 +11,6 @@ import org.mozilla.javascript.Context;
import org.mozilla.javascript.Parser; import org.mozilla.javascript.Parser;
import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ast.AstRoot; import org.mozilla.javascript.ast.AstRoot;
import org.mozilla.javascript.tools.shell.Global;
/** This is a set of tests for parsing and using BigInts. */ /** This is a set of tests for parsing and using BigInts. */
public class BigIntTest { public class BigIntTest {
@ -24,7 +23,7 @@ public class BigIntTest {
cx = Context.enter(); cx = Context.enter();
cx.setLanguageVersion(Context.VERSION_ES6); cx.setLanguageVersion(Context.VERSION_ES6);
cx.getWrapFactory().setJavaPrimitiveWrap(false); cx.getWrapFactory().setJavaPrimitiveWrap(false);
global = new Global(cx); global = cx.initStandardObjects();
} }
@After @After

Просмотреть файл

@ -13,7 +13,7 @@ import java.util.Set;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.mozilla.javascript.Context; import org.mozilla.javascript.Context;
import org.mozilla.javascript.tools.shell.Global; import org.mozilla.javascript.Scriptable;
/** /**
* Unit tests to check forEach loops. * Unit tests to check forEach loops.
@ -72,8 +72,7 @@ public class ForEachForOfTest {
Utils.runWithAllOptimizationLevels( Utils.runWithAllOptimizationLevels(
cx -> { cx -> {
cx.setLanguageVersion(Context.VERSION_ES6); cx.setLanguageVersion(Context.VERSION_ES6);
final Global scope = new Global(); final Scriptable scope = cx.initStandardObjects();
scope.init(cx);
Dto dto = new Dto(); Dto dto = new Dto();
dto.setData("foo"); dto.setData("foo");
@ -90,8 +89,7 @@ public class ForEachForOfTest {
Utils.runWithAllOptimizationLevels( Utils.runWithAllOptimizationLevels(
cx -> { cx -> {
cx.setLanguageVersion(Context.VERSION_ES6); cx.setLanguageVersion(Context.VERSION_ES6);
final Global scope = new Global(); final Scriptable scope = cx.initStandardObjects();
scope.init(cx);
Dto dto = new Dto(); Dto dto = new Dto();
dto.setData("foo"); dto.setData("foo");
@ -108,8 +106,7 @@ public class ForEachForOfTest {
Utils.runWithAllOptimizationLevels( Utils.runWithAllOptimizationLevels(
cx -> { cx -> {
cx.setLanguageVersion(Context.VERSION_ES6); cx.setLanguageVersion(Context.VERSION_ES6);
final Global scope = new Global(); final Scriptable scope = cx.initStandardObjects();
scope.init(cx);
Dto dto = new Dto(); Dto dto = new Dto();
dto.setData("foo"); dto.setData("foo");
@ -127,8 +124,7 @@ public class ForEachForOfTest {
Utils.runWithAllOptimizationLevels( Utils.runWithAllOptimizationLevels(
cx -> { cx -> {
cx.setLanguageVersion(Context.VERSION_ES6); cx.setLanguageVersion(Context.VERSION_ES6);
final Global scope = new Global(); final Scriptable scope = cx.initStandardObjects();
scope.init(cx);
Dto dto = new Dto(); Dto dto = new Dto();
dto.setData("foo"); dto.setData("foo");

Просмотреть файл

@ -15,20 +15,29 @@ import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mozilla.javascript.Context; import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.EcmaError; import org.mozilla.javascript.EcmaError;
import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.tools.shell.Global;
public class JavaIterableTest { public class JavaIterableTest {
protected final Global global = new Global(); private Context cx;
private Scriptable global;
public JavaIterableTest() { @Before
global.init(ContextFactory.getGlobal()); public void init() {
cx = Context.enter();
global = cx.initStandardObjects();
}
@After
public void cleanup() {
Context.exit();
} }
@Test @Test

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше