GithubHelp home page GithubHelp logo

mozilla / rhino Goto Github PK

View Code? Open in Web Editor NEW
4.0K 174.0 826.0 25.15 MB

Rhino is an open-source implementation of JavaScript written entirely in Java

Home Page: https://rhino.github.io

License: Other

Java 33.32% HTML 0.14% JavaScript 65.35% Shell 0.33% Makefile 0.02% Perl 0.84%

rhino's Introduction

Rhino: JavaScript in Java

Rhino (234581759)

Rhino is an implementation of JavaScript in Java.

License

Rhino is licensed under the MPL 2.0.

Releases

The current release is Rhino 1.7.15. Please see the Release Notes.

Releases
Rhino 1.7.15May 3, 2024
Rhino 1.7.14January 6, 2022
Rhino 1.7.13September 2, 2020
Rhino 1.7.12January 13, 2020
Rhino 1.7.11May 30, 2019
Rhino 1.7.10April 9, 2018
Rhino 1.7.9March 15, 2018
Rhino 1.7.8January 22, 2018
Rhino 1.7.7.2August 24, 2017
Rhino 1.7.7.1February 2, 2016
Rhino 1.7.7June 17, 2015
Rhino 1.7.6April 15, 2015
Rhino 1.7R5January 29, 2015

Compatibility table which shows which advanced JavaScript features from ES6, and ES2016+ are implemented in Rhino.

GitHub Action Status

Documentation

Information for script builders and embedders:

Archived

JavaDoc for all the APIs:

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

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

For normal development, you can build the code, run the static checks, and run all the tests like this:

git submodule init
git submodule update
./gradlew check

To just run the Rhino shell, you can do this from the top-level directory:

./gradlew run -q --console=plain

Alternately, you can build an all-in-one JAR and run that:

./gradlew shadowJar
java -jar rhino/build/libs/rhino-1.7.16-SNAPSHOT.jar

You can also run the benchmarks:

./gradlew jmh

Code Coverage

The "Jacoco" coverage is enabled by default for the main published modules as well as the special "tests" module. Coverage is generated for each of the main projects separately and available by running

./gradlew jacocoTestReport

To see an aggregated coverage report for everything, which is probably what you want, run

./gradlew testCodeCoverageReport

The result is in: ./tests/build/reports/jacoco/testCodeCoverageReport/html

Releasing and publishing new version

  1. Ensure all tests are passing
  2. Remove -SNAPSHOT from version in gradle.properties in project root folder
  3. Create file gradle.properties in $HOME/.gradle folder with following properties. Populate them with maven repo credentials and repo location.
mavenUser=
mavenPassword=
mavenSnapshotRepo=
mavenReleaseRepo=
  1. Run Gradle task to publish artifacts to Maven Central.
./gradlew publish
  1. Increase version and add -SNAPSHOT to it in gradle.properties in project root folder.
  2. Push gradle.properties to GitHub

Java 16 and later

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 --add-opens option to authorize the packages that your scripts shall use, for example:

--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

Most issues are managed on GitHub:

https://github.com/mozilla/rhino/issues

Contributing PRs

To submit a new PR, please use the following process:

  • Ensure that your entire build passes "./gradlew check". This will include code formatting and style checks and runs the tests.
  • Please write tests for what you fixed, unless you can show us that existing tests cover the changes. Use existing tests, such as those in "testsrc/org/mozilla/javascript/tests", as a guide.
  • If you fixed ECMAScript spec compatibility, take a look at test262.properties and see if you can un-disable some tests.
  • Push your change to GitHub and open a pull request.
  • Please be patient as Rhino is only maintained by volunteers and we may need some time to get back to you.
  • Thank you for contributing!

Code Formatting

Code formatting was introduced in 2021. The "spotless" plugin will fail your build if you have changed any files that have not yet been reformatted. Please use "spotlessApply" to reformat the necessary files.

If you are the first person to touch a big file that spotless wants to make 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 from more substantive changes.

Currently, you must be building on Java 11 for Spotless to run. We recommend that you have that ready. (We have not been able to figure out a version of Spotless and the Google formatting plugin that it uses that works on many Java versions.)

More Help

GitHub is the best place to go with questions. For example, we use "GitHub discussions":

https://github.com/mozilla/rhino/discussions

rhino's People

Contributors

anba avatar andreabergia avatar asashour avatar carlosame avatar diogoteles08 avatar ebourg avatar eshepelyuk avatar gbrail avatar hns avatar ibukanov avatar kitsoleksandrmaksymenko avatar kuzjka avatar maxistekfield avatar midgleyc avatar msmhrt avatar msridhar avatar norrisboyd avatar p-bakker avatar rbri avatar rpraml avatar sainaen avatar sideshowbarker avatar stijnkliemesch avatar syjer avatar szegedi avatar tntim96 avatar tonygermano avatar travisennis avatar tuchida avatar youngj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rhino's Issues

`default xml namespace` oddity

While debugging a function that uses default xml namespace while building a large document and calls out to other functions to build smaller nested chunks of the document, I noticed some sub elements were being written with xmlns="" and some weren't. I narrowed down the difference to the xmlns="" elements being generated by functions that contained inner functions. Here's an example that demonstrates the anomaly in 1.7R5:

function a() { return <a/>; }
function b() { var f = function() { }; return <b/>; }
function ab() { default xml namespace = 'urn:default'; var r = <ab/>; r.ab+=a(); r.ab+=b(); return r; }
ab()

Notice that var f = function() { }; is never used, just declared.

Result:

<ab xmlns="urn:default">
  <a/>
  <b xmlns=""/>
</ab>

Expected either:

<ab xmlns="urn:default">
  <a xmlns=""/>
  <b xmlns=""/>
</ab>

or

<ab xmlns="urn:default">
  <a/>
  <b/>
</ab>

Maybe? I can't tell from reading the E4X specification which if any of these is correct.

Java keywords not allowed in JavaScript?

I have a weird error and I'm not sure where this comes from. It looks like when using the RhinoScriptEngine that comes with Java, it is not allowed to use Java keywords in your JavaScript:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Test {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager ();
        ScriptEngine engine = manager.getEngineByName ("js");

        engine.eval("var obj = {};");
        engine.eval("obj.foo = 2;");        // OK
        engine.eval("obj.boolean = 2;");    // error
        engine.eval("obj.char = 2;");       // error
        engine.eval("obj.long = 2;");       // error
        engine.eval("obj.transient = 2;");  // error
        // etc... 
        // Java keywords not allowed in JavaScript?!
    }
}

Gives the following error:

Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: missing name after . operator (<Unknown source>#1) in <Unknown source> at line number 1
    at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:224)
    at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:240)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
    at Test.main(Test.java:12)
Caused by: sun.org.mozilla.javascript.internal.EvaluatorException: missing name after . operator (<Unknown source>#1)
    at sun.org.mozilla.javascript.internal.DefaultErrorReporter.runtimeError(DefaultErrorReporter.java:109)
    at sun.org.mozilla.javascript.internal.DefaultErrorReporter.error(DefaultErrorReporter.java:96)
    at sun.org.mozilla.javascript.internal.Parser.addError(Parser.java:231)
    at sun.org.mozilla.javascript.internal.Parser.addError(Parser.java:209)
    at sun.org.mozilla.javascript.internal.Parser.reportError(Parser.java:266)
    at sun.org.mozilla.javascript.internal.Parser.reportError(Parser.java:253)
    at sun.org.mozilla.javascript.internal.Parser.reportError(Parser.java:246)
    at sun.org.mozilla.javascript.internal.Parser.propertyAccess(Parser.java:2644)
    at sun.org.mozilla.javascript.internal.Parser.memberExprTail(Parser.java:2520)
    at sun.org.mozilla.javascript.internal.Parser.memberExpr(Parser.java:2495)
    at sun.org.mozilla.javascript.internal.Parser.unaryExpr(Parser.java:2369)
    at sun.org.mozilla.javascript.internal.Parser.mulExpr(Parser.java:2292)
    at sun.org.mozilla.javascript.internal.Parser.addExpr(Parser.java:2274)
    at sun.org.mozilla.javascript.internal.Parser.shiftExpr(Parser.java:2253)
    at sun.org.mozilla.javascript.internal.Parser.relExpr(Parser.java:2226)
    at sun.org.mozilla.javascript.internal.Parser.eqExpr(Parser.java:2196)
    at sun.org.mozilla.javascript.internal.Parser.bitAndExpr(Parser.java:2183)
    at sun.org.mozilla.javascript.internal.Parser.bitXorExpr(Parser.java:2170)
    at sun.org.mozilla.javascript.internal.Parser.bitOrExpr(Parser.java:2157)
    at sun.org.mozilla.javascript.internal.Parser.andExpr(Parser.java:2144)
    at sun.org.mozilla.javascript.internal.Parser.orExpr(Parser.java:2131)
    at sun.org.mozilla.javascript.internal.Parser.condExpr(Parser.java:2107)
    at sun.org.mozilla.javascript.internal.Parser.assignExpr(Parser.java:2076)
    at sun.org.mozilla.javascript.internal.Parser.expr(Parser.java:2053)
    at sun.org.mozilla.javascript.internal.Parser.nameOrLabel(Parser.java:1811)
    at sun.org.mozilla.javascript.internal.Parser.statementHelper(Parser.java:1075)
    at sun.org.mozilla.javascript.internal.Parser.statement(Parser.java:944)
    at sun.org.mozilla.javascript.internal.Parser.parse(Parser.java:569)
    at sun.org.mozilla.javascript.internal.Parser.parse(Parser.java:531)
    at sun.org.mozilla.javascript.internal.Context.compileImpl(Context.java:2438)
    at sun.org.mozilla.javascript.internal.Context.compileReader(Context.java:1355)
    at sun.org.mozilla.javascript.internal.Context.compileReader(Context.java:1327)
    at sun.org.mozilla.javascript.internal.Context.evaluateReader(Context.java:1166)
    at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:214)
    ... 3 more

This does happen when using Java 7 Oracle. It does not happen when using Java 6 OpenJDK or Java 7 OpenJDK. And it does not happen when using the standalone Rhino js.jar file.

in js how to use java reflect

java

java.util.Date.class.getField()

js

how to wirte?

  1. new java.util.Date().getClass().getField()
  2. Class.forName('java.util.Date').getField()

Is there a simple method to get the Class object?

Failing test under Mac OS X

The test suite includes a char-002.js test file which expects File.separatorChar to be equal to 58 (':') whereas on Mac OS X like unix, it is equal to 47. This fails the test suite.

I would have provided a patch but the file is in tests.tar.gz which does not seem to be a part of the rhino sources. How can I proceed to make the tests pass in my environment ? I would be glad to provide a patch back once the issue solved.

throws CodeGenerator NPE where I expected a JS ReferenceError

I'm running current git master. This is the simplest testcase I could find:

[foo.bar.id] = true

(I noticed that when I remove the last property access - [foo.bar] = true - I get a ReferenceError as expected)

~/rhino$ java -jar build/rhino1_7R5pre/js.jar -opt -1
Rhino 1.7 release 5 PRERELEASE 2013 02 26
js> [foo.bar.id] = true;
Exception in thread "main" java.lang.NullPointerException
at org.mozilla.javascript.CodeGenerator.visitExpression(CodeGenerator.java:497)
at org.mozilla.javascript.CodeGenerator.visitExpression(CodeGenerator.java:632)
at org.mozilla.javascript.CodeGenerator.visitExpression(CodeGenerator.java:704)
at org.mozilla.javascript.CodeGenerator.visitExpression(CodeGenerator.java:527)
at org.mozilla.javascript.CodeGenerator.visitExpression(CodeGenerator.java:959)
at org.mozilla.javascript.CodeGenerator.visitExpression(CodeGenerator.java:527)
at org.mozilla.javascript.CodeGenerator.visitExpression(CodeGenerator.java:959)
at org.mozilla.javascript.CodeGenerator.visitStatement(CodeGenerator.java:383)
at org.mozilla.javascript.CodeGenerator.visitStatement(CodeGenerator.java:276)
at org.mozilla.javascript.CodeGenerator.generateICodeFromTree(CodeGenerator.java:113)
at org.mozilla.javascript.CodeGenerator.compile(CodeGenerator.java:83)
at org.mozilla.javascript.Interpreter.compile(Interpreter.java:194)
at org.mozilla.javascript.Context.compileImpl(Context.java:2377)
at org.mozilla.javascript.Context.compileString(Context.java:1335)
at org.mozilla.javascript.Context.compileString(Context.java:1324)
at org.mozilla.javascript.tools.shell.Main.processSource(Main.java:491)
at org.mozilla.javascript.tools.shell.Main.processFiles(Main.java:176)
at org.mozilla.javascript.tools.shell.Main$IProxy.run(Main.java:100)
at org.mozilla.javascript.Context.call(Context.java:489)
at org.mozilla.javascript.ContextFactory.call(ContextFactory.java:504)
at org.mozilla.javascript.tools.shell.Main.exec(Main.java:158)
at org.mozilla.javascript.tools.shell.Main.main(Main.java:136)

Context(org.mozilla.javascript.ContextFactory) is not public in org.mozilla.javascript.Context; cannot be accessed from outside package

So depending on how Rhino is loaded the subject error may or may not occur. If I run the code from eclipse it works but when I run in maven it doesn't work. The complete error is as follows:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project rights-management: Compilation failure
[ERROR] /Users/sowens/Documents/workspace/rights-management/src/main/java/com/disney/tss/ft/rightsManagement/logic/scripted/ScriptExecutionContextFactory.java:[19,25] Context(org.mozilla.javascript.ContextFactory) is not public in org.mozilla.javascript.Context; cannot be accessed from outside package

The code in question is:
I have marked line 19 with 19>>> that is not part of the code listing.

public class ScriptExecutionContextFactory extends ContextFactory {
    public static class ScriptExecutionContext extends Context {
        final long startTime;
        protected ScriptExecutionContext(ScriptExecutionContextFactory contextFactory){
19>>>       super(contextFactory);
            this.startTime = System.currentTimeMillis();
        }
    }

    public ScriptExecutionContextFactory(){
        super();
    }

yada yada yada ...;

Suggestion: Split jar into core and tools

The Rhino jar bundles tools, REPL and debugger in it.

I suggest that the Rhino package be split into separate jars. Tentatively into "core" and "tools".

This will help reduce the size of the "core" package, which is what many projects would probably use for deployment.

Apart from size, there are other benefits to be had from a security point of view, such as reduction in surface-area of attacks.

The next major Rhino release (say 1.8.0) might be an opportunity to make the change.

non strict equality

If I try to execute the following code:

js > java.lang.System.out.println('0' == 0.0);

I get FALSE. Executing the same code ('0' == 0.0) in the Firefox Console it returns TRUE.

What should be the expected behavior?

Invokedynamic breaks CommonJS require()

After merging the invokedynamic branch with 1.7 / 1.8 branches, Rhino generates a ClassCastException when require('./foo.js') is called. The stack trace looks something like this

[CommonJS] Support for loading (nodejs) packages

Hello,

I'm trying to load a module's folder instead of a specific js file and I'm getting a error:

ReferenceError: "index" is not defined. (file:/****/modules/test#1).

  1. The root of the modules is configured to be: file:/****/modules/

  2. From a script (modules.js) I'm doing:

    var test = require("test");

    Where, test in a folder inside modules with an index.js file defining the module's startup.

Important:

If I define the require as:

    var test = require("test/index");

The code works perfect.

My Findings:

I'm using the class UrlModuleSourceProvider, and I guess I could check if the moduleId is a
directory, and then append the string "/index" to the moduleId in that situation, but I'm not 
sure if that is the best way to add the behaviour.

Could someone give me a hand?

Thanks!

Wrong toSource result for Arrays with trailing null/undefined elements

Array.prototype.toSource() returns a wrong result if the last element of the array is a null/undefined value:

Rhino 1.7 release 3 2011 07 19
js> [1].toSource()
[1]
js> [1,2].toSource()
[1, 2]
js> [null, 2].toSource()
[, 2]
js> [1, null].toSource()
[1, , ]
js> [1, undefined].toSource()
[1, , ]

Unable to get rhino to convert json

The following unit test fails due to the fact that Rhino 1.7r4 does not initialize the global scope with JSON:

@Test
public void findOutTypeReturnedFromRhino() throws JsonProcessingException{
    String jsScript = "function f(){ return JSON.stringify({property1:\"hello\", array1:[{subobject:1}]}); } f();";
    Context jsContext = Context.enter();
    Scriptable jsScope= jsContext.initStandardObjects();
    Object result = jsContext.evaluateString(jsScope, jsScript, "myscript.js", 1, null);
    System.out.println(result.getClass().getName());    
}

The exception returned is:
org.mozilla.javascript.EcmaError: ReferenceError: "JSON" is not defined. (myscript.js#1)
at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3557)
... more ...

load() doesn't update global scope with -require option set

test.js

load(["underscore.js"]);

_.each([1,2,3], function(n){ print(n); });

Without -require

$ java -jar ~/dev/rhino/build/rhino1_7R5pre/js.jar test.js
1
2
3

With -require

$ java -jar ~/dev/rhino/build/rhino1_7R5pre/js.jar -require test.js
js: uncaught JavaScript runtime exception: ReferenceError: "_" is not defined.

The same with 1.7R4

sandboxed modules cannot require with dot slash identifiers

Previously, it was possible to install a "sandboxed" require and require modules that used dot/slash identifiers to require other modules.

E.g.

main.js

try {
    var success = require("dot-relative/main").success;
    print("Success: " + success);
} catch (err) {
    print("Failed: " + err.message);
}

dot-relative/main.js

// ./sub/main is within the sandbox, right?
exports.success = require("./sub/main").success;

dot-relative/sub/main.js

exports.success = true;

At 2442919:

$ java -jar js.jar -modules . -sandbox main.js 
Failed: Module "dot-relative/sub/main" is not contained in sandbox.

`toSource()` on sync'ed function fails with TypeError

With git master:

java -jar build/rhino1_7R5pre/js.jar 
@IMPLEMENTATION.VERSION@
js> var fooSync = sync(function() {})
js> fooSync.toSource
function toSource() { [native code for Function.toSource, arity=1] }
js> fooSync.toSource()
js: uncaught JavaScript runtime exception: TypeError: Method "toSource" called on incompatible object.

I expected toSource() to work like on a non-synced function.

ClassFileWriter out of range index processing 2.4.3 jshint-rhino.js

From jshint/jshint#1422 using src
https://raw2.github.com/jshint/jshint/2.x/dist/jshint-rhino.js

Running a 2.3+ version of jshint-rhino.js through 1.7R5 causes the stack trace below processing a large array of constant values (line 28779).

$ rhino jshint-rhino.js 
Exception in thread "main" java.lang.IllegalArgumentException: out of range index
    at org.mozilla.classfile.ClassFileWriter.add(ClassFileWriter.java:579)
    at org.mozilla.classfile.ClassFileWriter.addLoadConstant(ClassFileWriter.java:676)
    at org.mozilla.classfile.ClassFileWriter.addPush(ClassFileWriter.java:929)
    at org.mozilla.javascript.optimizer.Codegen.pushNumberAsObject(Codegen.java:1087)
    at org.mozilla.javascript.optimizer.BodyCodegen.generateExpression(Codegen.java:2238)
    at org.mozilla.javascript.optimizer.BodyCodegen.visitArrayLiteral(Codegen.java:3085)
    at org.mozilla.javascript.optimizer.BodyCodegen.generateExpression(Codegen.java:2318)
    at org.mozilla.javascript.optimizer.BodyCodegen.visitSetProp(Codegen.java:5025)
    at org.mozilla.javascript.optimizer.BodyCodegen.generateExpression(Codegen.java:2592)
    at org.mozilla.javascript.optimizer.BodyCodegen.generateStatement(Codegen.java:2033)
    at org.mozilla.javascript.optimizer.BodyCodegen.generateStatement(Codegen.java:1858)
    at org.mozilla.javascript.optimizer.BodyCodegen.generateBodyCode(Codegen.java:1289)
    at org.mozilla.javascript.optimizer.Codegen.generateCode(Codegen.java:306)
    at org.mozilla.javascript.optimizer.Codegen.compileToClassFile(Codegen.java:166)
    at org.mozilla.javascript.optimizer.Codegen.compile(Codegen.java:75)
    at org.mozilla.javascript.Context.compileImpl(Context.java:2377)
    at org.mozilla.javascript.Context.compileString(Context.java:1335)
    at org.mozilla.javascript.Context.compileString(Context.java:1324)
    at org.mozilla.javascript.tools.shell.Main.processFileSecure(Main.java:591)
    at org.mozilla.javascript.tools.shell.Main.processFile(Main.java:556)
    at org.mozilla.javascript.tools.shell.Main.processSource(Main.java:527)
    at org.mozilla.javascript.tools.shell.Main.processFiles(Main.java:176)
    at org.mozilla.javascript.tools.shell.Main$IProxy.run(Main.java:100)
    at org.mozilla.javascript.Context.call(Context.java:489)
    at org.mozilla.javascript.ContextFactory.call(ContextFactory.java:504)
    at org.mozilla.javascript.tools.shell.Main.exec(Main.java:158)
    at org.mozilla.javascript.tools.shell.Main.main(Main.java:136)

In object literals, Rhino considers the property names `13` and `0x13` to be identical

Rhino throws an exception when it tries to parse the following file, with the message Property "13" already defined in this object literal:

'use strict';

var foo = {
    13: 'bar',
    0x13: 'baz'
};

This is because Rhino treats 13 and 0x13 as identical values, and in strict mode, object literals can't contain duplicate property names.

This bug is similar to #99.

Git project

Hi all,

I noticed few points in the current Git project:

  • There are some confusing tags, like "head" and "done", I believe they should be removed or renamed to something more meaningful
  • "build" and "lib" folders should be added to .gitignore
  • .csvignore still exists in three places: root, in "toolsrc/org/mozilla/javascript/tools/debugger" and its "downloaded" subfolder.

Thanks,
Ahmed

OSGi Manifest

Please add OSGi manifest headers to the rhino release.

Missing conversion from javadate to nativedate

Because of this missing conversion, comparison between java dates and javascript dates is not possible.

I do have a patch for this, however.. I cannot see where to put the diff so others can review this.

RHINO USAGE WARNING

The warning message that Rhino outputs when duplicate methods are registered may be unkind.
Can't find which class has duplicate method xxx from the message like "warning: RHINO USAGE WARNING: Invalid method "jsFunction_xxx": name "xxx" is already in use."

Please include class name in the message.

Change minimum Java version to 1.6

There is legacy code in the codebase to support Java 1.5, and we still use "retroweaver" to produce a JAR that is compatible with 1.4. However, we have no test infrastructure for this and a very limited audience. I think it's much safer if versions 1.8.0 and after have the 1.4 compatiblity stuff removed, and are compiled for version 1.6 and above.

Although 1.6 is end of life, I know that a lot of products still use it, however, so it would not make sense to support only newer versions.

Position incorrect for Parenthesized expression.

Given a file containing:

(a);

The absolute position of the AstNode will be 1 (the char index of the 'a').
Expected absolute position to be 0 (the index for the '(').

Contrast this with an array literal which has absolute position set correctly:

[a];

PVS-Studio

PVS-Studio: http://www.viva64.com/en/pvs-studio/

V567 Undefined behavior. The 'currentMap' variable is modified while being used twice between sequence points. aossessionmanager.cpp 140

u4 AOSSessionManager::threadprocSessionManager(AThread& thread)
{
....
currentMap = ((++currentMap) % pThis->m_HolderSize);
....
}


V576 Incorrect format. Consider checking the fourth actual argument of the 'sprintf_s' function. To print the value of pointer the '%p' should be used. memleakdetect.cpp 231

void* address;

void CMemLeakDetect::dumpMemoryTrace()
{
....
sprintf_s(buf, MLD_MAX_NAME_LENGTH, "Memory Leak <0x%X> "
"bytes(%d) occurance(%d) %s(%d)\n",
ainfo.address, ainfo.size, ainfo.occurance,
ainfo.fileName, ainfo.lineNumber);
....
}

And:
V576 Incorrect format. Consider checking the fourth actual argument of the 'sprintf_s' function. To print the value of pointer the '%p' should be used. memleakdetect.cpp 236

V576 Incorrect format. A different number of actual arguments is expected while calling 'sprintf_s' function. Expected: 4. Present: 5. memleakdetect.cpp 490

V662 Consider inspecting the loop expression. Different containers are utilized for setting up initial and final values of the iterator. aosconfiguration.cpp 93

MAP_LOCALE_DIRS m_LocaleStaticDirs;
MAP_LOCALE_DIRS m_LocaleDataDirs;

void AOSConfiguration::debugDump(std::ostream& os, int indent) const
{
....
for (AOSConfiguration::MAP_LOCALE_DIRS::const_iterator cit =
m_LocaleStaticDirs.begin();
cit != m_LocaleDataDirs.end(); ++cit)
....

}

V576 Incorrect format. Consider checking the sixth actual argument of the 'sprintf_s' function. The SIGNED integer type argument is expected. memleakdetect.cpp 261

DWORD memoccurance;

void CMemLeakDetect::dumpMemoryTrace()
{
....
_stprintf_s(buf, MLD_MAX_NAME_LENGTH,
_T("Total %d Memory Leaks: %d bytes Total Alocations %d\n\n"),
numLeaks, totalSize, memoccurance);
....
}

And
V576 Incorrect format. Consider checking the fifth actual argument of the 'sprintf_s' function. The SIGNED integer type argument is expected. memleakdetect.cpp 231
V576 Incorrect format. Consider checking the sixth actual argument of the 'sprintf_s' function. The SIGNED integer type argument is expected. memleakdetect.cpp 231
V576 Incorrect format. Consider checking the eighth actual argument of the 'sprintf_s' function. The SIGNED integer type argument is expected. memleakdetect.cpp 231
V576 Incorrect format. Consider checking the fifth actual argument of the 'sprintf_s' function. The SIGNED integer type argument is expected. memleakdetect.cpp 236
V576 Incorrect format. Consider checking the sixth actual argument of the 'sprintf_s' function. The SIGNED integer type argument is expected. memleakdetect.cpp 236
V576 Incorrect format. Consider checking the fourth actual argument of the 'sprintf_s' function. The SIGNED integer type argument is expected. memleakdetect.cpp 256
V576 Incorrect format. Consider checking the fifth actual argument of the 'sprintf_s' function. The SIGNED integer type argument is expected. memleakdetect.cpp 479

Error parsing commandline module path in Windows

The command:

java -cp js.jar org.mozilla.javascript.tools.shell.Main -modules "C:\Users\Gimmi\Sources\jsmake\"

Throws this rerror on Windows:

Exception in thread "main" java.lang.RuntimeException: java.net.URISyntaxException: Illegal character in path at index 5: Users\Gimmi\Sources\jsmake
        at org.mozilla.javascript.tools.shell.Global.installRequire(Global.java:182)
        at org.mozilla.javascript.tools.shell.Main$IProxy.run(Main.java:131)
        at org.mozilla.javascript.Context.call(Context.java:521)
        at org.mozilla.javascript.ContextFactory.call(ContextFactory.java:535)
        at org.mozilla.javascript.tools.shell.Main.exec(Main.java:198)
        at org.mozilla.javascript.tools.shell.Main.main(Main.java:174)
Caused by: java.net.URISyntaxException: Illegal character in path at index 5: Users\Gimmi\Sources\jsmake
        at java.net.URI$Parser.fail(URI.java:2809)
        at java.net.URI$Parser.checkChars(URI.java:2982)
        at java.net.URI$Parser.parseHierarchical(URI.java:3066)
        at java.net.URI$Parser.parse(URI.java:3024)
        at java.net.URI.(URI.java:578)
        at org.mozilla.javascript.tools.shell.Global.installRequire(Global.java:170)
        ... 5 more

This command instead seems to work (note the "" replaced with "/"):

java -cp js.jar org.mozilla.javascript.tools.shell.Main -modules "file:///C:/Users/Gimmi/Sources/jsmake/"

serialize() vs print() gotchas with UTF-8

Rhino (git 5f1ad11) (latest as of 7 July 2013) ...

serialize() munges random UTF-8 chars on both Windows and Centos. (i.e. the […] ellipsis worked, the horizontal [-] failed .. this is not a minus sign. Therefore, for me, serialize() is not trustworthy)

My workaround was to use Centos and redirection in order to save processed data using print()

in my stripped down as an example wrapper.js file...

...
var infile = arguments[0];
serialize(readFile(infile, 'UTF-8'), 'output_filename');
...

java -jar rhinojar ./wrapper.js named_file_containing_utf-8_chars

fails

However,
...
var infile = arguments[0];
print(readFile(infile, 'UTF-8'));
...

java -jar rhinojar ./wrapper.js named_file_containing_utf-8_chars > output_filename

works

... as it turned out, serialize() will also output a BOM which I didn't want. Therefore, print() won out, however, due to Windows cmd limitations, redirection of print() data containing utf-8 will fail without some effort. It was easier to install Java and Ant under Centos instead of chasing after Windows peculiarities.

Hope this report helps.

Caching compiled scripts in Google App Engine

I am looking to cache compiled scripts in Google App Engine. App Engine does some interesting things in the cloud. For local environments it is enough to stick the compiled script into a static hash, however in Google App Engine there is no guarantee that the class will stay loaded over time. As such I am getting poor hit ratios for compiled scripts stored in this way.

I tried to store the compiled script in memcache, but I run into an issue on retrieval from memcache in that the generated class used to represent that compiled script is not found by Google App Engine class loader.

I believe I can get good performance is I was able to cache the compile bytes that represent the AST created by the interpreter in memcache, then somehow construct a Script implementing object from that information.

My question is, is this feasible, can I expect a performance improvement with this method, or is there another approach I could try instead?

Thanks again for all your hard work on Rhino. It is truely a great piece of software!

ES5 Object not accessible when used in commonjs module

This code:

Object.defineProperties(obj, {
"property1": { value: true, writable: true },
"property2": { value: "Hello", writable: false}
});

will fail with the following exception:

org.mozilla.javascript.EcmaError: ReferenceError: "Object" is not defined.

Put old ES3 reserved words behind a flag

Rhino currently chokes on this code that contains an ES3 reserved word.

options.long

Java keywords that aren't used in JavaScript are not reserved anymore, as of ES5:
http://ecma-international.org/ecma-262/5.1/#sec-7.6.1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Reserved_Words

For this reason, I think that the JS tokenizer should only choke on ES3 reserved words when a flag is set. (or, even better, not at all)

The relevant code seems to be here:
https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/TokenStream.java#L135

Once that is fixed, the map below should probably be re-generated.
https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/TokenStream.java#L153

Parser fails on get/set in object literal in strict mode

getset.js:

(function () {
    "use strict";

    var a = {
        get value() {
            return this._value;
        },

        set value(val) {
            this._value = val;
        },
    };

})();

Output:

$ java -classpath "./lib/js.jar" org.mozilla.javascript.tools.shell.Main  getset.js
js: "getset.js", line 11: Property "value" already defined in this object literal.
js:         },
js: ........^

This isn't a problem in non-strict mode, since "duplicate" property declarations are permitted in that case.

Referencing an Object key that is a number/integer

We are passing in a NativeObject to a function that has an inner object that has a number for a key.

document = {
"12345": {
"a":1
},
"abc": {
"a":1
}
};

function r( document ){
var x = document["12345"];
var y = document["abc"];
}

x will be undefined, y will be the correct value.

Using the latest official release from the RHINO site.

Release Rhino 1.7R5

On 2012-07-20 02:15:52 PDT, Hannes said:

This is a known regression in 1.7R4 that has been fixed in git master. It is
the main reason 1.7R5 will be released soon.

It’s been almost a year. When can we expect a new official release? Is there anything we can do to help with the new release? (It seems to me just a release based on the current master branch would be fine.)

NativeObject should implement equals method

The NativeObject class should implement an equals method in accordance with the Map interface that it implements.

"Compares the specified object with this map for equality. Returns true if the given object is also a map and the two Maps represent the same mappings. More formally, two maps t1 and t2 represent the same mappings if t1.entrySet().equals(t2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface."

Instantiation of abstract java classes fails in 1.7R4

In 1.7R4 trying to instantiate an abstract java class fails (in 1.7R3 this works):

var pkg = org.apache.lucene.analysis;
var impl = {
    "tokenStream": function(fieldName, reader) {
        var tokenStream = new pkg.standard.StandardTokenizer(Version.LUCENE_35, reader);
        tokenStream = new pkg.LowerCaseFilter(Version.LUCENE_35, tokenStream);
        tokenStream = new pkg.ngram.NGramTokenFilter(tokenStream, minGram, maxGram);
        return tokenStream;
    }
};

new org.apache.lucene.analysis.Analyzer(impl);
Resulting exception

error instantiating (Wrapped java.lang.NoSuchMethodException: adapter1.(org.mozilla.javascript.Scriptable, org.mozilla.javascript.ContextFactory)): class org.apache.lucene.analysis.Analyzer is interface or abstract

Stacktrace
org.mozilla.javascript.EvaluatorException: error instantiating (Wrapped java.lang.NoSuchMethodException: adapter1.<init>(org.mozilla.javascript.Scriptable, org.mozilla.javascript.ContextFactory) (<stdin>#13)): class org.apache.lucene.analysis.Analyzer is interface or abstract (<stdin>#13)
    at org.mozilla.javascript.tools.ToolErrorReporter.runtimeError(ToolErrorReporter.java:111)
    at org.mozilla.javascript.Context.reportRuntimeError(Context.java:913)
    at org.mozilla.javascript.Context.reportRuntimeError(Context.java:969)
    at org.mozilla.javascript.Context.reportRuntimeError2(Context.java:939)
    at org.mozilla.javascript.NativeJavaClass.construct(NativeJavaClass.java:197)
    at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1519)
    at script(<stdin>:13)
    at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:815)
    at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:109)
    at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
    at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
    at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:120)
    at org.mozilla.javascript.tools.shell.Main.processSource(Main.java:502)
    at org.mozilla.javascript.tools.shell.Main.processFiles(Main.java:178)
    at org.mozilla.javascript.tools.shell.Main$IProxy.run(Main.java:102)
    at org.mozilla.javascript.Context.call(Context.java:489)
    at org.mozilla.javascript.ContextFactory.call(ContextFactory.java:504)
    at org.mozilla.javascript.tools.shell.Main.exec(Main.java:160)
    at org.mozilla.javascript.tools.shell.Main.main(Main.java:138)

NativeArray#isEmpty() always returns true

Whatever the length of NativeArray is, isEmpty() always returns true.
This is because isEmpty() evaluates the counter instance variable not used in NativeArray class (length variable is used there instead).

How to reproduce the bug:

import static junit.framework.Assert.assertEquals;
(snip)
final NativeArray nativeArray = new NativeArray(1);
assertEquals(1, nativeArray.size()); // => OK
assertEquals(false, nativeArray.isEmpty()); // => Assertion Error

Expected Code:
In ScriptableObject#isEmpty(),

return size() == 0;

I think this should be fixed as NativeArray class implements java.util.List interface.

XML processing performance issue in high concurrency scenarios

Using Rhino in a high concurrency situation with JavaScript that contains XML markup (I believe it's called E4X, or ECMAScript) seems to be affected by a hard-coded resource pool due to 26ee7ee

Sample E4X Script:

var myXml = <root><someelement></someelement></root>

In our test environment we got multiple thread with the following stack-trace:

"pool-62-thread-59" - Thread t@174
   java.lang.Thread.State: BLOCKED
at org.mozilla.javascript.xmlimpl.XmlProcessor.getDocumentBuilderFromPool(XmlProcessor.java:182)
- waiting to lock <71a4d2e4> (a org.mozilla.javascript.xmlimpl.XmlProcessor) owned by "pool-62-thread-19" t@134
at org.mozilla.javascript.xmlimpl.XmlProcessor.toXml(XmlProcessor.java:255)
at org.mozilla.javascript.xmlimpl.XmlNode.createElement(XmlNode.java:119)
at org.mozilla.javascript.xmlimpl.XMLLibImpl.parse(XMLLibImpl.java:444)
at org.mozilla.javascript.xmlimpl.XMLLibImpl.ecmaToXml(XMLLibImpl.java:477)
at org.mozilla.javascript.xmlimpl.XMLObjectImpl.ecmaToXml(XMLObjectImpl.java:838)
at org.mozilla.javascript.xmlimpl.XML.jsConstructor(XML.java:229)
at org.mozilla.javascript.xmlimpl.XMLObjectImpl.execIdCall(XMLObjectImpl.java:626)
at org.mozilla.javascript.IdFunctionObject.call(IdFunctionObject.java:129)
at org.mozilla.javascript.BaseFunction.construct(BaseFunction.java:374)
at org.mozilla.javascript.ScriptRuntime.newObject(ScriptRuntime.java:2440)
at <truncated due to irrelevancy>
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

Locked ownable synchronizers:
- locked <6a3fc851> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)

Which caused the CPU to be under-utilized at 33%.

Since there's no way of knowing exactly how Rhino will be used I suggest letting the developer configure the size of this pool (or providing other methods to control this bottleneck).

Inconsistent iteration over Node children

Node implements Iterable allowing iteration over its children.

The problem is that the functionality seems to be only implemented in very few of AstNode``s children. It works for list-like ones (e.g.,Block) but doesn't for many others (e.g.IfStatement). It makes navigating over the AST very difficult. Yes,Visitor` helps to some degree, but it forces programming in a certain style.

Is this behavior intended?

Considering the children are already identified by the Visitor, couldn't they also be exposed through the iterator (or maybe a separate iterator)?

Thanks!

arguments not recognized when using "-main" commandline option

I think there's a bug in comman line parsing with "-main" option, here's the repro:

Create this script in a file called "main.js"

print('arguments: ' + arguments);

Run this command:

java -jar js.jar main.js p1 p2 p3

The result is this (correct):

arguments: p1,p2,p3

Run this command:

java -jar js.jar -main main.js p1 p2 p3

The result is this (wrong):

js: Couldn't read source file "p1: p1 (The system cannot find the file specified)".
arguments: p2,p3

commonjs require on windows

Hi,

rhino-1.7R4.
I'm experiencing difficulties to load commonjs modules on windows (win 7, powershell env). Please, precise how to properly load commonjs modules if behaviour is not fully standard. I'm just testing with underscore for using a popular module.
Thanks,

ex:
PS D:\temp>mkdir test
PS D:\temp>cd test
PS D:\temp>mkdir node_modules
PS D:\temp>npm install underscore
PS D:\temp\test> java org.mozilla.javascript.tools.shell.Main -require -modules ./node_modules
Rhino 1.7 release 4 2012 06 18
js> require("underscore")
js: "file:/D:/temp/test/node_modules/underscore", line 1: erreur de syntaxe
js: .npmignore
js: .^
js: "file:/D:/temp/test/node_modules/underscore", line 1: La compilation a produit 1 erreur(s) de syntaxe.

removing .npmignore
PS D:\temp\test> rm \node_modules\underscore.npmignore
PS D:\temp\test\node_modules> java org.mozilla.javascript.tools.shell.Main -require -modules ./node_modules
js> require("underscore")
js: uncaught JavaScript runtime exception: ReferenceError: "CNAME" is not defined

removing all folders
PS D:\temp\test\node_modules> java org.mozilla.javascript.tools.shell.Main -require -modules ./node_modules
js> require("underscore")
js: uncaught JavaScript runtime exception: ReferenceError: "favicon" is not defined

PS D:\temp\test\node_modules> ls .\underscore
package.json
README.md
underscore-min.js
underscore.js

PS D:\temp\test\node_modules> java org.mozilla.javascript.tools.shell.Main -require -modules ./node_modules
js> require("underscore")
js: uncaught JavaScript runtime exception: ReferenceError: "README" is not defined

PS D:\temp\test\node_modules> java org.mozilla.javascript.tools.shell.Main -require -modules ./node_modules
js> require("underscore")
js: uncaught JavaScript runtime exception: ReferenceError: "underscore" is not defined

js> require("underscore.js")
js: exception from uncaught JavaScript throw: Error: Module "underscore.js" not found.

in fact cannot load it!

Also, couldn't modules full Path be prefixed with "/" automatically on windows?

PS D:\temp> java org.mozilla.javascript.tools.shell.Main -require -modules /D:/Javascript/Code
Rhino 1.7 release 4 2012 06 18
js> require("time")
[object Object]
js> quit()
PS D:\temp> java org.mozilla.javascript.tools.shell.Main -require -modules D:/path/to/modules
Rhino 1.7 release 4 2012 06 18
js> require("aModule")
org.mozilla.javascript.WrappedException: Wrapped java.net.MalformedURLException: unknown protocol: d
at org.mozilla.javascript.Context.throwAsScriptRuntimeEx(Context.java:1754)
at org.mozilla.javascript.commonjs.module.Require.getModule(Require.java:375)
at org.mozilla.javascript.commonjs.module.Require.getExportedModuleInterface(Require.java:264)
at org.mozilla.javascript.commonjs.module.Require.call(Require.java:218)
at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
at org.mozilla.javascript.gen._stdin__1._c_script_0(Unknown Source)
at org.mozilla.javascript.gen._stdin__1.call(Unknown Source)
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
at org.mozilla.javascript.gen._stdin__1.call(Unknown Source)
at org.mozilla.javascript.gen._stdin__1.exec(Unknown Source)
at org.mozilla.javascript.tools.shell.Main.processSource(Main.java:502)
at org.mozilla.javascript.tools.shell.Main.processFiles(Main.java:178)
at org.mozilla.javascript.tools.shell.Main$IProxy.run(Main.java:102)
at org.mozilla.javascript.Context.call(Context.java:489)
at org.mozilla.javascript.ContextFactory.call(ContextFactory.java:504)
at org.mozilla.javascript.tools.shell.Main.exec(Main.java:160)
at org.mozilla.javascript.tools.shell.Main.main(Main.java:138)
Caused by: java.net.MalformedURLException: unknown protocol: d
at java.net.URL.(URL.java:590)
at java.net.URL.(URL.java:480)
at java.net.URL.(URL.java:429)
at java.net.URI.toURL(URI.java:1096)
at org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider.loadFromActualUri(UrlModuleSourceProvider.java:137)
at org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider.loadFromUri(UrlModuleSourceProvider.java:127)
at org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider.loadFromPathList(UrlModuleSourceProvider.java:112)
at org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider.loadFromPrivilegedLocations(UrlModuleSourceProvider.java:93)
at org.mozilla.javascript.commonjs.module.provider.ModuleSourceProviderBase.loadSource(ModuleSourceProviderBase.java:41)
at org.mozilla.javascript.commonjs.module.provider.CachingModuleScriptProviderBase.getModuleScript(CachingModuleScriptProviderBase.java:69)
at org.mozilla.javascript.commonjs.module.provider.SoftCachingModuleScriptProvider.getModuleScript(SoftCachingModuleScriptProvider.java:67)
at org.mozilla.javascript.commonjs.module.Require.getModule(Require.java:363)
... 16 more

RequireJS and transcluded modules are not found in the sandbox

I've been trying to track down a strange require.js issue with rhino in my coffeescript-maven-plugin that appeared a month or two again in the rhino 1.8 branch and have finally traced down what I believe to be the problem.

I'm setting up a sandbox'd {{RequireJS}} context to load javascript off my plugins classpath, the coffee-script.js main modules transcludes other modules with:

_ref = require('./lexer'), Lexer = _ref.Lexer, RESERVED = _ref.RESERVED;
parser = require('./parser').parser;

and these now fail to be found in the sandbox. I've traced this down to a problem in {{org.mozilla.javascript.commonjs.module.provider.CachingModuleScriptProviderBase#getModuleScript}}:

public ModuleScript getModuleScript(Context cx, String moduleId,
        URI moduleUri, Scriptable paths) throws Exception
{

    final CachedModuleScript cachedModule1 = getLoadedModule(moduleId);
    final Object validator1 = getValidator(cachedModule1);
    final ModuleSource moduleSource = (moduleUri == null)
            ? moduleSourceProvider.loadSource(moduleId, paths, validator1)
            : moduleSourceProvider.loadSource(moduleUri, validator1);
    if(moduleSource == ModuleSourceProvider.NOT_MODIFIED) {

In the instance of the transcluded modules, {{moduleUri}} is set to a {{file://}} or {{jar://}} URI so the script provider tries to load it directly, rather than via the sandbox.

In {{org.mozilla.javascript.commonjs.module.Require#call}}:

        } else {
            // try to convert to a relative URI rooted on base
            id = base.relativize(current).resolve(id).toString();
            if (id.charAt(0) == '.') {

the module id being loaded ( {{./lexer}} ) is being relativized to {{lexer}}, and loaded as a non sandboxed module in {{getExportedModuleInterface}}.

I'm wondering why {{org.mozilla.javascript.commonjs.module.Require#call}} isn't calling:

// try to get the module script to see if it is on the module path
moduleScript = moduleScriptProvider.getModuleScript(
  cx, mainModuleId, null, paths);

as {{org.mozilla.javascript.commonjs.module.Require#requireMain}} is doing, this should allow recursive modules to be loaded from a sandbox.

I was initially going to wait until I had investigated further and tried some patches, but with the imminent release of 1.7R4 I thought I'd post this right now.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.