--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/Main.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/Main.java Thu Aug 28 14:53:37 2014 -0700
@@ -32,6 +32,7 @@
import java.io.PrintWriter;
import jdk.internal.org.objectweb.asm.ClassReader;
import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.util.CheckClassAdapter;
/**
@@ -39,6 +40,11 @@
*
*/
public class Main {
+ /**
+ * ASM version to be used by nasgen tool.
+ */
+ public static final int ASM_VERSION = Opcodes.ASM5;
+
private static final boolean DEBUG = Boolean.getBoolean("nasgen.debug");
private interface ErrorReporter {
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java Thu Aug 28 14:53:37 2014 -0700
@@ -32,7 +32,6 @@
import static jdk.internal.org.objectweb.asm.Opcodes.ALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.ANEWARRAY;
import static jdk.internal.org.objectweb.asm.Opcodes.ARETURN;
-import static jdk.internal.org.objectweb.asm.Opcodes.ASM4;
import static jdk.internal.org.objectweb.asm.Opcodes.ASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.BALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.BASTORE;
@@ -96,7 +95,7 @@
private final Type[] argumentTypes;
MethodGenerator(final MethodVisitor mv, final int access, final String name, final String descriptor) {
- super(ASM4, mv);
+ super(Main.ASM_VERSION, mv);
this.access = access;
this.name = name;
this.descriptor = descriptor;
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/NullVisitor.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/NullVisitor.java Thu Aug 28 14:53:37 2014 -0700
@@ -29,7 +29,6 @@
import jdk.internal.org.objectweb.asm.ClassVisitor;
import jdk.internal.org.objectweb.asm.FieldVisitor;
import jdk.internal.org.objectweb.asm.MethodVisitor;
-import jdk.internal.org.objectweb.asm.Opcodes;
/**
* A visitor that does nothing on visitXXX calls.
@@ -37,7 +36,7 @@
*/
public class NullVisitor extends ClassVisitor {
NullVisitor() {
- super(Opcodes.ASM4);
+ super(Main.ASM_VERSION);
}
@Override
@@ -47,7 +46,7 @@
final String desc,
final String signature,
final String[] exceptions) {
- return new MethodVisitor(Opcodes.ASM4) {
+ return new MethodVisitor(Main.ASM_VERSION) {
@Override
public AnnotationVisitor visitAnnotationDefault() {
return new NullAnnotationVisitor();
@@ -67,7 +66,7 @@
final String desc,
final String signature,
final Object value) {
- return new FieldVisitor(Opcodes.ASM4) {
+ return new FieldVisitor(Main.ASM_VERSION) {
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
return new NullAnnotationVisitor();
@@ -82,7 +81,7 @@
private static class NullAnnotationVisitor extends AnnotationVisitor {
NullAnnotationVisitor() {
- super(Opcodes.ASM4);
+ super(Main.ASM_VERSION);
}
}
}
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInfoCollector.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInfoCollector.java Thu Aug 28 14:53:37 2014 -0700
@@ -55,7 +55,7 @@
private String javaClassName;
ScriptClassInfoCollector(final ClassVisitor visitor) {
- super(Opcodes.ASM4, visitor);
+ super(Main.ASM_VERSION, visitor);
}
ScriptClassInfoCollector() {
@@ -80,7 +80,7 @@
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
final AnnotationVisitor delegateAV = super.visitAnnotation(desc, visible);
if (SCRIPT_CLASS_ANNO_DESC.equals(desc)) {
- return new AnnotationVisitor(Opcodes.ASM4, delegateAV) {
+ return new AnnotationVisitor(Main.ASM_VERSION, delegateAV) {
@Override
public void visit(final String name, final Object value) {
if ("value".equals(name)) {
@@ -98,7 +98,7 @@
public FieldVisitor visitField(final int fieldAccess, final String fieldName, final String fieldDesc, final String signature, final Object value) {
final FieldVisitor delegateFV = super.visitField(fieldAccess, fieldName, fieldDesc, signature, value);
- return new FieldVisitor(Opcodes.ASM4, delegateFV) {
+ return new FieldVisitor(Main.ASM_VERSION, delegateFV) {
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
final AnnotationVisitor delegateAV = super.visitAnnotation(descriptor, visible);
@@ -117,7 +117,7 @@
addScriptMember(memInfo);
- return new AnnotationVisitor(Opcodes.ASM4, delegateAV) {
+ return new AnnotationVisitor(Main.ASM_VERSION, delegateAV) {
// These could be "null" if values are not suppiled,
// in which case we have to use the default values.
private String name;
@@ -180,7 +180,7 @@
final MethodVisitor delegateMV = super.visitMethod(methodAccess, methodName, methodDesc,
signature, exceptions);
- return new MethodVisitor(Opcodes.ASM4, delegateMV) {
+ return new MethodVisitor(Main.ASM_VERSION, delegateMV) {
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
@@ -201,7 +201,7 @@
addScriptMember(memInfo);
- return new AnnotationVisitor(Opcodes.ASM4, delegateAV) {
+ return new AnnotationVisitor(Main.ASM_VERSION, delegateAV) {
// These could be "null" if values are not suppiled,
// in which case we have to use the default values.
private String name;
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java Thu Aug 28 14:53:37 2014 -0700
@@ -73,7 +73,7 @@
private boolean staticInitFound;
ScriptClassInstrumentor(final ClassVisitor visitor, final ScriptClassInfo sci) {
- super(Opcodes.ASM4, visitor);
+ super(Main.ASM_VERSION, visitor);
if (sci == null) {
throw new IllegalArgumentException("Null ScriptClassInfo, is the class annotated?");
}
@@ -103,7 +103,7 @@
final FieldVisitor delegateFV = super.visitField(fieldAccess, fieldName, fieldDesc,
signature, value);
- return new FieldVisitor(Opcodes.ASM4, delegateFV) {
+ return new FieldVisitor(Main.ASM_VERSION, delegateFV) {
@Override
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
if (ScriptClassInfo.annotations.containsKey(desc)) {
@@ -140,7 +140,7 @@
final MethodGenerator delegateMV = new MethodGenerator(super.visitMethod(methodAccess, methodName, methodDesc,
signature, exceptions), methodAccess, methodName, methodDesc);
- return new MethodVisitor(Opcodes.ASM4, delegateMV) {
+ return new MethodVisitor(Main.ASM_VERSION, delegateMV) {
@Override
public void visitInsn(final int opcode) {
// call $clinit$ just before return from <clinit>
--- a/nashorn/docs/genshelldoc.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/genshelldoc.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
@@ -61,7 +61,7 @@
for each (opt in Options.validOptions) {
-var isTimezone = (opt.type == "timezone");
+var isTimezone = (opt.type == "timezone");
var defValue = opt.defaultValue;
if (defValue == null) {
defValue = "<none>";
--- a/nashorn/docs/source/importpackageclass.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/importpackageclass.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -32,7 +32,7 @@
// load compatibility script
load("nashorn:mozilla_compat.js");
-// Import Java packages and classes
+// Import Java packages and classes
// like import package.*; in Java
importPackage(java.awt);
// like import java.awt.Frame in Java
--- a/nashorn/docs/source/javaarray.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/javaarray.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/docs/source/javaextend.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/javaextend.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/docs/source/javaimporter.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/javaimporter.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/docs/source/javatypes.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/javatypes.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/docs/source/overload.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/overload.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -31,6 +31,6 @@
var out = java.lang.System.out;
-// select a particular print function
+// select a particular print function
out["println(java.lang.Object)"]("hello");
--- a/nashorn/docs/source/runnable.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/runnable.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/docs/source/samfunc.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/samfunc.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/docs/source/test.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/docs/source/test.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/make/build.xml Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/make/build.xml Thu Aug 28 14:53:37 2014 -0700
@@ -128,6 +128,7 @@
<compilerarg value="-Xlint:all"/>
<compilerarg value="-XDignore.symbol.file"/>
<compilerarg value="-Xdiags:verbose"/>
+ <compilerarg value="-parameters"/>
</javac>
<copy todir="${build.classes.dir}/META-INF/services">
<fileset dir="${meta.inf.dir}/services/"/>
@@ -519,6 +520,8 @@
<java classname="${parallel.test.runner}" dir="${basedir}" fork="true">
<jvmarg line="${ext.class.path}"/>
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx} ${run.test.jvmsecurityargs} -Dbuild.dir=${build.dir}"/>
+ <!-- avoid too many typeinfo cache files. Each script is run only once anyway -->
+ <jvmarg line="-Dnashorn.typeInfo.disabled=true"/>
<classpath>
<pathelement path="${run.test.classpath}"/>
</classpath>
@@ -582,6 +585,8 @@
<!-- clone test262 git repo -->
<exec executable="${git.executable}">
<arg value="clone"/>
+ <arg value="--branch"/>
+ <arg value="es5-tests"/>
<arg value="https://github.com/tc39/test262"/>
<arg value="${test.external.dir}/test262"/>
</exec>
--- a/nashorn/make/project.properties Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/make/project.properties Thu Aug 28 14:53:37 2014 -0700
@@ -28,8 +28,8 @@
# source and target levels
build.compiler=modern
-javac.source=1.7
-javac.target=1.7
+javac.source=1.8
+javac.target=1.8
# nashorn version information
nashorn.version=0.1
@@ -202,7 +202,7 @@
# list of test262 test dirs to be excluded
test262-test-sys-prop.test.js.exclude.dir=\
${test262.suite.dir}/intl402/ \
- ${test262.suite.dir}/bestPractice/
+ ${test262.suite.dir}/bestPractice/
test262-test-sys-prop.test.failed.list.file=${build.dir}/test/failedTests
@@ -217,7 +217,7 @@
${test262.dir}/test/harness/sta.js
# testmarkdown test root
-testmarkdown-test-sys-prop.test.js.roots=${testmarkdown.dir}
+testmarkdown-test-sys-prop.test.js.roots=${testmarkdown.dir}
# execute testmarkdown tests in shared nashorn context or not?
testmarkdown-test-sys-prop.test.js.shared.context=false
@@ -227,7 +227,7 @@
${test.script.dir}${file.separator}markdown.js
# testjfx test root
-testjfx-test-sys-prop.test.js.roots=${testjfx.dir}
+testjfx-test-sys-prop.test.js.roots=${testjfx.dir}
# execute testjfx tests in shared nashorn context or not?
testjfx-test-sys-prop.test.js.shared.context=false
@@ -257,7 +257,7 @@
${nashorn.internal.tests.jar}:\
${nashorn.api.tests.jar}
-src.dir=src
+src.dir=src/jdk.scripting.nashorn/share/classes
test.src.dir=test/src
# -Xmx is used for all tests, -Xms only for octane benchmark
--- a/nashorn/samples/array_mapreduce.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/array_mapreduce.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -31,9 +31,9 @@
// Usage: jjs array_mapreduce.js
-// Many Array.prototype functions such as map,
+// Many Array.prototype functions such as map,
// filter, reduce, reduceRight, every, some are generic.
-// These functions accept ECMAScript array as well as
+// These functions accept ECMAScript array as well as
// many array-like objects including java arrays.
// So, you can do map/filter/reduce with Java streams or
// you can also use Array.prototype functions as below.
@@ -73,6 +73,6 @@
// print sum of squares of the random numbers
print("Square sum:",
reduce.call(
- map.call(jarr, function(x) x*x),
+ map.call(jarr, function(x) x*x),
function(x, y) x + y)
);
--- a/nashorn/samples/astviewer.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/astviewer.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -82,7 +82,7 @@
// load parser.js from nashorn resources
load("nashorn:parser.js");
-// read the full content of the file and parse it
+// read the full content of the file and parse it
// to get AST of the script specified
var ast = parse(readFully(sourceName));
--- a/nashorn/samples/barchart_weather.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/barchart_weather.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/call_lambda.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/call_lambda.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/counters.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/counters.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/dirname.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/dirname.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/disassemble.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/disassemble.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -33,7 +33,7 @@
// Simple .class disassembler that uses bundled ObjectWeb ASM
// classes in jdk8. WARNING: Bundled ObjectWeb ASM classes are
-// not part of official jdk8 API. It can be changed/removed
+// not part of official jdk8 API. It can be changed/removed
// without notice. So, this script is brittle by design!
// This example demonstrates passing arguments to script
--- a/nashorn/samples/engine/accessvar.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/accessvar.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/engine/callfunc.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/callfunc.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -29,7 +29,7 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-// simple example showing how to call a global script
+// simple example showing how to call a global script
// function from caller
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
@@ -42,7 +42,7 @@
engine.eval("function func(name) { print('I am func, hello ' + name) }");
// invoke functions, methods of code evaluated by engine
-// from javax.script.Invocable interface. But, hey,
+// from javax.script.Invocable interface. But, hey,
// calling code is JavaScript and don't worry about types :)
engine.invokeFunction("func", "Nashorn");
--- a/nashorn/samples/engine/callmethod.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/callmethod.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -55,7 +55,7 @@
CODE);
// invoke methods of an object in script world
-// from javax.script.Invocable interface. But, hey,
+// from javax.script.Invocable interface. But, hey,
// calling code is JavaScript and don't worry about types :)
// get that script object on which to call a method
--- a/nashorn/samples/engine/exposevar.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/exposevar.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/engine/foreignobject.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/foreignobject.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -54,7 +54,7 @@
// the class jdk.nashorn.api.scripting.ScriptObjectMirror
// But nashorn's dynalink linker can treat these objects
// specially to support natural script syntax to access..
-// In Java code, you need to use ScriptObjectMirror's
+// In Java code, you need to use ScriptObjectMirror's
// methods though. Once again, script world is simpler :-)
var foreignObj = engine.get("obj");
--- a/nashorn/samples/engine/hello.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/hello.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/engine/interface.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/interface.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -50,7 +50,7 @@
// create Java interface object whose methods are
// implemented by script functions. This is from
-// javax.script.Invocable. But we are in JS world,
+// javax.script.Invocable. But we are in JS world,
// don't worry about types :)
var Runnable = Java.type("java.lang.Runnable");
--- a/nashorn/samples/engine/interface2.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/interface2.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/engine/lambda_as_func.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/engine/lambda_as_func.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/env.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/env.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -31,8 +31,8 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-// In nashorn -scripting mode,
-// "$ENV" object exposes process
+// In nashorn -scripting mode,
+// "$ENV" object exposes process
// environment variables
print($ENV.PATH);
--- a/nashorn/samples/expression_closure.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/expression_closure.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/filebrowser.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/filebrowser.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/fileline.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/fileline.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/find_nonfinals.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Nashorn project uses "final" modifier for method parameters
+ * (like 'val' of Scala). This tool finds method parameters that
+ * miss final modifier.
+ */
+
+// Usage: jjs -J-Djava.ext.dirs=<your_nashorn_jar_dir> find_nonfinals.js
+
+var Class = Java.type("java.lang.Class");
+var System = Java.type("java.lang.System");
+var File = Java.type("java.io.File");
+var JarFile = Java.type("java.util.jar.JarFile");
+var Modifier = Java.type("java.lang.reflect.Modifier");
+
+// locate nashorn.jar from java.ext.dirs
+function findNashorn() {
+ var paths = System.getProperty("java.ext.dirs").split(':');
+ for each (var p in paths) {
+ var nashorn = p + File.separator + "nashorn.jar";
+ if (new File(nashorn).exists()) {
+ return nashorn;
+ }
+ }
+}
+
+// analyze a single Class and print info on non-final parameters
+function analyzeClass(cls) {
+ var methods = cls.getDeclaredMethods();
+ for each (var method in methods) {
+ // this requires -parameters option when compiling java sources
+ var params = method.parameters;
+ for each (var p in params) {
+ var modifiers = p.modifiers;
+ if (!Modifier.isFinal(modifiers)) {
+ if (! method.name.startsWith("access$")) {
+ print(method);
+ print(" ->", p);
+ }
+ }
+ }
+ }
+}
+
+var jarFile = findNashorn();
+// load each class and use reflection to analyze each Class
+new JarFile(jarFile).stream().forEach(
+ function(entry) {
+ var name = entry.name;
+ if (name.endsWith(".class")) {
+ var clsName = name.substring(0, name.lastIndexOf('.class'));
+ clsName = clsName.replace(/\//g, '.');
+ var cls = Class.forName(clsName);
+ analyzeClass(cls);
+ }
+ }
+)
--- a/nashorn/samples/fizzbuzz.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/fizzbuzz.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/for_each.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/for_each.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -42,7 +42,7 @@
var arr = new JArray(10);
// store squares as values
-for (i in arr)
+for (i in arr)
arr[i] = i*i;
// for .. each on java arrays
@@ -57,7 +57,7 @@
print("System properties");
for each (p in System.properties.entrySet()) {
print(p.key, "=", p.value);
-}
+}
// print process environment vars as name = value pairs
print("Process environment");
--- a/nashorn/samples/gaussian_random.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/gaussian_random.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -37,7 +37,7 @@
var r = new Random();
// expression closure (see expression_closure.js as well)
-// passed as lambda double generator. "print" passed as
+// passed as lambda double generator. "print" passed as
// double consumer lambda to 'forEach' method.
DoubleStream
--- a/nashorn/samples/gaussian_random_bind.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/gaussian_random_bind.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -34,7 +34,7 @@
var Random = Java.type("java.util.Random");
var DoubleStream = Java.type("java.util.stream.DoubleStream");
-// function as lambda double generator. "print" passed as
+// function as lambda double generator. "print" passed as
// double consumer lambda to 'forEach' method.
// Function.prototype.bind used to attach 'state' for the
// generator function.
--- a/nashorn/samples/gutenberg.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/gutenberg.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -69,7 +69,7 @@
// capture title, description now
inItem = true;
}
-
+
if (inItem) {
switch (local) {
case 'title':
--- a/nashorn/samples/heredoc.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/heredoc.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -38,14 +38,14 @@
var sender = "Buffy the Vampire Slayer";
var recipient = "Spike";
-
+
print(<<END
-
+
Dear ${recipient},
-
+
I wish you to leave Sunnydale and never return.
-
+
Not Quite Love,
${sender}
-
+
END);
--- a/nashorn/samples/interface_impl.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/interface_impl.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/javaastviewer.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/javaastviewer.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -56,8 +56,8 @@
// may not be exhaustive - any getAbc would become "abc" property or
// public field becomes a property of same name.
var ignoredProps = new HashSet();
- for each (var word in
- ['extending', 'implementing', 'init', 'mods', 'clazz', 'defs',
+ for each (var word in
+ ['extending', 'implementing', 'init', 'mods', 'clazz', 'defs',
'expr', 'tag', 'preferredPosition', 'qualid', 'recvparam',
'restype', 'params', 'startPosition', 'thrown',
'tree', 'typarams', 'typetag', 'vartype']) {
@@ -83,7 +83,7 @@
var visitor = new ConverterVisitor() {
// convert java AST node to a friendly script object
- // which can be viewed. Every node ends up in defaultAction
+ // which can be viewed. Every node ends up in defaultAction
// method of SimpleTreeVisitor method.
defaultAction: function (node, p) {
--- a/nashorn/samples/javacastcounter.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/javacastcounter.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -83,7 +83,7 @@
this.lineMap = node.lineMap;
this.fileName = node.sourceFile.name;
- // Using Java.super API to call super class method here
+ // Using Java.super API to call super class method here
return Java.super(counter).visitCompilationUnit(node, p);
},
--- a/nashorn/samples/javafoovars.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/javafoovars.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -30,7 +30,7 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-
+
// This example demonstrates Java subclassing by Java.extend
// and javac Compiler and Tree API. This example counts number
// of variables called "foo" in the given java source files!
@@ -38,7 +38,7 @@
print("Usage: jjs javafoovars.js -- <directory>");
exit(1);
}
-
+
// Java types used
var File = Java.type("java.io.File");
var Files = Java.type("java.nio.file.Files");
@@ -48,7 +48,7 @@
var Tree = Java.type("com.sun.source.tree.Tree");
var TreeScanner = Java.type("com.sun.source.util.TreeScanner");
var VariableTree = Java.type("com.sun.source.tree.VariableTree");
-
+
// count "foo"-s in the given .java files
function countFoo() {
// get the system compiler tool
@@ -63,7 +63,7 @@
// subclass SimpleTreeVisitor - to count variables called "foo"
var FooCounterVisitor = Java.extend(TreeScanner);
var fooCount = 0;
-
+
var visitor = new FooCounterVisitor() {
visitVariable: function (node, p) {
if (node.name.toString() == "foo") {
@@ -71,13 +71,13 @@
}
}
}
-
+
for each (var cu in task.parse()) {
cu.accept(visitor, null);
}
return fooCount;
}
-
+
// for each ".java" file in directory (recursively) count "foo".
function main(dir) {
var totalCount = 0;
@@ -99,5 +99,5 @@
});
print("Total foo count: " + totalCount);
}
-
+
main(new File(arguments[0]));
--- a/nashorn/samples/javaimporter.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/javaimporter.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -34,14 +34,14 @@
function readTextFromURL(url) {
- // equivalent to
- //
+ // equivalent to
+ //
// import java.io.*;
// import java.net.*;
// import java.lang.StringBuffer;
//
// only inside the 'with' statement
- with (new JavaImporter(java.io,
+ with (new JavaImporter(java.io,
java.net,
java.lang.StringBuilder)) {
var buf = new StringBuilder();
--- a/nashorn/samples/javalist.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/javalist.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/javamap.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/javamap.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -45,7 +45,7 @@
print(map['js']);
print(map.js);
-// also assign new key-value pair
+// also assign new key-value pair
// as 'property-value'
map['language'] = 'java';
print(map.get("language"));
--- a/nashorn/samples/javashell.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/javashell.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -130,7 +130,7 @@
// generate unique name
function uniqueName() {
var now = LocalDateTime.now().toString();
- // replace unsafe chars with '_'
+ // replace unsafe chars with '_'
return "JavaShell" + now.replace(/-|:|\./g, '_');
}
--- a/nashorn/samples/jsadapter_dom.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/jsadapter_dom.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -33,7 +33,7 @@
// Simple example that demonstrates reading XML Rss feed
// to generate a HTML file from script and show it by browser
-// Uses XML DOM parser and DOM element wrapped by script
+// Uses XML DOM parser and DOM element wrapped by script
// "proxy" (JSAdapter constructor)
// Java classes used
@@ -78,7 +78,7 @@
var node = nodeList.item(i);
if (node.nodeType == TEXT_NODE) {
text += node.nodeValue;
- }
+ }
}
return text;
--- a/nashorn/samples/jsobj_example.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/jsobj_example.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -33,7 +33,7 @@
var AbstractJSObject = Java.type("jdk.nashorn.api.scripting.AbstractJSObject");
-// JSObject example that uses a map for properties and
+// JSObject example that uses a map for properties and
// falls back to with methods on a java object (for missing
// properties
@@ -49,7 +49,7 @@
return function() {
var a = arguments;
switch (a.length) {
- case 0: return fallback[name]();
+ case 0: return fallback[name]();
case 1: return fallback[name](a[0]);
case 2: return fallback[name](a[0], a[1]);
case 3: return fallback[name](a[0], a[1], a[2]);
--- a/nashorn/samples/jsobject.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/jsobject.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/jsobject_mapreduce.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/jsobject_mapreduce.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -31,9 +31,9 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-// Many Array.prototype functions such as map,
+// Many Array.prototype functions such as map,
// filter, reduce, reduceRight, every, some are generic.
-// These functions accept ECMAScript array as well as
+// These functions accept ECMAScript array as well as
// many array-like objects including JSObjects.
// See also http://en.wikipedia.org/wiki/MapReduce
@@ -57,6 +57,6 @@
// print sum of squares of the random numbers
print("Square sum:",
reduce.call(
- map.call(buf, function(x) x*x),
+ map.call(buf, function(x) x*x),
function(x, y) x + y)
);
--- a/nashorn/samples/jsonviewer.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/jsonviewer.js Thu Aug 28 14:53:37 2014 -0700
@@ -4,22 +4,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -52,8 +52,8 @@
// read text content of a URL
function readTextFromURL(url) {
- // equivalent to
- //
+ // equivalent to
+ //
// import java.io.*;
// import java.net.*;
// import java.lang.StringBuffer;
--- a/nashorn/samples/letter.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/letter.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -43,7 +43,7 @@
// JavaScript style line comment is ok too.
print(<<EOF);
Dear ${obj.recipient},
-
+
I wish you all the best.
Regards,
--- a/nashorn/samples/list_mapreduce.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/list_mapreduce.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -31,9 +31,9 @@
// Usage: jjs list_mapreduce.js
-// Many Array.prototype functions such as map,
+// Many Array.prototype functions such as map,
// filter, reduce, reduceRight, every, some are generic.
-// These functions accept ECMAScript array as well as
+// These functions accept ECMAScript array as well as
// many array-like objects including java.util.ArrayLists.
// So, you can do map/filter/reduce with Java streams or
// you can also use Array.prototype functions as below.
@@ -81,6 +81,6 @@
// print sum of squares of the random numbers
print("Square sum:",
reduce.call(
- map.call(list, function(x) x*x),
+ map.call(list, function(x) x*x),
function(x, y) x + y)
);
--- a/nashorn/samples/locales.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/locales.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/logisticmap.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/logisticmap.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/options.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/options.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/parser.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/parser.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/readLine.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/readLine.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/sam_function.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/sam_function.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -46,6 +46,6 @@
}, 1000);
// wait for timer thread to print by
-// reading from stdin.
+// reading from stdin.
print("press any key to exit after message from timer...");
System.in.read();
--- a/nashorn/samples/shell.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/shell.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/stack.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/stack.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -33,7 +33,7 @@
// error objects. This property's value is a string
// that shows script stack trace.
-function g() {
+function g() {
throw new Error("wrong");
}
@@ -44,9 +44,9 @@
// Output looks something like:
//
// Error: wrong
-// at g (stack.js:37)
-// at f (stack.js:41)
-// at <program> (stack.js:52)
+// at g (stack.js:37)
+// at f (stack.js:41)
+// at <program> (stack.js:52)
try {
f();
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/try_with_resource.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* This sample implements Java-like try..with..resource construct for nashorn */
+
+if (arguments.length == 0) {
+ print("Usage: jjs try_with_resource.js -- <file name>");
+ exit(1);
+}
+
+// Object.create accepts prototype and properties object
+function With(res) {
+ return Object.create(With.prototype,
+ { res: { value: res } });
+}
+
+// reserved words can be used as property names - for example "try"
+With.prototype.try = function(callback) {
+ try {
+ callback();
+ } finally {
+ this.res.close();
+ }
+}
+
+var BufferedReader = Java.type("java.io.BufferedReader");
+var FileReader = Java.type("java.io.FileReader");
+
+var r = new BufferedReader(new FileReader(arguments[0]));
+
+// Java-like try..with..resource
+With(r).try(function() {
+ var s;
+ while ((s = r.readLine()) != null) {
+ print(s);
+ }
+})
--- a/nashorn/samples/uniform_random.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/uniform_random.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/uniq.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/uniq.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/uniqs.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/uniqs.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -31,7 +31,7 @@
// Usage: jjs uniqs.js -- <file>
// omit repeated lines and print unique lines
-// But this version uses Stream API
+// But this version uses Stream API
if (arguments.length < 1) {
print("Usage: jjs uniqs.js -- <file>");
--- a/nashorn/samples/weather.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/weather.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- a/nashorn/samples/word_histogram.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/word_histogram.js Thu Aug 28 14:53:37 2014 -0700
@@ -2,22 +2,22 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/samples/zipfs.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * - Neither the name of Oracle nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+if (arguments.length == 0) {
+ print("Usage: jjs zipfs.js -- <.zip/.jar file>")
+ exit(1)
+}
+
+var Files = Java.type("java.nio.file.Files")
+var FileSystems = Java.type("java.nio.file.FileSystems")
+var FileVisitOption = Java.type("java.nio.file.FileVisitOption")
+var Paths = Java.type("java.nio.file.Paths")
+
+var zipfile = Paths.get(arguments[0])
+var fs = FileSystems.newFileSystem(zipfile, null)
+var root = fs.rootDirectories[0]
+Files.walk(root, FileVisitOption.FOLLOW_LINKS).forEach(
+ function(p) (print(p), print(Files.readAttributes(p, "zip:*")))
+)
+fs.close()
--- a/nashorn/samples/ziplist.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/samples/ziplist.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
- *
+ *
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
- *
+ *
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
- *
+ *
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- *
+ *
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
- *
+ *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
@@ -30,7 +30,7 @@
*/
if (arguments.length == 0) {
- print("Usage: jjs ziplist <zip-file>");
+ print("Usage: jjs ziplist -- <zip-file>");
exit(1);
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ClassFilter.java Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package jdk.nashorn.api.scripting;
+
+/**
+ * Class filter (optional) to be used by nashorn script engine.
+ * jsr-223 program embedding nashorn script can set ClassFilter instance
+ * to be used when an engine instance is created.
+ */
+public interface ClassFilter {
+ /**
+ * Should the Java class of the specified name be exposed to scripts?
+ * @param className is the fully qualified name of the java class being
+ * checked. This will not be null. Only non-array class names will be
+ * passed.
+ * @return true if the java class can be exposed to scripts false otherwise
+ */
+ public boolean exposeToScripts(String className);
+}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/NashornScriptEngine.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/NashornScriptEngine.java Thu Aug 28 14:53:37 2014 -0700
@@ -40,7 +40,6 @@
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
-
import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.Compilable;
@@ -51,7 +50,6 @@
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
-
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ErrorManager;
@@ -95,9 +93,6 @@
// This is used as "shared" global if above option is true.
private final Global global;
- // default options passed to Nashorn Options object
- private static final String[] DEFAULT_OPTIONS = new String[] { "-doe" };
-
// Nashorn script engine error message management
private static final String MESSAGES_RESOURCE = "jdk.nashorn.api.scripting.resources.Messages";
@@ -115,11 +110,8 @@
}
}
- NashornScriptEngine(final NashornScriptEngineFactory factory, final ClassLoader appLoader) {
- this(factory, DEFAULT_OPTIONS, appLoader);
- }
-
- NashornScriptEngine(final NashornScriptEngineFactory factory, final String[] args, final ClassLoader appLoader) {
+ NashornScriptEngine(final NashornScriptEngineFactory factory, final String[] args, final ClassLoader appLoader, final ClassFilter classFilter) {
+ assert args != null : "null argument array";
this.factory = factory;
final Options options = new Options("nashorn");
options.process(args);
@@ -131,7 +123,7 @@
@Override
public Context run() {
try {
- return new Context(options, errMgr, appLoader);
+ return new Context(options, errMgr, appLoader, classFilter);
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/NashornScriptEngineFactory.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/NashornScriptEngineFactory.java Thu Aug 28 14:53:37 2014 -0700
@@ -135,10 +135,13 @@
return sb.toString();
}
+ // default options passed to Nashorn script engine
+ private static final String[] DEFAULT_OPTIONS = new String[] { "-doe" };
+
@Override
public ScriptEngine getScriptEngine() {
try {
- return new NashornScriptEngine(this, getAppClassLoader());
+ return new NashornScriptEngine(this, DEFAULT_OPTIONS, getAppClassLoader(), null);
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
@@ -152,10 +155,27 @@
*
* @param appLoader class loader to be used as script "app" class loader.
* @return newly created script engine.
+ * @throws SecurityException
+ * if the security manager's {@code checkPermission}
+ * denies {@code RuntimePermission("nashorn.setConfig")}
*/
public ScriptEngine getScriptEngine(final ClassLoader appLoader) {
- checkConfigPermission();
- return new NashornScriptEngine(this, appLoader);
+ return newEngine(DEFAULT_OPTIONS, appLoader, null);
+ }
+
+ /**
+ * Create a new Script engine initialized by given class filter.
+ *
+ * @param classFilter class filter to use.
+ * @return newly created script engine.
+ * @throws NullPointerException if {@code classFilter} is {@code null}
+ * @throws SecurityException
+ * if the security manager's {@code checkPermission}
+ * denies {@code RuntimePermission("nashorn.setConfig")}
+ */
+ public ScriptEngine getScriptEngine(final ClassFilter classFilter) {
+ classFilter.getClass(); // null check
+ return newEngine(DEFAULT_OPTIONS, getAppClassLoader(), classFilter);
}
/**
@@ -163,10 +183,14 @@
*
* @param args arguments array passed to script engine.
* @return newly created script engine.
+ * @throws NullPointerException if {@code args} is {@code null}
+ * @throws SecurityException
+ * if the security manager's {@code checkPermission}
+ * denies {@code RuntimePermission("nashorn.setConfig")}
*/
public ScriptEngine getScriptEngine(final String... args) {
- checkConfigPermission();
- return new NashornScriptEngine(this, args, getAppClassLoader());
+ args.getClass(); // null check
+ return newEngine(args, getAppClassLoader(), null);
}
/**
@@ -175,10 +199,44 @@
* @param args arguments array passed to script engine.
* @param appLoader class loader to be used as script "app" class loader.
* @return newly created script engine.
+ * @throws NullPointerException if {@code args} is {@code null}
+ * @throws SecurityException
+ * if the security manager's {@code checkPermission}
+ * denies {@code RuntimePermission("nashorn.setConfig")}
*/
public ScriptEngine getScriptEngine(final String[] args, final ClassLoader appLoader) {
+ args.getClass(); // null check
+ return newEngine(args, appLoader, null);
+ }
+
+ /**
+ * Create a new Script engine initialized by given arguments.
+ *
+ * @param args arguments array passed to script engine.
+ * @param appLoader class loader to be used as script "app" class loader.
+ * @param classFilter class filter to use.
+ * @return newly created script engine.
+ * @throws NullPointerException if {@code args} or {@code classFilter} is {@code null}
+ * @throws SecurityException
+ * if the security manager's {@code checkPermission}
+ * denies {@code RuntimePermission("nashorn.setConfig")}
+ */
+ public ScriptEngine getScriptEngine(final String[] args, final ClassLoader appLoader, final ClassFilter classFilter) {
+ args.getClass(); // null check
+ classFilter.getClass(); // null check
+ return newEngine(args, appLoader, classFilter);
+ }
+
+ private ScriptEngine newEngine(final String[] args, final ClassLoader appLoader, final ClassFilter classFilter) {
checkConfigPermission();
- return new NashornScriptEngine(this, args, appLoader);
+ try {
+ return new NashornScriptEngine(this, args, appLoader, classFilter);
+ } catch (final RuntimeException e) {
+ if (Context.DEBUG) {
+ e.printStackTrace();
+ }
+ throw e;
+ }
}
// -- Internals only below this point
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptObjectMirror.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/ScriptObjectMirror.java Thu Aug 28 14:53:37 2014 -0700
@@ -715,6 +715,23 @@
return newArgs;
}
+ /**
+ * Are the given objects mirrors to same underlying object?
+ *
+ * @param obj1 first object
+ * @param obj2 second object
+ * @return true if obj1 and obj2 are identical script objects or mirrors of it.
+ */
+ public static boolean identical(final Object obj1, final Object obj2) {
+ final Object o1 = (obj1 instanceof ScriptObjectMirror)?
+ ((ScriptObjectMirror)obj1).sobj : obj1;
+
+ final Object o2 = (obj2 instanceof ScriptObjectMirror)?
+ ((ScriptObjectMirror)obj2).sobj : obj2;
+
+ return o1 == o2;
+ }
+
// package-privates below this.
ScriptObjectMirror(final ScriptObject sobj, final Global global) {
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/AssignSymbols.java Thu Aug 28 14:53:37 2014 -0700
@@ -382,10 +382,6 @@
symbol.setFlags(flags);
}
- if((isVar || isParam) && compiler.useOptimisticTypes() && compiler.isOnDemandCompilation()) {
- compiler.declareLocalSymbol(name);
- }
-
return symbol;
}
@@ -688,6 +684,22 @@
}
@Override
+ public Node leaveBlock(final Block block) {
+ // It's not necessary to guard the marking of symbols as locals with this "if"condition for correctness, it's
+ // just an optimization -- runtime type calculation is not used when the compilation is not an on-demand
+ // optimistic compilation, so we can skip locals marking then.
+ if (compiler.useOptimisticTypes() && compiler.isOnDemandCompilation()) {
+ for (final Symbol symbol: block.getSymbols()) {
+ if (!symbol.isScope()) {
+ assert symbol.isVar() || symbol.isParam();
+ compiler.declareLocalSymbol(symbol.getName());
+ }
+ }
+ }
+ return block;
+ }
+
+ @Override
public Node leaveDELETE(final UnaryNode unaryNode) {
final FunctionNode currentFunctionNode = lc.getCurrentFunction();
final boolean strictMode = currentFunctionNode.isStrict();
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java Thu Aug 28 14:53:37 2014 -0700
@@ -56,7 +56,6 @@
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_OPTIMISTIC;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_PROGRAM_POINT_SHIFT;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_SCOPE;
-import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_STRICT;
import java.io.PrintWriter;
import java.util.ArrayDeque;
@@ -250,8 +249,6 @@
private final Deque<Label> scopeEntryLabels = new ArrayDeque<>();
- private final Set<Integer> initializedFunctionIds = new HashSet<>();
-
private static final Label METHOD_BOUNDARY = new Label("");
private final Deque<Label> catchLabels = new ArrayDeque<>();
// Number of live locals on entry to (and thus also break from) labeled blocks.
@@ -291,7 +288,7 @@
* @return the correct flags for a call site in the current function
*/
int getCallSiteFlags() {
- return lc.getCurrentFunction().isStrict() ? callSiteFlags | CALLSITE_STRICT : callSiteFlags;
+ return lc.getCurrentFunction().getCallSiteFlags() | callSiteFlags;
}
/**
@@ -1766,7 +1763,7 @@
}
// Debugging: print symbols? @see --print-symbols flag
- printSymbols(block, (isFunctionBody ? "Function " : "Block in ") + (function.getIdent() == null ? "<anonymous>" : function.getIdent().getName()));
+ printSymbols(block, function, (isFunctionBody ? "Function " : "Block in ") + (function.getIdent() == null ? "<anonymous>" : function.getIdent().getName()));
}
/**
@@ -1872,6 +1869,7 @@
// lingers around. Also, currently loading previously persisted optimistic types information only works if
// we're on-demand compiling a function, so with this strategy the :program method can also have the warmup
// benefit of using previously persisted types.
+ //
// NOTE that this means the first compiled class will effectively just have a :createProgramFunction method, and
// the RecompilableScriptFunctionData (RSFD) object in its constants array. It won't even have the :program
// method. This is by design. It does mean that we're wasting one compiler execution (and we could minimize this
@@ -1879,11 +1877,7 @@
// We could emit an initial separate compile unit with the initial version of :program in it to better utilize
// the compilation pipeline, but that would need more invasive changes, as currently the assumption that
// :program is emitted into the first compilation unit of the function lives in many places.
- if(!onDemand && lazy && env._optimistic_types && functionNode.isProgram()) {
- return true;
- }
-
- return false;
+ return !onDemand && lazy && env._optimistic_types && functionNode.isProgram();
}
@Override
@@ -4111,19 +4105,18 @@
* Debug code used to print symbols
*
* @param block the block we are in
+ * @param function the function we are in
* @param ident identifier for block or function where applicable
*/
- private void printSymbols(final Block block, final String ident) {
- if (!compiler.getScriptEnvironment()._print_symbols) {
- return;
- }
-
- final PrintWriter out = compiler.getScriptEnvironment().getErr();
- out.println("[BLOCK in '" + ident + "']");
- if (!block.printSymbols(out)) {
- out.println("<no symbols>");
- }
- out.println();
+ private void printSymbols(final Block block, final FunctionNode function, final String ident) {
+ if (compiler.getScriptEnvironment()._print_symbols || function.getFlag(FunctionNode.IS_PRINT_SYMBOLS)) {
+ final PrintWriter out = compiler.getScriptEnvironment().getErr();
+ out.println("[BLOCK in '" + ident + "']");
+ if (!block.printSymbols(out)) {
+ out.println("<no symbols>");
+ }
+ out.println();
+ }
}
@@ -4383,9 +4376,8 @@
createFunction.end();
}
- if (addInitializer && !initializedFunctionIds.contains(fnId) && !compiler.isOnDemandCompilation()) {
- functionNode.getCompileUnit().addFunctionInitializer(data, functionNode);
- initializedFunctionIds.add(fnId);
+ if (addInitializer && !compiler.isOnDemandCompilation()) {
+ compiler.addFunctionInitializer(data, functionNode);
}
// We don't emit a ScriptFunction on stack for the outermost compiled function (as there's no code being
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CompilationPhase.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CompilationPhase.java Thu Aug 28 14:53:37 2014 -0700
@@ -61,6 +61,7 @@
import jdk.nashorn.internal.ir.debug.PrintVisitor;
import jdk.nashorn.internal.ir.visitor.NodeVisitor;
import jdk.nashorn.internal.runtime.CodeInstaller;
+import jdk.nashorn.internal.runtime.FunctionInitializer;
import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
import jdk.nashorn.internal.runtime.ScriptEnvironment;
import jdk.nashorn.internal.runtime.logging.DebugLogger;
@@ -279,12 +280,12 @@
final PrintWriter err = senv.getErr();
//TODO separate phase for the debug printouts for abstraction and clarity
- if (senv._print_lower_ast) {
+ if (senv._print_lower_ast || fn.getFlag(FunctionNode.IS_PRINT_LOWER_AST)) {
err.println("Lower AST for: " + quote(newFunctionNode.getName()));
err.println(new ASTWriter(newFunctionNode));
}
- if (senv._print_lower_parse) {
+ if (senv._print_lower_parse || fn.getFlag(FunctionNode.IS_PRINT_LOWER_PARSE)) {
err.println("Lower AST for: " + quote(newFunctionNode.getName()));
err.println(new PrintVisitor(newFunctionNode));
}
@@ -324,15 +325,15 @@
final DebugLogger log = compiler.getLogger();
log.fine("Clearing bytecode cache");
+ compiler.clearBytecode();
for (final CompileUnit oldUnit : compiler.getCompileUnits()) {
- CompileUnit newUnit = map.get(oldUnit);
assert map.get(oldUnit) == null;
final StringBuilder sb = new StringBuilder(compiler.nextCompileUnitName());
if (phases.isRestOfCompilation()) {
sb.append("$restOf");
}
- newUnit = compiler.createCompileUnit(sb.toString(), oldUnit.getWeight());
+ final CompileUnit newUnit = compiler.createCompileUnit(sb.toString(), oldUnit.getWeight());
log.fine("Creating new compile unit ", oldUnit, " => ", newUnit);
map.put(oldUnit, newUnit);
assert newUnit != null;
@@ -502,8 +503,7 @@
long length = 0L;
final CodeInstaller<ScriptEnvironment> codeInstaller = compiler.getCodeInstaller();
-
- final Map<String, byte[]> bytecode = compiler.getBytecode();
+ final Map<String, byte[]> bytecode = compiler.getBytecode();
for (final Entry<String, byte[]> entry : bytecode.entrySet()) {
final String className = entry.getKey();
@@ -536,17 +536,18 @@
// initialize function in the compile units
for (final CompileUnit unit : compiler.getCompileUnits()) {
unit.setCode(installedClasses.get(unit.getUnitClassName()));
- unit.initializeFunctionsCode();
}
if (!compiler.isOnDemandCompilation()) {
- codeInstaller.storeCompiledScript(compiler.getSource(), compiler.getFirstCompileUnit().getUnitClassName(), bytecode, constants);
- }
-
- // remove installed bytecode from table in case compiler is reused
- for (final String className : installedClasses.keySet()) {
- log.fine("Removing installed class ", quote(className), " from bytecode table...");
- compiler.removeClass(className);
+ // Initialize functions
+ final Map<Integer, FunctionInitializer> initializers = compiler.getFunctionInitializers();
+ if (initializers != null) {
+ for (final Entry<Integer, FunctionInitializer> entry : initializers.entrySet()) {
+ final FunctionInitializer initializer = entry.getValue();
+ initializer.setCode(installedClasses.get(initializer.getClassName()));
+ compiler.getScriptFunctionData(entry.getKey()).initializeCode(initializer);
+ }
+ }
}
if (log.isEnabled()) {
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CompileUnit.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CompileUnit.java Thu Aug 28 14:53:37 2014 -0700
@@ -25,12 +25,8 @@
package jdk.nashorn.internal.codegen;
-import java.util.Collections;
-import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
-import jdk.nashorn.internal.ir.FunctionNode;
-import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
/**
* Used to track split class compilation.
@@ -46,36 +42,6 @@
private Class<?> clazz;
- private Set<FunctionInitializer> functionInitializers = new LinkedHashSet<>();
-
- private static class FunctionInitializer {
- final RecompilableScriptFunctionData data;
- final FunctionNode functionNode;
-
- FunctionInitializer(final RecompilableScriptFunctionData data, final FunctionNode functionNode) {
- this.data = data;
- this.functionNode = functionNode;
- }
-
- void initializeCode() {
- data.initializeCode(functionNode);
- }
-
- @Override
- public int hashCode() {
- return data.hashCode() + 31 * functionNode.hashCode();
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (obj == null || obj.getClass() != FunctionInitializer.class) {
- return false;
- }
- final FunctionInitializer other = (FunctionInitializer)obj;
- return data == other.data && functionNode == other.functionNode;
- }
- }
-
CompileUnit(final String className, final ClassEmitter classEmitter, final long initialWeight) {
this.className = className;
this.weight = initialWeight;
@@ -108,29 +74,6 @@
this.classEmitter = null;
}
- void addFunctionInitializer(final RecompilableScriptFunctionData data, final FunctionNode functionNode) {
- functionInitializers.add(new FunctionInitializer(data, functionNode));
- }
-
- /**
- * Returns true if this compile unit is responsible for initializing the specified function data with specified
- * function node.
- * @param data the function data to check
- * @param functionNode the function node to check
- * @return true if this unit is responsible for initializing the function data with the function node, otherwise
- * false
- */
- public boolean isInitializing(final RecompilableScriptFunctionData data, final FunctionNode functionNode) {
- return functionInitializers.contains(new FunctionInitializer(data, functionNode));
- }
-
- void initializeFunctionsCode() {
- for(final FunctionInitializer init : functionInitializers) {
- init.initializeCode();
- }
- functionInitializers = Collections.emptySet();
- }
-
/**
* Add weight to this compile unit
* @param w weight to add
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Compiler.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Compiler.java Thu Aug 28 14:53:37 2014 -0700
@@ -50,7 +50,6 @@
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.logging.Level;
-
import jdk.internal.dynalink.support.NameCodec;
import jdk.nashorn.internal.codegen.ClassEmitter.Flag;
import jdk.nashorn.internal.codegen.types.Type;
@@ -60,6 +59,7 @@
import jdk.nashorn.internal.ir.debug.ObjectSizeCalculator;
import jdk.nashorn.internal.runtime.CodeInstaller;
import jdk.nashorn.internal.runtime.Context;
+import jdk.nashorn.internal.runtime.FunctionInitializer;
import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
import jdk.nashorn.internal.runtime.ScriptEnvironment;
import jdk.nashorn.internal.runtime.ScriptObject;
@@ -89,8 +89,6 @@
private final String sourceName;
- private final String sourceURL;
-
private final boolean optimistic;
private final Map<String, byte[]> bytecode;
@@ -309,21 +307,19 @@
/**
* Constructor
*
- * @param context context
- * @param env script environment
- * @param installer code installer
- * @param source source to compile
- * @param sourceURL source URL, or null if not present
- * @param isStrict is this a strict compilation
+ * @param context context
+ * @param env script environment
+ * @param installer code installer
+ * @param source source to compile
+ * @param isStrict is this a strict compilation
*/
public Compiler(
final Context context,
final ScriptEnvironment env,
final CodeInstaller<ScriptEnvironment> installer,
final Source source,
- final String sourceURL,
final boolean isStrict) {
- this(context, env, installer, source, sourceURL, isStrict, false, null, null, null, null, null, null);
+ this(context, env, installer, source, isStrict, false, null, null, null, null, null, null);
}
/**
@@ -333,7 +329,6 @@
* @param env script environment
* @param installer code installer
* @param source source to compile
- * @param sourceURL source URL, or null if not present
* @param isStrict is this a strict compilation
* @param isOnDemand is this an on demand compilation
* @param compiledFunction compiled function, if any
@@ -348,7 +343,6 @@
final ScriptEnvironment env,
final CodeInstaller<ScriptEnvironment> installer,
final Source source,
- final String sourceURL,
final boolean isStrict,
final boolean isOnDemand,
final RecompilableScriptFunctionData compiledFunction,
@@ -365,8 +359,7 @@
this.bytecode = new LinkedHashMap<>();
this.log = initLogger(context);
this.source = source;
- this.sourceURL = sourceURL;
- this.sourceName = FunctionNode.getSourceName(source, sourceURL);
+ this.sourceName = FunctionNode.getSourceName(source);
this.onDemand = isOnDemand;
this.compiledFunction = compiledFunction;
this.types = types;
@@ -411,6 +404,15 @@
sb.append(compilationId).append('$');
}
+ if (types != null && compiledFunction.getFunctionNodeId() > 0) {
+ sb.append(compiledFunction.getFunctionNodeId());
+ final Type[] paramTypes = types.getParameterTypes(compiledFunction.getFunctionNodeId());
+ for (final Type t : paramTypes) {
+ sb.append(Type.getShortSignatureDescriptor(t));
+ }
+ sb.append('$');
+ }
+
sb.append(Compiler.safeSourceName(env, installer, source));
return sb.toString();
@@ -559,8 +561,11 @@
return Collections.unmodifiableMap(bytecode);
}
- byte[] getBytecode(final String className) {
- return bytecode.get(className);
+ /**
+ * Reset bytecode cache for compiler reuse.
+ */
+ void clearBytecode() {
+ bytecode.clear();
}
CompileUnit getFirstCompileUnit() {
@@ -584,15 +589,6 @@
bytecode.put(name, code);
}
- void removeClass(final String name) {
- assert bytecode.get(name) != null;
- bytecode.remove(name);
- }
-
- String getSourceURL() {
- return sourceURL;
- }
-
String nextCompileUnitName() {
final StringBuilder sb = new StringBuilder(firstCompileUnitName);
final int cuid = nextCompileUnitId.getAndIncrement();
@@ -603,8 +599,51 @@
return sb.toString();
}
- void clearCompileUnits() {
- compileUnits.clear();
+ Map<Integer, FunctionInitializer> functionInitializers;
+
+ void addFunctionInitializer(final RecompilableScriptFunctionData functionData, final FunctionNode functionNode) {
+ if (functionInitializers == null) {
+ functionInitializers = new HashMap<>();
+ }
+ if (!functionInitializers.containsKey(functionData)) {
+ functionInitializers.put(functionData.getFunctionNodeId(), new FunctionInitializer(functionNode));
+ }
+ }
+
+ Map<Integer, FunctionInitializer> getFunctionInitializers() {
+ return functionInitializers;
+ }
+
+ /**
+ * Persist current compilation with the given {@code cacheKey}.
+ * @param cacheKey cache key
+ * @param functionNode function node
+ */
+ public void persistClassInfo(final String cacheKey, final FunctionNode functionNode) {
+ if (cacheKey != null && env._persistent_cache) {
+ Map<Integer, FunctionInitializer> initializers;
+ // If this is an on-demand compilation create a function initializer for the function being compiled.
+ // Otherwise use function initializer map generated by codegen.
+ if (functionInitializers == null) {
+ initializers = new HashMap<>();
+ final FunctionInitializer initializer = new FunctionInitializer(functionNode, getInvalidatedProgramPoints());
+ initializers.put(functionNode.getId(), initializer);
+ } else {
+ initializers = functionInitializers;
+ }
+ final String mainClassName = getFirstCompileUnit().getUnitClassName();
+ installer.storeScript(cacheKey, source, mainClassName, bytecode, initializers, constantData.toArray(), compilationId);
+ }
+ }
+
+ /**
+ * Make sure the next compilation id is greater than {@code value}.
+ * @param value compilation id value
+ */
+ public static void updateCompilationId(final int value) {
+ if (value >= COMPILATION_ID.get()) {
+ COMPILATION_ID.set(value + 1);
+ }
}
CompileUnit addCompileUnit(final long initialWeight) {
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ConstantData.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ConstantData.java Thu Aug 28 14:53:37 2014 -0700
@@ -30,7 +30,6 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.PropertyMap;
/**
@@ -121,12 +120,7 @@
private final int hashCode;
public PropertyMapWrapper(final PropertyMap map) {
- int hash = 0;
- for (final Property property : map.getProperties()) {
- hash = hash << 7 ^ hash >> 7;
- hash ^= property.hashCode();
- }
- this.hashCode = hash;
+ this.hashCode = Arrays.hashCode(map.getProperties());
this.propertyMap = map;
}
@@ -137,14 +131,8 @@
@Override
public boolean equals(final Object other) {
- if (!(other instanceof PropertyMapWrapper)) {
- return false;
- }
-
- final Property[] ownProperties = propertyMap.getProperties();
- final Property[] otherProperties = ((PropertyMapWrapper) other).propertyMap.getProperties();
-
- return Arrays.equals(ownProperties, otherProperties);
+ return other instanceof PropertyMapWrapper &&
+ Arrays.equals(propertyMap.getProperties(), ((PropertyMapWrapper) other).propertyMap.getProperties());
}
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/FindScopeDepths.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/FindScopeDepths.java Thu Aug 28 14:53:37 2014 -0700
@@ -217,7 +217,6 @@
allocatorClassName,
allocatorMap,
nestedFunctions,
- compiler.getSourceURL(),
externalSymbolDepths.get(fnId),
internalSymbols.get(fnId)
);
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Lower.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Lower.java Thu Aug 28 14:53:37 2014 -0700
@@ -34,7 +34,6 @@
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
-
import jdk.nashorn.internal.ir.BaseNode;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.ir.Block;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/OptimisticTypesPersistence.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/OptimisticTypesPersistence.java Thu Aug 28 14:53:37 2014 -0700
@@ -40,8 +40,6 @@
import java.util.Base64;
import java.util.Date;
import java.util.Map;
-import java.util.TreeMap;
-
import jdk.nashorn.internal.codegen.types.Type;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
@@ -80,12 +78,11 @@
final StringBuilder b = new StringBuilder(48);
// Base64-encode the digest of the source, and append the function id.
b.append(source.getDigest()).append('-').append(functionId);
- // Finally, if this is a parameter-type specialized version of the function, add the parameter types to the file
- // name.
+ // Finally, if this is a parameter-type specialized version of the function, add the parameter types to the file name.
if(paramTypes != null && paramTypes.length > 0) {
b.append('-');
for(final Type t: paramTypes) {
- b.append(t.getBytecodeStackType());
+ b.append(Type.getShortSignatureDescriptor(t));
}
}
return new LocationDescriptor(new File(cacheDir, b.toString()));
@@ -108,7 +105,7 @@
*/
@SuppressWarnings("resource")
public static void store(final Object locationDescriptor, final Map<Integer, Type> optimisticTypes) {
- if(locationDescriptor == null) {
+ if(locationDescriptor == null || optimisticTypes.isEmpty()) {
return;
}
final File file = ((LocationDescriptor)locationDescriptor).file;
@@ -117,25 +114,10 @@
@Override
public Void run() {
synchronized(getFileLock(file)) {
- try (final FileOutputStream out = new FileOutputStream(file);) {
+ try (final FileOutputStream out = new FileOutputStream(file)) {
out.getChannel().lock(); // lock exclusive
final DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(out));
- dout.writeInt(optimisticTypes.size());
- for(final Map.Entry<Integer, Type> e: optimisticTypes.entrySet()) {
- dout.writeInt(e.getKey());
- final byte typeChar;
- final Type type = e.getValue();
- if(type == Type.OBJECT) {
- typeChar = 'L';
- } else if(type == Type.NUMBER) {
- typeChar = 'D';
- } else if(type == Type.LONG) {
- typeChar = 'J';
- } else {
- throw new AssertionError();
- }
- dout.write(typeChar);
- }
+ Type.writeTypeMap(optimisticTypes, dout);
dout.flush();
} catch(final Exception e) {
reportError("write", file, e);
@@ -166,24 +148,10 @@
return null;
}
synchronized(getFileLock(file)) {
- try (final FileInputStream in = new FileInputStream(file);) {
+ try (final FileInputStream in = new FileInputStream(file)) {
in.getChannel().lock(0, Long.MAX_VALUE, true); // lock shared
final DataInputStream din = new DataInputStream(new BufferedInputStream(in));
- final Map<Integer, Type> map = new TreeMap<>();
- final int size = din.readInt();
- for(int i = 0; i < size; ++i) {
- final int pp = din.readInt();
- final int typeChar = din.read();
- final Type type;
- switch(typeChar) {
- case 'L': type = Type.OBJECT; break;
- case 'D': type = Type.NUMBER; break;
- case 'J': type = Type.LONG; break;
- default: throw new AssertionError();
- }
- map.put(pp, type);
- }
- return map;
+ return Type.readTypeMap(din);
}
}
} catch (final Exception e) {
@@ -276,7 +244,7 @@
private static String getVersionDirName() throws Exception {
final URL url = OptimisticTypesPersistence.class.getResource("");
final String protocol = url.getProtocol();
- if(protocol.equals("jar")) {
+ if (protocol.equals("jar")) {
// Normal deployment: nashorn.jar
final String jarUrlFile = url.getFile();
final String filePath = jarUrlFile.substring(0, jarUrlFile.indexOf('!'));
@@ -310,12 +278,12 @@
for(final File f: dir.listFiles()) {
if(f.getName().endsWith(".class")) {
final long lastModified = f.lastModified();
- if(lastModified > currentMax) {
+ if (lastModified > currentMax) {
currentMax = lastModified;
}
- } else if(f.isDirectory()) {
+ } else if (f.isDirectory()) {
final long lastModified = getLastModifiedClassFile(f, currentMax);
- if(lastModified > currentMax) {
+ if (lastModified > currentMax) {
currentMax = lastModified;
}
}
@@ -325,7 +293,7 @@
private static Object[] createLockArray() {
final Object[] lockArray = new Object[Runtime.getRuntime().availableProcessors() * 2];
- for(int i = 0; i < lockArray.length; ++i) {
+ for (int i = 0; i < lockArray.length; ++i) {
lockArray[i] = new Object();
}
return lockArray;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/TypeEvaluator.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/TypeEvaluator.java Thu Aug 28 14:53:37 2014 -0700
@@ -115,6 +115,14 @@
return Type.typeFor(JSType.unboxedFieldType(value));
}
+ /**
+ * Declares a symbol name as belonging to a non-scoped local variable during an on-demand compilation of a single
+ * function. This method will add an explicit Undefined binding for the local into the runtime scope if it's
+ * otherwise implicitly undefined so that when an expression is evaluated for the name, it won't accidentally find
+ * an unrelated value higher up the scope chain. It is only required to call this method when doing an optimistic
+ * on-demand compilation.
+ * @param symbolName the name of the symbol that is to be declared as being a non-scoped local variable.
+ */
void declareLocalSymbol(final String symbolName) {
assert
compiler.useOptimisticTypes() &&
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/types/Type.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/types/Type.java Thu Aug 28 14:53:37 2014 -0700
@@ -48,10 +48,15 @@
import static jdk.internal.org.objectweb.asm.Opcodes.T_LONG;
import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
+import java.util.Map;
+import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import jdk.internal.org.objectweb.asm.Handle;
@@ -204,6 +209,20 @@
}
/**
+ * Return a character representing {@code type} in a method signature.
+ *
+ * @param type parameter type
+ * @return descriptor character
+ */
+ public static char getShortSignatureDescriptor(final Type type) {
+ // Use 'Z' for boolean parameters as we need to distinguish from int
+ if (type instanceof BooleanType) {
+ return 'Z';
+ }
+ return type.getBytecodeStackType();
+ }
+
+ /**
* Return the type for an internal type, package private - do not use
* outside code gen
*
@@ -275,6 +294,64 @@
return types;
}
+ /**
+ * Write a map of {@code int} to {@code Type} to an output stream. This is used to store deoptimization state.
+ *
+ * @param typeMap the type map
+ * @param output data output
+ * @throws IOException
+ */
+ public static void writeTypeMap(final Map<Integer, Type> typeMap, final DataOutput output) throws IOException {
+ if (typeMap == null) {
+ output.writeInt(0);
+ } else {
+ output.writeInt(typeMap.size());
+ for(final Map.Entry<Integer, Type> e: typeMap.entrySet()) {
+ output.writeInt(e.getKey());
+ final byte typeChar;
+ final Type type = e.getValue();
+ if(type == Type.OBJECT) {
+ typeChar = 'L';
+ } else if (type == Type.NUMBER) {
+ typeChar = 'D';
+ } else if (type == Type.LONG) {
+ typeChar = 'J';
+ } else {
+ throw new AssertionError();
+ }
+ output.writeByte(typeChar);
+ }
+ }
+ }
+
+ /**
+ * Read a map of {@code int} to {@code Type} from an input stream. This is used to store deoptimization state.
+ *
+ * @param input data input
+ * @return type map
+ * @throws IOException
+ */
+ public static Map<Integer, Type> readTypeMap(final DataInput input) throws IOException {
+ final int size = input.readInt();
+ if (size == 0) {
+ return null;
+ }
+ final Map<Integer, Type> map = new TreeMap<>();
+ for(int i = 0; i < size; ++i) {
+ final int pp = input.readInt();
+ final int typeChar = input.readByte();
+ final Type type;
+ switch(typeChar) {
+ case 'L': type = Type.OBJECT; break;
+ case 'D': type = Type.NUMBER; break;
+ case 'J': type = Type.LONG; break;
+ default: throw new AssertionError();
+ }
+ map.put(pp, type);
+ }
+ return map;
+ }
+
static jdk.internal.org.objectweb.asm.Type getInternalType(final String className) {
return jdk.internal.org.objectweb.asm.Type.getType(className);
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/CallNode.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/CallNode.java Thu Aug 28 14:53:37 2014 -0700
@@ -30,7 +30,6 @@
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
-
import jdk.nashorn.internal.codegen.types.Type;
import jdk.nashorn.internal.ir.annotations.Ignore;
import jdk.nashorn.internal.ir.annotations.Immutable;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/FunctionNode.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/FunctionNode.java Thu Aug 28 14:53:37 2014 -0700
@@ -25,12 +25,18 @@
package jdk.nashorn.internal.ir;
+import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_PROFILE;
+import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_STRICT;
+import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_TRACE;
+import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_TRACE_ENTEREXIT;
+import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_TRACE_MISSES;
+import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_TRACE_VALUES;
+
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
-import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import jdk.nashorn.internal.codegen.CompileUnit;
@@ -81,7 +87,7 @@
LOWERED,
/** program points have been assigned to unique locations */
PROGRAM_POINTS_ASSIGNED,
- /** any transformations of builtins have taken place, e.g. apply=>call */
+ /** any transformations of builtins have taken place, e.g. apply=>call */
BUILTINS_TRANSFORMED,
/** method has been split */
SPLIT,
@@ -150,9 +156,6 @@
/** Function flags. */
private final int flags;
- /** //@ sourceURL or //# sourceURL for program function nodes */
- private final String sourceURL;
-
/** Line number of function start */
private final int lineNumber;
@@ -232,6 +235,37 @@
/** Is this declared in a dynamic context */
public static final int IN_DYNAMIC_CONTEXT = 1 << 17;
+ /**
+ * The following flags are derived from directive comments within this function.
+ * Note that even IS_STRICT is one such flag but that requires special handling.
+ */
+
+ // parser, lower debugging this function
+ public static final int IS_PRINT_PARSE = 1 << 18;
+ public static final int IS_PRINT_LOWER_PARSE = 1 << 19;
+ public static final int IS_PRINT_AST = 1 << 20;
+ public static final int IS_PRINT_LOWER_AST = 1 << 21;
+ public static final int IS_PRINT_SYMBOLS = 1 << 22;
+
+ /** profile callsites in this function? */
+ public static final int IS_PROFILE = 1 << 23;
+
+ // callsite tracing, profiling within this function
+ /** trace callsite enterexit in this function? */
+ public static final int IS_TRACE_ENTEREXIT = 1 << 24;
+
+ /** trace callsite misses in this function? */
+ public static final int IS_TRACE_MISSES = 1 << 25;
+
+ /** trace callsite values in this function? */
+ public static final int IS_TRACE_VALUES = 1 << 26;
+
+ /** extension callsite flags mask */
+ public static final int EXTENSION_CALLSITE_FLAGS = IS_PRINT_PARSE |
+ IS_PRINT_LOWER_PARSE | IS_PRINT_AST | IS_PRINT_LOWER_AST |
+ IS_PRINT_SYMBOLS | IS_PROFILE | IS_TRACE_ENTEREXIT |
+ IS_TRACE_MISSES | IS_TRACE_VALUES;
+
/** Does this function or any nested functions contain an eval? */
private static final int HAS_DEEP_EVAL = HAS_EVAL | HAS_NESTED_EVAL;
@@ -269,7 +303,6 @@
* @param parameters parameter list
* @param kind kind of function as in {@link FunctionNode.Kind}
* @param flags initial flags
- * @param sourceURL sourceURL specified in script (optional)
*/
public FunctionNode(
final Source source,
@@ -283,8 +316,7 @@
final String name,
final List<IdentNode> parameters,
final FunctionNode.Kind kind,
- final int flags,
- final String sourceURL) {
+ final int flags) {
super(token, finish);
this.source = source;
@@ -300,7 +332,6 @@
this.compilationState = EnumSet.of(CompilationState.INITIALIZED);
this.declaredSymbols = new HashSet<>();
this.flags = flags;
- this.sourceURL = sourceURL;
this.compileUnit = null;
this.body = null;
this.thisProperties = 0;
@@ -311,7 +342,6 @@
final FunctionNode functionNode,
final long lastToken,
final int flags,
- final String sourceURL,
final String name,
final Type returnType,
final CompileUnit compileUnit,
@@ -324,7 +354,6 @@
this.lineNumber = functionNode.lineNumber;
this.flags = flags;
- this.sourceURL = sourceURL;
this.name = name;
this.returnType = returnType;
this.compileUnit = compileUnit;
@@ -363,6 +392,41 @@
}
/**
+ * Get additional callsite flags to be used specific to this function.
+ *
+ * @return callsite flags
+ */
+ public int getCallSiteFlags() {
+ int callsiteFlags = 0;
+ if (getFlag(IS_STRICT)) {
+ callsiteFlags |= CALLSITE_STRICT;
+ }
+
+ // quick check for extension callsite flags turned on by directives.
+ if ((flags & EXTENSION_CALLSITE_FLAGS) == 0) {
+ return callsiteFlags;
+ }
+
+ if (getFlag(IS_PROFILE)) {
+ callsiteFlags |= CALLSITE_PROFILE;
+ }
+
+ if (getFlag(IS_TRACE_MISSES)) {
+ callsiteFlags |= CALLSITE_TRACE | CALLSITE_TRACE_MISSES;
+ }
+
+ if (getFlag(IS_TRACE_VALUES)) {
+ callsiteFlags |= CALLSITE_TRACE | CALLSITE_TRACE_ENTEREXIT | CALLSITE_TRACE_VALUES;
+ }
+
+ if (getFlag(IS_TRACE_ENTEREXIT)) {
+ callsiteFlags |= CALLSITE_TRACE | CALLSITE_TRACE_ENTEREXIT;
+ }
+
+ return callsiteFlags;
+ }
+
+ /**
* Get the source for this function
* @return the source
*/
@@ -384,56 +448,50 @@
* @return name for the script source
*/
public String getSourceName() {
- return getSourceName(source, sourceURL);
+ return getSourceName(source);
}
/**
* Static source name getter
*
- * @param source
- * @param sourceURL
+ * @param source the source
* @return source name
*/
- public static String getSourceName(final Source source, final String sourceURL) {
- return sourceURL != null ? sourceURL : source.getName();
- }
-
- /**
- * get the sourceURL
- * @return the sourceURL
- */
- public String getSourceURL() {
- return sourceURL;
+ public static String getSourceName(final Source source) {
+ final String explicitURL = source.getExplicitURL();
+ return explicitURL != null ? explicitURL : source.getName();
}
/**
- * Set the sourceURL
+ * Function to parse nashorn per-function extension directive comments.
*
- * @param lc lexical context
- * @param newSourceURL source url string to set
- * @return function node or a new one if state was changed
+ * @param directive nashorn extension directive string
+ * @return integer flag for the given directive.
*/
- public FunctionNode setSourceURL(final LexicalContext lc, final String newSourceURL) {
- if (Objects.equals(sourceURL, newSourceURL)) {
- return this;
+ public static int getDirectiveFlag(final String directive) {
+ switch (directive) {
+ case "nashorn callsite trace enterexit":
+ return IS_TRACE_ENTEREXIT;
+ case "nashorn callsite trace misses":
+ return IS_TRACE_MISSES;
+ case "nashorn callsite trace objects":
+ return IS_TRACE_VALUES;
+ case "nashorn callsite profile":
+ return IS_PROFILE;
+ case "nashorn print parse":
+ return IS_PRINT_PARSE;
+ case "nashorn print lower parse":
+ return IS_PRINT_LOWER_PARSE;
+ case "nashorn print ast":
+ return IS_PRINT_AST;
+ case "nashorn print lower ast":
+ return IS_PRINT_LOWER_AST;
+ case "nashorn print symbols":
+ return IS_PRINT_SYMBOLS;
+ default:
+ // unknown/unsupported directive
+ return 0;
}
-
- return Node.replaceInLexicalContext(
- lc,
- this,
- new FunctionNode(
- this,
- lastToken,
- flags,
- newSourceURL,
- name,
- returnType,
- compileUnit,
- compilationState,
- body,
- parameters,
- thisProperties,
- rootClass));
}
/**
@@ -469,11 +527,11 @@
}
/**
- * Check whether the state of this FunctionNode contains a given compilation<
+ * Check whether the state of this FunctionNode contains a given compilation
* state.
*
* A node can be in many states at once, e.g. both lowered and initialized.
- * To check for an exact state, use {FunctionNode{@link #hasState(EnumSet)}
+ * To check for an exact state, use {@link #hasState(EnumSet)}
*
* @param state state to check for
* @return true if state is present in the total compilation state of this FunctionNode
@@ -504,7 +562,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
returnType,
compileUnit,
@@ -576,7 +633,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
returnType,
compileUnit,
@@ -733,7 +789,6 @@
(body.needsScope() ?
FunctionNode.HAS_SCOPE_BLOCK :
0),
- sourceURL,
name,
returnType,
compileUnit,
@@ -829,7 +884,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
returnType,
compileUnit,
@@ -890,7 +944,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
returnType,
compileUnit,
@@ -926,7 +979,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
returnType,
compileUnit,
@@ -992,7 +1044,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
returnType,
compileUnit,
@@ -1071,7 +1122,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
type,
compileUnit,
@@ -1118,7 +1168,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
returnType,
compileUnit,
@@ -1174,7 +1223,6 @@
this,
lastToken,
flags,
- sourceURL,
name,
returnType,
compileUnit,
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LexicalContext.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LexicalContext.java Thu Aug 28 14:53:37 2014 -0700
@@ -27,7 +27,6 @@
import java.io.File;
import java.util.Iterator;
import java.util.NoSuchElementException;
-
import jdk.nashorn.internal.runtime.Debug;
import jdk.nashorn.internal.runtime.Source;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/LiteralNode.java Thu Aug 28 14:53:37 2014 -0700
@@ -29,7 +29,6 @@
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
-
import jdk.nashorn.internal.codegen.CompileUnit;
import jdk.nashorn.internal.codegen.types.ArrayType;
import jdk.nashorn.internal.codegen.types.Type;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Node.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/Node.java Thu Aug 28 14:53:37 2014 -0700
@@ -27,7 +27,6 @@
import java.util.ArrayList;
import java.util.List;
-
import jdk.nashorn.internal.ir.visitor.NodeVisitor;
import jdk.nashorn.internal.parser.Token;
import jdk.nashorn.internal.parser.TokenType;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornTextifier.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornTextifier.java Thu Aug 28 14:53:37 2014 -0700
@@ -39,7 +39,6 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import jdk.internal.org.objectweb.asm.Attribute;
import jdk.internal.org.objectweb.asm.Handle;
import jdk.internal.org.objectweb.asm.Label;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java Thu Aug 28 14:53:37 2014 -0700
@@ -46,12 +46,11 @@
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
-
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
-
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
+import jdk.nashorn.api.scripting.ClassFilter;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import jdk.nashorn.internal.codegen.ApplySpecialization;
import jdk.nashorn.internal.codegen.CompilerConstants.Call;
@@ -396,19 +395,19 @@
private ScriptObject builtinJavafx;
private ScriptObject builtinJavax;
private ScriptObject builtinOrg;
- private ScriptObject builtinJavaImporter;
+ private ScriptFunction builtinJavaImporter;
private ScriptObject builtinJavaApi;
- private ScriptObject builtinArrayBuffer;
- private ScriptObject builtinDataView;
- private ScriptObject builtinInt8Array;
- private ScriptObject builtinUint8Array;
- private ScriptObject builtinUint8ClampedArray;
- private ScriptObject builtinInt16Array;
- private ScriptObject builtinUint16Array;
- private ScriptObject builtinInt32Array;
- private ScriptObject builtinUint32Array;
- private ScriptObject builtinFloat32Array;
- private ScriptObject builtinFloat64Array;
+ private ScriptFunction builtinArrayBuffer;
+ private ScriptFunction builtinDataView;
+ private ScriptFunction builtinInt8Array;
+ private ScriptFunction builtinUint8Array;
+ private ScriptFunction builtinUint8ClampedArray;
+ private ScriptFunction builtinInt16Array;
+ private ScriptFunction builtinUint16Array;
+ private ScriptFunction builtinInt32Array;
+ private ScriptFunction builtinUint32Array;
+ private ScriptFunction builtinFloat32Array;
+ private ScriptFunction builtinFloat64Array;
/*
* ECMA section 13.2.3 The [[ThrowTypeError]] Function Object
@@ -545,6 +544,14 @@
// Runtime interface to Global
/**
+ * Is there a class filter in the current Context?
+ * @return class filter
+ */
+ public ClassFilter getClassFilter() {
+ return context.getClassFilter();
+ }
+
+ /**
* Is this global of the given Context?
* @param ctxt the context
* @return true if this global belongs to the given Context
@@ -1688,15 +1695,15 @@
this.quit = ScriptFunctionImpl.makeFunction("quit", EXIT);
// built-in constructors
- this.builtinArray = (ScriptFunction)initConstructor("Array");
- this.builtinBoolean = (ScriptFunction)initConstructor("Boolean");
- this.builtinDate = (ScriptFunction)initConstructor("Date");
- this.builtinJSON = initConstructor("JSON");
- this.builtinJSAdapter = (ScriptFunction)initConstructor("JSAdapter");
- this.builtinMath = initConstructor("Math");
- this.builtinNumber = (ScriptFunction)initConstructor("Number");
- this.builtinRegExp = (ScriptFunction)initConstructor("RegExp");
- this.builtinString = (ScriptFunction)initConstructor("String");
+ this.builtinArray = initConstructor("Array", ScriptFunction.class);
+ this.builtinBoolean = initConstructor("Boolean", ScriptFunction.class);
+ this.builtinDate = initConstructor("Date", ScriptFunction.class);
+ this.builtinJSON = initConstructor("JSON", ScriptObject.class);
+ this.builtinJSAdapter = initConstructor("JSAdapter", ScriptFunction.class);
+ this.builtinMath = initConstructor("Math", ScriptObject.class);
+ this.builtinNumber = initConstructor("Number", ScriptFunction.class);
+ this.builtinRegExp = initConstructor("RegExp", ScriptFunction.class);
+ this.builtinString = initConstructor("String", ScriptFunction.class);
// initialize String.prototype.length to 0
// add String.prototype.length
@@ -1777,7 +1784,7 @@
private void initErrorObjects() {
// Error objects
- this.builtinError = (ScriptFunction)initConstructor("Error");
+ this.builtinError = initConstructor("Error", ScriptFunction.class);
final ScriptObject errorProto = getErrorPrototype();
// Nashorn specific accessors on Error.prototype - stack, lineNumber, columnNumber and fileName
@@ -1810,12 +1817,12 @@
}
private ScriptFunction initErrorSubtype(final String name, final ScriptObject errorProto) {
- final ScriptObject cons = initConstructor(name);
+ final ScriptFunction cons = initConstructor(name, ScriptFunction.class);
final ScriptObject prototype = ScriptFunction.getPrototype(cons);
prototype.set(NativeError.NAME, name, false);
prototype.set(NativeError.MESSAGE, "", false);
prototype.setInitialProto(errorProto);
- return (ScriptFunction)cons;
+ return cons;
}
private void initJavaAccess() {
@@ -1827,8 +1834,8 @@
this.builtinJavafx = new NativeJavaPackage("javafx", objectProto);
this.builtinJavax = new NativeJavaPackage("javax", objectProto);
this.builtinOrg = new NativeJavaPackage("org", objectProto);
- this.builtinJavaImporter = initConstructor("JavaImporter");
- this.builtinJavaApi = initConstructor("Java");
+ this.builtinJavaImporter = initConstructor("JavaImporter", ScriptFunction.class);
+ this.builtinJavaApi = initConstructor("Java", ScriptObject.class);
}
private void initScripting(final ScriptEnvironment scriptEnv) {
@@ -1881,17 +1888,17 @@
}
private void initTypedArray() {
- this.builtinArrayBuffer = initConstructor("ArrayBuffer");
- this.builtinDataView = initConstructor("DataView");
- this.builtinInt8Array = initConstructor("Int8Array");
- this.builtinUint8Array = initConstructor("Uint8Array");
- this.builtinUint8ClampedArray = initConstructor("Uint8ClampedArray");
- this.builtinInt16Array = initConstructor("Int16Array");
- this.builtinUint16Array = initConstructor("Uint16Array");
- this.builtinInt32Array = initConstructor("Int32Array");
- this.builtinUint32Array = initConstructor("Uint32Array");
- this.builtinFloat32Array = initConstructor("Float32Array");
- this.builtinFloat64Array = initConstructor("Float64Array");
+ this.builtinArrayBuffer = initConstructor("ArrayBuffer", ScriptFunction.class);
+ this.builtinDataView = initConstructor("DataView", ScriptFunction.class);
+ this.builtinInt8Array = initConstructor("Int8Array", ScriptFunction.class);
+ this.builtinUint8Array = initConstructor("Uint8Array", ScriptFunction.class);
+ this.builtinUint8ClampedArray = initConstructor("Uint8ClampedArray", ScriptFunction.class);
+ this.builtinInt16Array = initConstructor("Int16Array", ScriptFunction.class);
+ this.builtinUint16Array = initConstructor("Uint16Array", ScriptFunction.class);
+ this.builtinInt32Array = initConstructor("Int32Array", ScriptFunction.class);
+ this.builtinUint32Array = initConstructor("Uint32Array", ScriptFunction.class);
+ this.builtinFloat32Array = initConstructor("Float32Array", ScriptFunction.class);
+ this.builtinFloat64Array = initConstructor("Float64Array", ScriptFunction.class);
}
private void copyBuiltins() {
@@ -1936,7 +1943,7 @@
}
private void initDebug() {
- this.addOwnProperty("Debug", Attribute.NOT_ENUMERABLE, initConstructor("Debug"));
+ this.addOwnProperty("Debug", Attribute.NOT_ENUMERABLE, initConstructor("Debug", ScriptObject.class));
}
private Object printImpl(final boolean newLine, final Object... objects) {
@@ -1968,7 +1975,7 @@
* These classes are generated by nasgen tool and so we have to use
* reflection to load and create new instance of these classes.
*/
- private ScriptObject initConstructor(final String name) {
+ private <T extends ScriptObject> T initConstructor(final String name, final Class<T> clazz) {
try {
// Assuming class name pattern for built-in JS constructors.
final StringBuilder sb = new StringBuilder("jdk.nashorn.internal.objects.");
@@ -1977,8 +1984,8 @@
sb.append(name);
sb.append("$Constructor");
- final Class<?> funcClass = Class.forName(sb.toString());
- final ScriptObject res = (ScriptObject)funcClass.newInstance();
+ final Class<?> funcClass = Class.forName(sb.toString());
+ final T res = clazz.cast(funcClass.newInstance());
if (res instanceof ScriptFunction) {
// All global constructor prototypes are not-writable,
@@ -1992,9 +1999,7 @@
}
res.setIsBuiltin();
-
return res;
-
} catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
@@ -2008,7 +2013,7 @@
// to play with object references carefully!!
private void initFunctionAndObject() {
// First-n-foremost is Function
- this.builtinFunction = (ScriptFunction)initConstructor("Function");
+ this.builtinFunction = initConstructor("Function", ScriptFunction.class);
// create global anonymous function
final ScriptFunction anon = ScriptFunctionImpl.newAnonymousFunction();
@@ -2030,7 +2035,7 @@
typeErrorThrower.preventExtensions();
// now initialize Object
- this.builtinObject = (ScriptFunction)initConstructor("Object");
+ this.builtinObject = initConstructor("Object", ScriptFunction.class);
final ScriptObject ObjectPrototype = getObjectPrototype();
// Object.getPrototypeOf(Function.prototype) === Object.prototype
anon.setInitialProto(ObjectPrototype);
@@ -2154,7 +2159,7 @@
/**
* Tag a reserved name as invalidated - used when someone writes
* to a property with this name - overly conservative, but link time
- * is too late to apply e.g. apply->call specialization
+ * is too late to apply e.g. apply->call specialization
* @param name property name
*/
public void invalidateReservedName(final String name) {
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeJava.java Thu Aug 28 14:53:37 2014 -0700
@@ -45,8 +45,8 @@
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ListAdapter;
import jdk.nashorn.internal.runtime.PropertyMap;
+import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
-import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
import jdk.nashorn.internal.runtime.linker.JavaAdapterFactory;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeObject.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeObject.java Thu Aug 28 14:53:37 2014 -0700
@@ -39,7 +39,6 @@
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
-
import jdk.internal.dynalink.beans.BeansLinker;
import jdk.internal.dynalink.beans.StaticClass;
import jdk.internal.dynalink.linker.GuardedInvocation;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeString.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeString.java Thu Aug 28 14:53:37 2014 -0700
@@ -39,6 +39,7 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
+import java.util.Set;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
@@ -391,10 +392,12 @@
/**
* return a List of own keys associated with the object.
* @param all True if to include non-enumerable keys.
+ * @param nonEnumerable set of non-enumerable properties seen already.Used
+ * to filter out shadowed, but enumerable properties from proto children.
* @return Array of keys.
*/
@Override
- public String[] getOwnKeys(final boolean all) {
+ protected String[] getOwnKeys(final boolean all, final Set<String> nonEnumerable) {
final List<Object> keys = new ArrayList<>();
// add string index keys
@@ -403,7 +406,7 @@
}
// add super class properties
- keys.addAll(Arrays.asList(super.getOwnKeys(all)));
+ keys.addAll(Arrays.asList(super.getOwnKeys(all, nonEnumerable)));
return keys.toArray(new String[keys.size()]);
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/annotations/Optimistic.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/annotations/Optimistic.java Thu Aug 28 14:53:37 2014 -0700
@@ -40,7 +40,7 @@
* in NativeArray that takes an int, write
*
* <pre>
- * @SpecializedFunction @Optimistic
+ * {@literal @}SpecializedFunction {@literal @}Optimistic
* public static int push(final Object self, final int x, final int programPoint) {
* try {
* //push code assuming that this is an int array
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/AbstractParser.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/AbstractParser.java Thu Aug 28 14:53:37 2014 -0700
@@ -91,9 +91,6 @@
/** What should line numbers be counted from? */
protected final int lineOffset;
- /** //@ sourceURL or //# sourceURL */
- protected String sourceURL;
-
/**
* Construct a parser.
*
@@ -182,7 +179,7 @@
// currently only @sourceURL=foo supported
private void checkDirectiveComment() {
// if already set, ignore this one
- if (sourceURL != null) {
+ if (source.getExplicitURL() != null) {
return;
}
@@ -190,7 +187,7 @@
final int len = comment.length();
// 4 characters for directive comment marker //@\s or //#\s
if (len > 4 && comment.substring(4).startsWith(SOURCE_URL_PREFIX)) {
- sourceURL = comment.substring(4 + SOURCE_URL_PREFIX.length());
+ source.setExplicitURL(comment.substring(4 + SOURCE_URL_PREFIX.length()));
}
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Parser.java Thu Aug 28 14:53:37 2014 -0700
@@ -106,6 +106,8 @@
import jdk.nashorn.internal.ir.VarNode;
import jdk.nashorn.internal.ir.WhileNode;
import jdk.nashorn.internal.ir.WithNode;
+import jdk.nashorn.internal.ir.debug.ASTWriter;
+import jdk.nashorn.internal.ir.debug.PrintVisitor;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ErrorManager;
import jdk.nashorn.internal.runtime.JSErrorType;
@@ -346,9 +348,10 @@
expect(EOF);
function.setFinish(source.getLength() - 1);
-
function = restoreFunctionNode(function, token); //commit code
function = function.setBody(lc, function.getBody().setNeedsScope(lc));
+
+ printAST(function);
return function;
} catch (final Exception e) {
handleParseException(e);
@@ -477,8 +480,7 @@
name,
parameters,
kind,
- flags,
- sourceURL);
+ flags);
lc.push(functionNode);
// Create new block, and just put it on the context stack, restoreFunctionNode() will associate it with the
@@ -702,10 +704,6 @@
script = restoreFunctionNode(script, token); //commit code
script = script.setBody(lc, script.getBody().setNeedsScope(lc));
- // user may have directive comment to set sourceURL
- if (sourceURL != null) {
- script = script.setSourceURL(lc, sourceURL);
- }
return script;
}
@@ -805,6 +803,12 @@
verifyStrictIdent(param, "function parameter");
}
}
+ } else if (Context.DEBUG) {
+ final int flag = FunctionNode.getDirectiveFlag(directive);
+ if (flag != 0) {
+ final FunctionNode function = lc.getCurrentFunction();
+ lc.setFlag(function, flag);
+ }
}
}
}
@@ -2814,14 +2818,24 @@
lastToken = token;
expect(RBRACE);
functionNode.setFinish(finish);
-
}
} finally {
functionNode = restoreFunctionNode(functionNode, lastToken);
}
+ printAST(functionNode);
return functionNode;
}
+ private void printAST(final FunctionNode functionNode) {
+ if (functionNode.getFlag(FunctionNode.IS_PRINT_AST)) {
+ env.getErr().println(new ASTWriter(functionNode));
+ }
+
+ if (functionNode.getFlag(FunctionNode.IS_PRINT_PARSE)) {
+ env.getErr().println(new PrintVisitor(functionNode, true, false));
+ }
+ }
+
private void addFunctionDeclarations(final FunctionNode functionNode) {
assert lc.peek() == lc.getFunctionBody(functionNode);
VarNode lastDecl = null;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/AccessorProperty.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/AccessorProperty.java Thu Aug 28 14:53:37 2014 -0700
@@ -136,16 +136,16 @@
}
/** Seed getter for the primitive version of this field (in -Dnashorn.fields.dual=true mode) */
- private transient MethodHandle primitiveGetter;
+ transient MethodHandle primitiveGetter;
/** Seed setter for the primitive version of this field (in -Dnashorn.fields.dual=true mode) */
- private transient MethodHandle primitiveSetter;
+ transient MethodHandle primitiveSetter;
/** Seed getter for the Object version of this field */
- private transient MethodHandle objectGetter;
+ transient MethodHandle objectGetter;
/** Seed setter for the Object version of this field */
- private transient MethodHandle objectSetter;
+ transient MethodHandle objectSetter;
/**
* Current type of this object, in object only mode, this is an Object.class. In dual-fields mode
@@ -185,10 +185,10 @@
* @param key the property key
* @param flags the property flags
* @param slot spill slot
- * @param objectGetter
- * @param objectSetter
- * @param primitiveGetter
- * @param primitiveSetter
+ * @param primitiveGetter primitive getter
+ * @param primitiveSetter primitive setter
+ * @param objectGetter object getter
+ * @param objectSetter object setter
*/
protected AccessorProperty(
final String key,
@@ -255,7 +255,7 @@
}
/**
- * Normal ACCESS PROPERTY constructor given a structure glass.
+ * Normal ACCESS PROPERTY constructor given a structure class.
* Constructor for dual field AccessorPropertys.
*
* @param key property key
@@ -267,6 +267,7 @@
super(key, flags, slot);
initGetterSetter(structure);
+ initializeType();
}
private void initGetterSetter(final Class<?> structure) {
@@ -291,8 +292,6 @@
objectSetter = gs.objectSetters[slot];
primitiveSetter = gs.primitiveSetters[slot];
}
-
- initializeType();
}
/**
@@ -412,8 +411,8 @@
}
}
- @Override
- public long getLongValue(final ScriptObject self, final ScriptObject owner) {
+ @Override
+ public long getLongValue(final ScriptObject self, final ScriptObject owner) {
try {
return (long)getGetter(long.class).invokeExact((Object)self);
} catch (final Error | RuntimeException e) {
@@ -531,12 +530,13 @@
@Override
void initMethodHandles(final Class<?> structure) {
+ // sanity check for structure class
if (!ScriptObject.class.isAssignableFrom(structure) || !StructureLoader.isStructureClass(structure.getName())) {
throw new IllegalArgumentException();
}
- if (!isSpill()) {
- initGetterSetter(structure);
- }
+ // this method is overridden in SpillProperty
+ assert !isSpill();
+ initGetterSetter(structure);
}
@Override
@@ -712,7 +712,7 @@
private MethodHandle debug(final MethodHandle mh, final Class<?> forType, final Class<?> type, final String tag) {
- if (!Global.hasInstance()) {
+ if (!Context.DEBUG || !Global.hasInstance()) {
return mh;
}
@@ -734,7 +734,7 @@
}
private MethodHandle debugReplace(final Class<?> oldType, final Class<?> newType, final PropertyMap oldMap, final PropertyMap newMap) {
- if (!Global.hasInstance()) {
+ if (!Context.DEBUG || !Global.hasInstance()) {
return REPLACE_MAP;
}
@@ -767,7 +767,7 @@
}
private static MethodHandle debugInvalidate(final String key, final SwitchPoint sp) {
- if (!Global.hasInstance()) {
+ if (!Context.DEBUG || !Global.hasInstance()) {
return INVALIDATE_SP;
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CodeInstaller.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CodeInstaller.java Thu Aug 28 14:53:37 2014 -0700
@@ -92,5 +92,14 @@
* @param classBytes map of class names to class bytes
* @param constants constants array
*/
- public void storeCompiledScript(Source source, String mainClassName, Map<String, byte[]> classBytes, Object[] constants);
+ public void storeScript(String cacheKey, Source source, String mainClassName, Map<String, byte[]> classBytes,
+ Map<Integer, FunctionInitializer> initializers, Object[] constants, int compilationId);
+
+ /**
+ * Load a previously compiled script
+ * @param source the script source
+ * @param functionKey the function id and signature
+ * @return compiled script data
+ */
+ public StoredScript loadScript(Source source, String functionKey);
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CodeStore.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CodeStore.java Thu Aug 28 14:53:37 2014 -0700
@@ -38,25 +38,30 @@
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Map;
+import jdk.nashorn.internal.codegen.types.Type;
+import jdk.nashorn.internal.runtime.logging.DebugLogger;
+import jdk.nashorn.internal.runtime.logging.Loggable;
+import jdk.nashorn.internal.runtime.logging.Logger;
/**
* A code cache for persistent caching of compiled scripts.
*/
-final class CodeStore {
+@Logger(name="codestore")
+final class CodeStore implements Loggable {
private final File dir;
private final int minSize;
+ private final DebugLogger log;
// Default minimum size for storing a compiled script class
private final static int DEFAULT_MIN_SIZE = 1000;
/**
* Constructor
- * @param path directory to store code in
* @throws IOException
*/
- public CodeStore(final String path) throws IOException {
- this(path, DEFAULT_MIN_SIZE);
+ public CodeStore(final Context context, final String path) throws IOException {
+ this(context, path, DEFAULT_MIN_SIZE);
}
/**
@@ -65,9 +70,20 @@
* @param minSize minimum file size for caching scripts
* @throws IOException
*/
- public CodeStore(final String path, final int minSize) throws IOException {
+ public CodeStore(final Context context, final String path, final int minSize) throws IOException {
this.dir = checkDirectory(path);
this.minSize = minSize;
+ this.log = initLogger(context);
+ }
+
+ @Override
+ public DebugLogger initLogger(final Context context) {
+ return context.getLogger(getClass());
+ }
+
+ @Override
+ public DebugLogger getLogger() {
+ return log;
}
private static File checkDirectory(final String path) throws IOException {
@@ -77,11 +93,11 @@
public File run() throws IOException {
final File dir = new File(path).getAbsoluteFile();
if (!dir.exists() && !dir.mkdirs()) {
- throw new IOException("Could not create directory: " + dir);
+ throw new IOException("Could not create directory: " + dir.getPath());
} else if (!dir.isDirectory()) {
- throw new IOException("Not a directory: " + dir);
+ throw new IOException("Not a directory: " + dir.getPath());
} else if (!dir.canRead() || !dir.canWrite()) {
- throw new IOException("Directory not readable or writable: " + dir);
+ throw new IOException("Directory not readable or writable: " + dir.getPath());
}
return dir;
}
@@ -91,69 +107,85 @@
}
}
+ private File getCacheFile(final Source source, final String functionKey) {
+ return new File(dir, source.getDigest() + '-' + functionKey);
+ }
+
+ /**
+ * Generate a string representing the function with {@code functionId} and {@code paramTypes}.
+ * @param functionId function id
+ * @param paramTypes parameter types
+ * @return a string representing the function
+ */
+ public static String getCacheKey(final int functionId, final Type[] paramTypes) {
+ final StringBuilder b = new StringBuilder().append(functionId);
+ if(paramTypes != null && paramTypes.length > 0) {
+ b.append('-');
+ for(final Type t: paramTypes) {
+ b.append(Type.getShortSignatureDescriptor(t));
+ }
+ }
+ return b.toString();
+ }
+
/**
* Return a compiled script from the cache, or null if it isn't found.
*
* @param source the source
- * @return the compiled script or null
- * @throws IOException
- * @throws ClassNotFoundException
+ * @param functionKey the function key
+ * @return the stored script or null
*/
- public CompiledScript getScript(final Source source) throws IOException, ClassNotFoundException {
+ public StoredScript loadScript(final Source source, final String functionKey) {
if (source.getLength() < minSize) {
return null;
}
- final File file = new File(dir, source.getDigest());
+ final File file = getCacheFile(source, functionKey);
try {
- return AccessController.doPrivileged(new PrivilegedExceptionAction<CompiledScript>() {
+ return AccessController.doPrivileged(new PrivilegedExceptionAction<StoredScript>() {
@Override
- public CompiledScript run() throws IOException, ClassNotFoundException {
+ public StoredScript run() throws IOException, ClassNotFoundException {
if (!file.exists()) {
return null;
}
try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)))) {
- final CompiledScript compiledScript = (CompiledScript) in.readObject();
- compiledScript.setSource(source);
- return compiledScript;
+ final StoredScript storedScript = (StoredScript) in.readObject();
+ getLogger().info("loaded ", source, "-", functionKey);
+ return storedScript;
}
}
});
} catch (final PrivilegedActionException e) {
- final Exception ex = e.getException();
- if (ex instanceof IOException) {
- throw (IOException) ex;
- } else if (ex instanceof ClassNotFoundException) {
- throw (ClassNotFoundException) ex;
- }
- throw (new RuntimeException(ex));
+ getLogger().warning("failed to load ", source, "-", functionKey, ": ", e.getException());
+ return null;
}
}
/**
* Store a compiled script in the cache.
*
+ * @param functionKey the function key
* @param source the source
* @param mainClassName the main class name
* @param classBytes a map of class bytes
* @param constants the constants array
- * @throws IOException
*/
- public void putScript(final Source source, final String mainClassName, final Map<String, byte[]> classBytes, final Object[] constants)
- throws IOException {
+ public void storeScript(final String functionKey, final Source source, final String mainClassName, final Map<String, byte[]> classBytes,
+ final Map<Integer, FunctionInitializer> initializers, final Object[] constants, final int compilationId) {
if (source.getLength() < minSize) {
return;
}
for (final Object constant : constants) {
// Make sure all constant data is serializable
if (! (constant instanceof Serializable)) {
+ getLogger().warning("cannot store ", source, " non serializable constant ", constant);
return;
}
}
- final File file = new File(dir, source.getDigest());
- final CompiledScript script = new CompiledScript(source, mainClassName, classBytes, constants);
+ final File file = getCacheFile(source, functionKey);
+ final StoredScript script = new StoredScript(compilationId, mainClassName, classBytes, initializers, constants);
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@@ -162,11 +194,12 @@
try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) {
out.writeObject(script);
}
+ getLogger().info("stored ", source, "-", functionKey);
return null;
}
});
} catch (final PrivilegedActionException e) {
- throw (IOException) e.getException();
+ getLogger().warning("failed to store ", script, "-", functionKey, ": ", e.getException());
}
}
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CompiledFunction.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CompiledFunction.java Thu Aug 28 14:53:37 2014 -0700
@@ -37,9 +37,12 @@
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
+import java.util.function.Supplier;
import java.util.logging.Level;
+import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.nashorn.internal.codegen.Compiler;
import jdk.nashorn.internal.codegen.Compiler.CompilationPhases;
+import jdk.nashorn.internal.codegen.TypeMap;
import jdk.nashorn.internal.codegen.types.ArrayType;
import jdk.nashorn.internal.codegen.types.Type;
import jdk.nashorn.internal.ir.FunctionNode;
@@ -69,7 +72,8 @@
private MethodHandle invoker;
private MethodHandle constructor;
private OptimismInfo optimismInfo;
- private int flags; // from FunctionNode
+ private final int flags; // from FunctionNode
+ private final MethodType callSiteType;
CompiledFunction(final MethodHandle invoker) {
this(invoker, null);
@@ -80,19 +84,20 @@
}
CompiledFunction(final MethodHandle invoker, final MethodHandle constructor) {
- this(invoker, constructor, DebugLogger.DISABLED_LOGGER);
+ this(invoker, constructor, 0, null, DebugLogger.DISABLED_LOGGER);
}
- CompiledFunction(final MethodHandle invoker, final MethodHandle constructor, final DebugLogger log) {
+ CompiledFunction(final MethodHandle invoker, final MethodHandle constructor, final int flags, final MethodType callSiteType, final DebugLogger log) {
this.invoker = invoker;
this.constructor = constructor;
+ this.flags = flags;
+ this.callSiteType = callSiteType;
this.log = log;
}
CompiledFunction(final MethodHandle invoker, final RecompilableScriptFunctionData functionData,
- final Map<Integer, Type> invalidatedProgramPoints, final int flags) {
- this(invoker, null, functionData.getLogger());
- this.flags = flags;
+ final Map<Integer, Type> invalidatedProgramPoints, final MethodType callSiteType, final int flags) {
+ this(invoker, null, flags, callSiteType, functionData.getLogger());
if ((flags & FunctionNode.IS_DEOPTIMIZABLE) != 0) {
optimismInfo = new OptimismInfo(functionData, invalidatedProgramPoints);
} else {
@@ -125,9 +130,9 @@
* Returns an invoker method handle for this function. Note that the handle is safely composable in
* the sense that you can compose it with other handles using any combinators even if you can't affect call site
* invalidation. If this compiled function is non-optimistic, then it returns the same value as
- * {@link #getInvoker()}. However, if the function is optimistic, then this handle will incur an overhead as it will
- * add an intermediate internal call site that can relink itself when the function needs to regenerate its code to
- * always point at the latest generated code version.
+ * {@link #getInvokerOrConstructor(boolean)}. However, if the function is optimistic, then this handle will
+ * incur an overhead as it will add an intermediate internal call site that can relink itself when the function
+ * needs to regenerate its code to always point at the latest generated code version.
* @return a guaranteed composable invoker method handle for this function.
*/
MethodHandle createComposableInvoker() {
@@ -142,7 +147,7 @@
* all other cases, use {@link #createComposableConstructor()}.
* @return a direct constructor method handle for this function.
*/
- MethodHandle getConstructor() {
+ private MethodHandle getConstructor() {
if (constructor == null) {
constructor = createConstructorFromInvoker(createInvokerForPessimisticCaller());
}
@@ -163,8 +168,6 @@
* Compose a constructor from an invoker.
*
* @param invoker invoker
- * @param needsCallee do we need to pass a callee
- *
* @return the composed constructor
*/
private static MethodHandle createConstructorFromInvoker(final MethodHandle invoker) {
@@ -425,6 +428,9 @@
}
boolean matchesCallSite(final MethodType callSiteType, final boolean pickVarArg) {
+ if (callSiteType.equals(this.callSiteType)) {
+ return true;
+ }
final MethodType type = type();
final int fnParamCount = getParamCount(type);
final boolean isVarArg = fnParamCount == Integer.MAX_VALUE;
@@ -462,17 +468,7 @@
return type.parameterType(paramCount - 1).isArray() ? Integer.MAX_VALUE : paramCount;
}
- /**
- * Returns the switch point embodying the optimistic assumptions in this compiled function. It should be used to
- * guard any linking to the function's invoker or constructor.
- * @return the switch point embodying the optimistic assumptions in this compiled function. Null is returned if the
- * function has no optimistic assumptions.
- */
- SwitchPoint getOptimisticAssumptionsSwitchPoint() {
- return canBeDeoptimized() ? optimismInfo.optimisticAssumptions : null;
- }
-
- boolean canBeDeoptimized() {
+ private boolean canBeDeoptimized() {
return optimismInfo != null;
}
@@ -491,19 +487,73 @@
relinkComposableInvoker(cs, this, isConstructor);
return cs.dynamicInvoker();
}
+
+ private static class HandleAndAssumptions {
+ final MethodHandle handle;
+ final SwitchPoint assumptions;
+
+ HandleAndAssumptions(final MethodHandle handle, final SwitchPoint assumptions) {
+ this.handle = handle;
+ this.assumptions = assumptions;
+ }
+
+ GuardedInvocation createInvocation() {
+ return new GuardedInvocation(handle, assumptions);
+ }
+ }
+
+ /**
+ * Returns a pair of an invocation created with a passed-in supplier and a non-invalidated switch point for
+ * optimistic assumptions (or null for the switch point if the function can not be deoptimized). While the method
+ * makes a best effort to return a non-invalidated switch point (compensating for possible deoptimizing
+ * recompilation happening on another thread) it is still possible that by the time this method returns the
+ * switchpoint has been invalidated by a {@code RewriteException} triggered on another thread for this function.
+ * This is not a problem, though, as these switch points are always used to produce call sites that fall back to
+ * relinking when they are invalidated, and in this case the execution will end up here again. What this method
+ * basically does is minimize such busy-loop relinking while the function is being recompiled on a different thread.
+ * @param invocationSupplier the supplier that constructs the actual invocation method handle; should use the
+ * {@code CompiledFunction} method itself in some capacity.
+ * @return a tuple object containing the method handle as created by the supplier and an optimistic assumptions
+ * switch point that is guaranteed to not have been invalidated before the call to this method (or null if the
+ * function can't be further deoptimized).
+ */
+ private synchronized HandleAndAssumptions getValidOptimisticInvocation(final Supplier<MethodHandle> invocationSupplier) {
+ for(;;) {
+ final MethodHandle handle = invocationSupplier.get();
+ final SwitchPoint assumptions = canBeDeoptimized() ? optimismInfo.optimisticAssumptions : null;
+ if(assumptions != null && assumptions.hasBeenInvalidated()) {
+ // We can be in a situation where one thread is in the middle of a deoptimizing compilation when we hit
+ // this and thus, it has invalidated the old switch point, but hasn't created the new one yet. Note that
+ // the behavior of invalidating the old switch point before recompilation, and only creating the new one
+ // after recompilation is by design. If we didn't wait here for the recompilation to complete, we would
+ // be busy looping through the fallback path of the invalidated switch point, relinking the call site
+ // again with the same invalidated switch point, invoking the fallback, etc. stealing CPU cycles from
+ // the recompilation task we're dependent on. This can still happen if the switch point gets invalidated
+ // after we grabbed it here, in which case we'll indeed do one busy relink immediately.
+ try {
+ wait();
+ } catch (final InterruptedException e) {
+ // Intentionally ignored. There's nothing meaningful we can do if we're interrupted
+ }
+ } else {
+ return new HandleAndAssumptions(handle, assumptions);
+ }
+ }
+ }
+
private static void relinkComposableInvoker(final CallSite cs, final CompiledFunction inv, final boolean constructor) {
- final MethodHandle handle = inv.getInvokerOrConstructor(constructor);
- final SwitchPoint assumptions = inv.getOptimisticAssumptionsSwitchPoint();
+ final HandleAndAssumptions handleAndAssumptions = inv.getValidOptimisticInvocation(new Supplier<MethodHandle>() {
+ @Override
+ public MethodHandle get() {
+ return inv.getInvokerOrConstructor(constructor);
+ }
+ });
+ final MethodHandle handle = handleAndAssumptions.handle;
+ final SwitchPoint assumptions = handleAndAssumptions.assumptions;
final MethodHandle target;
if(assumptions == null) {
target = handle;
} else {
- // This assertion can obviously fail in a multithreaded environment, as we can be in a situation where
- // one thread is in the middle of a deoptimizing compilation when we hit this and thus, it has invalidated
- // the old switch point, but hasn't created the new one yet. Note that the behavior of invalidating the old
- // switch point before recompilation, and only creating the new one after recompilation is by design.
- // TODO: We need to think about thread safety of CompiledFunction objects.
- assert !assumptions.hasBeenInvalidated();
final MethodHandle relink = MethodHandles.insertArguments(RELINK_COMPOSABLE_INVOKER, 0, cs, inv, constructor);
target = assumptions.guardWithTest(handle, MethodHandles.foldArguments(cs.dynamicInvoker(), relink));
}
@@ -514,7 +564,41 @@
return selectCtor ? getConstructor() : createInvokerForPessimisticCaller();
}
- MethodHandle createInvoker(final Class<?> callSiteReturnType, final int callerProgramPoint) {
+ /**
+ * Returns a guarded invocation for this function when not invoked as a constructor. The guarded invocation has no
+ * guard but it potentially has an optimistic assumptions switch point. As such, it will probably not be used as a
+ * final guarded invocation, but rather as a holder for an invocation handle and switch point to be decomposed and
+ * reassembled into a different final invocation by the user of this method. Any recompositions should take care to
+ * continue to use the switch point. If that is not possible, use {@link #createComposableInvoker()} instead.
+ * @return a guarded invocation for an ordinary (non-constructor) invocation of this function.
+ */
+ GuardedInvocation createFunctionInvocation(final Class<?> callSiteReturnType, final int callerProgramPoint) {
+ return getValidOptimisticInvocation(new Supplier<MethodHandle>() {
+ @Override
+ public MethodHandle get() {
+ return createInvoker(callSiteReturnType, callerProgramPoint);
+ }
+ }).createInvocation();
+ }
+
+ /**
+ * Returns a guarded invocation for this function when invoked as a constructor. The guarded invocation has no guard
+ * but it potentially has an optimistic assumptions switch point. As such, it will probably not be used as a final
+ * guarded invocation, but rather as a holder for an invocation handle and switch point to be decomposed and
+ * reassembled into a different final invocation by the user of this method. Any recompositions should take care to
+ * continue to use the switch point. If that is not possible, use {@link #createComposableConstructor()} instead.
+ * @return a guarded invocation for invocation of this function as a constructor.
+ */
+ GuardedInvocation createConstructorInvocation() {
+ return getValidOptimisticInvocation(new Supplier<MethodHandle>() {
+ @Override
+ public MethodHandle get() {
+ return getConstructor();
+ }
+ }).createInvocation();
+ }
+
+ private MethodHandle createInvoker(final Class<?> callSiteReturnType, final int callerProgramPoint) {
final boolean isOptimistic = canBeDeoptimized();
MethodHandle handleRewriteException = isOptimistic ? createRewriteExceptionHandler() : null;
@@ -601,7 +685,7 @@
* @param re the rewrite exception that was raised
* @return the method handle for the rest-of method, for folding composition.
*/
- private MethodHandle handleRewriteException(final OptimismInfo oldOptInfo, final RewriteException re) {
+ private synchronized MethodHandle handleRewriteException(final OptimismInfo oldOptInfo, final RewriteException re) {
if (log.isEnabled()) {
log.info(new RecompilationEvent(Level.INFO, re, re.getReturnValueNonDestructive()), "RewriteException ", re.getMessageShort());
}
@@ -639,6 +723,15 @@
logRecompile("Rest-of compilation [CODE PIPELINE REUSE] ", fn, callSiteType, effectiveOptInfo.invalidatedProgramPoints);
final FunctionNode normalFn = compiler.compile(fn, CompilationPhases.COMPILE_FROM_BYTECODE);
+ if (effectiveOptInfo.data.usePersistentCodeCache()) {
+ final RecompilableScriptFunctionData data = effectiveOptInfo.data;
+ final int functionNodeId = data.getFunctionNodeId();
+ final TypeMap typeMap = data.typeMap(callSiteType);
+ final Type[] paramTypes = typeMap == null ? null : typeMap.getParameterTypes(functionNodeId);
+ final String cacheKey = CodeStore.getCacheKey(functionNodeId, paramTypes);
+ compiler.persistClassInfo(cacheKey, normalFn);
+ }
+
FunctionNode fn2 = effectiveOptInfo.reparse();
fn2 = compiler.compile(fn2, CompilationPhases.COMPILE_UPTO_BYTECODE);
log.info("Done.");
@@ -664,17 +757,18 @@
} else {
optimismInfo = null; // If we got to a point where we no longer have optimistic assumptions, let the optimism info go.
}
+ notifyAll();
return restOf;
}
private MethodHandle restOfHandle(final OptimismInfo info, final FunctionNode restOfFunction, final boolean canBeDeoptimized) {
assert info != null;
- assert restOfFunction.getCompileUnit().getUnitClassName().indexOf("restOf") != -1;
+ assert restOfFunction.getCompileUnit().getUnitClassName().contains("restOf");
final MethodHandle restOf =
changeReturnType(
- info.data.lookupWithExplicitType(
- restOfFunction,
+ info.data.lookupCodeMethod(
+ restOfFunction.getCompileUnit().getCode(),
MH.type(restOfFunction.getReturnType().getTypeClass(),
RewriteException.class)),
Object.class);
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CompiledFunctions.java Thu Aug 21 14:16:28 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,183 +0,0 @@
-/*
- * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package jdk.nashorn.internal.runtime;
-
-import static jdk.nashorn.internal.lookup.Lookup.MH;
-
-import java.lang.invoke.MethodType;
-import java.util.LinkedList;
-
-/**
- * This is a list of code versions of a function.
- * The list is sorted in ascending order of generic descriptors
- */
-final class CompiledFunctions {
-
- private final String name;
- final LinkedList<CompiledFunction> functions = new LinkedList<>();
-
- CompiledFunctions(final String name) {
- this.name = name;
- }
-
- void add(final CompiledFunction f) {
- functions.add(f);
- }
-
- void addAll(final CompiledFunctions fs) {
- functions.addAll(fs.functions);
- }
-
- boolean isEmpty() {
- return functions.isEmpty();
- }
-
- int size() {
- return functions.size();
- }
-
- @Override
- public String toString() {
- return '\'' + name + "' code=" + functions;
- }
-
- private static MethodType widen(final MethodType cftype) {
- final Class<?>[] paramTypes = new Class<?>[cftype.parameterCount()];
- for (int i = 0; i < cftype.parameterCount(); i++) {
- paramTypes[i] = cftype.parameterType(i).isPrimitive() ? cftype.parameterType(i) : Object.class;
- }
- return MH.type(cftype.returnType(), paramTypes);
- }
-
- /**
- * Used to find an apply to call version that fits this callsite.
- * We cannot just, as in the normal matcher case, return e.g. (Object, Object, int)
- * for (Object, Object, int, int, int) or we will destroy the semantics and get
- * a function that, when padded with undefineds, behaves differently
- * @param type actual call site type
- * @return apply to call that perfectly fits this callsite or null if none found
- */
- CompiledFunction lookupExactApplyToCall(final MethodType type) {
- for (final CompiledFunction cf : functions) {
- if (!cf.isApplyToCall()) {
- continue;
- }
-
- final MethodType cftype = cf.type();
- if (cftype.parameterCount() != type.parameterCount()) {
- continue;
- }
-
- if (widen(cftype).equals(widen(type))) {
- return cf;
- }
- }
-
- return null;
- }
-
- private CompiledFunction pick(final MethodType callSiteType, final boolean canPickVarArg) {
- for (final CompiledFunction candidate : functions) {
- if (candidate.matchesCallSite(callSiteType, false)) {
- return candidate;
- }
- }
- return null;
- }
-
- /**
- * Returns the compiled function best matching the requested call site method type
- * @param callSiteType
- * @param recompilable
- * @param hasThis
- * @return
- */
- CompiledFunction best(final MethodType callSiteType, final boolean recompilable) {
- assert callSiteType.parameterCount() >= 2 : callSiteType; // Must have at least (callee, this)
- assert callSiteType.parameterType(0).isAssignableFrom(ScriptFunction.class) : callSiteType; // Callee must be assignable from script function
-
- if (recompilable) {
- final CompiledFunction candidate = pick(callSiteType, false);
- if (candidate != null) {
- return candidate;
- }
- return pick(callSiteType, true); //try vararg last
- }
-
- CompiledFunction best = null;
- for(final CompiledFunction candidate: functions) {
- if(candidate.betterThanFinal(best, callSiteType)) {
- best = candidate;
- }
- }
-
- return best;
- }
-
- /**
- * Returns true if functions managed by this {@code CompiledFunctions} require a callee. This method is only safe to
- * be invoked for a {@code CompiledFunctions} that is not empty. As such, it should only be used from
- * {@link FinalScriptFunctionData} and not from {@link RecompilableScriptFunctionData}.
- * @return true if the functions need a callee, false otherwise.
- */
- boolean needsCallee() {
- final boolean needsCallee = functions.getFirst().needsCallee();
- assert allNeedCallee(needsCallee);
- return needsCallee;
- }
-
- private boolean allNeedCallee(final boolean needCallee) {
- for (final CompiledFunction inv : functions) {
- if(inv.needsCallee() != needCallee) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * If this CompiledFunctions object belongs to a {@code FinalScriptFunctionData}, get a method type for a generic
- * invoker. It will either be a vararg type, if any of the contained functions is vararg, or a generic type of the
- * arity of the largest arity of all functions.
- * @return the method type for the generic invoker
- */
- MethodType getFinalGenericType() {
- int max = 0;
- for(final CompiledFunction fn: functions) {
- final MethodType t = fn.type();
- if(ScriptFunctionData.isVarArg(t)) {
- // 2 for (callee, this, args[])
- return MethodType.genericMethodType(2, true);
- }
- final int paramCount = t.parameterCount() - (ScriptFunctionData.needsCallee(t) ? 1 : 0);
- if(paramCount > max) {
- max = paramCount;
- }
- }
- // +1 for callee
- return MethodType.genericMethodType(max + 1);
- }
-
-}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CompiledScript.java Thu Aug 21 14:16:28 2014 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,127 +0,0 @@
-/*
- * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package jdk.nashorn.internal.runtime;
-
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.Map;
-
-/**
- * Class representing a compiled script.
- */
-final class CompiledScript implements Serializable {
-
- /** Main class name. */
- private final String mainClassName;
-
- /** Map of class names to class bytes. */
- private final Map<String, byte[]> classBytes;
-
- /** Constants array. */
- private final Object[] constants;
-
- /** The source */
- private transient Source source;
-
- private static final long serialVersionUID = 2958227232195298340L;
-
- /**
- * Constructor.
- *
- * @param mainClassName main class name
- * @param classBytes map of class names to class bytes
- * @param constants constants array
- */
- CompiledScript(final Source source, final String mainClassName, final Map<String, byte[]> classBytes, final Object[] constants) {
- this.source = source;
- this.mainClassName = mainClassName;
- this.classBytes = classBytes;
- this.constants = constants;
- }
-
- /**
- * Returns the main class name.
- * @return the main class name
- */
- public String getMainClassName() {
- return mainClassName;
- }
-
- /**
- * Returns a map of class names to class bytes.
- * @return map of class bytes
- */
- public Map<String, byte[]> getClassBytes() {
- return classBytes;
- }
-
- /**
- * Returns the constants array.
- * @return constants array
- */
- public Object[] getConstants() {
- return constants;
- }
-
- /**
- * Returns the source of this cached script.
- * @return the source
- */
- public Source getSource() {
- return source;
- }
-
- /**
- * Sets the source of this cached script.
- * @param source the source
- */
- void setSource(final Source source) {
- this.source = source;
- }
-
- @Override
- public int hashCode() {
- int hash = mainClassName.hashCode();
- hash = 31 * hash + classBytes.hashCode();
- hash = 31 * hash + Arrays.hashCode(constants);
- return hash;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof CompiledScript)) {
- return false;
- }
-
- final CompiledScript cs = (CompiledScript) obj;
- return mainClassName.equals(cs.mainClassName)
- && classBytes.equals(cs.classBytes)
- && Arrays.equals(constants, cs.constants);
- }
-}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ConsString.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ConsString.java Thu Aug 28 14:53:37 2014 -0700
@@ -91,14 +91,14 @@
return new CharSequence[] { left, right };
}
- private CharSequence flattened(boolean flattenNested) {
+ private CharSequence flattened(final boolean flattenNested) {
if (state != STATE_FLATTENED) {
flatten(flattenNested);
}
return left;
}
- private synchronized void flatten(boolean flattenNested) {
+ private synchronized void flatten(final boolean flattenNested) {
// We use iterative traversal as recursion may exceed the stack size limit.
final char[] chars = new char[length];
int pos = length;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java Thu Aug 28 14:53:37 2014 -0700
@@ -65,6 +65,7 @@
import javax.script.ScriptEngine;
import jdk.internal.org.objectweb.asm.ClassReader;
import jdk.internal.org.objectweb.asm.util.CheckClassAdapter;
+import jdk.nashorn.api.scripting.ClassFilter;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import jdk.nashorn.internal.codegen.Compiler;
import jdk.nashorn.internal.codegen.Compiler.CompilationPhases;
@@ -164,10 +165,13 @@
public void initialize(final Collection<Class<?>> classes, final Source source, final Object[] constants) {
// do these in parallel, this significantly reduces class installation overhead
// however - it still means that every thread needs a separate doPrivileged
+ final Global global = currentGlobal.get();
classes.parallelStream().forEach(
new Consumer<Class<?>>() {
@Override
public void accept(final Class<?> clazz) {
+ // Global threadlocal may be needed by StructureLoader during in field lookup.
+ currentGlobal.set(global);
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
@@ -210,16 +214,21 @@
}
@Override
- public void storeCompiledScript(final Source source, final String mainClassName,
- final Map<String, byte[]> classBytes, final Object[] constants) {
+ public void storeScript(final String classInfoFile, final Source source, final String mainClassName,
+ final Map<String,byte[]> classBytes, final Map<Integer, FunctionInitializer> initializers,
+ final Object[] constants, final int compilationId) {
if (context.codeStore != null) {
- try {
- context.codeStore.putScript(source, mainClassName, classBytes, constants);
- } catch (final IOException e) {
- throw new RuntimeException(e);
- }
+ context.codeStore.storeScript(classInfoFile, source, mainClassName, classBytes, initializers, constants, compilationId);
}
}
+
+ @Override
+ public StoredScript loadScript(final Source source, final String functionKey) {
+ if (context.codeStore != null) {
+ return context.codeStore.loadScript(source, functionKey);
+ }
+ return null;
+ }
}
/** Is Context global debug mode enabled ? */
@@ -341,6 +350,9 @@
/** Unique id for 'eval' */
private final AtomicLong uniqueEvalId;
+ /** Optional class filter to use for Java classes. Can be null. */
+ private final ClassFilter classFilter;
+
private static final ClassLoader myLoader = Context.class.getClassLoader();
private static final StructureLoader sharedLoader;
@@ -395,7 +407,19 @@
* @param appLoader application class loader
*/
public Context(final Options options, final ErrorManager errors, final ClassLoader appLoader) {
- this(options, errors, new PrintWriter(System.out, true), new PrintWriter(System.err, true), appLoader);
+ this(options, errors, appLoader, (ClassFilter)null);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param options options from command line or Context creator
+ * @param errors error manger
+ * @param appLoader application class loader
+ * @param classFilter class filter to use
+ */
+ public Context(final Options options, final ErrorManager errors, final ClassLoader appLoader, final ClassFilter classFilter) {
+ this(options, errors, new PrintWriter(System.out, true), new PrintWriter(System.err, true), appLoader, classFilter);
}
/**
@@ -408,11 +432,26 @@
* @param appLoader application class loader
*/
public Context(final Options options, final ErrorManager errors, final PrintWriter out, final PrintWriter err, final ClassLoader appLoader) {
+ this(options, errors, out, err, appLoader, (ClassFilter)null);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param options options from command line or Context creator
+ * @param errors error manger
+ * @param out output writer for this Context
+ * @param err error writer for this Context
+ * @param appLoader application class loader
+ * @param classFilter class filter to use
+ */
+ public Context(final Options options, final ErrorManager errors, final PrintWriter out, final PrintWriter err, final ClassLoader appLoader, final ClassFilter classFilter) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission(NASHORN_CREATE_CONTEXT));
}
+ this.classFilter = classFilter;
this.env = new ScriptEnvironment(options, out, err);
this._strict = env._strict;
this.appLoader = appLoader;
@@ -447,7 +486,7 @@
if (env._persistent_cache) {
try {
final String cacheDir = Options.getStringProperty("nashorn.persistent.code.cache", "nashorn_code_cache");
- codeStore = new CodeStore(cacheDir);
+ codeStore = new CodeStore(this, cacheDir);
} catch (final IOException e) {
throw new RuntimeException("Error initializing code cache", e);
}
@@ -465,6 +504,15 @@
initLoggers();
}
+
+ /**
+ * Get the class filter for this context
+ * @return class filter
+ */
+ public ClassFilter getClassFilter() {
+ return classFilter;
+ }
+
/**
* Get the error manager for this context
* @return error manger
@@ -882,6 +930,11 @@
throw new ClassNotFoundException(fullName);
}
+ // give chance to ClassFilter to filter out, if present
+ if (classFilter != null && !classFilter.exposeToScripts(fullName)) {
+ throw new ClassNotFoundException(fullName);
+ }
+
// check package access as soon as possible!
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
@@ -1080,30 +1133,27 @@
return script;
}
- CompiledScript compiledScript = null;
+ StoredScript storedScript = null;
FunctionNode functionNode = null;
+ final boolean useCodeStore = env._persistent_cache && !env._parse_only && !env._optimistic_types;
+ final String cacheKey = useCodeStore ? CodeStore.getCacheKey(0, null) : null;
- if (!env._parse_only && codeStore != null) {
- try {
- compiledScript = codeStore.getScript(source);
- } catch (IOException | ClassNotFoundException e) {
- getLogger(Compiler.class).warning("Error loading ", source, " from cache: ", e);
- // Fall back to normal compilation
- }
+ if (useCodeStore) {
+ storedScript = codeStore.loadScript(source, cacheKey);
}
- if (compiledScript == null) {
+ if (storedScript == null) {
functionNode = new Parser(env, source, errMan, strict, getLogger(Parser.class)).parse();
if (errors.hasErrors()) {
return null;
}
- if (env._print_ast) {
+ if (env._print_ast || functionNode.getFlag(FunctionNode.IS_PRINT_AST)) {
getErr().println(new ASTWriter(functionNode));
}
- if (env._print_parse) {
+ if (env._print_parse || functionNode.getFlag(FunctionNode.IS_PRINT_PARSE)) {
getErr().println(new PrintVisitor(functionNode, true, false));
}
}
@@ -1117,7 +1167,7 @@
final CodeSource cs = new CodeSource(url, (CodeSigner[])null);
final CodeInstaller<ScriptEnvironment> installer = new ContextCodeInstaller(this, loader, cs);
- if (functionNode != null) {
+ if (storedScript == null) {
final CompilationPhases phases = Compiler.CompilationPhases.COMPILE_ALL;
final Compiler compiler = new Compiler(
@@ -1125,12 +1175,14 @@
env,
installer,
source,
- functionNode.getSourceURL(),
strict | functionNode.isStrict());
- script = compiler.compile(functionNode, phases).getRootClass();
+ final FunctionNode compiledFunction = compiler.compile(functionNode, phases);
+ script = compiledFunction.getRootClass();
+ compiler.persistClassInfo(cacheKey, compiledFunction);
} else {
- script = install(compiledScript, installer);
+ Compiler.updateCompilationId(storedScript.getCompilationId());
+ script = install(storedScript, source, installer);
}
cacheClass(source, script);
@@ -1155,27 +1207,26 @@
return uniqueScriptId.getAndIncrement();
}
-
/**
* Install a previously compiled class from the code cache.
*
- * @param compiledScript cached script containing class bytes and constants
+ * @param storedScript cached script containing class bytes and constants
* @return main script class
*/
- private static Class<?> install(final CompiledScript compiledScript, final CodeInstaller<ScriptEnvironment> installer) {
+ private static Class<?> install(final StoredScript storedScript, final Source source, final CodeInstaller<ScriptEnvironment> installer) {
final Map<String, Class<?>> installedClasses = new HashMap<>();
- final Source source = compiledScript.getSource();
- final Object[] constants = compiledScript.getConstants();
- final String rootClassName = compiledScript.getMainClassName();
- final byte[] rootByteCode = compiledScript.getClassBytes().get(rootClassName);
- final Class<?> rootClass = installer.install(rootClassName, rootByteCode);
+ final Object[] constants = storedScript.getConstants();
+ final String mainClassName = storedScript.getMainClassName();
+ final byte[] mainClassBytes = storedScript.getClassBytes().get(mainClassName);
+ final Class<?> mainClass = installer.install(mainClassName, mainClassBytes);
+ final Map<Integer, FunctionInitializer> initialzers = storedScript.getInitializers();
- installedClasses.put(rootClassName, rootClass);
+ installedClasses.put(mainClassName, mainClass);
- for (final Map.Entry<String, byte[]> entry : compiledScript.getClassBytes().entrySet()) {
+ for (final Map.Entry<String, byte[]> entry : storedScript.getClassBytes().entrySet()) {
final String className = entry.getKey();
- if (className.equals(rootClassName)) {
+ if (className.equals(mainClassName)) {
continue;
}
final byte[] code = entry.getValue();
@@ -1187,11 +1238,17 @@
for (final Object constant : constants) {
if (constant instanceof RecompilableScriptFunctionData) {
- ((RecompilableScriptFunctionData) constant).initTransients(source, installer);
+ final RecompilableScriptFunctionData data = (RecompilableScriptFunctionData) constant;
+ data.initTransients(source, installer);
+ if (initialzers != null) {
+ final FunctionInitializer initializer = initialzers.get(data.getFunctionNodeId());
+ initializer.setCode(installedClasses.get(initializer.getClassName()));
+ data.initializeCode(initializer);
+ }
}
}
- return rootClass;
+ return mainClass;
}
/**
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ECMAErrors.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ECMAErrors.java Thu Aug 28 14:53:37 2014 -0700
@@ -28,7 +28,6 @@
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
-
import jdk.nashorn.internal.codegen.CompilerConstants;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.scripts.JS;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/FinalScriptFunctionData.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/FinalScriptFunctionData.java Thu Aug 28 14:53:37 2014 -0700
@@ -27,6 +27,7 @@
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
+import java.util.List;
/**
* This is a subclass that represents a script function that may not be regenerated.
@@ -44,10 +45,10 @@
* @param functions precompiled code
* @param flags {@link ScriptFunctionData} flags
*/
- FinalScriptFunctionData(final String name, final int arity, final CompiledFunctions functions, final int flags) {
+ FinalScriptFunctionData(final String name, final int arity, final List<CompiledFunction> functions, final int flags) {
super(name, arity, flags);
- assert !functions.needsCallee();
code.addAll(functions);
+ assert !needsCallee();
}
/**
@@ -76,8 +77,19 @@
}
@Override
- boolean needsCallee() {
- return code.needsCallee();
+ protected boolean needsCallee() {
+ final boolean needsCallee = code.getFirst().needsCallee();
+ assert allNeedCallee(needsCallee);
+ return needsCallee;
+ }
+
+ private boolean allNeedCallee(final boolean needCallee) {
+ for (final CompiledFunction inv : code) {
+ if(inv.needsCallee() != needCallee) {
+ return false;
+ }
+ }
+ return true;
}
@Override
@@ -86,7 +98,20 @@
// actually correct for lots of built-ins. E.g. ECMAScript 5.1 section 15.5.3.2 prescribes that
// Script.fromCharCode([char0[, char1[, ...]]]) has a declared arity of 1 even though it's a variable arity
// method.
- return code.getFinalGenericType();
+ int max = 0;
+ for(final CompiledFunction fn: code) {
+ final MethodType t = fn.type();
+ if(ScriptFunctionData.isVarArg(t)) {
+ // 2 for (callee, this, args[])
+ return MethodType.genericMethodType(2, true);
+ }
+ final int paramCount = t.parameterCount() - (ScriptFunctionData.needsCallee(t) ? 1 : 0);
+ if(paramCount > max) {
+ max = paramCount;
+ }
+ }
+ // +1 for callee
+ return MethodType.genericMethodType(max + 1);
}
private void addInvoker(final MethodHandle mh) {
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/FunctionInitializer.java Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.nashorn.internal.runtime;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.lang.invoke.MethodType;
+import java.util.Map;
+import jdk.nashorn.internal.codegen.CompileUnit;
+import jdk.nashorn.internal.codegen.FunctionSignature;
+import jdk.nashorn.internal.codegen.types.Type;
+import jdk.nashorn.internal.ir.FunctionNode;
+
+/**
+ * Class that contains information allowing us to look up a method handle implementing a JavaScript function
+ * from a generated class. This is used both for code coming from codegen and for persistent serialized code.
+ */
+public final class FunctionInitializer implements Serializable {
+
+ private final String className;
+ private final MethodType methodType;
+ private final int flags;
+ private transient Map<Integer, Type> invalidatedProgramPoints;
+ private transient Class<?> code;
+
+ private static final long serialVersionUID = -5420835725902966692L;
+
+ /**
+ * Constructor.
+ *
+ * @param functionNode the function node
+ */
+ public FunctionInitializer(final FunctionNode functionNode) {
+ this(functionNode, null);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param functionNode the function node
+ * @param invalidatedProgramPoints invalidated program points
+ */
+ public FunctionInitializer(final FunctionNode functionNode, final Map<Integer, Type> invalidatedProgramPoints) {
+ this.className = functionNode.getCompileUnit().getUnitClassName();
+ this.methodType = new FunctionSignature(functionNode).getMethodType();
+ this.flags = functionNode.getFlags();
+ this.invalidatedProgramPoints = invalidatedProgramPoints;
+
+ final CompileUnit cu = functionNode.getCompileUnit();
+ if (cu != null) {
+ this.code = cu.getCode();
+ }
+
+ assert className != null;
+ }
+
+ /**
+ * Returns the name of the class implementing the function.
+ *
+ * @return the class name
+ */
+ public String getClassName() {
+ return className;
+ }
+
+ /**
+ * Returns the type of the method implementing the function.
+ *
+ * @return the method type
+ */
+ public MethodType getMethodType() {
+ return methodType;
+ }
+
+ /**
+ * Returns the function flags.
+ *
+ * @return function flags
+ */
+ public int getFlags() {
+ return flags;
+ }
+
+ /**
+ * Returns the class implementing the function.
+ *
+ * @return the class
+ */
+ public Class<?> getCode() {
+ return code;
+ }
+
+ /**
+ * Set the class implementing the function
+ * @param code the class
+ */
+ public void setCode(final Class<?> code) {
+ // Make sure code has not been set and has expected class name
+ if (this.code != null) {
+ throw new IllegalStateException("code already set");
+ }
+ assert className.equals(code.getTypeName().replace('.', '/')) : "unexpected class name";
+ this.code = code;
+ }
+
+ /**
+ * Returns the map of invalidated program points.
+ *
+ * @return invalidated program points
+ */
+ public Map<Integer, Type> getInvalidatedProgramPoints() {
+ return invalidatedProgramPoints;
+ }
+
+ private void writeObject(final ObjectOutputStream out) throws IOException {
+ out.defaultWriteObject();
+ Type.writeTypeMap(invalidatedProgramPoints, out);
+ }
+
+ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ invalidatedProgramPoints = Type.readTypeMap(in);
+ }
+}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/NativeJavaPackage.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/NativeJavaPackage.java Thu Aug 28 14:53:37 2014 -0700
@@ -25,8 +25,8 @@
package jdk.nashorn.internal.runtime;
+import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.isValid;
-import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Property.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Property.java Thu Aug 28 14:53:37 2014 -0700
@@ -287,17 +287,6 @@
}
/**
- * Does this property use any slots in the spill array described in
- * {@link Property#isSpill}? In that case how many. Currently a property
- * only uses max one spill slot, but this may change in future representations
- *
- * @return number of spill slots a property is using
- */
- public int getSpillCount() {
- return 0;
- }
-
- /**
* Add more property flags to the property. Properties are immutable here,
* so any property change that results in a larger flag set results in the
* property being cloned. Use only the return value
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/PropertyMap.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/PropertyMap.java Thu Aug 28 14:53:37 2014 -0700
@@ -36,6 +36,7 @@
import java.lang.invoke.SwitchPoint;
import java.lang.ref.SoftReference;
import java.util.Arrays;
+import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
@@ -88,6 +89,8 @@
/** property listeners */
private transient PropertyListeners listeners;
+ private transient BitSet freeSlots;
+
private static final long serialVersionUID = -7041836752008732533L;
/**
@@ -129,6 +132,7 @@
this.fieldMaximum = propertyMap.fieldMaximum;
// We inherit the parent property listeners instance. It will be cloned when a new listener is added.
this.listeners = propertyMap.listeners;
+ this.freeSlots = propertyMap.freeSlots;
if (Context.DEBUG) {
count++;
@@ -350,6 +354,51 @@
return addPropertyNoHistory(new AccessorProperty(property, bindTo));
}
+ // Get a logical slot index for a property, with spill slot 0 starting at fieldMaximum.
+ private int logicalSlotIndex(final Property property) {
+ final int slot = property.getSlot();
+ if (slot < 0) {
+ return -1;
+ }
+ return property.isSpill() ? slot + fieldMaximum : slot;
+ }
+
+ // Update boundaries and flags after a property has been added
+ private void updateFlagsAndBoundaries(final Property newProperty) {
+ if(newProperty.isSpill()) {
+ spillLength = Math.max(spillLength, newProperty.getSlot() + 1);
+ } else {
+ fieldCount = Math.max(fieldCount, newProperty.getSlot() + 1);
+ }
+ if (isValidArrayIndex(getArrayIndex(newProperty.getKey()))) {
+ setContainsArrayKeys();
+ }
+ }
+
+ // Update the free slots bitmap for a property that has been deleted and/or added.
+ private void updateFreeSlots(final Property oldProperty, final Property newProperty) {
+ // Free slots bitset is possibly shared with parent map, so we must clone it before making modifications.
+ boolean freeSlotsCloned = false;
+ if (oldProperty != null) {
+ final int slotIndex = logicalSlotIndex(oldProperty);
+ if (slotIndex >= 0) {
+ final BitSet newFreeSlots = freeSlots == null ? new BitSet() : (BitSet)freeSlots.clone();
+ assert !newFreeSlots.get(slotIndex);
+ newFreeSlots.set(slotIndex);
+ freeSlots = newFreeSlots;
+ freeSlotsCloned = true;
+ }
+ }
+ if (freeSlots != null && newProperty != null) {
+ final int slotIndex = logicalSlotIndex(newProperty);
+ if (slotIndex > -1 && freeSlots.get(slotIndex)) {
+ final BitSet newFreeSlots = freeSlotsCloned ? freeSlots : ((BitSet)freeSlots.clone());
+ newFreeSlots.clear(slotIndex);
+ freeSlots = newFreeSlots.isEmpty() ? null : newFreeSlots;
+ }
+ }
+ }
+
/**
* Add a property to the map without adding it to the history. This should be used for properties that
* can't be shared such as bound properties, or properties that are expected to be added only once.
@@ -363,15 +412,9 @@
}
final PropertyHashMap newProperties = properties.immutableAdd(property);
final PropertyMap newMap = new PropertyMap(this, newProperties);
+ newMap.updateFlagsAndBoundaries(property);
+ newMap.updateFreeSlots(null, property);
- if(!property.isSpill()) {
- newMap.fieldCount = Math.max(newMap.fieldCount, property.getSlot() + 1);
- }
- if (isValidArrayIndex(getArrayIndex(property.getKey()))) {
- newMap.setContainsArrayKeys();
- }
-
- newMap.spillLength += property.getSpillCount();
return newMap;
}
@@ -392,15 +435,8 @@
final PropertyHashMap newProperties = properties.immutableAdd(property);
newMap = new PropertyMap(this, newProperties);
addToHistory(property, newMap);
-
- if (!property.isSpill()) {
- newMap.fieldCount = Math.max(newMap.fieldCount, property.getSlot() + 1);
- }
- if (isValidArrayIndex(getArrayIndex(property.getKey()))) {
- newMap.setContainsArrayKeys();
- }
-
- newMap.spillLength += property.getSpillCount();
+ newMap.updateFlagsAndBoundaries(property);
+ newMap.updateFreeSlots(null, property);
}
return newMap;
@@ -422,7 +458,20 @@
if (newMap == null && properties.containsKey(key)) {
final PropertyHashMap newProperties = properties.immutableRemove(key);
- newMap = new PropertyMap(this, newProperties);
+ final boolean isSpill = property.isSpill();
+ final int slot = property.getSlot();
+ // If deleted property was last field or spill slot we can make it reusable by reducing field/slot count.
+ // Otherwise mark it as free in free slots bitset.
+ if (isSpill && slot >= 0 && slot == spillLength - 1) {
+ newMap = new PropertyMap(newProperties, className, fieldCount, fieldMaximum, spillLength - 1, containsArrayKeys());
+ newMap.freeSlots = freeSlots;
+ } else if (!isSpill && slot >= 0 && slot == fieldCount - 1) {
+ newMap = new PropertyMap(newProperties, className, fieldCount - 1, fieldMaximum, spillLength, containsArrayKeys());
+ newMap.freeSlots = freeSlots;
+ } else {
+ newMap = new PropertyMap(this, newProperties);
+ newMap.updateFreeSlots(property, null);
+ }
addToHistory(property, newMap);
}
@@ -471,7 +520,10 @@
* spillLength remains same in case (1) and (2) because of slot reuse. Only for case (3), we need
* to add spill count of the newly added UserAccessorProperty property.
*/
- newMap.spillLength = spillLength;
+ if (!sameType) {
+ newMap.spillLength = Math.max(spillLength, newProperty.getSlot() + 1);
+ newMap.updateFreeSlots(oldProperty, newProperty);
+ }
return newMap;
}
@@ -486,7 +538,7 @@
* @return the newly created UserAccessorProperty
*/
public UserAccessorProperty newUserAccessors(final String key, final int propertyFlags) {
- return new UserAccessorProperty(key, propertyFlags, spillLength);
+ return new UserAccessorProperty(key, propertyFlags, getFreeSpillSlot());
}
/**
@@ -514,10 +566,11 @@
final PropertyMap newMap = new PropertyMap(this, newProperties);
for (final Property property : otherProperties) {
+ // This method is only safe to use with non-slotted, native getter/setter properties
+ assert property.getSlot() == -1;
if (isValidArrayIndex(getArrayIndex(property.getKey()))) {
newMap.setContainsArrayKeys();
}
- newMap.spillLength += property.getSpillCount();
}
return newMap;
@@ -790,29 +843,37 @@
boolean isFrozen() {
return !isExtensible() && allFrozen();
}
+
/**
- * Get the number of fields allocated for this {@link PropertyMap}.
+ * Return a free field slot for this map, or {@code -1} if none is available.
*
- * @return Number of fields allocated.
+ * @return free field slot or -1
*/
- int getFieldCount() {
- return fieldCount;
- }
- /**
- * Get maximum number of fields available for this {@link PropertyMap}.
- *
- * @return Number of fields available.
- */
- int getFieldMaximum() {
- return fieldMaximum;
+ int getFreeFieldSlot() {
+ if (freeSlots != null) {
+ final int freeSlot = freeSlots.nextSetBit(0);
+ if (freeSlot > -1 && freeSlot < fieldMaximum) {
+ return freeSlot;
+ }
+ }
+ if (fieldCount < fieldMaximum) {
+ return fieldCount;
+ }
+ return -1;
}
/**
- * Get length of spill area associated with this {@link PropertyMap}.
+ * Get a free spill slot for this map.
*
- * @return Length of spill area.
+ * @return free spill slot
*/
- int getSpillLength() {
+ int getFreeSpillSlot() {
+ if (freeSlots != null) {
+ final int freeSlot = freeSlots.nextSetBit(fieldMaximum);
+ if (freeSlot > -1) {
+ return freeSlot - fieldMaximum;
+ }
+ }
return spillLength;
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/RecompilableScriptFunctionData.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/RecompilableScriptFunctionData.java Thu Aug 28 14:53:37 2014 -0700
@@ -32,13 +32,12 @@
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Collections;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
-
import jdk.internal.dynalink.support.NameCodec;
-import jdk.nashorn.internal.codegen.CompileUnit;
import jdk.nashorn.internal.codegen.Compiler;
import jdk.nashorn.internal.codegen.Compiler.CompilationPhases;
import jdk.nashorn.internal.codegen.CompilerConstants;
@@ -73,11 +72,6 @@
private final String functionName;
- // TODO: try to eliminate the need for this somehow, either by allowing Source to change its name, allowing a
- // function to internally replace its Source with one of a different name, or storing this additional field in the
- // Source object.
- private final String sourceURL;
-
/** The line number where this function begins. */
private final int lineNumber;
@@ -128,7 +122,6 @@
* @param allocatorClassName name of our allocator class, will be looked up dynamically if used as a constructor
* @param allocatorMap allocator map to seed instances with, when constructing
* @param nestedFunctions nested function map
- * @param sourceURL source URL
* @param externalScopeDepths external scope depths
* @param internalSymbols internal symbols to method, defined in its scope
*/
@@ -138,7 +131,6 @@
final String allocatorClassName,
final PropertyMap allocatorMap,
final Map<Integer, RecompilableScriptFunctionData> nestedFunctions,
- final String sourceURL,
final Map<String, Integer> externalScopeDepths,
final Set<String> internalSymbols) {
@@ -155,7 +147,6 @@
this.source = functionNode.getSource();
this.token = tokenFor(functionNode);
this.installer = installer;
- this.sourceURL = sourceURL;
this.allocatorClassName = allocatorClassName;
this.allocatorMap = allocatorMap;
this.nestedFunctions = nestedFunctions;
@@ -366,7 +357,7 @@
final FunctionNode program = parser.parse(CompilerConstants.PROGRAM.symbolName(), descPosition, Token.descLength(token), true);
// Parser generates a program AST even if we're recompiling a single function, so when we are only recompiling a
// single function, extract it from the program.
- return (isProgram ? program : extractFunctionFromScript(program)).setName(null, functionName).setSourceURL(null, sourceURL);
+ return (isProgram ? program : extractFunctionFromScript(program)).setName(null, functionName);
}
TypeMap typeMap(final MethodType fnCallSiteType) {
@@ -395,18 +386,18 @@
final ScriptObject runtimeScope, final Map<Integer, Type> invalidatedProgramPoints,
final int[] continuationEntryPoints) {
final TypeMap typeMap = typeMap(actualCallSiteType);
- final Object typeInformationFile = OptimisticTypesPersistence.getLocationDescriptor(source, functionNodeId, typeMap == null ? null : typeMap.getParameterTypes(functionNodeId));
+ final Type[] paramTypes = typeMap == null ? null : typeMap.getParameterTypes(functionNodeId);
+ final Object typeInformationFile = OptimisticTypesPersistence.getLocationDescriptor(source, functionNodeId, paramTypes);
final Context context = Context.getContextTrusted();
return new Compiler(
context,
context.getEnv(),
installer,
functionNode.getSource(), // source
- functionNode.getSourceURL(),
isStrict() | functionNode.isStrict(), // is strict
true, // is on demand
this, // compiledFunction, i.e. this RecompilableScriptFunctionData
- typeMap(actualCallSiteType), // type map
+ typeMap, // type map
getEffectiveInvalidatedProgramPoints(invalidatedProgramPoints, typeInformationFile), // invalidated program points
typeInformationFile,
continuationEntryPoints, // continuation entry points
@@ -431,7 +422,7 @@
return loadedProgramPoints != null ? loadedProgramPoints : new TreeMap<Integer, Type>();
}
- private TypeSpecializedFunction compileTypeSpecialization(final MethodType actualCallSiteType, final ScriptObject runtimeScope) {
+ private FunctionInitializer compileTypeSpecialization(final MethodType actualCallSiteType, final ScriptObject runtimeScope, final boolean persist) {
// We're creating an empty script object for holding local variables. AssignSymbols will populate it with
// explicit Undefined values for undefined local variables (see AssignSymbols#defineSymbol() and
// CompilationEnvironment#declareLocalSymbol()).
@@ -440,21 +431,79 @@
log.info("Type specialization of '", functionName, "' signature: ", actualCallSiteType);
}
+ final boolean persistentCache = usePersistentCodeCache() && persist;
+ String cacheKey = null;
+ if (persistentCache) {
+ final TypeMap typeMap = typeMap(actualCallSiteType);
+ final Type[] paramTypes = typeMap == null ? null : typeMap.getParameterTypes(functionNodeId);
+ cacheKey = CodeStore.getCacheKey(functionNodeId, paramTypes);
+ final StoredScript script = installer.loadScript(source, cacheKey);
+
+ if (script != null) {
+ Compiler.updateCompilationId(script.getCompilationId());
+ return install(script);
+ }
+ }
+
final FunctionNode fn = reparse();
final Compiler compiler = getCompiler(fn, actualCallSiteType, runtimeScope);
+ final FunctionNode compiledFn = compiler.compile(fn, CompilationPhases.COMPILE_ALL);
- final FunctionNode compiledFn = compiler.compile(fn, CompilationPhases.COMPILE_ALL);
- return new TypeSpecializedFunction(compiledFn, compiler.getInvalidatedProgramPoints());
+ if (persist && !compiledFn.getFlag(FunctionNode.HAS_APPLY_TO_CALL_SPECIALIZATION)) {
+ compiler.persistClassInfo(cacheKey, compiledFn);
+ }
+ return new FunctionInitializer(compiledFn, compiler.getInvalidatedProgramPoints());
}
- private static class TypeSpecializedFunction {
- private final FunctionNode fn;
- private final Map<Integer, Type> invalidatedProgramPoints;
+
+ /**
+ * Install this script using the given {@code installer}.
+ *
+ * @param script the compiled script
+ * @return the function initializer
+ */
+ private FunctionInitializer install(final StoredScript script) {
+
+ final Map<String, Class<?>> installedClasses = new HashMap<>();
+ final String mainClassName = script.getMainClassName();
+ final byte[] mainClassBytes = script.getClassBytes().get(mainClassName);
+
+ final Class<?> mainClass = installer.install(mainClassName, mainClassBytes);
+
+ installedClasses.put(mainClassName, mainClass);
+
+ for (final Map.Entry<String, byte[]> entry : script.getClassBytes().entrySet()) {
+ final String className = entry.getKey();
+ final byte[] code = entry.getValue();
+
+ if (className.equals(mainClassName)) {
+ continue;
+ }
- TypeSpecializedFunction(final FunctionNode fn, final Map<Integer, Type> invalidatedProgramPoints) {
- this.fn = fn;
- this.invalidatedProgramPoints = invalidatedProgramPoints;
+ installedClasses.put(className, installer.install(className, code));
}
+
+ final Map<Integer, FunctionInitializer> initializers = script.getInitializers();
+ assert initializers != null;
+ assert initializers.size() == 1;
+ final FunctionInitializer initializer = initializers.values().iterator().next();
+
+ final Object[] constants = script.getConstants();
+ for (int i = 0; i < constants.length; i++) {
+ if (constants[i] instanceof RecompilableScriptFunctionData) {
+ // replace deserialized function data with the ones we already have
+ constants[i] = getScriptFunctionData(((RecompilableScriptFunctionData) constants[i]).getFunctionNodeId());
+ }
+ }
+
+ installer.initialize(installedClasses.values(), source, constants);
+ initializer.setCode(installedClasses.get(initializer.getClassName()));
+ return initializer;
+ }
+
+ boolean usePersistentCodeCache() {
+ final ScriptEnvironment env = installer.getOwner();
+ return env._persistent_cache && env._optimistic_types;
}
private MethodType explicitParams(final MethodType callSiteType) {
@@ -502,61 +551,57 @@
return f;
}
- MethodHandle lookup(final FunctionNode fn) {
- final MethodType type = new FunctionSignature(fn).getMethodType();
- log.info("Looking up ", DebugLogger.quote(fn.getName()), " type=", type);
- return lookupWithExplicitType(fn, new FunctionSignature(fn).getMethodType());
+ MethodHandle lookup(final FunctionInitializer fnInit) {
+ final MethodType type = fnInit.getMethodType();
+ return lookupCodeMethod(fnInit.getCode(), type);
}
- MethodHandle lookupWithExplicitType(final FunctionNode fn, final MethodType targetType) {
- return lookupCodeMethod(fn.getCompileUnit(), targetType);
+ MethodHandle lookup(final FunctionNode fn) {
+ final MethodType type = new FunctionSignature(fn).getMethodType();
+ return lookupCodeMethod(fn.getCompileUnit().getCode(), type);
}
- private MethodHandle lookupCodeMethod(final CompileUnit compileUnit, final MethodType targetType) {
- return MH.findStatic(LOOKUP, compileUnit.getCode(), functionName, targetType);
+ MethodHandle lookupCodeMethod(final Class<?> code, final MethodType targetType) {
+ log.info("Looking up ", DebugLogger.quote(name), " type=", targetType);
+ return MH.findStatic(LOOKUP, code, functionName, targetType);
}
/**
* Initializes this function data with the eagerly generated version of the code. This method can only be invoked
* by the compiler internals in Nashorn and is public for implementation reasons only. Attempting to invoke it
* externally will result in an exception.
- * @param functionNode the functionNode belonging to this data
*/
- public void initializeCode(final FunctionNode functionNode) {
+ public void initializeCode(final FunctionInitializer initializer) {
// Since the method is public, we double-check that we aren't invoked with an inappropriate compile unit.
- if(!(code.isEmpty() && functionNode.getCompileUnit().isInitializing(this, functionNode))) {
- throw new IllegalStateException(functionNode.getName() + " id=" + functionNode.getId());
+ if(!code.isEmpty()) {
+ throw new IllegalStateException(name);
}
- addCode(functionNode);
+ addCode(lookup(initializer), null, null, initializer.getFlags());
}
- private CompiledFunction addCode(final MethodHandle target, final Map<Integer, Type> invalidatedProgramPoints, final int fnFlags) {
- final CompiledFunction cfn = new CompiledFunction(target, this, invalidatedProgramPoints, fnFlags);
+ private CompiledFunction addCode(final MethodHandle target, final Map<Integer, Type> invalidatedProgramPoints,
+ final MethodType callSiteType, final int fnFlags) {
+ final CompiledFunction cfn = new CompiledFunction(target, this, invalidatedProgramPoints, callSiteType, fnFlags);
code.add(cfn);
return cfn;
}
- private CompiledFunction addCode(final FunctionNode fn) {
- return addCode(lookup(fn), null, fn.getFlags());
- }
-
/**
* Add code with specific call site type. It will adapt the type of the looked up method handle to fit the call site
* type. This is necessary because even if we request a specialization that takes an "int" parameter, we might end
* up getting one that takes a "double" etc. because of internal function logic causes widening (e.g. assignment of
* a wider value to the parameter variable). However, we use the method handle type for matching subsequent lookups
* for the same specialization, so we must adapt the handle to the expected type.
- * @param tfn the function
+ * @param fnInit the function
* @param callSiteType the call site type
* @return the compiled function object, with its type matching that of the call site type.
*/
- private CompiledFunction addCode(final TypeSpecializedFunction tfn, final MethodType callSiteType) {
- final FunctionNode fn = tfn.fn;
- if (fn.isVarArg()) {
- return addCode(fn);
+ private CompiledFunction addCode(final FunctionInitializer fnInit, final MethodType callSiteType) {
+ if (isVariableArity()) {
+ return addCode(lookup(fnInit), fnInit.getInvalidatedProgramPoints(), callSiteType, fnInit.getFlags());
}
- final MethodHandle handle = lookup(fn);
+ final MethodHandle handle = lookup(fnInit);
final MethodType fromType = handle.type();
MethodType toType = needsCallee(fromType) ? callSiteType.changeParameterType(0, ScriptFunction.class) : callSiteType.dropParameterTypes(0, 1);
toType = toType.changeReturnType(fromType.returnType());
@@ -581,41 +626,39 @@
toType = toType.dropParameterTypes(fromCount, toCount);
}
- return addCode(lookup(fn).asType(toType), tfn.invalidatedProgramPoints, fn.getFlags());
+ return addCode(lookup(fnInit).asType(toType), fnInit.getInvalidatedProgramPoints(), callSiteType, fnInit.getFlags());
}
@Override
- CompiledFunction getBest(final MethodType callSiteType, final ScriptObject runtimeScope) {
- synchronized (code) {
- CompiledFunction existingBest = super.getBest(callSiteType, runtimeScope);
- if (existingBest == null) {
- existingBest = addCode(compileTypeSpecialization(callSiteType, runtimeScope), callSiteType);
- }
+ synchronized CompiledFunction getBest(final MethodType callSiteType, final ScriptObject runtimeScope) {
+ CompiledFunction existingBest = super.getBest(callSiteType, runtimeScope);
+ if (existingBest == null) {
+ existingBest = addCode(compileTypeSpecialization(callSiteType, runtimeScope, true), callSiteType);
+ }
- assert existingBest != null;
- //we are calling a vararg method with real args
- boolean applyToCall = existingBest.isVarArg() && !CompiledFunction.isVarArgsType(callSiteType);
+ assert existingBest != null;
+ //we are calling a vararg method with real args
+ boolean applyToCall = existingBest.isVarArg() && !CompiledFunction.isVarArgsType(callSiteType);
- //if the best one is an apply to call, it has to match the callsite exactly
- //or we need to regenerate
- if (existingBest.isApplyToCall()) {
- final CompiledFunction best = code.lookupExactApplyToCall(callSiteType);
- if (best != null) {
- return best;
- }
- applyToCall = true;
+ //if the best one is an apply to call, it has to match the callsite exactly
+ //or we need to regenerate
+ if (existingBest.isApplyToCall()) {
+ final CompiledFunction best = lookupExactApplyToCall(callSiteType);
+ if (best != null) {
+ return best;
}
+ applyToCall = true;
+ }
- if (applyToCall) {
- final TypeSpecializedFunction tfn = compileTypeSpecialization(callSiteType, runtimeScope);
- if (tfn.fn.hasOptimisticApplyToCall()) { //did the specialization work
- existingBest = addCode(tfn, callSiteType);
- }
+ if (applyToCall) {
+ final FunctionInitializer fnInit = compileTypeSpecialization(callSiteType, runtimeScope, false);
+ if ((fnInit.getFlags() & FunctionNode.HAS_APPLY_TO_CALL_SPECIALIZATION) != 0) { //did the specialization work
+ existingBest = addCode(fnInit, callSiteType);
}
+ }
- return existingBest;
- }
+ return existingBest;
}
@Override
@@ -638,6 +681,18 @@
}
/**
+ * Return the function node id.
+ * @return the function node id
+ */
+ public int getFunctionNodeId() {
+ return functionNodeId;
+ }
+
+ public Source getSource() {
+ return source;
+ }
+
+ /**
* Return a script function data based on a function id, either this function if
* the id matches or a nested function based on functionId. This goes down into
* nested functions until all leaves are exhausted.
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptFunction.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptFunction.java Thu Aug 28 14:53:37 2014 -0700
@@ -423,9 +423,9 @@
* @param constructor constructor
* @return prototype, or null if given constructor is not a ScriptFunction
*/
- public static ScriptObject getPrototype(final Object constructor) {
- if (constructor instanceof ScriptFunction) {
- final Object proto = ((ScriptFunction)constructor).getPrototype();
+ public static ScriptObject getPrototype(final ScriptFunction constructor) {
+ if (constructor != null) {
+ final Object proto = constructor.getPrototype();
if (proto instanceof ScriptObject) {
return (ScriptObject)proto;
}
@@ -465,7 +465,7 @@
final MethodType type = desc.getMethodType();
assert desc.getMethodType().returnType() == Object.class && !NashornCallSiteDescriptor.isOptimistic(desc);
final CompiledFunction cf = data.getBestConstructor(type, scope);
- final GuardedInvocation bestCtorInv = new GuardedInvocation(cf.getConstructor(), cf.getOptimisticAssumptionsSwitchPoint());
+ final GuardedInvocation bestCtorInv = cf.createConstructorInvocation();
//TODO - ClassCastException
return new GuardedInvocation(pairArguments(bestCtorInv.getInvocation(), type), getFunctionGuard(this, cf.getFlags()), bestCtorInv.getSwitchPoints(), null);
}
@@ -545,11 +545,7 @@
final int programPoint = NashornCallSiteDescriptor.isOptimistic(desc) ? NashornCallSiteDescriptor.getProgramPoint(desc) : INVALID_PROGRAM_POINT;
final CompiledFunction cf = data.getBestInvoker(type, scope);
- final GuardedInvocation bestInvoker =
- new GuardedInvocation(
- cf.createInvoker(type.returnType(), programPoint),
- cf.getOptimisticAssumptionsSwitchPoint());
-
+ final GuardedInvocation bestInvoker = cf.createFunctionInvocation(type.returnType(), programPoint);
final MethodHandle callHandle = bestInvoker.getInvocation();
if (data.needsCallee()) {
@@ -742,7 +738,7 @@
final Object[] varArgs = (Object[])args[paramCount - 1];
// -1 'cause we're not passing the vararg array itself
final int copiedArgCount = args.length - 1;
- int varArgCount = varArgs.length;
+ final int varArgCount = varArgs.length;
// Spread arguments for the delegate createApplyOrCallCall invocation.
final Object[] spreadArgs = new Object[copiedArgCount + varArgCount];
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptFunctionData.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptFunctionData.java Thu Aug 28 14:53:37 2014 -0700
@@ -35,6 +35,8 @@
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
+import java.util.LinkedList;
+import java.util.List;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
@@ -54,9 +56,10 @@
/** Name of the function or "" for anonymous functions */
protected final String name;
- /** All versions of this function that have been generated to code */
- // TODO: integrate it into ScriptFunctionData; there's not much reason for this to be in its own class.
- protected transient CompiledFunctions code;
+ /**
+ * A list of code versions of a function sorted in ascending order of generic descriptors.
+ */
+ protected transient LinkedList<CompiledFunction> code = new LinkedList<>();
/** Function flags */
protected int flags;
@@ -71,7 +74,7 @@
* multiple threads concurrently, but we still tolerate a race condition in it as all values stored into it are
* idempotent.
*/
- private volatile GenericInvokers genericInvokers;
+ private volatile transient GenericInvokers genericInvokers;
private static final MethodHandle BIND_VAR_ARGS = findOwnMH("bindVarArgs", Object[].class, Object[].class, Object[].class);
@@ -108,7 +111,6 @@
*/
ScriptFunctionData(final String name, final int arity, final int flags) {
this.name = name;
- this.code = new CompiledFunctions(name);
this.flags = flags;
setArity(arity);
}
@@ -222,8 +224,7 @@
* and not suddenly a "real" object
*
* @param callSiteType callsite type
- * @return guarded invocation with method handle to best invoker and potentially a switch point guarding optimistic
- * assumptions.
+ * @return compiled function object representing the best invoker.
*/
final CompiledFunction getBestInvoker(final MethodType callSiteType, final ScriptObject runtimeScope) {
final CompiledFunction cf = getBest(callSiteType, runtimeScope);
@@ -298,6 +299,50 @@
return lgenericInvokers;
}
+ private static MethodType widen(final MethodType cftype) {
+ final Class<?>[] paramTypes = new Class<?>[cftype.parameterCount()];
+ for (int i = 0; i < cftype.parameterCount(); i++) {
+ paramTypes[i] = cftype.parameterType(i).isPrimitive() ? cftype.parameterType(i) : Object.class;
+ }
+ return MH.type(cftype.returnType(), paramTypes);
+ }
+
+ /**
+ * Used to find an apply to call version that fits this callsite.
+ * We cannot just, as in the normal matcher case, return e.g. (Object, Object, int)
+ * for (Object, Object, int, int, int) or we will destroy the semantics and get
+ * a function that, when padded with undefineds, behaves differently
+ * @param type actual call site type
+ * @return apply to call that perfectly fits this callsite or null if none found
+ */
+ CompiledFunction lookupExactApplyToCall(final MethodType type) {
+ for (final CompiledFunction cf : code) {
+ if (!cf.isApplyToCall()) {
+ continue;
+ }
+
+ final MethodType cftype = cf.type();
+ if (cftype.parameterCount() != type.parameterCount()) {
+ continue;
+ }
+
+ if (widen(cftype).equals(widen(type))) {
+ return cf;
+ }
+ }
+
+ return null;
+ }
+
+ CompiledFunction pickFunction(final MethodType callSiteType, final boolean canPickVarArg) {
+ for (final CompiledFunction candidate : code) {
+ if (candidate.matchesCallSite(callSiteType, canPickVarArg)) {
+ return candidate;
+ }
+ }
+ return null;
+ }
+
/**
* Returns the best function for the specified call site type.
* @param callSiteType The call site type. Call site types are expected to have the form
@@ -308,16 +353,38 @@
* @return the best function for the specified call site type.
*/
CompiledFunction getBest(final MethodType callSiteType, final ScriptObject runtimeScope) {
- return code.best(callSiteType, isRecompilable());
+ assert callSiteType.parameterCount() >= 2 : callSiteType; // Must have at least (callee, this)
+ assert callSiteType.parameterType(0).isAssignableFrom(ScriptFunction.class) : callSiteType; // Callee must be assignable from script function
+
+ if (isRecompilable()) {
+ final CompiledFunction candidate = pickFunction(callSiteType, false);
+ if (candidate != null) {
+ return candidate;
+ }
+ return pickFunction(callSiteType, true); //try vararg last
+ }
+
+ CompiledFunction best = null;
+ for(final CompiledFunction candidate: code) {
+ if(candidate.betterThanFinal(best, callSiteType)) {
+ best = candidate;
+ }
+ }
+
+ return best;
}
+
abstract boolean isRecompilable();
CompiledFunction getGeneric(final ScriptObject runtimeScope) {
return getBest(getGenericType(), runtimeScope);
}
-
+ /**
+ * Get a method type for a generic invoker.
+ * @return the method type for the generic invoker
+ */
abstract MethodType getGenericType();
/**
@@ -353,7 +420,7 @@
// Clear the callee and this flags
final int boundFlags = flags & ~NEEDS_CALLEE & ~USES_THIS;
- final CompiledFunctions boundList = new CompiledFunctions(fn.getName());
+ final List<CompiledFunction> boundList = new LinkedList<>();
final ScriptObject runtimeScope = fn.getScope();
final CompiledFunction bindTarget = new CompiledFunction(getGenericInvoker(runtimeScope), getGenericConstructor(runtimeScope));
boundList.add(bind(bindTarget, fn, self, allArgs));
@@ -806,6 +873,6 @@
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
- code = new CompiledFunctions(name);
+ code = new LinkedList<>();
}
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptObject.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptObject.java Thu Aug 28 14:53:37 2014 -0700
@@ -1324,7 +1324,19 @@
* @param all True if to include non-enumerable keys.
* @return Array of keys.
*/
- public String[] getOwnKeys(final boolean all) {
+ public final String[] getOwnKeys(final boolean all) {
+ return getOwnKeys(all, null);
+ }
+
+ /**
+ * return an array of own property keys associated with the object.
+ *
+ * @param all True if to include non-enumerable keys.
+ * @param nonEnumerable set of non-enumerable properties seen already.Used
+ to filter out shadowed, but enumerable properties from proto children.
+ * @return Array of keys.
+ */
+ protected String[] getOwnKeys(final boolean all, final Set<String> nonEnumerable) {
final List<Object> keys = new ArrayList<>();
final PropertyMap selfMap = this.getMap();
@@ -1338,8 +1350,21 @@
}
for (final Property property : selfMap.getProperties()) {
- if (all || property.isEnumerable()) {
- keys.add(property.getKey());
+ final boolean enumerable = property.isEnumerable();
+ final String key = property.getKey();
+ if (all) {
+ keys.add(key);
+ } else if (enumerable) {
+ // either we don't have non-enumerable filter set or filter set
+ // does not contain the current property.
+ if (nonEnumerable == null || !nonEnumerable.contains(key)) {
+ keys.add(key);
+ }
+ } else {
+ // store this non-enumerable property for later proto walk
+ if (nonEnumerable != null) {
+ nonEnumerable.add(key);
+ }
}
}
@@ -2398,8 +2423,9 @@
@Override
protected void init() {
final Set<String> keys = new LinkedHashSet<>();
+ final Set<String> nonEnumerable = new HashSet<>();
for (ScriptObject self = object; self != null; self = self.getProto()) {
- keys.addAll(Arrays.asList(self.getOwnKeys(false)));
+ keys.addAll(Arrays.asList(self.getOwnKeys(false, nonEnumerable)));
}
this.values = keys.toArray(new String[keys.size()]);
}
@@ -2413,8 +2439,9 @@
@Override
protected void init() {
final ArrayList<Object> valueList = new ArrayList<>();
+ final Set<String> nonEnumerable = new HashSet<>();
for (ScriptObject self = object; self != null; self = self.getProto()) {
- for (final String key : self.getOwnKeys(false)) {
+ for (final String key : self.getOwnKeys(false, nonEnumerable)) {
valueList.add(self.get(key));
}
}
@@ -2430,20 +2457,19 @@
*/
private Property addSpillProperty(final String key, final int propertyFlags, final Object value, final boolean hasInitialValue) {
final PropertyMap propertyMap = getMap();
- final int fieldCount = propertyMap.getFieldCount();
- final int fieldMax = propertyMap.getFieldMaximum();
+ final int fieldSlot = propertyMap.getFreeFieldSlot();
Property property;
- if (fieldCount < fieldMax) {
+ if (fieldSlot > -1) {
property = hasInitialValue ?
- new AccessorProperty(key, propertyFlags, fieldCount, this, value) :
- new AccessorProperty(key, propertyFlags, getClass(), fieldCount);
+ new AccessorProperty(key, propertyFlags, fieldSlot, this, value) :
+ new AccessorProperty(key, propertyFlags, getClass(), fieldSlot);
property = addOwnProperty(property);
} else {
- final int spillCount = propertyMap.getSpillLength();
+ final int spillSlot = propertyMap.getFreeSpillSlot();
property = hasInitialValue ?
- new SpillProperty(key, propertyFlags, spillCount, this, value) :
- new SpillProperty(key, propertyFlags, spillCount);
+ new SpillProperty(key, propertyFlags, spillSlot, this, value) :
+ new SpillProperty(key, propertyFlags, spillSlot);
property = addOwnProperty(property);
ensureSpillSize(property.getSlot());
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptRuntime.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptRuntime.java Thu Aug 28 14:53:37 2014 -0700
@@ -702,6 +702,9 @@
if (x instanceof ScriptObject && y instanceof ScriptObject) {
return x == y;
}
+ if (x instanceof ScriptObjectMirror || y instanceof ScriptObjectMirror) {
+ return ScriptObjectMirror.identical(x, y);
+ }
return equalValues(x, y);
}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/SetMethodCreator.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/SetMethodCreator.java Thu Aug 28 14:53:37 2014 -0700
@@ -160,7 +160,7 @@
}
private SetMethod createNewPropertySetter() {
- final SetMethod sm = map.getFieldCount() < map.getFieldMaximum() ? createNewFieldSetter() : createNewSpillPropertySetter();
+ final SetMethod sm = map.getFreeFieldSlot() > -1 ? createNewFieldSetter() : createNewSpillPropertySetter();
final PropertyListeners listeners = map.getListeners();
if (listeners != null) {
listeners.propertyAdded(sm.property);
@@ -205,11 +205,11 @@
}
private SetMethod createNewFieldSetter() {
- return createNewSetter(new AccessorProperty(getName(), 0, sobj.getClass(), getMap().getFieldCount(), type));
+ return createNewSetter(new AccessorProperty(getName(), 0, sobj.getClass(), getMap().getFreeFieldSlot(), type));
}
private SetMethod createNewSpillPropertySetter() {
- return createNewSetter(new SpillProperty(getName(), 0, getMap().getSpillLength(), type));
+ return createNewSetter(new SpillProperty(getName(), 0, getMap().getFreeSpillSlot(), type));
}
private PropertyMap getNewMap(final Property property) {
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java Thu Aug 28 14:53:37 2014 -0700
@@ -87,6 +87,9 @@
/** Base64-encoded SHA1 digest of this source object */
private volatile byte[] digest;
+ /** source URL set via //@ sourceURL or //# sourceURL directive */
+ private String explicitURL;
+
// Do *not* make this public, ever! Trusts the URL and content.
private Source(final String name, final String base, final Data data) {
this.name = name;
@@ -597,6 +600,22 @@
}
/**
+ * Get explicit source URL.
+ * @return URL set vial sourceURL directive
+ */
+ public String getExplicitURL() {
+ return explicitURL;
+ }
+
+ /**
+ * Set explicit source URL.
+ * @param explicitURL URL set via sourceURL directive
+ */
+ public void setExplicitURL(final String explicitURL) {
+ this.explicitURL = explicitURL;
+ }
+
+ /**
* Returns whether this source was submitted via 'eval' call or not.
*
* @return true if this source represents code submitted via 'eval'
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/SpillProperty.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/SpillProperty.java Thu Aug 28 14:53:37 2014 -0700
@@ -207,8 +207,11 @@
}
@Override
- public int getSpillCount() {
- return 1;
+ void initMethodHandles(final Class<?> structure) {
+ final int slot = getSlot();
+ primitiveGetter = primitiveGetter(slot);
+ primitiveSetter = primitiveSetter(slot);
+ objectGetter = objectGetter(slot);
+ objectSetter = objectSetter(slot);
}
-
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/StoredScript.java Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.nashorn.internal.runtime;
+
+import java.io.Serializable;
+import java.util.Arrays;
+import java.util.Map;
+
+/**
+ * Class representing a persistent compiled script.
+ */
+public final class StoredScript implements Serializable {
+
+ /** Compilation id */
+ private final int compilationId;
+
+ /** Main class name. */
+ private final String mainClassName;
+
+ /** Map of class names to class bytes. */
+ private final Map<String, byte[]> classBytes;
+
+ /** Constants array. */
+ private final Object[] constants;
+
+ /** Function initializers */
+ private final Map<Integer, FunctionInitializer> initializers;
+
+ private static final long serialVersionUID = 2958227232195298340L;
+
+ /**
+ * Constructor.
+ *
+ * @param mainClassName main class name
+ * @param classBytes map of class names to class bytes
+ * @param constants constants array
+ */
+ public StoredScript(final int compilationId, final String mainClassName, final Map<String, byte[]> classBytes, final Map<Integer, FunctionInitializer> initializers, final Object[] constants) {
+ this.compilationId = compilationId;
+ this.mainClassName = mainClassName;
+ this.classBytes = classBytes;
+ this.constants = constants;
+ this.initializers = initializers;
+ }
+
+ public int getCompilationId() {
+ return compilationId;
+ }
+
+ /**
+ * Returns the main class name.
+ * @return the main class name
+ */
+ public String getMainClassName() {
+ return mainClassName;
+ }
+
+ /**
+ * Returns a map of class names to class bytes.
+ * @return map of class bytes
+ */
+ public Map<String, byte[]> getClassBytes() {
+ return classBytes;
+ }
+
+ /**
+ * Returns the constants array.
+ * @return constants array
+ */
+ public Object[] getConstants() {
+ return constants;
+ }
+
+ Map<Integer, FunctionInitializer> getInitializers() {
+ return initializers;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = mainClassName.hashCode();
+ hash = 31 * hash + classBytes.hashCode();
+ hash = 31 * hash + Arrays.hashCode(constants);
+ return hash;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof StoredScript)) {
+ return false;
+ }
+
+ final StoredScript cs = (StoredScript) obj;
+ return mainClassName.equals(cs.mainClassName)
+ && classBytes.equals(cs.classBytes)
+ && Arrays.equals(constants, cs.constants);
+ }
+}
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/UserAccessorProperty.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/UserAccessorProperty.java Thu Aug 28 14:53:37 2014 -0700
@@ -43,16 +43,6 @@
* Property with user defined getters/setters. Actual getter and setter
* functions are stored in underlying ScriptObject. Only the 'slot' info is
* stored in the property.
- *
- * The slots here denote either ScriptObject embed field number or spill
- * array index. For spill array index, we use slot value of
- * (index + ScriptObject.embedSize). See also ScriptObject.getEmbedOrSpill
- * method. Negative slot value means that the corresponding getter or setter
- * is null. Note that always two slots are allocated in ScriptObject - but
- * negative (less by 1) slot number is stored for null getter or setter.
- * This is done so that when the property is redefined with a different
- * getter and setter (say, both non-null), we'll have spill slots to store
- * those. When a slot is negative, (-slot - 1) is the embed/spill index.
*/
public final class UserAccessorProperty extends SpillProperty {
@@ -117,10 +107,9 @@
/**
* Constructor
*
- * @param key property key
- * @param flags property flags
- * @param getterSlot getter slot, starting at first embed
- * @param setterSlot setter slot, starting at first embed
+ * @param key property key
+ * @param flags property flags
+ * @param slot spill slot
*/
UserAccessorProperty(final String key, final int flags, final int slot) {
super(key, flags, slot);
@@ -206,17 +195,17 @@
@Override
public void setValue(final ScriptObject self, final ScriptObject owner, final int value, final boolean strict) {
- setValue(self, owner, value, strict);
+ setValue(self, owner, (Object) value, strict);
}
@Override
public void setValue(final ScriptObject self, final ScriptObject owner, final long value, final boolean strict) {
- setValue(self, owner, value, strict);
+ setValue(self, owner, (Object) value, strict);
}
@Override
public void setValue(final ScriptObject self, final ScriptObject owner, final double value, final boolean strict) {
- setValue(self, owner, value, strict);
+ setValue(self, owner, (Object) value, strict);
}
@Override
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/WithObject.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/WithObject.java Thu Aug 28 14:53:37 2014 -0700
@@ -31,7 +31,6 @@
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.SwitchPoint;
-
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterBytecodeGenerator.java Thu Aug 28 14:53:37 2014 -0700
@@ -66,6 +66,7 @@
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.Type;
import jdk.internal.org.objectweb.asm.commons.InstructionAdapter;
+import jdk.nashorn.api.scripting.ScriptUtils;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ScriptFunction;
@@ -134,10 +135,12 @@
* implemented securely.
*/
final class JavaAdapterBytecodeGenerator {
+ private static final Type SCRIPTUTILS_TYPE = Type.getType(ScriptUtils.class);
private static final Type OBJECT_TYPE = Type.getType(Object.class);
private static final Type CLASS_TYPE = Type.getType(Class.class);
static final String OBJECT_TYPE_NAME = OBJECT_TYPE.getInternalName();
+ static final String SCRIPTUTILS_TYPE_NAME = SCRIPTUTILS_TYPE.getInternalName();
static final String INIT = "<init>";
@@ -172,6 +175,7 @@
private static final String GET_GLOBAL_METHOD_DESCRIPTOR = Type.getMethodDescriptor(OBJECT_TYPE);
private static final String GET_CLASS_METHOD_DESCRIPTOR = Type.getMethodDescriptor(CLASS_TYPE);
private static final String EXPORT_RETURN_VALUE_METHOD_DESCRIPTOR = Type.getMethodDescriptor(OBJECT_TYPE, OBJECT_TYPE);
+ private static final String UNWRAP_METHOD_DESCRIPTOR = Type.getMethodDescriptor(OBJECT_TYPE, OBJECT_TYPE);
private static final String GET_CONVERTER_METHOD_DESCRIPTOR = Type.getMethodDescriptor(METHOD_HANDLE_TYPE, CLASS_TYPE);
private static final String TO_CHAR_PRIMITIVE_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.CHAR_TYPE, OBJECT_TYPE);
private static final String TO_STRING_METHOD_DESCRIPTOR = Type.getMethodDescriptor(STRING_TYPE, OBJECT_TYPE);
@@ -927,10 +931,14 @@
invokeValueOf(mv, "Double", 'D');
break;
case Type.ARRAY:
- case Type.OBJECT:
case Type.METHOD:
// Already boxed
break;
+ case Type.OBJECT:
+ if(t.equals(OBJECT_TYPE)) {
+ mv.invokestatic(SCRIPTUTILS_TYPE_NAME, "unwrap", UNWRAP_METHOD_DESCRIPTOR, false);
+ }
+ break;
default:
// Not expecting anything else (e.g. VOID)
assert false;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaAdapterServices.java Thu Aug 28 14:53:37 2014 -0700
@@ -47,6 +47,7 @@
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.Type;
import jdk.internal.org.objectweb.asm.commons.InstructionAdapter;
+import jdk.nashorn.api.scripting.ScriptUtils;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
@@ -214,12 +215,12 @@
/**
* Invoked when returning Object from an adapted method to filter out internal Nashorn objects that must not be seen
- * by the callers. Currently only transforms {@code ConsString} into {@code String}.
+ * by the callers. Currently only transforms {@code ConsString} into {@code String} and transforms {@code ScriptObject} into {@code ScriptObjectMirror}.
* @param obj the return value
* @return the filtered return value.
*/
public static Object exportReturnValue(final Object obj) {
- return NashornBeansLinker.exportArgument(obj);
+ return ScriptUtils.wrap(NashornBeansLinker.exportArgument(obj));
}
/**
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/ReflectionCheckLinker.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/ReflectionCheckLinker.java Thu Aug 28 14:53:37 2014 -0700
@@ -25,6 +25,8 @@
package jdk.nashorn.internal.runtime.linker;
+import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
+
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import jdk.internal.dynalink.CallSiteDescriptor;
@@ -33,7 +35,9 @@
import jdk.internal.dynalink.linker.LinkerServices;
import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
+import jdk.nashorn.api.scripting.ClassFilter;
import jdk.nashorn.internal.runtime.Context;
+import jdk.nashorn.internal.objects.Global;
/**
* Check java reflection permission for java reflective and java.lang.invoke access from scripts
@@ -100,6 +104,12 @@
}
static void checkReflectionAccess(final Class<?> clazz, final boolean isStatic) {
+ final Global global = Context.getGlobal();
+ final ClassFilter cf = global.getClassFilter();
+ if (cf != null && isReflectiveCheckNeeded(clazz, isStatic)) {
+ throw typeError("no.reflection.with.classfilter");
+ }
+
final SecurityManager sm = System.getSecurityManager();
if (sm != null && isReflectiveCheckNeeded(clazz, isStatic)) {
checkReflectionPermission(sm);
@@ -107,6 +117,12 @@
}
private static void checkLinkRequest(final LinkRequest origRequest) {
+ final Global global = Context.getGlobal();
+ final ClassFilter cf = global.getClassFilter();
+ if (cf != null) {
+ throw typeError("no.reflection.with.classfilter");
+ }
+
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
final LinkRequest requestWithoutContext = origRequest.withoutRuntimeContext(); // Nashorn has no runtime context
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties Thu Aug 28 14:53:37 2014 -0700
@@ -81,6 +81,7 @@
type.error.not.a.numeric.array={0} is not a numeric array
type.error.not.a.bytebuffer={0} is not a java.nio.ByteBuffer
type.error.not.an.arraybuffer.in.dataview=First arg to DataView constructor must be an ArrayBuffer
+type.error.no.reflection.with.classfilter=Java reflection not supported when class filter is present
# operations not permitted on undefined
type.error.cant.call.undefined=Cannot call undefined
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/Shell.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/Shell.java Thu Aug 28 14:53:37 2014 -0700
@@ -266,7 +266,6 @@
env,
null,
functionNode.getSource(),
- functionNode.getSourceURL(),
env._strict | functionNode.isStrict()).
compile(functionNode, CompilationPhases.COMPILE_ALL_NO_INSTALL);
}
@@ -443,19 +442,16 @@
continue;
}
- Object res;
try {
- res = context.eval(global, source, global, "<shell>", env._strict);
+ final Object res = context.eval(global, source, global, "<shell>", env._strict);
+ if (res != ScriptRuntime.UNDEFINED) {
+ err.println(JSType.toString(res));
+ }
} catch (final Exception e) {
err.println(e);
if (env._dump_on_error) {
e.printStackTrace(err);
}
- continue;
- }
-
- if (res != ScriptRuntime.UNDEFINED) {
- err.println(JSType.toString(res));
}
}
} finally {
--- a/nashorn/test/script/basic/JDK-8015969.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8015969.js Thu Aug 28 14:53:37 2014 -0700
@@ -37,6 +37,24 @@
'use strict';
try {
+ context = 444;
+ print("FAILED!! context write should have thrown error");
+} catch (e) {
+ if (! (e instanceof TypeError)) {
+ print("TypeError expected but got " + e);
+ }
+}
+
+try {
+ engine = "hello";
+ print("FAILED!! engine write should have thrown error");
+} catch (e) {
+ if (! (e instanceof TypeError)) {
+ print("TypeError expected but got " + e);
+ }
+}
+
+try {
delete context;
print("FAILED!! context delete should have thrown error");
} catch (e) {
--- a/nashorn/test/script/basic/JDK-8038413.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8038413.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
@@ -31,7 +31,7 @@
// When adapting a method returning Integer to an optimistic call site
// expecting int, can't forego filters because of null. That is, the
// Integer->int conversion can't be left to the automatisms present in
-// java.lang.invoke.MethodHandle.asType() because of potential null
+// java.lang.invoke.MethodHandle.asType() because of potential null
// values.
var IntegerArray = Java.type("java.lang.Integer[]");
var arr = new IntegerArray(1);
--- a/nashorn/test/script/basic/JDK-8043232.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8043232.js Thu Aug 28 14:53:37 2014 -0700
@@ -58,8 +58,8 @@
}
// constructor of a non-existent class
-checkIt(function() new (java.lang["NonExistent(String)"])());
-
+checkIt(function() new (java.lang["NonExistent(String)"])());
+
// non-existent constructor of an existing class
checkIt(function() new (java.lang["Object(String)"])());
--- a/nashorn/test/script/basic/JDK-8044695.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8044695.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- a/nashorn/test/script/basic/JDK-8044750.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8044750.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8046026.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8046026: CompiledFunction.relinkComposableInvoker assert is being hit
+ * JDK-8044770: crash with jdk9-dev/nashorn during global object initialization from MT test
+ * JDK-8047770: NPE in deoptimizing recompilation in multithreaded
+ *
+ * @test
+ * @run
+ */
+
+(function() {
+var n = 1 << 25;
+var ThreadLocalRandom = java.util.concurrent.ThreadLocalRandom;
+var m = java.util.stream.IntStream.range(0, n)
+ .parallel() // this is the essence of this test. We must trigger parallel execution
+ .filter(function() {
+ var tlr = ThreadLocalRandom.current();
+
+ var x = tlr.nextDouble(-1.0, 1.0);
+ var y = tlr.nextDouble(-1.0, 1.0);
+
+ return x * x + y * y <= 1.0;
+ })
+ .count();
+var pi = (4.0 * m) / n;
+print(pi.toFixed(2));
+})()
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8046026.js.EXPECTED Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,1 @@
+3.14
--- a/nashorn/test/script/basic/JDK-8046905.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8046905.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
@@ -36,7 +36,7 @@
// Running three times so that we test an already linked call site too:
// i==0: linking initially with assumed optimistic returned type int.
// i==1: linking after deoptimization with returned type Object.
-// i==2: re-running code linked in previous iteration. This will
+// i==2: re-running code linked in previous iteration. This will
// properly exercise the guards too.
print("1 level of apply")
for(i = 0; i < 3; ++i) {
@@ -69,7 +69,7 @@
print(apply.apply(apply,[apply,invocation]))
// First change after i==1, so it relinks an otherwise stable linkage
if(i == 1) {
- invocation = [sort,[[8,7,6,5]]];
+ invocation = [sort,[[8,7,6,5]]];
} else if(i == 2) {
invocation = [join,[[8,7,6,5],["-"]]];
}
--- a/nashorn/test/script/basic/JDK-8047067.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8047067.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
@@ -33,4 +33,4 @@
// program points that'd cause incorrect continuation program point in
// the rest-of, and therefore a bad stack, and therefore an AIOOBE in
// the continuation setup code.
-eval("23", ({})[/x/])
+eval("23", ({})[/x/])
--- a/nashorn/test/script/basic/JDK-8047166.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8047166.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- a/nashorn/test/script/basic/JDK-8047357.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8047357.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- a/nashorn/test/script/basic/JDK-8047369.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8047369.js Thu Aug 28 14:53:37 2014 -0700
@@ -23,7 +23,7 @@
/**
* JDK-8047369: Add regression tests for passing test cases of JDK-8024971
- *
+ *
* @test
* @run
* @option -scripting
@@ -76,14 +76,14 @@
evalExpectValue(<<CODE
var s = "(function() { return y })()";
- (function() {
+ (function() {
with({ y:1 })
eval(s)
})();
- (function() {
- with({
+ (function() {
+ with({
get y() { return "get"; }
- })
+ })
return eval(s)
})();
CODE, "get");
@@ -93,19 +93,19 @@
evalExpectValue(<<CODE
function f(o) {
- var eval=0;
+ var eval=0;
with({
get eval() { return o.eval }
- })
+ })
return eval("1+2");
- }
+ }
f(this);
CODE, 3)
evalExpectValue(<<CODE
function f() {
var a=1,e=2;
- try {
+ try {
throw 3
} catch(e) {
return + function g(){return eval('a+e')}()
@@ -125,9 +125,9 @@
// makeFuncAndCall("L1:try { return } finally { break L1 }");
evalExpectValue(<<CODE
- function f() {
+ function f() {
function g() { return 0 }
- function g() { return 1 }
+ function g() { return 1 }
function g$1() { return 2 }
return g$1()
}
@@ -139,7 +139,7 @@
function f() {
function g() {return 0 }
var h = function g() { return 1 };
- function g$1() { return 2 };
+ function g$1() { return 2 };
return h()
}
@@ -171,7 +171,7 @@
// evalExpectValue("(1000000000000000128).toFixed().toString()", "1000000000000000128");
try {
- Function("-", {
+ Function("-", {
toString: function() {
throw "err"
}
--- a/nashorn/test/script/basic/JDK-8047371.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8047371.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- a/nashorn/test/script/basic/JDK-8047728.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8047728.js Thu Aug 28 14:53:37 2014 -0700
@@ -29,7 +29,7 @@
*/
function func(x) {
- var o = {x:0};
+ var o = {x:0};
with(o){
delete x;
}
@@ -42,7 +42,7 @@
function func2() {
var x;
- var o = {x:0};
+ var o = {x:0};
with(o){
delete x;
}
--- a/nashorn/test/script/basic/JDK-8047959.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8047959.js Thu Aug 28 14:53:37 2014 -0700
@@ -49,11 +49,11 @@
print("typeof foo? " + typeof foo);
print("foo = " + foo);
-var x = "global";
+var x = "global";
(function(){
eval("var x='local'");
print("x in function = "+ x);
print("delete x? = " + delete x);
print("x after delete = " + x);
})();
-print("x = " + x);
+print("x = " + x);
--- a/nashorn/test/script/basic/JDK-8048079_1.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8048079_1.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- a/nashorn/test/script/basic/JDK-8048079_2.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8048079_2.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- a/nashorn/test/script/basic/JDK-8048586.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8048586.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- a/nashorn/test/script/basic/JDK-8049086.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8049086.js Thu Aug 28 14:53:37 2014 -0700
@@ -59,7 +59,7 @@
// (c) FunctionalInterface objects (d) JSObjects that are 'functions'
print("java.awt.Color is java function? " + Java.isJavaFunction(java.awt.Color));
-print("java.lang.Runnable instance is java function? "
+print("java.lang.Runnable instance is java function? "
+ Java.isJavaFunction(new java.lang.Runnable(function() {})));
print("eval is java function? " + Java.isJavaFunction(eval));
print("println is java function? " + Java.isJavaFunction(println));
--- a/nashorn/test/script/basic/JDK-8051439.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/JDK-8051439.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
@@ -29,24 +29,24 @@
*/
// Test + operator
-function f1() {
- var x;
- for (var i = 0;i < 3; i++) {
- x = x + i;
+function f1() {
+ var x;
+ for (var i = 0;i < 3; i++) {
+ x = x + i;
}
- x = x + "test";
- return x;
-}
+ x = x + "test";
+ return x;
+}
// Test += operator
-function f2() {
- var x;
- for (var i = 0;i < 3; i++) {
- x += i;
+function f2() {
+ var x;
+ for (var i = 0;i < 3; i++) {
+ x += i;
}
- x += "test";
- return x;
-}
+ x += "test";
+ return x;
+}
print(f1());
print(f2());
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/basic/JDK-8054503.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * 8054503: test/script/external/test262/test/suite/ch12/12.6/12.6.4/12.6.4-2.js fails with tip
+ *
+ * @test
+ * @run
+ */
+
+function MyFunc() {}
+
+MyFunc.prototype.foo = 42;
+var obj = new MyFunc();
+Object.defineProperty(obj, "foo", {
+ value: "hello",
+ enumerable: false
+});
+
+for (var p in obj) {
+ if (p == "foo") {
+ fail("'foo' is not expected here!");
+ }
+}
+
+for each (var p in obj) {
+ if (p == "hello" || p == 42) {
+ fail("'foo' value is not expected here");
+ }
+}
--- a/nashorn/test/script/basic/compile-octane-normal.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/compile-octane-normal.js Thu Aug 28 14:53:37 2014 -0700
@@ -29,6 +29,7 @@
* forever, so make this test future safe, we specify them explicitly
*
* @test
+ * @fork
* @runif external.octane
* @option -scripting
* @option -Dnashorn.typeInfo.disabled=true
@@ -37,5 +38,5 @@
*/
var fn = __DIR__ + 'compile-octane.js';
-var url = "file://" + fn;
+var url = "file://" + fn;
loadWithNewGlobal(new java.net.URL(url));
--- a/nashorn/test/script/basic/compile-octane-splitter.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/compile-octane-splitter.js Thu Aug 28 14:53:37 2014 -0700
@@ -29,6 +29,7 @@
* forever, so make this test future safe, we specify them explicitly
*
* @test
+ * @fork
* @option -Dnashorn.compiler.splitter.threshold=1000
* @fork
* @runif external.octane
@@ -39,5 +40,5 @@
*/
var fn = __DIR__ + 'compile-octane.js';
-var url = "file://" + fn;
+var url = "file://" + fn;
loadWithNewGlobal(new java.net.URL(url));
--- a/nashorn/test/script/basic/compile-octane.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/basic/compile-octane.js Thu Aug 28 14:53:37 2014 -0700
@@ -31,7 +31,7 @@
* This means that if you use this subtest as a compilation test
* harness, pass the arguments:
*
- * -scripting -Dnashorn.typeInfo.disabled=true --class-cache-size=0
+ * -scripting -Dnashorn.typeInfo.disabled=true --class-cache-size=0
* --persistent-code-cache=false
*
* @subtest
@@ -40,7 +40,7 @@
load(__DIR__ + 'octane-payload.js');
var DEFAULT_ITERS = 1; //default is one iteration through each benchmark
-var iters = DEFAULT_ITERS;
+var iters = DEFAULT_ITERS;
var args = [];
if (typeof $ARGS !== 'undefined') {
@@ -55,11 +55,11 @@
for (var i = 0; i < args.length; ) {
var arg = args[i];
if (arg === '--iterations') {
- iters = +args[++i];
+ iters = +args[++i];
} else if (arg === '--verbose') {
- verbose = true;
+ verbose = true;
} else {
- onlyTheseTests.push(arg);
+ onlyTheseTests.push(arg);
}
i++;
}
@@ -74,7 +74,7 @@
function print_if_verbose(x) {
if (verbose) {
- print(x);
+ print(x);
}
}
@@ -94,46 +94,46 @@
var files = tests[j].files;
if (onlyTheseTests.length > 0 && !contains(onlyTheseTests, test_name)) {
- print_if_verbose("Skipping " + test_name);
- continue;
+ print_if_verbose("Skipping " + test_name);
+ continue;
}
if (!contains(testsCompiled, test_name)) {
- testsCompiled.push(test_name);
+ testsCompiled.push(test_name);
}
var str = "Compiling '" + test_name + "'...";
if (files.length > 1) {
- str += " (" + files.length + " files)";
+ str += " (" + files.length + " files)";
}
if (iters != 1) {
- str += " (" + iters + " times)";
+ str += " (" + iters + " times)";
}
str + "...";
print(str);
for (var iteration = 0; iteration < iters; iteration++) {
- //get a new global to avoid symbol pollution and reloads of base
- //in the same namespace
- var newGlobal = loadWithNewGlobal({script:'this', name:'test'});
+ //get a new global to avoid symbol pollution and reloads of base
+ //in the same namespace
+ var newGlobal = loadWithNewGlobal({script:'this', name:'test'});
- //load base into the new global so we get BenchmarkSuite etc
- newGlobal.load(base);
+ //load base into the new global so we get BenchmarkSuite etc
+ newGlobal.load(base);
- //load all files in the single benchmark
- for (var k in files) {
- var file = files[k];
- if (iteration >= 0) { //only display message on first iteration
- var str2 = "\t";
- if (iters > 1) {
- str2 += " [iteration " + (iteration + 1) + "]";
- }
- str2 += " processing file: " + file + "...";
- print_if_verbose(str2);
- }
- newGlobal.load("file://" + path + file);
- }
+ //load all files in the single benchmark
+ for (var k in files) {
+ var file = files[k];
+ if (iteration >= 0) { //only display message on first iteration
+ var str2 = "\t";
+ if (iters > 1) {
+ str2 += " [iteration " + (iteration + 1) + "]";
+ }
+ str2 += " processing file: " + file + "...";
+ print_if_verbose(str2);
+ }
+ newGlobal.load("file://" + path + file);
+ }
}
print("Done.");
}
--- a/nashorn/test/script/nosecurity/JDK-8044798.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/nosecurity/JDK-8044798.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
@@ -91,7 +91,7 @@
for each (var info in infos) {
for each (var f in valueDescFields) {
print(f.name, "=", f.get(info));
- }
+ }
}
// valueInfos - user defined object
@@ -99,7 +99,7 @@
for each (var info in infos) {
for each (var f in valueDescFields) {
print(f.name, "=", f.get(info));
- }
+ }
}
// valueAsString
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/nosecurity/JDK-8044851.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8044851: nashorn properties leak memory
+ *
+ * @test
+ * @run
+ * @option -Dnashorn.debug=true
+ * @fork
+ */
+
+function printProperty(value, property) {
+ print(value, property.getKey(), property.isSpill() ? "spill" : "field", property.getSlot());
+}
+
+var obj = {}, i, name;
+
+for (i = 0; i < 8; ++i) {
+ name = 'property' + i;
+ obj[name] = 'a' + i;
+ printProperty(obj[name], Debug.map(obj).findProperty(name));
+}
+print();
+
+for (i = 0; i < 8; ++i) {
+ name = 'property' + i;
+ delete obj[name];
+}
+
+for (i = 0; i < 8; ++i) {
+ name = 'property' + i;
+ obj[name] = 'b' + i;
+ printProperty(obj[name], Debug.map(obj).findProperty(name));
+}
+print();
+
+for (i = 0; i < 8; ++i) {
+ name = 'property' + i;
+ Object.defineProperty(obj, name, {get: function() {return i;}, set: function(v) {}, configurable: true});
+ printProperty(obj[name], Debug.map(obj).findProperty(name));
+}
+print();
+
+for (i = 0; i < 8; ++i) {
+ name = 'property' + i;
+ delete obj[name];
+}
+
+for (i = 0; i < 8; ++i) {
+ name = 'property' + i;
+ obj[name] = 'c' + i;
+ printProperty(obj[name], Debug.map(obj).findProperty(name));
+}
+print();
+
+for (i = 7; i > -1; --i) {
+ name = 'property' + i;
+ delete obj[name];
+}
+
+for (i = 0; i < 8; ++i) {
+ name = 'property' + i;
+ obj[name] = 'd' + i;
+ printProperty(obj[name], Debug.map(obj).findProperty(name));
+}
+print();
+
+for (i = 0; i < 8; ++i) {
+ name = 'property' + i;
+ Object.defineProperty(obj, name, {get: function() {return i;}, set: function(v) {}});
+ printProperty(obj[name], Debug.map(obj).findProperty(name));
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/nosecurity/JDK-8044851.js.EXPECTED Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,53 @@
+a0 property0 field 0
+a1 property1 field 1
+a2 property2 field 2
+a3 property3 field 3
+a4 property4 spill 0
+a5 property5 spill 1
+a6 property6 spill 2
+a7 property7 spill 3
+
+b0 property0 field 0
+b1 property1 field 1
+b2 property2 field 2
+b3 property3 field 3
+b4 property4 spill 0
+b5 property5 spill 1
+b6 property6 spill 2
+b7 property7 spill 3
+
+0 property0 spill 4
+1 property1 spill 5
+2 property2 spill 6
+3 property3 spill 7
+4 property4 spill 8
+5 property5 spill 0
+6 property6 spill 1
+7 property7 spill 2
+
+c0 property0 field 0
+c1 property1 field 1
+c2 property2 field 2
+c3 property3 field 3
+c4 property4 spill 0
+c5 property5 spill 1
+c6 property6 spill 2
+c7 property7 spill 3
+
+d0 property0 field 0
+d1 property1 field 1
+d2 property2 field 2
+d3 property3 field 3
+d4 property4 spill 0
+d5 property5 spill 1
+d6 property6 spill 2
+d7 property7 spill 3
+
+0 property0 spill 4
+1 property1 spill 5
+2 property2 spill 6
+3 property3 spill 7
+4 property4 spill 8
+5 property5 spill 0
+6 property6 spill 1
+7 property7 spill 2
--- a/nashorn/test/script/nosecurity/JDK-8050964.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/nosecurity/JDK-8050964.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/nosecurity/JDK-8055034.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8055034: jjs exits interactive mode if exception was thrown when trying to print value of last evaluated expression
+ *
+ * @test
+ * @option -scripting
+ * @run
+ */
+
+// assume that this script is run with "nashorn.jar" System
+// property set to relative or absolute path of nashorn.jar
+
+if (typeof fail != 'function') {
+ fail = print;
+}
+
+var System = java.lang.System;
+var File = java.io.File;
+var javahome = System.getProperty("java.home");
+var nashornJar = new File(System.getProperty("nashorn.jar"));
+if (! nashornJar.isAbsolute()) {
+ nashornJar = new File(".", nashornJar);
+}
+var nashornJarDir = nashornJar.parentFile.absolutePath;
+
+// we want to use nashorn.jar passed and not the one that comes with JRE
+var jjsCmd = javahome + "/../bin/jjs";
+jjsCmd += " -J-Djava.ext.dirs=" + nashornJarDir;
+jjsCmd = jjsCmd.toString().replaceAll(/\//g, File.separater);
+
+$EXEC(jjsCmd, "var x = Object.create(null);\nx;\nprint('PASSED');\nexit(0)");
+
+// $ERR has all interactions including prompts! Just check for error substring.
+var err = $ERR.trim();
+if (! err.contains("TypeError: Cannot get default string value")) {
+ fail("Error stream does not contain expected error message");
+}
+
+// should print "PASSED"
+print($OUT.trim());
+// exit code should be 0
+print("exit code = " + $EXIT);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/nosecurity/JDK-8055034.js.EXPECTED Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,2 @@
+PASSED
+exit code = 0
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/nosecurity/JDK-8055107.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * JDK-8055107: Extension directives to turn on callsite profiling, tracing, AST print and other debug features locally
+ *
+ * @test
+ * @option -Dnashorn.debug=true
+ * @option -scripting
+ * @run
+ * @fork
+ */
+
+function runScriptEngine(code) {
+ var imports = new JavaImporter(
+ java.io, java.lang, java.util, javax.script);
+
+ with(imports) {
+ var m = new ScriptEngineManager();
+ // get current System.err
+ var oldErr = System.err;
+ var baos = new ByteArrayOutputStream();
+ var newErr = new PrintStream(baos);
+ try {
+ // set new standard err
+ System.setErr(newErr);
+ var engine = m.getEngineByName("nashorn");
+ engine.eval(code);
+ newErr.flush();
+ return new java.lang.String(baos.toByteArray());
+ } finally {
+ // restore System.err to old value
+ System.setErr(oldErr);
+ }
+ }
+}
+
+// nashorn callsite trace enterexit
+var str = runScriptEngine(<<CODE
+function func() {
+ "nashorn callsite trace enterexit";
+ k();
+}
+
+function k() {
+ var x = "hello";
+}
+
+func();
+CODE);
+
+if (!str.contains(" ENTER ")) {
+ fail("expected 'ENTER' in trace mode output");
+}
+
+if (!str.contains(" EXIT ")) {
+ fail("expected 'EXIT' in trace mode output");
+}
+
+// nashorn callsite trace objects
+var str = runScriptEngine(<<CODE
+"nashorn callsite trace objects";
+function func(x) {
+}
+
+func("hello");
+CODE);
+
+if (!str.contains(" ENTER ")) {
+ fail("expected 'ENTER' in trace mode output");
+}
+
+if (!str.contains(" EXIT ")) {
+ fail("expected 'EXIT' in trace mode output");
+}
+
+if (!str.contains("hello")) {
+ fail("expected argument to be traced in trace objects mode");
+}
+
+// nashorn callsite trace misses
+str = runScriptEngine(<<CODE
+function f() {
+ "nashorn callsite trace misses";
+ k();
+}
+
+function k() {}
+f();
+CODE);
+
+if (!str.contains(" MISS ")) {
+ fail("expected callsite MISS trace messages");
+}
+
+// nashorn print lower ast
+str = runScriptEngine(<<CODE
+function foo() {
+ "nashorn print lower ast";
+ var x = 'hello';
+}
+foo();
+CODE);
+
+if (!str.contains("Lower AST for: 'foo'") ||
+ !str.contains("nashorn print lower ast")) {
+ fail("expected Lower AST to be printed for 'foo'");
+}
+
+// nashorn print ast
+str = runScriptEngine(<<CODE
+function foo() {
+ "nashorn print ast";
+}
+CODE);
+if (!str.contains("[function ") ||
+ !str.contains("nashorn print ast")) {
+ fail("expected AST to be printed");
+}
+
+// nashorn print symbols
+str = runScriptEngine(<<CODE
+function bar(a) {
+ "nashorn print symbols";
+ if (a) print(a);
+}
+
+bar();
+CODE)
+
+if (!str.contains("[BLOCK in 'Function bar']")) {
+ fail("expected symbols to be printed for 'bar'");
+}
+
+// nashorn print parse
+str = runScriptEngine(<<CODE
+"nashorn print parse";
+
+function func() {}
+CODE);
+
+if (!str.contains("function func") ||
+ !str.contains("nashorn print parse")) {
+ fail("expected nashorn print parse output");
+}
+
+// nashorn print lower parse
+str = runScriptEngine(<<CODE
+"nashorn print lower parse";
+
+function func() {}
+
+func()
+CODE);
+
+if (!str.contains("function {U%}func") ||
+ !str.contains("nashorn print lower parse")) {
+ fail("expected nashorn print lower parse output");
+}
--- a/nashorn/test/script/nosecurity/debuggersupportapi.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/nosecurity/debuggersupportapi.js Thu Aug 28 14:53:37 2014 -0700
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
+ *
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
- *
+ *
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
- *
+ *
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
+ *
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
--- a/nashorn/test/script/trusted/JDK-8006529.js Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/script/trusted/JDK-8006529.js Thu Aug 28 14:53:37 2014 -0700
@@ -120,7 +120,7 @@
var sourceForMethod = Source.class.getMethod("sourceFor", java.lang.String.class, java.lang.String.class)
var ParserConstructor = Parser.class.getConstructor(ScriptEnvironment.class, Source.class, ErrorManager.class)
-var CompilerConstructor = Compiler.class.getConstructor(Context.class, ScriptEnvironment.class, CodeInstaller.class, Source.class, String.class, boolean.class);
+var CompilerConstructor = Compiler.class.getConstructor(Context.class, ScriptEnvironment.class, CodeInstaller.class, Source.class, boolean.class);
// compile(script) -- compiles a script specified as a string with its
// source code, returns a jdk.nashorn.internal.ir.FunctionNode object
@@ -134,7 +134,7 @@
var parser = ParserConstructor.newInstance(env, source, ThrowErrorManager.class.newInstance());
var func = parseMethod.invoke(parser);
- var compiler = CompilerConstructor.newInstance(ctxt, env, null, source, null, false);
+ var compiler = CompilerConstructor.newInstance(ctxt, env, null, source, false);
return compileMethod.invoke(compiler, func, phases);
};
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/trusted/classfilter.js Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * ClassFilter to filter out java classes in a script engine.
+ *
+ * @test
+ * @run
+ */
+
+var NashornScriptEngineFactory = Java.type("jdk.nashorn.api.scripting.NashornScriptEngineFactory");
+
+var fac = new NashornScriptEngineFactory();
+// allow only "java.*" classes to be accessed
+var e = fac.getScriptEngine(
+ function(name) name.startsWith("java."));
+
+function evalIt(str) {
+ print(str + " evalutes to " + e.eval(str));
+}
+
+function evalExpectError(str) {
+ try {
+ print(e.eval(str));
+ fail("expected error for: " + str);
+ } catch(exp) {
+ print(str + " throws " + exp);
+ }
+}
+
+evalIt("typeof javax.script.ScriptContext");
+evalIt("typeof javax.script.ScriptEngine");
+evalIt("typeof java.util.Vector");
+evalIt("typeof java.util.Map");
+evalIt("typeof java.util.HashMap");
+// should be able to call methods, create objects of java.* classes
+evalIt("var m = new java.util.HashMap(); m.put('foo', 42); m");
+evalIt("java.lang.System.out.println");
+evalIt("java.lang.System.exit");
+
+evalExpectError("new javax.script.SimpleBindings");
+evalExpectError("Java.type('javax.script.ScriptContext')");
+evalExpectError("java.lang.Class.forName('javax.script.ScriptContext')");
+
+try {
+ fac["getScriptEngine(ClassFilter)"](null);
+ fail("should have thrown NPE");
+} catch (e) {
+ if (! (e instanceof java.lang.NullPointerException)) {
+ fail("NPE expected, got " + e);
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/test/script/trusted/classfilter.js.EXPECTED Thu Aug 28 14:53:37 2014 -0700
@@ -0,0 +1,11 @@
+typeof javax.script.ScriptContext evalutes to object
+typeof javax.script.ScriptEngine evalutes to object
+typeof java.util.Vector evalutes to function
+typeof java.util.Map evalutes to function
+typeof java.util.HashMap evalutes to function
+var m = new java.util.HashMap(); m.put('foo', 42); m evalutes to {foo=42}
+java.lang.System.out.println evalutes to [jdk.internal.dynalink.beans.OverloadedDynamicMethod java.io.PrintStream.println]
+java.lang.System.exit evalutes to [jdk.internal.dynalink.beans.SimpleDynamicMethod void java.lang.System.exit(int)]
+new javax.script.SimpleBindings throws java.lang.RuntimeException: java.lang.ClassNotFoundException: javax.script.SimpleBindings
+Java.type('javax.script.ScriptContext') throws java.lang.RuntimeException: java.lang.ClassNotFoundException: javax.script.ScriptContext
+java.lang.Class.forName('javax.script.ScriptContext') throws javax.script.ScriptException: TypeError: Java reflection not supported when class filter is present in <eval> at line number 1
--- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptEngineTest.java Thu Aug 28 14:53:37 2014 -0700
@@ -623,12 +623,40 @@
final ScriptEngine e = m.getEngineByName("nashorn");
e.put(ScriptEngine.FILENAME, "test");
- Object enumerable = e.eval(
+ final Object enumerable = e.eval(
"Object.getOwnPropertyDescriptor(this, " +
" 'javax.script.filename').enumerable");
assertEquals(enumerable, Boolean.FALSE);
}
+ @Test
+ public void nashornConfigSecurityTest() {
+ final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
+ try {
+ fac.getScriptEngine(new ClassFilter() {
+ @Override
+ public boolean exposeToScripts(final String name) {
+ return true;
+ }
+ });
+ fail("SecurityException should have been thrown");
+ } catch (final SecurityException exp) {}
+ }
+
+ @Test
+ public void nashornConfigSecurityTest2() {
+ final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
+ try {
+ fac.getScriptEngine(new String[0], null, new ClassFilter() {
+ @Override
+ public boolean exposeToScripts(final String name) {
+ return true;
+ }
+ });
+ fail("SecurityException should have been thrown");
+ } catch (final SecurityException exp) {}
+ }
+
private static void checkProperty(final ScriptEngine e, final String name)
throws ScriptException {
final String value = System.getProperty(name);
--- a/nashorn/test/src/jdk/nashorn/api/scripting/ScriptObjectMirrorTest.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/ScriptObjectMirrorTest.java Thu Aug 28 14:53:37 2014 -0700
@@ -34,7 +34,9 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.function.Function;
import javax.script.Bindings;
+import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
@@ -306,4 +308,57 @@
// getMember("obj.foo") - thereby getting null instead of undefined
assertEquals("undefined", engine.eval(TEST_SCRIPT, newGlobal));
}
+
+ public interface MirrorCheckExample {
+ Object test1(Object arg);
+ Object test2(Object arg);
+ boolean compare(Object o1, Object o2);
+ }
+
+ // @bug 8053910: ScriptObjectMirror causing havoc with Invocation interface
+ @Test
+ public void checkMirrorToObject() throws Exception {
+ final ScriptEngineManager engineManager = new ScriptEngineManager();
+ final ScriptEngine engine = engineManager.getEngineByName("nashorn");
+ final Invocable invocable = (Invocable)engine;
+
+ engine.eval("function test1(arg) { return { arg: arg }; }");
+ engine.eval("function test2(arg) { return arg; }");
+ engine.eval("function compare(arg1, arg2) { return arg1 == arg2; }");
+
+ final Map<String, Object> map = new HashMap<>();
+ map.put("option", true);
+
+ final MirrorCheckExample example = invocable.getInterface(MirrorCheckExample.class);
+
+ final Object value1 = invocable.invokeFunction("test1", map);
+ final Object value2 = example.test1(map);
+ final Object value3 = invocable.invokeFunction("test2", value2);
+ final Object value4 = example.test2(value2);
+
+ // check that Object type argument receives a ScriptObjectMirror
+ // when ScriptObject is passed
+ assertEquals(ScriptObjectMirror.class, value1.getClass());
+ assertEquals(ScriptObjectMirror.class, value2.getClass());
+ assertEquals(ScriptObjectMirror.class, value3.getClass());
+ assertEquals(ScriptObjectMirror.class, value4.getClass());
+ assertTrue((boolean)invocable.invokeFunction("compare", value1, value1));
+ assertTrue((boolean)example.compare(value1, value1));
+ assertTrue((boolean)invocable.invokeFunction("compare", value3, value4));
+ assertTrue((boolean)example.compare(value3, value4));
+ }
+
+ // @bug 8053910: ScriptObjectMirror causing havoc with Invocation interface
+ @Test
+ @SuppressWarnings("unchecked")
+ public void mirrorUnwrapInterfaceMethod() throws Exception {
+ final ScriptEngineManager engineManager = new ScriptEngineManager();
+ final ScriptEngine engine = engineManager.getEngineByName("nashorn");
+ final Invocable invocable = (Invocable)engine;
+ engine.eval("function apply(obj) { " +
+ " return obj instanceof Packages.jdk.nashorn.api.scripting.ScriptObjectMirror; " +
+ "}");
+ final Function<Object,Object> func = invocable.getInterface(Function.class);
+ assertFalse((boolean)func.apply(engine.eval("({ x: 2 })")));
+ }
}
--- a/nashorn/test/src/jdk/nashorn/internal/runtime/CodeStoreAndPathTest.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/runtime/CodeStoreAndPathTest.java Thu Aug 28 14:53:37 2014 -0700
@@ -96,7 +96,7 @@
final String codeCache = "build/nashorn_code_cache";
final String oldUserDir = System.getProperty("user.dir");
- private static final String[] ENGINE_OPTIONS = new String[]{"--persistent-code-cache"};
+ private static final String[] ENGINE_OPTIONS = new String[]{"--persistent-code-cache", "--optimistic-types=false", "--lazy-compilation=false"};
public void checkCompiledScripts(final DirectoryStream<Path> stream, int numberOfScripts) throws IOException {
for (final Path file : stream) {
--- a/nashorn/test/src/jdk/nashorn/internal/runtime/ConsStringTest.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/runtime/ConsStringTest.java Thu Aug 28 14:53:37 2014 -0700
@@ -26,11 +26,7 @@
package jdk.nashorn.internal.runtime;
import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-import jdk.nashorn.internal.runtime.JSType;
-import jdk.nashorn.internal.runtime.ScriptRuntime;
import org.testng.annotations.Test;
/**
--- a/nashorn/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java Thu Aug 21 14:16:28 2014 -0700
+++ b/nashorn/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java Thu Aug 28 14:53:37 2014 -0700
@@ -35,6 +35,7 @@
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
+import jdk.nashorn.api.scripting.ClassFilter;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import org.testng.annotations.Test;
@@ -220,8 +221,98 @@
assertTrue(e.eval("typeof bar").equals("function"));
}
+ @Test
+ public void classFilterTest() throws ScriptException {
+ final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
+ final ScriptEngine e = fac.getScriptEngine(new ClassFilter() {
+ @Override
+ public boolean exposeToScripts(final String fullName) {
+ // don't allow anything that is not "java."
+ return fullName.startsWith("java.");
+ }
+ });
- @Test public void nashornSwallowsConstKeyword() throws Exception {
+ assertEquals(e.eval("typeof javax.script.ScriptEngine"), "object");
+ assertEquals(e.eval("typeof java.util.Vector"), "function");
+
+ try {
+ e.eval("Java.type('javax.script.ScriptContext')");
+ fail("should not reach here");
+ } catch (final ScriptException | RuntimeException se) {
+ if (! (se.getCause() instanceof ClassNotFoundException)) {
+ fail("ClassNotFoundException expected");
+ }
+ }
+ }
+
+ @Test
+ public void classFilterTest2() throws ScriptException {
+ final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
+ final ScriptEngine e = fac.getScriptEngine(new String[0], Thread.currentThread().getContextClassLoader(),
+ new ClassFilter() {
+ @Override
+ public boolean exposeToScripts(final String fullName) {
+ // don't allow anything that is not "java."
+ return fullName.startsWith("java.");
+ }
+ });
+
+ assertEquals(e.eval("typeof javax.script.ScriptEngine"), "object");
+ assertEquals(e.eval("typeof java.util.Vector"), "function");
+
+ try {
+ e.eval("Java.type('javax.script.ScriptContext')");
+ fail("should not reach here");
+ } catch (final ScriptException | RuntimeException se) {
+ if (! (se.getCause() instanceof ClassNotFoundException)) {
+ fail("ClassNotFoundException expected");
+ }
+ }
+ }
+
+ @Test
+ public void nullClassFilterTest() {
+ final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
+ try {
+ fac.getScriptEngine((ClassFilter)null);
+ fail("should have thrown NPE");
+ } catch (NullPointerException npe) {}
+ }
+
+ @Test
+ public void nullClassFilterTest2() {
+ final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
+ try {
+ fac.getScriptEngine(new String[0], null, null);
+ fail("should have thrown NPE");
+ } catch (NullPointerException npe) {}
+ }
+
+ @Test
+ public void nullArgsTest() {
+ final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
+ try {
+ fac.getScriptEngine((String[])null);
+ fail("should have thrown NPE");
+ } catch (NullPointerException npe) {}
+ }
+
+ @Test
+ public void nullArgsTest2() {
+ final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
+ try {
+ fac.getScriptEngine(null, null, new ClassFilter() {
+ @Override
+ public boolean exposeToScripts(final String name) {
+ return true;
+ }
+ });
+ fail("should have thrown NPE");
+ } catch (NullPointerException npe) {}
+ }
+
+ @Test
+ public void nashornSwallowsConstKeyword() throws Exception {
final NashornScriptEngineFactory f = new NashornScriptEngineFactory();
final String[] args = new String[] { "--const-as-var" };
final ScriptEngine engine = f.getScriptEngine(args);