8241749: Remove the Nashorn JavaScript Engine

Reviewed-by: jlaskey, ihse, mchung
This commit is contained in:
Athijegannathan Sundararajan 2020-04-16 12:26:20 +05:30
parent dc6d76f518
commit d5cd165965
3322 changed files with 10 additions and 741220 deletions

View file

@ -668,12 +668,6 @@ endif
################################################################################ ################################################################################
ifeq ($(MODULE), jdk.scripting.nashorn)
include CompileJavaModulesNashorn.gmk
endif
################################################################################
$(eval $(call IncludeCustomExtension, CompileJavaModules-post.gmk)) $(eval $(call IncludeCustomExtension, CompileJavaModules-post.gmk))
################################################################################ ################################################################################

View file

@ -1,54 +0,0 @@
#
# Copyright (c) 2010, 2018, 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.
#
NASGEN_SRC := $(TOPDIR)/make/nashorn/buildtools/nasgen/src
ASM_SRC := $(TOPDIR)/src/java.base/share/classes/jdk/internal/org/objectweb/asm
# Build nasgen
$(eval $(call SetupJavaCompilation, BUILD_NASGEN, \
SETUP := GENERATE_OLDBYTECODE, \
SRC := $(NASGEN_SRC) $(ASM_SRC), \
BIN := $(BUILDTOOLS_OUTPUTDIR)/nasgen_classes, \
))
NASHORN_CLASSES_DIR := $(JDK_OUTPUTDIR)/modules/$(MODULE)
NASGEN_RUN_FILE := $(NASHORN_CLASSES_DIR)/_the.nasgen.run
NASGEN_OPTIONS := \
-cp $(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
--patch-module java.base=$(BUILDTOOLS_OUTPUTDIR)/nasgen_classes \
--add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
--add-exports java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED \
#
# Run nasgen to modify classes in jdk.nashorn.internal.objects package
$(NASGEN_RUN_FILE): $(BUILD_NASGEN) $($(MODULE))
$(ECHO) Running nasgen
$(JAVA_SMALL) $(NASGEN_OPTIONS) \
jdk.nashorn.internal.tools.nasgen.Main $(@D) \
jdk.nashorn.internal.objects $(@D)
$(TOUCH) $@
TARGETS += $(NASGEN_RUN_FILE)

View file

@ -356,7 +356,6 @@ jdk_JTREG_NATIVEPATH := $(TEST_IMAGE_DIR)/jdk/jtreg/native
jdk_JTREG_PROBLEM_LIST += $(TOPDIR)/test/jdk/ProblemList.txt jdk_JTREG_PROBLEM_LIST += $(TOPDIR)/test/jdk/ProblemList.txt
jaxp_JTREG_PROBLEM_LIST += $(TOPDIR)/test/jaxp/ProblemList.txt jaxp_JTREG_PROBLEM_LIST += $(TOPDIR)/test/jaxp/ProblemList.txt
langtools_JTREG_PROBLEM_LIST += $(TOPDIR)/test/langtools/ProblemList.txt langtools_JTREG_PROBLEM_LIST += $(TOPDIR)/test/langtools/ProblemList.txt
nashorn_JTREG_PROBLEM_LIST += $(TOPDIR)/test/nashorn/ProblemList.txt
hotspot_JTREG_PROBLEM_LIST += $(TOPDIR)/test/hotspot/jtreg/ProblemList.txt hotspot_JTREG_PROBLEM_LIST += $(TOPDIR)/test/hotspot/jtreg/ProblemList.txt
langtools_JTREG_MAX_MEM := 768m langtools_JTREG_MAX_MEM := 768m

View file

@ -43,7 +43,7 @@ $(eval $(call IncludeCustomExtension, common/FindTests.gmk))
TEST_BASEDIRS += $(TOPDIR)/test $(TOPDIR) TEST_BASEDIRS += $(TOPDIR)/test $(TOPDIR)
# JTREG_TESTROOTS might have been set by a custom extension # JTREG_TESTROOTS might have been set by a custom extension
JTREG_TESTROOTS += $(addprefix $(TOPDIR)/test/, hotspot/jtreg jdk langtools nashorn jaxp) JTREG_TESTROOTS += $(addprefix $(TOPDIR)/test/, hotspot/jtreg jdk langtools jaxp)
# Extract the names of the Jtreg group files from the TEST.ROOT files. The # Extract the names of the Jtreg group files from the TEST.ROOT files. The
# TEST.ROOT files being properties files can be interpreted as makefiles so # TEST.ROOT files being properties files can be interpreted as makefiles so

View file

@ -112,7 +112,6 @@ PLATFORM_MODULES += \
jdk.jsobject \ jdk.jsobject \
jdk.localedata \ jdk.localedata \
jdk.naming.dns \ jdk.naming.dns \
jdk.scripting.nashorn \
jdk.security.auth \ jdk.security.auth \
jdk.security.jgss \ jdk.security.jgss \
jdk.xml.dom \ jdk.xml.dom \
@ -130,7 +129,6 @@ endif
JRE_TOOL_MODULES += \ JRE_TOOL_MODULES += \
jdk.jdwp.agent \ jdk.jdwp.agent \
jdk.incubator.jpackage \ jdk.incubator.jpackage \
jdk.scripting.nashorn.shell \
# #
################################################################################ ################################################################################
@ -172,7 +170,6 @@ DOCS_MODULES += \
jdk.naming.rmi \ jdk.naming.rmi \
jdk.net \ jdk.net \
jdk.nio.mapmode \ jdk.nio.mapmode \
jdk.scripting.nashorn \
jdk.sctp \ jdk.sctp \
jdk.security.auth \ jdk.security.auth \
jdk.security.jgss \ jdk.security.jgss \

View file

@ -1,51 +0,0 @@
#
# Copyright (c) 2018, 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.
#
default: all
include $(SPEC)
include MakeBase.gmk
include TextFileProcessing.gmk
################################################################################
# Version file needs to be processed with version numbers
VERSION_FILE := jdk/nashorn/internal/runtime/resources/version.properties
$(eval $(call SetupTextFileProcessing, BUILD_VERSION_FILE, \
SOURCE_FILES := $(TOPDIR)/src/$(MODULE)/share/classes/$(VERSION_FILE).template, \
OUTPUT_FILE := $(SUPPORT_OUTPUTDIR)/gensrc/$(MODULE)/$(VERSION_FILE), \
REPLACEMENTS := \
@@VERSION_STRING@@ => $(VERSION_STRING) ; \
@@VERSION_SHORT@@ => $(VERSION_SHORT) , \
))
TARGETS += $(NASGEN_RUN_FILE) $(BUILD_VERSION_FILE)
################################################################################
all: $(TARGETS)
.PHONY: all default

View file

@ -1,32 +0,0 @@
#
# Copyright (c) 2011, 2016, 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.
#
include LauncherCommon.gmk
$(eval $(call SetupBuildLauncher, jjs, \
MAIN_CLASS := jdk.nashorn.tools.jjs.Main, \
JAVA_ARGS := --add-modules ALL-DEFAULT, \
CFLAGS := -DENABLE_ARG_FILES, \
))

View file

@ -1,435 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project
name="nashorn-benchmarks"
default="all"
basedir=".."
xmlns:if="ant:if">
<!--
Below are the octane benchmarks that should be run.
The ones that are excluded, as Nashorn currently has
some issues with them (functionality or performance)
are commented out
-->
<!-- box2d -->
<target name="octane-box2d" depends="octane-box2d-nashorn"/>
<target name="octane-box2d-nashorn" depends="jar">
<run-one cond="octane.benchmark.box2d" runtime="nashorn"/>
</target>
<target name="octane-box2d-v8" depends="jar">
<run-one cond="octane.benchmark.box2d" runtime="v8"/>
</target>
<target name="octane-box2d-rhino" depends="jar">
<run-one cond="octane.benchmark.box2d" runtime="rhino"/>
</target>
<!-- code-load -->
<target name="octane-code-load" depends="octane-code-load-nashorn"/>
<target name="octane-code-load-nashorn" depends="jar">
<run-one cond="octane.benchmark.code-load" runtime="nashorn"/>
</target>
<target name="octane-code-load-v8" depends="jar">
<run-one cond="octane.benchmark.code-load" runtime="v8"/>
</target>
<target name="octane-code-load-rhino" depends="jar">
<run-one cond="octane.benchmark.code-load" runtime="rhino"/>
</target>
<!-- crypto -->
<target name="octane-crypto" depends="octane-crypto-nashorn"/>
<target name="octane-crypto-nashorn" depends="jar">
<run-one cond="octane.benchmark.crypto" runtime="nashorn"/>
</target>
<target name="octane-crypto-v8" depends="jar">
<run-one cond="octane.benchmark.crypto" runtime="v8"/>
</target>
<target name="octane-crypto-rhino" depends="jar">
<run-one cond="octane.benchmark.crypto" runtime="rhino"/>
</target>
<!-- deltablue -->
<target name="octane-deltablue" depends="octane-deltablue-nashorn"/>
<target name="octane-deltablue-nashorn" depends="jar">
<run-one cond="octane.benchmark.deltablue" runtime="nashorn"/>
</target>
<target name="octane-deltablue-v8" depends="jar">
<run-one cond="octane.benchmark.deltablue" runtime="v8"/>
</target>
<target name="octane-deltablue-rhino" depends="jar">
<run-one cond="octane.benchmark.deltablue" runtime="rhino"/>
</target>
<!-- earley-boyer -->
<target name="octane-earley-boyer" depends="octane-earley-boyer-nashorn"/>
<target name="octane-earley-boyer-nashorn" depends="jar">
<run-one cond="octane.benchmark.earley-boyer" runtime="nashorn"/>
</target>
<target name="octane-earley-boyer-v8" depends="jar">
<run-one cond="octane.benchmark.earley-boyer" runtime="v8"/>
</target>
<target name="octane-earley-boyer-rhino" depends="jar">
<run-one cond="octane.benchmark.earley-boyer" runtime="rhino"/>
</target>
<!-- gbemu -->
<target name="octane-gbemu" depends="octane-gbemu-nashorn"/>
<target name="octane-gbemu-nashorn" depends="jar">
<run-one cond="octane.benchmark.gbemu" runtime="nashorn"/>
</target>
<target name="octane-gbemu-v8" depends="jar">
<run-one cond="octane.benchmark.gbemu" runtime="v8"/>
</target>
<target name="octane-gbemu-rhino" depends="jar">
<run-one cond="octane.benchmark.gbemu" runtime="rhino"/>
</target>
<!-- mandreel -->
<target name="octane-mandreel" depends="octane-mandreel-nashorn"/>
<target name="octane-mandreel-nashorn" depends="jar">
<run-one cond="octane.benchmark.mandreel" runtime="nashorn"/>
</target>
<target name="octane-mandreel-v8" depends="jar">
<run-one cond="octane.benchmark.mandreel" runtime="v8"/>
</target>
<target name="octane-mandreel-rhino" depends="jar">
<run-one cond="octane.benchmark.mandreel" runtime="rhino"/>
</target>
<!-- navier-stokes -->
<target name="octane-navier-stokes" depends="octane-navier-stokes-nashorn"/>
<target name="octane-navier-stokes-nashorn" depends="jar">
<run-one cond="octane.benchmark.navier-stokes" runtime="nashorn"/>
</target>
<target name="octane-navier-stokes-v8" depends="jar">
<run-one cond="octane.benchmark.navier-stokes" runtime="v8"/>
</target>
<target name="octane-navier-stokes-rhino" depends="jar">
<run-one cond="octane.benchmark.navier-stokes" runtime="rhino"/>
</target>
<!-- pdfjs -->
<target name="octane-pdfjs" depends="octane-pdfjs-nashorn"/>
<target name="octane-pdfjs-nashorn" depends="jar">
<run-one cond="octane.benchmark.pdfjs" runtime="nashorn"/>
</target>
<target name="octane-pdfjs-v8" depends="jar">
<run-one cond="octane.benchmark.pdfjs" runtime="v8"/>
</target>
<target name="octane-pdfjs-rhino" depends="jar">
<run-one cond="octane.benchmark.pdfjs" runtime="rhino"/>
</target>
<!-- raytrace -->
<target name="octane-raytrace" depends="octane-raytrace-nashorn"/>
<target name="octane-raytrace-nashorn" depends="jar">
<run-one cond="octane.benchmark.raytrace" runtime="nashorn"/>
</target>
<target name="octane-raytrace-v8" depends="jar">
<run-one cond="octane.benchmark.raytrace" runtime="v8"/>
</target>
<target name="octane-raytrace-rhino" depends="jar">
<run-one cond="octane.benchmark.raytrace" runtime="rhino"/>
</target>
<!-- regexp -->
<target name="octane-regexp" depends="octane-regexp-nashorn"/>
<target name="octane-regexp-nashorn" depends="jar">
<run-one cond="octane.benchmark.regexp" runtime="nashorn"/>
</target>
<target name="octane-regexp-v8" depends="jar">
<run-one cond="octane.benchmark.regexp" runtime="v8"/>
</target>
<target name="octane-regexp-rhino" depends="jar">
<run-one cond="octane.benchmark.regexp" runtime="rhino"/>
</target>
<!-- richards -->
<target name="octane-richards" depends="octane-richards-nashorn"/>
<target name="octane-richards-nashorn" depends="jar">
<run-one cond="octane.benchmark.richards" runtime="nashorn"/>
</target>
<target name="octane-richards-v8" depends="jar">
<run-one cond="octane.benchmark.richards" runtime="v8"/>
</target>
<target name="octane-richards-rhino" depends="jar">
<run-one cond="octane.benchmark.richards" runtime="rhino"/>
</target>
<!-- splay -->
<target name="octane-splay" depends="octane-splay-nashorn"/>
<target name="octane-splay-nashorn" depends="jar">
<run-one cond="octane.benchmark.splay" runtime="nashorn"/>
</target>
<target name="octane-splay-v8" depends="jar">
<run-one cond="octane.benchmark.splay" runtime="v8"/>
</target>
<target name="octane-splay-rhino" depends="jar">
<run-one cond="octane.benchmark.splay" runtime="rhino"/>
</target>
<!-- typescript -->
<target name="octane-typescript" depends="octane-typescript-nashorn"/>
<target name="octane-typescript-nashorn" depends="jar">
<run-one cond="octane.benchmark.typescript" runtime="nashorn"/>
</target>
<target name="octane-typescript-v8" depends="jar">
<run-one cond="octane.benchmark.typescript" runtime="v8"/>
</target>
<target name="octane-typescript-rhino" depends="jar">
<run-one cond="octane.benchmark.typescript" runtime="rhino"/>
</target>
<!-- zlib -->
<target name="octane-zlib" depends="octane-zlib-nashorn"/>
<target name="octane-zlib-nashorn" depends="jar">
<run-one cond="octane.benchmark.zlib" runtime="nashorn"/>
</target>
<target name="octane-zlib-v8" depends="jar">
<run-one cond="octane.benchmark.zlib" runtime="v8"/>
</target>
<target name="octane-zlib-rhino" depends="jar">
<run-one cond="octane.benchmark.zlib" runtime="rhino"/>
</target>
<target name="-define-nashorn-task">
<ant dir="${nashorntask.dir}" inheritAll="false"/>
<taskdef name="nashorn" classname="jdk.nashorn.ant.NashornTask"
classpath="${nashorntask.dist.dir}/nashorntask.jar"/>
</target>
<!--
Benchmark runners for one or more benchmarks, single
or multiple process
-->
<target name="octane-process-separate" if="${octane-test-sys-prop.separate.process}"
depends="-define-nashorn-task">
<echo message="Running each benchmark in separate processes, starting new JVMs for each."/>
<nashorn><![CDATA[
var props = [];
for (var prop in project.getProperties()) {
if (prop.startsWith("octane.benchmark.")) {
props.push(prop);
}
}
//sort benchmark props in alphabetical order by name
props.sort(function(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
var runtime = project.getProperty("runtime");
for (var i in props) {
var task = project.createTask("run-one");
// workaround for https://issues.apache.org/bugzilla/show_bug.cgi?id=53831, still not fixed
if (task.getOwningTarget() == null) {
task.setOwningTarget(self.getOwningTarget());
}
var prop = props[i];
task.setDynamicAttribute("cond", prop);
task.setDynamicAttribute("runtime", runtime);
task.perform();
}
]]></nashorn>
</target>
<target name="octane-process-single" unless="${octane-test-sys-prop.separate.process}">
<echo message="Running all benchmarks in the same process."/>
<pathconvert property="octane.benchmarks" pathsep=" ">
<propertyset>
<propertyref prefix="octane.benchmark."/>
</propertyset>
</pathconvert>
<antcall target="run-octane${runtime}">
<param name="octane-tests" value="${octane.benchmarks}"/>
</antcall>
</target>
<!--
run 'octane' in single or separate processes based on config
This uses nashorn as the default runtime
-->
<target name="octane-nashorn" depends="jar">
<property name="runtime" value="nashorn"/>
<antcall target="octane-process-separate"/>
<antcall target="octane-process-single"/>
</target>
<!-- alias for 'octane' -->
<target name="octane" depends="octane-nashorn"/>
<!-- run octane benchmarks using octane as runtime -->
<target name="octane-v8" depends="jar">
<property name="runtime" value="v8"/>
<antcall target="octane-process-separate"/>
<antcall target="octane-process-single"/>
</target>
<!-- run octane benchmarks using Rhino as runtime -->
<target name="octane-rhino" depends="jar">
<property name="runtime" value="rhino"/>
<antcall target="octane-process-separate"/>
<antcall target="octane-process-single"/>
</target>
<macrodef name="run-one">
<attribute name="cond"/>
<attribute name="runtime" default=""/>
<sequential>
<antcall target="run-octane-@{runtime}" if:set="@{cond}">
<param name="octane-tests" value="${@{cond}}"/>
</antcall>
</sequential>
</macrodef>
<target name="run-octane-nashorn">
<java classname="${nashorn.shell.tool}"
classpath="${run.test.classpath}"
fork="true">
<jvmarg line="${run.test.jvmargs.octane} -Xms${run.test.xms} -Xmx${run.test.xmx}"/>
<!-- pass on all properties prefixed with 'nashorn' to the runtime -->
<syspropertyset>
<propertyref prefix="nashorn."/>
</syspropertyset>
<arg value="${octane-test-sys-prop.test.js.framework}"/>
<arg value="-scripting"/>
<arg value="--"/>
<arg value="${octane-tests}"/>
<arg value="--runtime"/>
<arg value="nashorn"/>
<arg value="--verbose"/>
<arg value="--iterations ${octane.iterations}"/>
</java>
</target>
<target name="run-octane-v8">
<exec executable="${v8.shell}">
<arg value="${octane-test-sys-prop.test.js.framework}"/>
<arg value="--"/>
<arg value="${octane-tests}"/>
<arg value="--runtime"/>
<arg value="v8"/>
<arg value="--verbose"/>
<arg value="--iterations ${octane.iterations}"/>
</exec>
</target>
<target name="run-octane-rhino">
<java jar="${rhino.jar}"
classpath="${run.test.classpath}"
fork="true"
dir=".">
<jvmarg line="${run.test.jvmargs.octane} -Xms${run.test.xms} -Xmx${run.test.xmx}"/>
<arg value="-opt"/>
<arg value="9"/>
<arg value="${octane-test-sys-prop.test.js.framework}"/>
<arg value="${octane-tests}"/>
<arg value="--runtime"/>
<arg value="rhino"/>
<arg value="--verbose"/>
<arg value="--iterations ${octane.iterations}"/>
</java>
</target>
<!-- run octane with all known runtimes for comparison -->
<target name="octane-all" depends="octane, octane-v8, octane-rhino">
<exec executable="${v8.shell}">
<arg value="${octane-test-sys-prop.test.js.framework}"/>
<arg value="${octane-tests}/"/>
</exec>
</target>
<target name="sunspider-init" depends="jar">
<fileset id="sunspider-set"
dir="${sunspider-test-sys-prop.test.js.roots}"
excludes="${sunspider-test-sys-prop.test.js.exclude.list}">
<include name="**/*.js"/>
</fileset>
<pathconvert pathsep=" " property="sunspider-tests" refid="sunspider-set"/>
</target>
<!--- SUNSPIDER JOB BELOW -->
<!-- run sunspider with Nashorn -->
<target name="sunspider" depends="sunspider-nashorn"/>
<target name="sunspider-nashorn" depends="sunspider-init">
<java classname="${nashorn.shell.tool}"
classpath="${run.test.classpath}"
fork="true">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx}"/>
<arg value="-timezone=PST"/>
<arg value="--class-cache-size=50"/>
<arg value="${sunspider-test-sys-prop.test.js.framework}"/>
<arg value="--"/>
<arg value="${sunspider-tests}/"/>
<arg value="--verbose"/>
<arg value="--times"/>
<arg value="${sunspider.iterations}"/>
</java>
</target>
<!-- run sunspider with v8 -->
<target name="sunspider-v8" depends="sunspider-init">
<exec executable="${v8.shell}">
<arg value="${sunspider-test-sys-prop.test.js.framework}"/>
<arg value="--"/>
<arg value="${sunspider-tests}/"/>
<arg value="--verbose"/>
<arg value="--times"/>
<arg value="${sunspider.iterations}"/>
</exec>
</target>
<!-- run sunspider with Rhino -->
<target name="sunspider-rhino" depends="sunspider-init">
<java jar="${rhino.jar}"
classpath="${run.test.classpath}"
fork="true"
dir=".">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx}"/>
<arg value="-opt"/>
<arg value="9"/>
<arg value="${sunspider-test-sys-prop.test.js.framework}"/>
<arg value="${sunspider-tests}/"/>
<arg value="--verbose"/>
<arg value="--times"/>
<arg value="${sunspider.iterations}"/>
</java>
</target>
</project>

View file

@ -1,79 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project name="build-nasgen" default="run-nasgen" basedir=".">
<description>Builds and runs nasgen.</description>
<import file="build.xml"/>
<target name="build-nasgen" depends="prepare">
<ant inheritAll="false" dir="${nashorn.make.dir}/buildtools/nasgen"
antfile="build.xml" target="jar"/>
</target>
<target name="run-nasgen" depends="build-nasgen">
<java classname="${nasgen.tool}" fork="true" failonerror="true">
<classpath>
<pathelement location="${basedir}/jcov2/lib/jcov_j2se_rt.jar"/>
<pathelement location="${build.dir}/nasgen/dist/nasgen.jar"/>
</classpath>
<jvmarg line="${nasgen.module.imports}"/>
<arg value="${nashorn.module.classes.dir}"/>
<arg value="jdk.nashorn.internal.objects"/>
<arg value="${nashorn.module.classes.dir}"/>
</java>
</target>
<target name="run-nasgen-eclipse" depends="load-properties">
<mkdir dir="${basedir}/build/eclipse/.nasgentmp"/>
<java classname="jdk.nashorn.internal.tools.nasgen.Main" fork="true" failonerror="true">
<classpath>
<pathelement location="${basedir}/buildtools/nasgen/dist/nasgen.jar"/>
</classpath>
<jvmarg line="${nasgen.module.imports}"/>
<arg value="${basedir}/build/eclipse"/>
<arg value="jdk.nashorn.internal.objects"/>
<arg value="${basedir}/build/eclipse/.nasgentmp"/>
</java>
<move todir="${basedir}/build/eclipse/jdk/nashorn/internal/objects">
<fileset dir="${basedir}/build/eclipse/.nasgentmp/jdk/nashorn/internal/objects">
<include name="*.class"/>
</fileset>
</move>
<delete includeemptydirs="true"><fileset dir="${basedir}/build/eclipse/.nasgentmp" includes="**"/></delete>
<copy todir="${basedir}/build/eclipse/jdk/nashorn/internal/objects" preservelastmodified="true">
<fileset dir="${basedir}/build/eclipse/jdk/nashorn/internal/objects">
<include name="**/*.class"/>
</fileset>
</copy>
</target>
<target name="clean-nasgen">
<ant inheritAll="false" dir="${nashorn.make.dir}/buildtools/nasgen"
antfile="build.xml" target="clean"/>
</target>
</project>

View file

@ -1,883 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2010, 2018, 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.
-->
<project name="nashorn" default="test" basedir="../..">
<import file="build-nasgen.xml"/>
<import file="code_coverage.xml"/>
<target name="load-properties">
<!-- set default values to run.test.jvmargs.external property -->
<condition property="run.test.jvmargs.external" value="">
<not><isset property="run.test.jvmargs.external"/></not>
</condition>
<!-- loading locally defined resources and properties. NB they owerwrite default ones defined later -->
<property file="${user.home}/.nashorn.project.local.properties"/>
<loadproperties srcFile="make/nashorn/project.properties"/>
</target>
<target name="init-conditions" depends="load-properties">
<path id="nashorn.jar.path">
<pathelement location="${nashorn.jar}"/>
</path>
<condition property="svn.executable" value="/usr/local/bin/svn" else="svn">
<available file="/usr/local/bin/svn"/>
</condition>
<condition property="hg.executable" value="/usr/local/bin/hg" else="hg">
<available file="/usr/local/bin/hg"/>
</condition>
<condition property="git.executable" value="/usr/local/bin/git" else="git">
<available file="/usr/local/bin/git"/>
</condition>
<!-- check if TestNG and dependencies are available, and download them if they aren't -->
<antcall target="get-testng"/>
<condition property="testng.available" value="true">
<and>
<available file="${file.reference.testng.jar}"/>
<available file="${file.reference.jcommander.jar}"/>
<available file="${file.reference.bsh.jar}"/>
<available file="${file.reference.snakeyaml.jar}"/>
</and>
</condition>
<!-- check if asmtools-6.0.jar is available, and download it if it isn't -->
<!--
<available property="asmtools.already.present" file="${file.reference.asmtools.jar}"/>
<antcall target="get-asmtools"/>
<available property="asmtools.available" file="${file.reference.asmtools.jar}"/>
-->
<!-- check if Jemmy ang TestNG are avaiable -->
<condition property="jemmy.jfx.testng.available" value="true">
<and>
<available file="${file.reference.jemmyfx.jar}"/>
<available file="${file.reference.jemmycore.jar}"/>
<available file="${file.reference.jemmyawtinput.jar}"/>
<available file="${file.reference.jfxrt.jar}"/>
<isset property="testng.available"/>
</and>
</condition>
<!-- enable/disable make code coverage -->
<condition property="cc.enabled">
<istrue value="${make.code.coverage}" />
</condition>
<!-- exclude tests in exclude lists -->
<condition property="exclude.list" value="${nashorn.make.dir}/exclude/exclude_list_cc.txt" else="${nashorn.make.dir}/exclude/exclude_list.txt">
<istrue value="${make.code.coverage}" />
</condition>
<condition property="jfr.options" value="${run.test.jvmargs.jfr}" else="">
<istrue value="${jfr}"/>
</condition>
<condition property="test-sys-prop-no-security.os.not.windows">
<not>
<os family="windows"/>
</not>
</condition>
<!--set windows cygwin/cmd specific properties-->
<property environment="env"/>
<condition property="test-sys-prop-no-security.os.not.windows.cmd">
<not>
<and>
<os family="windows"/>
<not>
<isset property="env.SHELL"/>
</not>
</and>
</not>
</condition>
</target>
<!-- check minimum ant version required to be 1.9.5 -->
<target name="check-ant-version">
<property name="ant.version.required" value="1.9.5"/>
<antversion property="ant.current.version" />
<fail message="The current ant version, ${ant.current.version}, is too old. Please use 1.9.5 or above.">
<condition>
<not>
<antversion atleast="${ant.version.required}"/>
</not>
</condition>
</fail>
</target>
<target name="check-java-version">
<!-- look for a Class that is available only in jdk1.8 or above -->
<!-- core/exposed API class is better than an implementation class -->
<available property="jdk1.8+" classname="java.util.stream.Stream"/>
<!-- need jdk1.8 or above -->
<fail message="Unsupported Java version: ${ant.java.version}. Please use Java version 1.8 or greater." unless="jdk1.8+">
</fail>
</target>
<target name="init" depends="check-ant-version, check-java-version, init-conditions, init-cc">
<!-- extends jvm args -->
<property name="run.test.jvmargs" value="${run.test.jvmargs.main} ${run.test.cc.jvmargs} ${jfr.options}"/>
<property name="run.test.jvmargs.octane" value="${run.test.jvmargs.octane.main} ${run.test.cc.jvmargs} ${jfr.options}"/>
<echo message="run.test.jvmargs=${run.test.jvmargs}"/>
<echo message="run.test.jvmargs.octane=${run.test.jvmargs.octane}"/>
<echo message="run.test.xms=${run.test.xms}"/>
<echo message="run.test.xmx=${run.test.xmx}"/>
</target>
<target name="prepare" depends="init">
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.classes.dir}"/>
<mkdir dir="${nashorn.module.classes.dir}"/>
<mkdir dir="${dynalink.module.classes.dir}"/>
<mkdir dir="${nashorn.shell.module.classes.dir}"/>
<mkdir dir="${nashorn.module.classes.dir}/META-INF/services"/>
<mkdir dir="${build.test.classes.dir}"/>
<mkdir dir="${dist.dir}"/>
<mkdir dir="${dist.javadoc.dir}"/>
</target>
<target name="clean" depends="init, clean-nasgen, init-cc-cleanup">
<delete includeemptydirs="true">
<fileset dir="${build.dir}" erroronmissingdir="false"/>
</delete>
<delete dir="${dist.dir}"/>
<delete dir="${jdk.build.dir}/nashorn_code_cache"/>
<delete file="${basedir}/NashornProfile.txt"/>
</target>
<target name="compile" depends="prepare" description="Compiles nashorn">
<javac srcdir="${dynalink.module.src.dir}"
destdir="${dynalink.module.classes.dir}"
debug="${javac.debug}"
encoding="${javac.encoding}"
includeantruntime="false" fork="true">
<compilerarg value="-Xlint:all"/>
<compilerarg value="-XDignore.symbol.file"/>
<compilerarg value="-Xdiags:verbose"/>
<compilerarg value="-parameters"/>
</javac>
<!-- patch-module does not like module-info.class files! -->
<delete>
<fileset dir="${build.classes.dir}" includes="**/module-info.class"/>
</delete>
<javac srcdir="${nashorn.module.src.dir}"
destdir="${nashorn.module.classes.dir}"
debug="${javac.debug}"
encoding="${javac.encoding}"
includeantruntime="false" fork="true">
<compilerarg value="-Xlint:all"/>
<compilerarg value="-XDignore.symbol.file"/>
<compilerarg value="-Xdiags:verbose"/>
<compilerarg value="-parameters"/>
<compilerarg line="${nashorn.override.option}"/>
</javac>
<!-- patch-module does not like module-info.class files! -->
<delete>
<fileset dir="${build.classes.dir}" includes="**/module-info.class"/>
</delete>
<javac srcdir="${nashorn.shell.module.src.dir}"
destdir="${nashorn.shell.module.classes.dir}"
debug="${javac.debug}"
encoding="${javac.encoding}"
includeantruntime="false" fork="true">
<compilerarg value="-Xlint:all"/>
<compilerarg value="-XDignore.symbol.file"/>
<compilerarg value="-Xdiags:verbose"/>
<compilerarg value="-parameters"/>
<compilerarg line="${nashorn.override.option}"/>
</javac>
<!-- patch-module does not like module-info.class files! -->
<delete>
<fileset dir="${build.classes.dir}" includes="**/module-info.class"/>
</delete>
<copy todir="${nashorn.module.classes.dir}/jdk/nashorn/api/scripting/resources">
<fileset dir="${nashorn.module.src.dir}/jdk/nashorn/api/scripting/resources/"/>
</copy>
<copy todir="${nashorn.module.classes.dir}/jdk/nashorn/internal/runtime/resources">
<fileset dir="${nashorn.module.src.dir}/jdk/nashorn/internal/runtime/resources/"/>
</copy>
<copy todir="${nashorn.module.classes.dir}/jdk/nashorn/tools/resources">
<fileset dir="${nashorn.module.src.dir}/jdk/nashorn/tools/resources/"/>
</copy>
<copy file="${dynalink.module.src.dir}/jdk/dynalink/support/messages.properties" todir="${dynalink.module.classes.dir}/jdk/dynalink/support"/>
<copy file="${nashorn.module.src.dir}/jdk/nashorn/internal/codegen/anchor.properties" todir="${nashorn.module.classes.dir}/jdk/nashorn/internal/codegen"/>
<copy todir="${nashorn.shell.module.classes.dir}/jdk/nashorn/tools/jjs/resources">
<fileset dir="${nashorn.shell.module.src.dir}/jdk/nashorn/tools/jjs/resources/"/>
</copy>
<echo message="version_string=${nashorn.fullversion}" file="${nashorn.module.classes.dir}/jdk/nashorn/internal/runtime/resources/version.properties"/>
<echo file="${nashorn.module.classes.dir}/jdk/nashorn/internal/runtime/resources/version.properties" append="true">${line.separator}</echo>
<echo message="version_short=${nashorn.version}" file="${nashorn.module.classes.dir}/jdk/nashorn/internal/runtime/resources/version.properties" append="true"/>
</target>
<target name="jar" depends="compile, run-nasgen, generate-cc-template" description="Creates nashorn.jar" unless="compile.suppress.jar">
<jar jarfile="${dynalink.jar}">
<fileset dir="${dynalink.module.classes.dir}"/>
</jar>
<jar jarfile="${nashorn.jar}" index="true" filesetmanifest="merge">
<fileset dir="${nashorn.module.classes.dir}"/>
<manifest>
<attribute name="Archiver-Version" value="n/a"/>
<attribute name="Build-Jdk" value="${java.runtime.version}"/>
<attribute name="Built-By" value="n/a"/>
<attribute name="Created-By" value="Ant jar task"/>
<section name="jdk/nashorn/">
<attribute name="Implementation-Title" value="${nashorn.product.name}"/>
<attribute name="Implementation-Version" value="${nashorn.version}"/>
</section>
</manifest>
</jar>
<jar jarfile="${jjs.jar}">
<fileset dir="${nashorn.shell.module.classes.dir}"/>
</jar>
</target>
<target name="use-promoted-nashorn" depends="init">
<delete file="${dist.dir}/nashorn.jar"/>
<copy file="${java.home}/lib/ext/nashorn.jar" todir="${dist.dir}"/>
<property name="compile.suppress.jar" value="defined"/>
</target>
<!-- generate javadoc for Nashorn classes -->
<target name="javadoc" depends="jar" unless="test.class">
<javadoc destdir="${dist.javadoc.dir}" use="yes"
windowtitle="${nashorn.product.name} ${nashorn.version}"
additionalparam="-quiet" failonerror="true" useexternalfile="true">
<arg value="--patch-module"/>
<arg value="jdk.scripting.nashorn=${basedir}/${nashorn.module.src.dir}"/>
<arg value="--patch-module"/>
<arg value="jdk.dynalink=${basedir}/${dynalink.module.src.dir}"/>
<arg value="--module-source-path"/>
<arg value="."/>
<arg value="${javadoc.option}"/>
<fileset dir="${nashorn.module.src.dir}" includes="**/*.java"/>
<fileset dir="${dynalink.module.src.dir}" includes="**/*.java"/>
<link offline="true" href="${javadoc.base.url}" packagelistLoc="${javadoc.element.list}"/>
</javadoc>
</target>
<!-- generate javadoc only for nashorn extension api classes -->
<target name="nashornapi" depends="jar">
<mkdir dir="${dist.nashornapi.javadoc.dir}"/>
<javadoc destdir="${dist.nashornapi.javadoc.dir}" use="yes"
windowtitle="${nashorn.product.name} ${nashorn.version}"
additionalparam="-quiet" failonerror="true" useexternalfile="true">
<arg value="--patch-module"/>
<arg value="jdk.scripting.nashorn=${basedir}/${nashorn.module.src.dir}"/>
<arg value="--patch-module"/>
<arg value="jdk.dynalink=${basedir}/${dynalink.module.src.dir}"/>
<arg value="--module-source-path"/>
<arg value="."/>
<arg value="${javadoc.option}"/>
<fileset dir="${nashorn.module.src.dir}" includes="jdk/nashorn/api/**/*.java"/>
<link offline="true" href="${javadoc.base.url}" packagelistLoc="${javadoc.element.list}"/>
</javadoc>
</target>
<!-- generate javadoc only for Dynalink API classes -->
<target name="dynalinkapi" depends="jar">
<mkdir dir="${dist.dynalinkapi.javadoc.dir}"/>
<javadoc destdir="${dist.dynalinkapi.javadoc.dir}" use="yes"
windowtitle="Dynalink"
additionalparam="-quiet" failonerror="true" useexternalfile="true">
<arg value="--patch-module"/>
<arg value="jdk.scripting.nashorn=${basedir}/${nashorn.module.src.dir}"/>
<arg value="--patch-module"/>
<arg value="jdk.dynalink=${basedir}/${dynalink.module.src.dir}"/>
<arg value="--module-source-path"/>
<arg value="."/>
<arg value="${javadoc.option}"/>
<fileset dir="${dynalink.module.src.dir}" includes="**/*.java"/>
<link offline="true" href="${javadoc.base.url}" packagelistLoc="${javadoc.element.list}"/>
</javadoc>
</target>
<target name="javadocapi" depends="nashornapi, dynalinkapi"/>
<!-- generate all docs -->
<target name="docs" depends="javadoc"/>
<!-- create .zip and .tar.gz for nashorn binaries and scripts. -->
<target name="dist" depends="jar">
<zip destfile="${build.zip}" basedir=".."
excludes="nashorn/bin/*.sh" includes="nashorn/bin/** nashorn/dist/**"/>
<tar destfile="${build.gzip}" basedir=".." compression="gzip"
excludes="nashorn/bin/*.sh" includes="nashorn/bin/** nashorn/dist/**"/>
</target>
<target name="compile-test" depends="compile, run-nasgen" if="testng.available">
<!-- testng task -->
<taskdef name="testng" classname="org.testng.TestNGAntTask"
classpath="${testng.ant.classpath}"/>
<javac srcdir="${test.src.dir}"
destdir="${build.test.classes.dir}"
classpath="${javac.test.classpath}"
debug="${javac.debug}"
encoding="${javac.encoding}"
includeantruntime="false" fork="true">
<compilerarg line="${nashorn.override.option}"/>
<compilerarg value="-Xlint:unchecked"/>
<compilerarg value="-Xlint:deprecation"/>
<compilerarg value="-Xdiags:verbose"/>
<compilerarg line="${test.module.imports.compile.time}"/>
</javac>
<copy todir="${build.test.classes.dir}/META-INF/services">
<fileset dir="${test.src.dir}/META-INF/services/"/>
</copy>
<copy todir="${build.test.classes.dir}/jdk/nashorn/internal/runtime/test/resources">
<fileset dir="${test.src.dir}/jdk/nashorn/internal/runtime/test/resources"/>
</copy>
<copy todir="${build.test.classes.dir}/jdk/nashorn/internal/runtime/doubleconv/test/resources">
<fileset dir="${test.src.dir}/jdk/nashorn/internal/runtime/doubleconv/test/resources"/>
</copy>
<copy todir="${build.test.classes.dir}/jdk/nashorn/api/scripting/test/resources">
<fileset dir="${test.src.dir}/jdk/nashorn/api/scripting/test/resources"/>
</copy>
<!-- tests that check nashorn internals and internal API -->
<jar jarfile="${nashorn.internal.tests.jar}">
<fileset dir="${build.test.classes.dir}" includes="**/internal/**"/>
<fileset dir="${build.test.classes.dir}" includes="**/test/tools/**"/>
<fileset dir="${build.test.classes.dir}" includes="**/models/**"/>
<fileset dir="${build.test.classes.dir}" includes="**/jdk/dynalink/test/Trusted**"/>
<fileset dir="${build.test.classes.dir}" includes="**/META-INF/**"/>
</jar>
<!-- tests that check nashorn script engine (jsr-223) API and dynalink API -->
<jar jarfile="${nashorn.api.tests.jar}">
<fileset dir="${build.test.classes.dir}" includes="**/jdk/dynalink/**" excludes="**/jdk/dynalink/test/Trusted**"/>
<fileset dir="${build.test.classes.dir}" includes="**/api/**"/>
<fileset dir="${build.test.classes.dir}" includes="**/META-INF/**"/>
<fileset dir="${build.test.classes.dir}" includes="**/resources/*.js"/>
<fileset dir="${build.test.classes.dir}" includes="**/UnnamedPackage**"/>
</jar>
</target>
<target name="generate-security-config" depends="generate-policy-file, generate-security-properties-file"/>
<target name="generate-security-properties-file" depends="prepare">
<echo file="${build.dir}/nashorn.security.properties">
package.access=sun.misc.,\
sun.reflect.,\
jdk.nashorn.internal.
</echo>
</target>
<target name="generate-policy-file" depends="prepare">
<echo file="${build.dir}/nashorn.policy">
grant codeBase "file:/${basedir}/${dynalink.module.classes.dir}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${basedir}/${nashorn.module.classes.dir}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${basedir}/${nashorn.internal.tests.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${basedir}/${nashorn.api.tests.jar}" {
permission java.util.PropertyPermission "parserapitest.*", "read";
permission java.util.PropertyPermission "test.*", "read";
permission java.util.PropertyPermission "test262.*", "read";
permission java.io.FilePermission "${basedir}/test/nashorn/-","read";
permission java.io.FilePermission "$${user.dir}", "read";
permission java.util.PropertyPermission "user.dir", "read";
};
grant codeBase "file:/${basedir}/${file.reference.testng.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${basedir}/${file.reference.jcommander.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${basedir}/${file.reference.bsh.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${basedir}/${file.reference.snakeyaml.jar}" {
permission java.security.AllPermission;
};
//// in case of absolute path:
grant codeBase "file:/${nashorn.internal.tests.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${file.reference.testng.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${file.reference.jcommander.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${file.reference.bsh.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${file.reference.snakeyaml.jar}" {
permission java.security.AllPermission;
};
grant codeBase "file:/${basedir}/${test.script.dir}/trusted/*" {
permission java.security.AllPermission;
};
grant codeBase "file:/${basedir}/${test.script.dir}/maptests/*" {
permission java.io.FilePermission "${basedir}/${test.script.dir}/maptests/*","read";
permission java.lang.RuntimePermission "nashorn.debugMode";
};
grant codeBase "file:/${basedir}/${test.script.dir}/basic/*" {
permission java.io.FilePermission "${basedir}/${test.script.dir}/-", "read";
permission java.io.FilePermission "$${user.dir}", "read";
permission java.util.PropertyPermission "user.dir", "read";
permission java.util.PropertyPermission "nashorn.test.*", "read";
};
grant codeBase "file:/${basedir}/${test.script.dir}/basic/apply_to_call/*" {
permission java.io.FilePermission "${basedir}/${test.script.dir}/-", "read";
permission java.io.FilePermission "$${user.dir}", "read";
permission java.util.PropertyPermission "user.dir", "read";
permission java.util.PropertyPermission "nashorn.test.*", "read";
};
grant codeBase "file:/${basedir}/${test.script.dir}/basic/parser/*" {
permission java.io.FilePermission "${basedir}/${test.script.dir}/-", "read";
permission java.io.FilePermission "$${user.dir}", "read";
permission java.util.PropertyPermission "user.dir", "read";
permission java.util.PropertyPermission "nashorn.test.*", "read";
};
grant codeBase "file:/${basedir}/${test.script.dir}/basic/es6/*" {
permission java.io.FilePermission "${basedir}/${test.script.dir}/-", "read";
permission java.io.FilePermission "$${user.dir}", "read";
permission java.util.PropertyPermission "user.dir", "read";
permission java.util.PropertyPermission "nashorn.test.*", "read";
};
grant codeBase "file:/${basedir}/${test.script.dir}/basic/JDK-8010946-privileged.js" {
permission java.util.PropertyPermission "java.security.policy", "read";
};
grant codeBase "file:/${basedir}/${test.script.dir}/basic/classloader.js" {
permission java.lang.RuntimePermission "nashorn.JavaReflection";
};
grant codeBase "file:/${basedir}/${test.script.dir}/markdown.js" {
permission java.io.FilePermission "${basedir}/${test.script.dir}/external/showdown/-", "read";
};
grant codeBase "file:/${basedir}/${test.script.dir}/basic/JDK-8158467.js" {
permission java.lang.RuntimePermission "nashorn.setConfig";
};
</echo>
<replace file="${build.dir}/nashorn.policy"><replacetoken>\</replacetoken><replacevalue>/</replacevalue></replace> <!--hack for Windows - to make URLs with normal path separators -->
<replace file="${build.dir}/nashorn.policy"><replacetoken>//</replacetoken><replacevalue>/</replacevalue></replace> <!--hack for Unix - to avoid leading // in URLs -->
</target>
<target name="check-external-tests">
<available file="${test.external.dir}/prototype" property="test-sys-prop.external.prototype"/>
<available file="${test.external.dir}/sunspider" property="test-sys-prop.external.sunspider"/>
<available file="${test.external.dir}/underscore" property="test-sys-prop.external.underscore"/>
<available file="${test.external.dir}/octane" property="test-sys-prop.external.octane"/>
<available file="${test.external.dir}/yui" property="test-sys-prop.external.yui"/>
<available file="${test.external.dir}/jquery" property="test-sys-prop.external.jquery"/>
<available file="${test.external.dir}/test262" property="test-sys-prop.external.test262"/>
<available file="${test.external.dir}/showdown" property="test-sys-prop.external.markdown"/>
</target>
<target name="check-testng" unless="testng.available">
<echo message="WARNING: TestNG not available, will not run tests. Please copy TestNG and dependency JARs to the ${test.lib} directory."/>
</target>
<!-- only to be invoked as dependency of "test" target -->
<target name="-test-classes-all" depends="jar" unless="test.class">
<fileset id="test.classes" dir="${build.test.classes.dir}">
<include name="**/dynalink/beans/test/*Test.class"/>
<include name="**/dynalink/linker/support/test/*Test.class"/>
<include name="**/dynalink/support/test/*Test.class"/>
<include name="**/dynalink/test/*Test.class"/>
<include name="**/api/javaaccess/test/*Test.class"/>
<include name="**/api/scripting/test/*Test.class"/>
<include name="**/api/tree/test/*Test.class"/>
<include name="**/codegen/test/*Test.class"/>
<include name="**/parser/test/*Test.class"/>
<include name="**/runtime/test/*Test.class"/>
<include name="**/runtime/doubleconv/test/*Test.class"/>
<include name="**/runtime/regexp/test/*Test.class"/>
<include name="**/runtime/regexp/joni/test/*Test.class"/>
<include name="**/framework/*Test.class"/>
</fileset>
</target>
<!-- only to be invoked as dependency of "test" target -->
<target name="-test-classes-single" depends="jar" if="test.class">
<fileset id="test.classes" dir="${build.test.classes.dir}">
<include name="${test.class}*"/>
</fileset>
</target>
<!-- only to be invoked as dependency of "test" target -->
<target name="-test-nosecurity" unless="test.class">
<fileset id="test.nosecurity.classes" dir="${build.test.classes.dir}">
<include name="**/framework/ScriptTest.class"/>
<include name="**/runtime/linker/test/*Test.class"/>
</fileset>
<testng outputdir="${build.nosecurity.test.results.dir}/${testResultsSubDir}" classfilesetref="test.nosecurity.classes"
verbose="${testng.verbose}" haltonfailure="true" useDefaultListeners="false" listeners="${testng.listeners}" workingDir="${basedir}">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx} -Dbuild.dir=${build.dir}"/>
<sysproperty key="nashorn.jar" value="${dist.dir}/nashorn.jar"/>
<propertyset>
<propertyref prefix="nashorn."/>
</propertyset>
<propertyset>
<propertyref prefix="test-sys-prop-no-security."/>
<mapper from="test-sys-prop-no-security.*" to="*" type="glob"/>
</propertyset>
<sysproperty key="optimistic.override" value="${optimistic}"/>
<classpath>
<pathelement path="${run.test.classpath}"/>
</classpath>
</testng>
</target>
<!-- only to be invoked as dependency of "test" target -->
<target name="-test-security">
<delete dir="${build.dir}/nashorn_code_cache"/>
<property name="debug.test.jvmargs" value=""/>
<testng outputdir="${build.test.results.dir}/${testResultsSubDir}" classfilesetref="test.classes"
verbose="${testng.verbose}" haltonfailure="true" useDefaultListeners="false" listeners="${testng.listeners}" workingDir="${basedir}">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx} ${run.test.jvmsecurityargs} -Dbuild.dir=${build.dir}"/>
<jvmarg line="${debug.test.jvmargs}"/>
<propertyset>
<propertyref prefix="nashorn."/>
</propertyset>
<propertyset>
<propertyref prefix="test-sys-prop."/>
<mapper from="test-sys-prop.*" to="*" type="glob"/>
</propertyset>
<sysproperty key="optimistic.override" value="${optimistic}"/>
<sysproperty key="test.js.excludes.file" value="${exclude.list}"/>
<classpath>
<pathelement path="${run.test.classpath}"/>
</classpath>
</testng>
</target>
<target name="test" depends="prepare, javadoc, test-pessimistic, test-optimistic"/>
<target name="test-optimistic" depends="jar, -test-classes-all,-test-classes-single, check-testng, check-external-tests, compile-test, generate-security-config" if="testng.available">
<echo message="Running test suite in OPTIMISTIC mode..."/>
<antcall target="-test-nosecurity" inheritRefs="true">
<param name="optimistic" value="true"/>
<param name="testResultsSubDir" value="optimistic"/>
</antcall>
<antcall target="-test-security" inheritRefs="true">
<param name="optimistic" value="true"/>
<param name="testResultsSubDir" value="optimistic"/>
</antcall>
</target>
<target name="test-pessimistic" depends="jar, -test-classes-all,-test-classes-single, check-testng, check-external-tests, compile-test, generate-security-config" if="testng.available">
<echo message="Running test suite in PESSIMISTIC mode..."/>
<antcall target="-test-nosecurity" inheritRefs="true">
<param name="optimistic" value="false"/>
<param name="testResultsSubDir" value="pessimistic"/>
</antcall>
<antcall target="-test-security" inheritRefs="true">
<param name="optimistic" value="false"/>
<param name="testResultsSubDir" value="pessimistic"/>
</antcall>
</target>
<target name="check-jemmy.jfx.testng" unless="jemmy.jfx.testng.available">
<echo message="WARNING: Jemmy or JavaFX or TestNG not available, will not run tests. Please copy TestNG and dependency JARs, JemmyCore.jar, JemmyFX.jar, JemmyAWTInput.jar to the test${file.separator}lib directory. And make sure you have jfxrt.jar in ${java.home}${file.separator}lib${file.separator}ext dir."/>
</target>
<target name="testjfx" depends="jar, check-jemmy.jfx.testng, compile-test" if="jemmy.jfx.testng.available">
<fileset id="test.classes" dir="${build.test.classes.dir}">
<include name="**/framework/*Test.class"/>
</fileset>
<copy file="${file.reference.jfxrt.jar}" todir="dist"/>
<condition property="jfx.prism.order" value="-Dprism.order=j2d" else=" ">
<not>
<os family="mac"/>
</not>
</condition>
<testng outputdir="${build.test.results.dir}" classfilesetref="test.classes"
verbose="${testng.verbose}" haltonfailure="true" useDefaultListeners="false" listeners="${testng.listeners}" workingDir="${basedir}">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx} -Dbuild.dir=${build.dir}"/>
<propertyset>
<propertyref prefix="testjfx-test-sys-prop."/>
<mapper from="testjfx-test-sys-prop.*" to="*" type="glob"/>
</propertyset>
<sysproperty key="test.fork.jvm.options" value="${testjfx-test-sys-prop.test.fork.jvm.options} ${jfx.prism.order}"/>
<classpath>
<pathelement path="${testjfx.run.test.classpath}"/>
</classpath>
</testng>
</target>
<target name="testmarkdown" depends="jar, check-testng, check-external-tests, compile-test, generate-security-config" if="testng.available">
<fileset id="test.classes" dir="${build.test.classes.dir}">
<include name="**/framework/*Test.class"/>
</fileset>
<testng outputdir="${build.test.results.dir}" classfilesetref="test.classes"
verbose="${testng.verbose}" haltonfailure="true" useDefaultListeners="false" listeners="${testng.listeners}" workingDir="${basedir}">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx} ${run.test.jvmsecurityargs} -Dbuild.dir=${build.dir}"/>
<propertyset>
<propertyref prefix="testmarkdown-test-sys-prop."/>
<mapper from="testmarkdown-test-sys-prop.*" to="*" type="glob"/>
</propertyset>
<classpath>
<pathelement path="${run.test.classpath}"/>
</classpath>
</testng>
</target>
<target name="test262" depends="jar, check-testng, check-external-tests, compile-test, generate-security-config" if="testng.available">
<fileset id="test.classes" dir="${build.test.classes.dir}">
<include name="**/framework/*Test.class"/>
</fileset>
<testng outputdir="${build.test.results.dir}" classfilesetref="test.classes"
verbose="${testng.verbose}" haltonfailure="true" useDefaultListeners="false" listeners="${testng.listeners}" workingDir="${basedir}">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx} ${run.test.jvmsecurityargs} -Dbuild.dir=${build.dir}"/>
<propertyset>
<propertyref prefix="nashorn."/>
</propertyset>
<propertyset>
<propertyref prefix="test262-test-sys-prop."/>
<mapper from="test262-test-sys-prop.*" to="*" type="glob"/>
</propertyset>
<classpath>
<pathelement path="${run.test.classpath}"/>
</classpath>
</testng>
</target>
<target name="test262parallel" depends="test262-parallel"/>
<target name="test262-parallel" depends="jar, check-testng, check-external-tests, compile-test, generate-security-config" if="testng.available">
<!-- use just build.test.classes.dir to avoid referring to TestNG -->
<java classname="${parallel.test.runner}" dir="${basedir}" fork="true" failonerror="true">
<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>
<syspropertyset>
<propertyref prefix="test262-test-sys-prop."/>
<mapper type="glob" from="test262-test-sys-prop.*" to="*"/>
</syspropertyset>
</java>
</target>
<target name="testparallel" depends="test-parallel"/>
<target name="test-parallel" depends="jar, check-testng, check-external-tests, compile-test, generate-security-config" if="testng.available">
<!-- use just build.test.classes.dir to avoid referring to TestNG -->
<java classname="${parallel.test.runner}" dir="${basedir}"
failonerror="true"
fork="true">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx} ${run.test.jvmsecurityargs}"/>
<classpath>
<pathelement path="${run.test.classpath}"/>
<pathelement path="${build.test.classes.dir}"/>
</classpath>
<syspropertyset>
<propertyref prefix="test-sys-prop."/>
<mapper type="glob" from="test-sys-prop.*" to="*"/>
</syspropertyset>
</java>
</target>
<target name="all" depends="test, docs"
description="Build, test and generate docs for nashorn"/>
<target name="run" depends="jar"
description="Run the shell with a sample script">
<java classname="${nashorn.shell.tool}" fork="true" dir="${basedir}/src/sample/nashorn">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx}"/>
<arg value="-dump-on-error"/>
<arg value="test.js"/>
</java>
</target>
<target name="debug" depends="jar"
description="Debug the shell with a sample script">
<java classname="${nashorn.shell.tool}" fork="true" dir="${basedir}/src/sample/nashorn">
<jvmarg line="${run.test.jvmargs} -Xmx${run.test.xmx}"/>
<arg value="--print-code"/>
<arg value="--verify-code"/>
<arg value="--print-symbols"/>
<jvmarg value="-Dnashorn.codegen.debug=true"/>
<arg value="test.js"/>
</java>
</target>
<!-- targets to get external script tests -->
<!-- test262 test suite -->
<target name="get-test262" depends="init" unless="${test-sys-prop.external.test262}">
<!-- 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>
</target>
<target name="update-test262" depends="init" if="${test-sys-prop.external.test262}">
<!-- update test262 git repo -->
<exec executable="${git.executable}" dir="${test.external.dir}/test262">
<arg value="pull"/>
</exec>
</target>
<!-- octane benchmark -->
<target name="get-octane" depends="init" unless="${test-sys-prop.external.octane}">
<!-- checkout octane benchmarks -->
<exec executable="${git.executable}">
<arg value="clone"/>
<arg value="https://github.com/chromium/octane"/>
<arg value="${test.external.dir}/octane"/>
</exec>
</target>
<target name="update-octane" depends="init" if="${test-sys-prop.external.octane}">
<!-- update octane benchmarks -->
<exec executable="${git.executable}" dir="${test.external.dir}/octane">
<arg value="pull"/>
</exec>
</target>
<!-- sunspider benchmark -->
<target name="get-sunspider" depends="init" unless="${test-sys-prop.external.sunspider}">
<!-- checkout sunspider -->
<exec executable="${svn.executable}">
<arg value="--non-interactive"/>
<arg value="--trust-server-cert"/>
<arg value="checkout"/>
<arg value="http://svn.webkit.org/repository/webkit/trunk/PerformanceTests/SunSpider"/>
<arg value="${test.external.dir}/sunspider"/>
</exec>
</target>
<target name="update-sunspider" depends="init" if="${test-sys-prop.external.sunspider}">
<!-- update sunspider -->
<exec executable="${svn.executable}" dir="${test.external.dir}/sunspider">
<arg value="--non-interactive"/>
<arg value="--trust-server-cert"/>
<arg value="update"/>
</exec>
</target>
<!-- get all external test scripts -->
<target name="externals" depends="init, check-external-tests, get-test262, get-octane, get-sunspider">
<!-- make external test dir -->
<mkdir dir="${test.external.dir}"/>
<!-- jquery -->
<mkdir dir="${test.external.dir}/jquery"/>
<get src="http://code.jquery.com/jquery-1.7.2.js" dest="${test.external.dir}/jquery" skipexisting="true" ignoreerrors="true"/>
<get src="http://code.jquery.com/jquery-1.7.2.min.js" dest="${test.external.dir}/jquery" skipexisting="true" ignoreerrors="true"/>
<!-- prototype -->
<mkdir dir="${test.external.dir}/prototype"/>
<get src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.0/prototype.js" dest="${test.external.dir}/prototype" usetimestamp="true" skipexisting="true" ignoreerrors="true"/>
<!-- underscorejs -->
<mkdir dir="${test.external.dir}/underscore"/>
<get src="http://underscorejs.org/underscore.js" dest="${test.external.dir}/underscore" skipexisting="true" ignoreerrors="true" tryGzipEncoding="true"/>
<get src="http://underscorejs.org/underscore-min.js" dest="${test.external.dir}/underscore" skipexisting="true" ignoreerrors="true" tryGzipEncoding="true"/>
<!-- yui -->
<mkdir dir="${test.external.dir}/yui"/>
<get src="http://yui.yahooapis.com/3.5.1/build/yui/yui.js" dest="${test.external.dir}/yui" skipexisting="true" ignoreerrors="true" tryGzipEncoding="true"/>
<get src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js" dest="${test.external.dir}/yui" skipexisting="true" ignoreerrors="true" tryGzipEncoding="true"/>
<!-- showdown -->
<mkdir dir="${test.external.dir}/showdown"/>
<get src="https://raw.githubusercontent.com/showdownjs/showdown/0.5.4/src/showdown.js" dest="${test.external.dir}/showdown" skipexisting="true" ignoreerrors="true"/>
<get src="https://raw.githubusercontent.com/showdownjs/showdown/0.5.4/src/extensions/table.js" dest="${test.external.dir}/showdown" skipexisting="true" ignoreerrors="true"/>
</target>
<!-- update external test suites that are pulled from source control systems -->
<target name="update-externals" depends="init, check-external-tests, update-test262, update-octane, update-sunspider"/>
<!-- run all perf tests -->
<target name="perf" depends="externals, update-externals, sunspider, octane"/>
<!-- download and install testng.jar -->
<target name="get-testng">
<get dest="${test.lib}" skipexisting="true">
<url url="http://central.maven.org/maven2/org/testng/testng/6.8/testng-6.8.jar"/>
<url url="http://central.maven.org/maven2/com/beust/jcommander/1.27/jcommander-1.27.jar"/>
<url url="http://central.maven.org/maven2/org/beanshell/bsh/2.0b4/bsh-2.0b4.jar"/>
<url url="http://central.maven.org/maven2/org/yaml/snakeyaml/1.6/snakeyaml-1.6.jar"/>
</get>
</target>
<!-- download and install asmtools.jar -->
<target name="get-asmtools" unless="asmtools.already.present">
<get src="https://adopt-openjdk.ci.cloudbees.com/view/OpenJDK/job/asmtools/lastSuccessfulBuild/artifact/asmtools-6.0.tar.gz" dest="${test.lib}" skipexisting="true" ignoreerrors="true"/>
<untar src="${test.lib}${file.separator}asmtools-6.0.tar.gz" dest="${test.lib}" compression="gzip"/>
<!-- they are tar.gz'ing a .zip file! -->
<unzip src="${test.lib}${file.separator}asmtools-6.0.zip" dest="${test.lib}">
<patternset>
<include name="asmtools-6.0/lib/asmtools.jar"/>
</patternset>
</unzip>
<move file="${test.lib}${file.separator}asmtools-6.0${file.separator}lib${file.separator}asmtools.jar" tofile="${test.lib}${file.separator}asmtools.jar"/>
<delete dir="${test.lib}${file.separator}asmtools-6.0"/>
</target>
<!-- run all tests -->
<target name="alltests" depends="externals, update-externals, test, test262parallel, testmarkdown, perf"/>
<import file="build-benchmark.xml"/>
</project>

View file

@ -1,34 +0,0 @@
Nasgen is a tool for processing Java classes that implement native
JavaScript objects. It does so by looking for the
com.oracle.nashorn.objects.annotations.ScriptClass annotation and other
annotations in that package.
For each class "C", nasgen instruments the original class and generates
two additional classes: a "C$Prototype" class for the JavaScript
prototype object, and a "C$Constructor" class for the JavaScript
constructor function.
Each class instrumented or generated by nasgen contains a private static
"$nasgenmap$" field of type com.oracle.nashorn.runtime.PropertyMap and
static initializer block to initialize the field to the object's
JavaScript properties.
Members annotated with @Function, @Property, @Getter, and @Setter are
mapped to the $Constructor, $Prototype, or main class, depending on the
value of the annotation's 'where' field. By default, @Property, @Getter,
and @Setter belong to the main class while @Function methods without
explicit 'where' field belong to the $Prototype class. The @Constructor
annotation marks a method to be invoked as JavaScript constructor.
Nasgen enforces all @Function/@Getter/@Setter/@Constructor annotated
methods to be declared as static. Static final @Property fields remain
in the main class while other @Property fields are moved to respective
classes depending on the annotation's 'where' value. For functions
mapped to the $Prototype or $Constructor class, nasgen also generates
getters and setters prefixed by G$ and S$, respectively.
Nasgen-generated classes are hidden from normal ClassLoaders by giving
them a ".clazz" file name extension instead of the standard ".class"
extension. This allows script classes to be loaded independently by each
Nashorn context through the com.oracle.nashorn.runtime.StructureLoader
class loader.

View file

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project name="nasgen" default="all" basedir=".">
<target name="init">
<loadproperties srcFile="project.properties"/>
</target>
<target name="prepare" depends="init">
<mkdir dir="${nasgen.build.classes.dir}"/>
<mkdir dir="${nasgen.dist.dir}"/>
<mkdir dir="${nasgen.dist.dir}/lib"/>
</target>
<target name="clean" depends="init">
<delete dir="${nasgen.build.dir}"/>
<delete dir="${nasgen.dist.dir}"/>
</target>
<target name="compile" depends="prepare" description="Compiles the nasgen sources">
<javac srcdir="${src.dir}"
destdir="${nasgen.build.classes.dir}"
debug="${javac.debug}"
includeantruntime="false" fork="true">
<compilerarg line="${nasgen.module.imports}"/>
<compilerarg value="-Xlint:unchecked"/>
<compilerarg value="-Xlint:deprecation"/>
<compilerarg value="-XDignore.symbol.file"/>
</javac>
</target>
<target name="jar" depends="compile" description="Creates nasgen.jar">
<jar jarfile="${nasgen.dist.jar}" basedir="${nasgen.build.classes.dir}" manifest="${meta.inf.dir}/MANIFEST.MF"/>
</target>
<target name="dist" depends="jar"/>
<target name="all" depends="dist"
description="Builds sources and generates nasgen.jar"/>
</project>

View file

@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/build/classes" />
<output-test url="file://$MODULE_DIR$/build/test/classes" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/build" />
<excludeFolder url="file://$MODULE_DIR$/dist" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="asm" />
</component>
</module>

View file

@ -1,48 +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.
#
# 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.
#
application.title=nasgen
# source and target levels
build.compiler=modern
# This directory is removed when the project is cleaned:
nasgen.build.dir=../../../../build/nashorn/nasgen
nasgen.build.classes.dir=${nasgen.build.dir}/classes
# This directory is removed when the project is cleaned:
nasgen.dist.dir=${nasgen.build.dir}/dist
nasgen.dist.jar=${nasgen.dist.dir}/nasgen.jar
nasgen.dist.javadoc.dir=${nasgen.dist.dir}/javadoc
javac.debug=true
nasgen.module.imports=\
--add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
--add-exports java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED
meta.inf.dir=${src.dir}/META-INF
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
run.jvmargs=
src.dir=src

View file

@ -1,4 +0,0 @@
Manifest-Version: 1.0
Class-Path: lib/ant-1.7.1.jar
Main-Class: jdk.nashorn.internal.tools.nasgen.Main

View file

@ -1,397 +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.tools.nasgen;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKESTATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKEVIRTUAL;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_CREATE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_CREATE_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.ARRAYLIST_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.ARRAYLIST_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.CLINIT;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTIONS_EMPTY_LIST;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTIONS_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_ADD;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_ADD_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.GETTER_PREFIX;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.GET_CLASS_NAME;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.GET_CLASS_NAME_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.LIST_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.NATIVESYMBOL_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_NEWMAP;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_NEWMAP_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_CREATEBUILTIN;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_CREATEBUILTIN_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_CREATEBUILTIN_SPECS_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETARITY;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETARITY_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETDOCUMENTATIONKEY;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETDOCUMENTATIONKEY_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SETTER_PREFIX;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SYMBOL_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SYMBOL_PREFIX;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.TYPE_OBJECT;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import jdk.internal.org.objectweb.asm.ClassReader;
import jdk.internal.org.objectweb.asm.ClassVisitor;
import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.FieldVisitor;
import jdk.internal.org.objectweb.asm.Handle;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.Type;
import jdk.nashorn.internal.tools.nasgen.MemberInfo.Kind;
/**
* Base class for class generator classes.
*
*/
public class ClassGenerator {
/** ASM class writer used to output bytecode for this class */
protected final ClassWriter cw;
/**
* Constructor
*/
protected ClassGenerator() {
this.cw = makeClassWriter();
}
MethodGenerator makeStaticInitializer() {
return makeStaticInitializer(cw);
}
MethodGenerator makeConstructor() {
return makeConstructor(cw);
}
MethodGenerator makeMethod(final int access, final String name, final String desc) {
return makeMethod(cw, access, name, desc);
}
void addMapField() {
addMapField(cw);
}
void addField(final String name, final String desc) {
addField(cw, name, desc);
}
void addFunctionField(final String name) {
addFunctionField(cw, name);
}
void addGetter(final String owner, final MemberInfo memInfo) {
addGetter(cw, owner, memInfo);
}
void addSetter(final String owner, final MemberInfo memInfo) {
addSetter(cw, owner, memInfo);
}
void emitGetClassName(final String name) {
final MethodGenerator mi = makeMethod(ACC_PUBLIC, GET_CLASS_NAME, GET_CLASS_NAME_DESC);
mi.loadLiteral(name);
mi.returnValue();
mi.computeMaxs();
mi.visitEnd();
}
static ClassWriter makeClassWriter() {
return new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
@Override
protected String getCommonSuperClass(final String type1, final String type2) {
try {
return super.getCommonSuperClass(type1, type2);
} catch (final RuntimeException | LinkageError e) {
if (MemberInfo.isScriptObject(type1) && MemberInfo.isScriptObject(type2)) {
return StringConstants.SCRIPTOBJECT_TYPE;
}
return StringConstants.OBJECT_TYPE;
}
}
};
}
static MethodGenerator makeStaticInitializer(final ClassVisitor cv) {
return makeStaticInitializer(cv, CLINIT);
}
static MethodGenerator makeStaticInitializer(final ClassVisitor cv, final String name) {
final int access = ACC_PUBLIC | ACC_STATIC;
final String desc = DEFAULT_INIT_DESC;
final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null);
return new MethodGenerator(mv, access, name, desc);
}
static MethodGenerator makeConstructor(final ClassVisitor cv) {
final int access = 0;
final String name = INIT;
final String desc = DEFAULT_INIT_DESC;
final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null);
return new MethodGenerator(mv, access, name, desc);
}
static MethodGenerator makeMethod(final ClassVisitor cv, final int access, final String name, final String desc) {
final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null);
return new MethodGenerator(mv, access, name, desc);
}
static void emitStaticInitPrefix(final MethodGenerator mi, final String className, final int memberCount) {
mi.visitCode();
if (memberCount > 0) {
// new ArrayList(int)
mi.newObject(ARRAYLIST_TYPE);
mi.dup();
mi.push(memberCount);
mi.invokeSpecial(ARRAYLIST_TYPE, INIT, ARRAYLIST_INIT_DESC);
// stack: ArrayList
} else {
// java.util.Collections.EMPTY_LIST
mi.getStatic(COLLECTIONS_TYPE, COLLECTIONS_EMPTY_LIST, LIST_DESC);
// stack List
}
}
static void emitStaticInitSuffix(final MethodGenerator mi, final String className) {
// stack: Collection
// pmap = PropertyMap.newMap(Collection<Property>);
mi.invokeStatic(PROPERTYMAP_TYPE, PROPERTYMAP_NEWMAP, PROPERTYMAP_NEWMAP_DESC);
// $nasgenmap$ = pmap;
mi.putStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC);
mi.returnVoid();
mi.computeMaxs();
mi.visitEnd();
}
@SuppressWarnings("fallthrough")
private static Type memInfoType(final MemberInfo memInfo) {
switch (memInfo.getJavaDesc().charAt(0)) {
case 'I': return Type.INT_TYPE;
case 'J': return Type.LONG_TYPE;
case 'D': return Type.DOUBLE_TYPE;
default: assert false : memInfo.getJavaDesc();
case 'L': return TYPE_OBJECT;
}
}
private static String getterDesc(final MemberInfo memInfo) {
return Type.getMethodDescriptor(memInfoType(memInfo));
}
private static String setterDesc(final MemberInfo memInfo) {
return Type.getMethodDescriptor(Type.VOID_TYPE, memInfoType(memInfo));
}
static void addGetter(final ClassVisitor cv, final String owner, final MemberInfo memInfo) {
final int access = ACC_PUBLIC;
final String name = GETTER_PREFIX + memInfo.getJavaName();
final String desc = getterDesc(memInfo);
final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null);
final MethodGenerator mi = new MethodGenerator(mv, access, name, desc);
mi.visitCode();
if (memInfo.isStatic() && memInfo.getKind() == Kind.PROPERTY) {
mi.getStatic(owner, memInfo.getJavaName(), memInfo.getJavaDesc());
} else {
mi.loadLocal(0);
mi.getField(owner, memInfo.getJavaName(), memInfo.getJavaDesc());
}
mi.returnValue();
mi.computeMaxs();
mi.visitEnd();
}
static void addSetter(final ClassVisitor cv, final String owner, final MemberInfo memInfo) {
final int access = ACC_PUBLIC;
final String name = SETTER_PREFIX + memInfo.getJavaName();
final String desc = setterDesc(memInfo);
final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null);
final MethodGenerator mi = new MethodGenerator(mv, access, name, desc);
mi.visitCode();
if (memInfo.isStatic() && memInfo.getKind() == Kind.PROPERTY) {
mi.loadLocal(1);
mi.putStatic(owner, memInfo.getJavaName(), memInfo.getJavaDesc());
} else {
mi.loadLocal(0);
mi.loadLocal(1);
mi.putField(owner, memInfo.getJavaName(), memInfo.getJavaDesc());
}
mi.returnVoid();
mi.computeMaxs();
mi.visitEnd();
}
static void addMapField(final ClassVisitor cv) {
// add a PropertyMap static field
final FieldVisitor fv = cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL,
PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC, null, null);
if (fv != null) {
fv.visitEnd();
}
}
static void addField(final ClassVisitor cv, final String name, final String desc) {
final FieldVisitor fv = cv.visitField(ACC_PRIVATE, name, desc, null, null);
if (fv != null) {
fv.visitEnd();
}
}
static void addFunctionField(final ClassVisitor cv, final String name) {
addField(cv, name, OBJECT_DESC);
}
static void newFunction(final MethodGenerator mi, final String objName, final String className, final MemberInfo memInfo, final List<MemberInfo> specs) {
final boolean arityFound = (memInfo.getArity() != MemberInfo.DEFAULT_ARITY);
loadFunctionName(mi, memInfo.getName());
mi.visitLdcInsn(new Handle(H_INVOKESTATIC, className, memInfo.getJavaName(), memInfo.getJavaDesc(), false));
assert specs != null;
if (!specs.isEmpty()) {
mi.memberInfoArray(className, specs);
mi.invokeStatic(SCRIPTFUNCTION_TYPE, SCRIPTFUNCTION_CREATEBUILTIN, SCRIPTFUNCTION_CREATEBUILTIN_SPECS_DESC);
} else {
mi.invokeStatic(SCRIPTFUNCTION_TYPE, SCRIPTFUNCTION_CREATEBUILTIN, SCRIPTFUNCTION_CREATEBUILTIN_DESC);
}
if (arityFound) {
mi.dup();
mi.push(memInfo.getArity());
mi.invokeVirtual(SCRIPTFUNCTION_TYPE, SCRIPTFUNCTION_SETARITY, SCRIPTFUNCTION_SETARITY_DESC);
}
mi.dup();
mi.loadLiteral(memInfo.getDocumentationKey(objName));
mi.invokeVirtual(SCRIPTFUNCTION_TYPE, SCRIPTFUNCTION_SETDOCUMENTATIONKEY, SCRIPTFUNCTION_SETDOCUMENTATIONKEY_DESC);
}
static void linkerAddGetterSetter(final MethodGenerator mi, final String className, final MemberInfo memInfo) {
final String propertyName = memInfo.getName();
// stack: Collection
// dup of Collection instance
mi.dup();
// Load property name, converting to Symbol if it begins with "@@"
loadPropertyKey(mi, propertyName);
// setup flags
mi.push(memInfo.getAttributes());
// setup getter method handle
String javaName = GETTER_PREFIX + memInfo.getJavaName();
mi.visitLdcInsn(new Handle(H_INVOKEVIRTUAL, className, javaName, getterDesc(memInfo), false));
// setup setter method handle
if (memInfo.isFinal()) {
mi.pushNull();
} else {
javaName = SETTER_PREFIX + memInfo.getJavaName();
mi.visitLdcInsn(new Handle(H_INVOKEVIRTUAL, className, javaName, setterDesc(memInfo), false));
}
// property = AccessorProperty.create(key, flags, getter, setter);
mi.invokeStatic(ACCESSORPROPERTY_TYPE, ACCESSORPROPERTY_CREATE, ACCESSORPROPERTY_CREATE_DESC);
// boolean Collection.add(property)
mi.invokeInterface(COLLECTION_TYPE, COLLECTION_ADD, COLLECTION_ADD_DESC);
// pop return value of Collection.add
mi.pop();
// stack: Collection
}
static void linkerAddGetterSetter(final MethodGenerator mi, final String className, final MemberInfo getter, final MemberInfo setter) {
final String propertyName = getter.getName();
// stack: Collection
// dup of Collection instance
mi.dup();
// Load property name, converting to Symbol if it begins with "@@"
loadPropertyKey(mi, propertyName);
// setup flags
mi.push(getter.getAttributes());
// setup getter method handle
mi.visitLdcInsn(new Handle(H_INVOKESTATIC, className,
getter.getJavaName(), getter.getJavaDesc(), false));
// setup setter method handle
if (setter == null) {
mi.pushNull();
} else {
mi.visitLdcInsn(new Handle(H_INVOKESTATIC, className,
setter.getJavaName(), setter.getJavaDesc(), false));
}
// property = AccessorProperty.create(key, flags, getter, setter);
mi.invokeStatic(ACCESSORPROPERTY_TYPE, ACCESSORPROPERTY_CREATE, ACCESSORPROPERTY_CREATE_DESC);
// boolean Collection.add(property)
mi.invokeInterface(COLLECTION_TYPE, COLLECTION_ADD, COLLECTION_ADD_DESC);
// pop return value of Collection.add
mi.pop();
// stack: Collection
}
static ScriptClassInfo getScriptClassInfo(final String fileName) throws IOException {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName))) {
return getScriptClassInfo(new ClassReader(bis));
}
}
static ScriptClassInfo getScriptClassInfo(final byte[] classBuf) {
return getScriptClassInfo(new ClassReader(classBuf));
}
private static void loadFunctionName(final MethodGenerator mi, final String propertyName) {
if (propertyName.startsWith(SYMBOL_PREFIX)) {
mi.loadLiteral("Symbol[" + propertyName.substring(2) + "]");
} else {
mi.loadLiteral(propertyName);
}
}
private static void loadPropertyKey(final MethodGenerator mi, final String propertyName) {
if (propertyName.startsWith(SYMBOL_PREFIX)) {
mi.getStatic(NATIVESYMBOL_TYPE, propertyName.substring(2), SYMBOL_DESC);
} else {
mi.loadLiteral(propertyName);
}
}
private static ScriptClassInfo getScriptClassInfo(final ClassReader reader) {
final ScriptClassInfoCollector scic = new ScriptClassInfoCollector();
reader.accept(scic, 0);
return scic.getScriptClassInfo();
}
}

View file

@ -1,281 +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.tools.nasgen;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKESTATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.V1_7;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.CONSTRUCTOR_SUFFIX;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_SETCONSTRUCTOR;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_INIT_DESC3;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_INIT_DESC4;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETARITY;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETARITY_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETDOCUMENTATIONKEY;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETDOCUMENTATIONKEY_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETPROTOTYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETPROTOTYPE_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTOBJECT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTOBJECT_TYPE;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import jdk.internal.org.objectweb.asm.Handle;
/**
* This class generates constructor class for a @ScriptClass annotated class.
*
*/
public class ConstructorGenerator extends ClassGenerator {
private final ScriptClassInfo scriptClassInfo;
private final String className;
private final MemberInfo constructor;
private final int memberCount;
private final List<MemberInfo> specs;
ConstructorGenerator(final ScriptClassInfo sci) {
this.scriptClassInfo = sci;
this.className = scriptClassInfo.getConstructorClassName();
this.constructor = scriptClassInfo.getConstructor();
this.memberCount = scriptClassInfo.getConstructorMemberCount();
this.specs = scriptClassInfo.getSpecializedConstructors();
}
byte[] getClassBytes() {
// new class extending from ScriptObject
final String superClass = (constructor != null)? SCRIPTFUNCTION_TYPE : SCRIPTOBJECT_TYPE;
cw.visit(V1_7, ACC_FINAL, className, null, superClass, null);
if (memberCount > 0) {
// add fields
emitFields();
// add <clinit>
emitStaticInitializer();
}
// add <init>
emitConstructor();
if (constructor == null) {
emitGetClassName(scriptClassInfo.getName());
}
cw.visitEnd();
return cw.toByteArray();
}
// --Internals only below this point
private void emitFields() {
// Introduce "Function" type instance fields for each
// constructor @Function in script class and introduce instance
// fields for each constructor @Property in the script class.
for (MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isConstructorFunction()) {
addFunctionField(memInfo.getJavaName());
memInfo = (MemberInfo)memInfo.clone();
memInfo.setJavaDesc(OBJECT_DESC);
memInfo.setJavaAccess(ACC_PUBLIC);
addGetter(className, memInfo);
addSetter(className, memInfo);
} else if (memInfo.isConstructorProperty()) {
if (memInfo.isStaticFinal()) {
addGetter(scriptClassInfo.getJavaName(), memInfo);
} else {
addField(memInfo.getJavaName(), memInfo.getJavaDesc());
memInfo = (MemberInfo)memInfo.clone();
memInfo.setJavaAccess(ACC_PUBLIC);
addGetter(className, memInfo);
addSetter(className, memInfo);
}
}
}
addMapField();
}
private void emitStaticInitializer() {
final MethodGenerator mi = makeStaticInitializer();
emitStaticInitPrefix(mi, className, memberCount);
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isConstructorFunction() || memInfo.isConstructorProperty()) {
linkerAddGetterSetter(mi, className, memInfo);
} else if (memInfo.isConstructorGetter()) {
final MemberInfo setter = scriptClassInfo.findSetter(memInfo);
linkerAddGetterSetter(mi, scriptClassInfo.getJavaName(), memInfo, setter);
}
}
emitStaticInitSuffix(mi, className);
}
private void emitConstructor() {
final MethodGenerator mi = makeConstructor();
mi.visitCode();
callSuper(mi);
if (memberCount > 0) {
// initialize Function type fields
initFunctionFields(mi);
// initialize data fields
initDataFields(mi);
}
if (constructor != null) {
initPrototype(mi);
final int arity = constructor.getArity();
if (arity != MemberInfo.DEFAULT_ARITY) {
mi.loadThis();
mi.push(arity);
mi.invokeVirtual(SCRIPTFUNCTION_TYPE, SCRIPTFUNCTION_SETARITY,
SCRIPTFUNCTION_SETARITY_DESC);
}
mi.loadThis();
mi.loadLiteral(scriptClassInfo.getName());
mi.invokeVirtual(SCRIPTFUNCTION_TYPE, SCRIPTFUNCTION_SETDOCUMENTATIONKEY,
SCRIPTFUNCTION_SETDOCUMENTATIONKEY_DESC);
}
mi.returnVoid();
mi.computeMaxs();
mi.visitEnd();
}
private void loadMap(final MethodGenerator mi) {
if (memberCount > 0) {
mi.getStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC);
}
}
private void callSuper(final MethodGenerator mi) {
String superClass, superDesc;
mi.loadThis();
if (constructor == null) {
// call ScriptObject.<init>
superClass = SCRIPTOBJECT_TYPE;
superDesc = (memberCount > 0) ? SCRIPTOBJECT_INIT_DESC : DEFAULT_INIT_DESC;
loadMap(mi);
} else {
// call Function.<init>
superClass = SCRIPTFUNCTION_TYPE;
superDesc = (memberCount > 0) ? SCRIPTFUNCTION_INIT_DESC4 : SCRIPTFUNCTION_INIT_DESC3;
mi.loadLiteral(constructor.getName());
mi.visitLdcInsn(new Handle(H_INVOKESTATIC, scriptClassInfo.getJavaName(), constructor.getJavaName(), constructor.getJavaDesc(), false));
loadMap(mi);
mi.memberInfoArray(scriptClassInfo.getJavaName(), specs); //pushes null if specs empty
}
mi.invokeSpecial(superClass, INIT, superDesc);
}
private void initFunctionFields(final MethodGenerator mi) {
assert memberCount > 0;
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (!memInfo.isConstructorFunction()) {
continue;
}
mi.loadThis();
newFunction(mi, scriptClassInfo.getName(), scriptClassInfo.getJavaName(), memInfo, scriptClassInfo.findSpecializations(memInfo.getJavaName()));
mi.putField(className, memInfo.getJavaName(), OBJECT_DESC);
}
}
private void initDataFields(final MethodGenerator mi) {
assert memberCount > 0;
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (!memInfo.isConstructorProperty() || memInfo.isFinal()) {
continue;
}
final Object value = memInfo.getValue();
if (value != null) {
mi.loadThis();
mi.loadLiteral(value);
mi.putField(className, memInfo.getJavaName(), memInfo.getJavaDesc());
} else if (!memInfo.getInitClass().isEmpty()) {
final String clazz = memInfo.getInitClass();
mi.loadThis();
mi.newObject(clazz);
mi.dup();
mi.invokeSpecial(clazz, INIT, DEFAULT_INIT_DESC);
mi.putField(className, memInfo.getJavaName(), memInfo.getJavaDesc());
}
}
}
private void initPrototype(final MethodGenerator mi) {
assert constructor != null;
mi.loadThis();
final String protoName = scriptClassInfo.getPrototypeClassName();
mi.newObject(protoName);
mi.dup();
mi.invokeSpecial(protoName, INIT, DEFAULT_INIT_DESC);
mi.dup();
mi.loadThis();
mi.invokeStatic(PROTOTYPEOBJECT_TYPE, PROTOTYPEOBJECT_SETCONSTRUCTOR,
PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC);
mi.invokeVirtual(SCRIPTFUNCTION_TYPE, SCRIPTFUNCTION_SETPROTOTYPE, SCRIPTFUNCTION_SETPROTOTYPE_DESC);
}
/**
* Entry point for ConstructorGenerator run separately as an application. Will display
* usage. Takes one argument, a class name.
* @param args args vector
* @throws IOException if class can't be read
*/
public static void main(final String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: " + ConstructorGenerator.class.getName() + " <class>");
System.exit(1);
}
final String className = args[0].replace('.', '/');
final ScriptClassInfo sci = getScriptClassInfo(className + ".class");
if (sci == null) {
System.err.println("No @ScriptClass in " + className);
System.exit(2);
throw new IOException(); // get rid of warning for sci.verify() below - may be null
}
try {
sci.verify();
} catch (final Exception e) {
System.err.println(e.getMessage());
System.exit(3);
}
final ConstructorGenerator gen = new ConstructorGenerator(sci);
try (FileOutputStream fos = new FileOutputStream(className + CONSTRUCTOR_SUFFIX + ".class")) {
fos.write(gen.getClassBytes());
}
}
}

View file

@ -1,187 +0,0 @@
/*
* Copyright (c) 2010, 2018, 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.tools.nasgen;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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;
/**
* Main class for the "nasgen" tool.
*
*/
public class Main {
/**
* ASM version to be used by nasgen tool.
*/
public static final int ASM_VERSION = Opcodes.ASM7;
private static final boolean DEBUG = Boolean.getBoolean("nasgen.debug");
private interface ErrorReporter {
public void error(String msg);
}
/**
* Public entry point for Nasgen if invoked from command line. Nasgen takes three arguments
* in order: input directory, package list, output directory
*
* @param args argument vector
*/
public static void main(final String[] args) {
final ErrorReporter reporter = new ErrorReporter() {
@Override
public void error(final String msg) {
Main.error(msg, 1);
}
};
if (args.length == 3) {
processAll(args[0], args[1], args[2], reporter);
} else {
error("Usage: nasgen <input-dir> <package-list> <output-dir>", 1);
}
}
private static void processAll(final String in, final String pkgList, final String out, final ErrorReporter reporter) {
final File inDir = new File(in);
if (!inDir.exists() || !inDir.isDirectory()) {
reporter.error(in + " does not exist or not a directory");
return;
}
final File outDir = new File(out);
if (!outDir.exists() || !outDir.isDirectory()) {
reporter.error(out + " does not exist or not a directory");
return;
}
final String[] packages = pkgList.split(":");
for (String pkg : packages) {
pkg = pkg.replace('.', File.separatorChar);
final File dir = new File(inDir, pkg);
final File[] classes = dir.listFiles();
for (final File clazz : classes) {
if (clazz.isFile() && clazz.getName().endsWith(".class")) {
if (! process(clazz, new File(outDir, pkg), reporter)) {
return;
}
}
}
}
}
private static boolean process(final File inFile, final File outDir, final ErrorReporter reporter) {
try {
byte[] buf = new byte[(int)inFile.length()];
try (FileInputStream fin = new FileInputStream(inFile)) {
fin.read(buf);
}
final ScriptClassInfo sci = ClassGenerator.getScriptClassInfo(buf);
if (sci != null) {
try {
sci.verify();
} catch (final Exception e) {
reporter.error(e.getMessage());
return false;
}
// create necessary output package dir
outDir.mkdirs();
// instrument @ScriptClass
final ClassWriter writer = ClassGenerator.makeClassWriter();
final ClassReader reader = new ClassReader(buf);
final ScriptClassInstrumentor inst = new ScriptClassInstrumentor(writer, sci);
reader.accept(inst, 0);
//noinspection UnusedAssignment
// write instrumented class
try (FileOutputStream fos = new FileOutputStream(new File(outDir, inFile.getName()))) {
buf = writer.toByteArray();
if (DEBUG) {
verify(buf);
}
fos.write(buf);
}
// simple class name without package prefix
String simpleName = inFile.getName();
simpleName = simpleName.substring(0, simpleName.indexOf(".class"));
if (sci.isPrototypeNeeded()) {
// generate prototype class
final PrototypeGenerator protGen = new PrototypeGenerator(sci);
buf = protGen.getClassBytes();
if (DEBUG) {
verify(buf);
}
try (FileOutputStream fos = new FileOutputStream(new File(outDir, simpleName + StringConstants.PROTOTYPE_SUFFIX + ".class"))) {
fos.write(buf);
}
}
if (sci.isConstructorNeeded()) {
// generate constructor class
final ConstructorGenerator consGen = new ConstructorGenerator(sci);
buf = consGen.getClassBytes();
if (DEBUG) {
verify(buf);
}
try (FileOutputStream fos = new FileOutputStream(new File(outDir, simpleName + StringConstants.CONSTRUCTOR_SUFFIX + ".class"))) {
fos.write(buf);
}
}
}
return true;
} catch (final IOException | RuntimeException e) {
if (DEBUG) {
e.printStackTrace(System.err);
}
reporter.error(e.getMessage());
return false;
}
}
private static void verify(final byte[] buf) {
final ClassReader cr = new ClassReader(buf);
CheckClassAdapter.verify(cr, false, new PrintWriter(System.err));
}
private static void error(final String msg, final int exitCode) {
System.err.println(msg);
System.exit(exitCode);
}
}

View file

@ -1,613 +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.tools.nasgen;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_ARRAY_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJ_PKG;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.RUNTIME_PKG;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTS_PKG;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.STRING_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.TYPE_SYMBOL;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.org.objectweb.asm.Type;
/**
* Details about a Java method or field annotated with any of the field/method
* annotations from the jdk.nashorn.internal.objects.annotations package.
*/
public final class MemberInfo implements Cloneable {
// class loader of this class
private static final ClassLoader MY_LOADER = MemberInfo.class.getClassLoader();
/**
* The different kinds of available class annotations
*/
public static enum Kind {
/**
* This is a script class
*/
SCRIPT_CLASS,
/**
* This is a constructor
*/
CONSTRUCTOR,
/**
* This is a function
*/
FUNCTION,
/**
* This is a getter
*/
GETTER,
/**
* This is a setter
*/
SETTER,
/**
* This is a property
*/
PROPERTY,
/**
* This is a specialized version of a function
*/
SPECIALIZED_FUNCTION,
}
// keep in sync with jdk.nashorn.internal.objects.annotations.Attribute
static final int DEFAULT_ATTRIBUTES = 0x0;
static final int DEFAULT_ARITY = -2;
// the kind of the script annotation - one of the above constants
private MemberInfo.Kind kind;
// script property name
private String name;
// script property attributes
private int attributes;
// name of the java member
private String javaName;
// type descriptor of the java member
private String javaDesc;
// access bits of the Java field or method
private int javaAccess;
// initial value for static @Property fields
private Object value;
// class whose object is created to fill property value
private String initClass;
// arity of the Function or Constructor
private int arity;
private Where where;
private Type linkLogicClass;
private boolean isSpecializedConstructor;
private boolean isOptimistic;
private boolean convertsNumericArgs;
/**
* @return the kind
*/
public Kind getKind() {
return kind;
}
/**
* @param kind the kind to set
*/
public void setKind(final Kind kind) {
this.kind = kind;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(final String name) {
this.name = name;
}
/**
* Tag something as specialized constructor or not
* @param isSpecializedConstructor boolean, true if specialized constructor
*/
public void setIsSpecializedConstructor(final boolean isSpecializedConstructor) {
this.isSpecializedConstructor = isSpecializedConstructor;
}
/**
* Check if something is a specialized constructor
* @return true if specialized constructor
*/
public boolean isSpecializedConstructor() {
return isSpecializedConstructor;
}
/**
* Check if this is an optimistic builtin function
* @return true if optimistic builtin
*/
public boolean isOptimistic() {
return isOptimistic;
}
/**
* Tag something as optimistic builtin or not
* @param isOptimistic boolean, true if builtin constructor
*/
public void setIsOptimistic(final boolean isOptimistic) {
this.isOptimistic = isOptimistic;
}
/**
* Check if this function converts arguments for numeric parameters to numbers
* so it's safe to pass booleans as 0 and 1
* @return true if it is safe to convert arguments to numbers
*/
public boolean convertsNumericArgs() {
return convertsNumericArgs;
}
/**
* Tag this as a function that converts arguments for numeric params to numbers
* @param convertsNumericArgs if true args can be safely converted to numbers
*/
public void setConvertsNumericArgs(final boolean convertsNumericArgs) {
this.convertsNumericArgs = convertsNumericArgs;
}
/**
* Get the SpecializedFunction guard for specializations, i.e. optimistic
* builtins
* @return specialization, null if none
*/
public Type getLinkLogicClass() {
return linkLogicClass;
}
/**
* Set the SpecializedFunction link logic class for specializations, i.e. optimistic
* builtins
* @param linkLogicClass link logic class
*/
public void setLinkLogicClass(final Type linkLogicClass) {
this.linkLogicClass = linkLogicClass;
}
/**
* @return the attributes
*/
public int getAttributes() {
return attributes;
}
/**
* @param attributes the attributes to set
*/
public void setAttributes(final int attributes) {
this.attributes = attributes;
}
/**
* @return the javaName
*/
public String getJavaName() {
return javaName;
}
/**
* @param javaName the javaName to set
*/
public void setJavaName(final String javaName) {
this.javaName = javaName;
}
/**
* @return the javaDesc
*/
public String getJavaDesc() {
return javaDesc;
}
void setJavaDesc(final String javaDesc) {
this.javaDesc = javaDesc;
}
int getJavaAccess() {
return javaAccess;
}
void setJavaAccess(final int access) {
this.javaAccess = access;
}
Object getValue() {
return value;
}
void setValue(final Object value) {
this.value = value;
}
Where getWhere() {
return where;
}
void setWhere(final Where where) {
this.where = where;
}
boolean isFinal() {
return (javaAccess & Opcodes.ACC_FINAL) != 0;
}
boolean isStatic() {
return (javaAccess & Opcodes.ACC_STATIC) != 0;
}
boolean isStaticFinal() {
return isStatic() && isFinal();
}
boolean isInstanceGetter() {
return kind == Kind.GETTER && where == Where.INSTANCE;
}
/**
* Check whether this MemberInfo is a getter that resides in the instance
*
* @return true if instance setter
*/
boolean isInstanceSetter() {
return kind == Kind.SETTER && where == Where.INSTANCE;
}
boolean isInstanceProperty() {
return kind == Kind.PROPERTY && where == Where.INSTANCE;
}
boolean isInstanceFunction() {
return kind == Kind.FUNCTION && where == Where.INSTANCE;
}
boolean isPrototypeGetter() {
return kind == Kind.GETTER && where == Where.PROTOTYPE;
}
boolean isPrototypeSetter() {
return kind == Kind.SETTER && where == Where.PROTOTYPE;
}
boolean isPrototypeProperty() {
return kind == Kind.PROPERTY && where == Where.PROTOTYPE;
}
boolean isPrototypeFunction() {
return kind == Kind.FUNCTION && where == Where.PROTOTYPE;
}
boolean isConstructorGetter() {
return kind == Kind.GETTER && where == Where.CONSTRUCTOR;
}
boolean isConstructorSetter() {
return kind == Kind.SETTER && where == Where.CONSTRUCTOR;
}
boolean isConstructorProperty() {
return kind == Kind.PROPERTY && where == Where.CONSTRUCTOR;
}
boolean isConstructorFunction() {
return kind == Kind.FUNCTION && where == Where.CONSTRUCTOR;
}
boolean isConstructor() {
return kind == Kind.CONSTRUCTOR;
}
void verify() {
switch (kind) {
case CONSTRUCTOR: {
final Type returnType = Type.getReturnType(javaDesc);
if (!isJSObjectType(returnType)) {
error("return value of a @Constructor method should be of Object type, found " + returnType);
}
final Type[] argTypes = Type.getArgumentTypes(javaDesc);
if (argTypes.length < 2) {
error("@Constructor methods should have at least 2 args");
}
if (!argTypes[0].equals(Type.BOOLEAN_TYPE)) {
error("first argument of a @Constructor method should be of boolean type, found " + argTypes[0]);
}
if (!isJavaLangObject(argTypes[1])) {
error("second argument of a @Constructor method should be of Object type, found " + argTypes[0]);
}
if (argTypes.length > 2) {
for (int i = 2; i < argTypes.length - 1; i++) {
if (!isJavaLangObject(argTypes[i])) {
error(i + "'th argument of a @Constructor method should be of Object type, found " + argTypes[i]);
}
}
final String lastArgTypeDesc = argTypes[argTypes.length - 1].getDescriptor();
final boolean isVarArg = lastArgTypeDesc.equals(OBJECT_ARRAY_DESC);
if (!lastArgTypeDesc.equals(OBJECT_DESC) && !isVarArg) {
error("last argument of a @Constructor method is neither Object nor Object[] type: " + lastArgTypeDesc);
}
if (isVarArg && argTypes.length > 3) {
error("vararg of a @Constructor method has more than 3 arguments");
}
}
}
break;
case FUNCTION: {
final Type returnType = Type.getReturnType(javaDesc);
if (!(isValidJSType(returnType) || Type.VOID_TYPE == returnType)) {
error("return value of a @Function method should be a valid JS type, found " + returnType);
}
final Type[] argTypes = Type.getArgumentTypes(javaDesc);
if (argTypes.length < 1) {
error("@Function methods should have at least 1 arg");
}
if (!isJavaLangObject(argTypes[0])) {
error("first argument of a @Function method should be of Object type, found " + argTypes[0]);
}
if (argTypes.length > 1) {
for (int i = 1; i < argTypes.length - 1; i++) {
if (!isJavaLangObject(argTypes[i])) {
error(i + "'th argument of a @Function method should be of Object type, found " + argTypes[i]);
}
}
final String lastArgTypeDesc = argTypes[argTypes.length - 1].getDescriptor();
final boolean isVarArg = lastArgTypeDesc.equals(OBJECT_ARRAY_DESC);
if (!lastArgTypeDesc.equals(OBJECT_DESC) && !isVarArg) {
error("last argument of a @Function method is neither Object nor Object[] type: " + lastArgTypeDesc);
}
if (isVarArg && argTypes.length > 2) {
error("vararg @Function method has more than 2 arguments");
}
}
}
break;
case SPECIALIZED_FUNCTION: {
final Type returnType = Type.getReturnType(javaDesc);
if (!(isValidJSType(returnType) || (isSpecializedConstructor() && Type.VOID_TYPE == returnType))) {
error("return value of a @SpecializedFunction method should be a valid JS type, found " + returnType);
}
final Type[] argTypes = Type.getArgumentTypes(javaDesc);
for (int i = 0; i < argTypes.length; i++) {
if (!isValidJSType(argTypes[i])) {
error(i + "'th argument of a @SpecializedFunction method is not valid JS type, found " + argTypes[i]);
}
}
}
break;
case GETTER: {
final Type[] argTypes = Type.getArgumentTypes(javaDesc);
if (argTypes.length != 1) {
error("@Getter methods should have one argument");
}
if (!isJavaLangObject(argTypes[0])) {
error("first argument of a @Getter method should be of Object type, found: " + argTypes[0]);
}
if (Type.getReturnType(javaDesc).equals(Type.VOID_TYPE)) {
error("return type of getter should not be void");
}
}
break;
case SETTER: {
final Type[] argTypes = Type.getArgumentTypes(javaDesc);
if (argTypes.length != 2) {
error("@Setter methods should have two arguments");
}
if (!isJavaLangObject(argTypes[0])) {
error("first argument of a @Setter method should be of Object type, found: " + argTypes[0]);
}
if (!Type.getReturnType(javaDesc).toString().equals("V")) {
error("return type of of a @Setter method should be void, found: " + Type.getReturnType(javaDesc));
}
}
break;
case PROPERTY: {
if (where == Where.CONSTRUCTOR) {
if (isStatic()) {
if (!isFinal()) {
error("static Where.CONSTRUCTOR @Property should be final");
}
if (!isJSPrimitiveType(Type.getType(javaDesc))) {
error("static Where.CONSTRUCTOR @Property should be a JS primitive");
}
}
} else if (where == Where.PROTOTYPE) {
if (isStatic()) {
if (!isFinal()) {
error("static Where.PROTOTYPE @Property should be final");
}
if (!isJSPrimitiveType(Type.getType(javaDesc))) {
error("static Where.PROTOTYPE @Property should be a JS primitive");
}
}
}
}
break;
default:
break;
}
}
/**
* Returns if the given (internal) name of a class represents a ScriptObject subtype.
*/
public static boolean isScriptObject(final String name) {
// very crude check for ScriptObject subtype!
if (name.startsWith(OBJ_PKG + "Native") ||
name.equals(OBJ_PKG + "Global") ||
name.equals(OBJ_PKG + "ArrayBufferView")) {
return true;
}
if (name.startsWith(RUNTIME_PKG)) {
final String simpleName = name.substring(name.lastIndexOf('/') + 1);
switch (simpleName) {
case "ScriptObject":
case "ScriptFunction":
case "NativeJavaPackage":
case "Scope":
return true;
}
}
if (name.startsWith(SCRIPTS_PKG)) {
final String simpleName = name.substring(name.lastIndexOf('/') + 1);
switch (simpleName) {
case "JD":
case "JO":
return true;
}
}
return false;
}
private static boolean isValidJSType(final Type type) {
return isJSPrimitiveType(type) || isJSObjectType(type);
}
private static boolean isJSPrimitiveType(final Type type) {
switch (type.getSort()) {
case Type.BOOLEAN:
case Type.INT:
case Type.DOUBLE:
return true;
default:
return type != TYPE_SYMBOL;
}
}
private static boolean isJSObjectType(final Type type) {
return isJavaLangObject(type) || isJavaLangString(type) || isScriptObject(type);
}
private static boolean isJavaLangObject(final Type type) {
return type.getDescriptor().equals(OBJECT_DESC);
}
private static boolean isJavaLangString(final Type type) {
return type.getDescriptor().equals(STRING_DESC);
}
private static boolean isScriptObject(final Type type) {
if (type.getSort() != Type.OBJECT) {
return false;
}
return isScriptObject(type.getInternalName());
}
private void error(final String msg) {
throw new RuntimeException(javaName + " of type " + javaDesc + " : " + msg);
}
/**
* @return the initClass
*/
String getInitClass() {
return initClass;
}
/**
* @param initClass the initClass to set
*/
void setInitClass(final String initClass) {
this.initClass = initClass;
}
@Override
protected Object clone() {
try {
return super.clone();
} catch (final CloneNotSupportedException e) {
assert false : "clone not supported " + e;
return null;
}
}
/**
* @return the arity
*/
int getArity() {
return arity;
}
/**
* @param arity the arity to set
*/
void setArity(final int arity) {
this.arity = arity;
}
String getDocumentationKey(final String objName) {
if (kind == Kind.FUNCTION) {
final StringBuilder buf = new StringBuilder(objName);
switch (where) {
case CONSTRUCTOR:
break;
case PROTOTYPE:
buf.append(".prototype");
break;
case INSTANCE:
buf.append(".this");
break;
}
buf.append('.');
buf.append(name);
return buf.toString();
}
return null;
}
}

View file

@ -1,454 +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.tools.nasgen;
import static jdk.internal.org.objectweb.asm.Opcodes.AALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.AASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.ACONST_NULL;
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.ASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.BALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.BASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.BIPUSH;
import static jdk.internal.org.objectweb.asm.Opcodes.CALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.CASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.CHECKCAST;
import static jdk.internal.org.objectweb.asm.Opcodes.DALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.DASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.DCONST_0;
import static jdk.internal.org.objectweb.asm.Opcodes.DRETURN;
import static jdk.internal.org.objectweb.asm.Opcodes.DUP;
import static jdk.internal.org.objectweb.asm.Opcodes.DUP2;
import static jdk.internal.org.objectweb.asm.Opcodes.FALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.FASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.FCONST_0;
import static jdk.internal.org.objectweb.asm.Opcodes.FRETURN;
import static jdk.internal.org.objectweb.asm.Opcodes.GETFIELD;
import static jdk.internal.org.objectweb.asm.Opcodes.GETSTATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKESTATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.IALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.IASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.ICONST_0;
import static jdk.internal.org.objectweb.asm.Opcodes.ICONST_1;
import static jdk.internal.org.objectweb.asm.Opcodes.ILOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESTATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static jdk.internal.org.objectweb.asm.Opcodes.IRETURN;
import static jdk.internal.org.objectweb.asm.Opcodes.ISTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.LALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.LASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.LCONST_0;
import static jdk.internal.org.objectweb.asm.Opcodes.LRETURN;
import static jdk.internal.org.objectweb.asm.Opcodes.NEW;
import static jdk.internal.org.objectweb.asm.Opcodes.POP;
import static jdk.internal.org.objectweb.asm.Opcodes.PUTFIELD;
import static jdk.internal.org.objectweb.asm.Opcodes.PUTSTATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.RETURN;
import static jdk.internal.org.objectweb.asm.Opcodes.SALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.SASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.SIPUSH;
import static jdk.internal.org.objectweb.asm.Opcodes.SWAP;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJ_ANNO_PKG;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SPECIALIZATION_INIT2;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SPECIALIZATION_INIT3;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SPECIALIZATION_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.TYPE_SPECIALIZATION;
import java.util.List;
import jdk.internal.org.objectweb.asm.Handle;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.Type;
/**
* Base class for all method generating classes.
*
*/
public class MethodGenerator extends MethodVisitor {
private final int access;
private final String name;
private final String descriptor;
private final Type returnType;
private final Type[] argumentTypes;
static final Type EMPTY_LINK_LOGIC_TYPE = Type.getType("L" + OBJ_ANNO_PKG + "SpecializedFunction$LinkLogic$Empty;");
MethodGenerator(final MethodVisitor mv, final int access, final String name, final String descriptor) {
super(Main.ASM_VERSION, mv);
this.access = access;
this.name = name;
this.descriptor = descriptor;
this.returnType = Type.getReturnType(descriptor);
this.argumentTypes = Type.getArgumentTypes(descriptor);
}
int getAccess() {
return access;
}
final String getName() {
return name;
}
final String getDescriptor() {
return descriptor;
}
final Type getReturnType() {
return returnType;
}
final Type[] getArgumentTypes() {
return argumentTypes;
}
/**
* Check whether access for this method is static
* @return true if static
*/
protected final boolean isStatic() {
return (getAccess() & ACC_STATIC) != 0;
}
/**
* Check whether this method is a constructor
* @return true if constructor
*/
protected final boolean isConstructor() {
return "<init>".equals(name);
}
void newObject(final String type) {
super.visitTypeInsn(NEW, type);
}
void newObjectArray(final String type) {
super.visitTypeInsn(ANEWARRAY, type);
}
void loadThis() {
if ((access & ACC_STATIC) != 0) {
throw new IllegalStateException("no 'this' inside static method");
}
super.visitVarInsn(ALOAD, 0);
}
void returnValue() {
super.visitInsn(returnType.getOpcode(IRETURN));
}
void returnVoid() {
super.visitInsn(RETURN);
}
// load, store
void arrayLoad(final Type type) {
super.visitInsn(type.getOpcode(IALOAD));
}
void arrayLoad() {
super.visitInsn(AALOAD);
}
void arrayStore(final Type type) {
super.visitInsn(type.getOpcode(IASTORE));
}
void arrayStore() {
super.visitInsn(AASTORE);
}
void loadLiteral(final Object value) {
super.visitLdcInsn(value);
}
void classLiteral(final String className) {
super.visitLdcInsn(className);
}
void loadLocal(final Type type, final int index) {
super.visitVarInsn(type.getOpcode(ILOAD), index);
}
void loadLocal(final int index) {
super.visitVarInsn(ALOAD, index);
}
void storeLocal(final Type type, final int index) {
super.visitVarInsn(type.getOpcode(ISTORE), index);
}
void storeLocal(final int index) {
super.visitVarInsn(ASTORE, index);
}
void checkcast(final String type) {
super.visitTypeInsn(CHECKCAST, type);
}
// push constants/literals
void pushNull() {
super.visitInsn(ACONST_NULL);
}
void push(final int value) {
if (value >= -1 && value <= 5) {
super.visitInsn(ICONST_0 + value);
} else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
super.visitIntInsn(BIPUSH, value);
} else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
super.visitIntInsn(SIPUSH, value);
} else {
super.visitLdcInsn(value);
}
}
void loadClass(final String className) {
super.visitLdcInsn(Type.getObjectType(className));
}
void pop() {
super.visitInsn(POP);
}
// various "dups"
void dup() {
super.visitInsn(DUP);
}
void dup2() {
super.visitInsn(DUP2);
}
void swap() {
super.visitInsn(SWAP);
}
void dupArrayValue(final int arrayOpcode) {
switch (arrayOpcode) {
case IALOAD: case FALOAD:
case AALOAD: case BALOAD:
case CALOAD: case SALOAD:
case IASTORE: case FASTORE:
case AASTORE: case BASTORE:
case CASTORE: case SASTORE:
dup();
break;
case LALOAD: case DALOAD:
case LASTORE: case DASTORE:
dup2();
break;
default:
throw new AssertionError("invalid dup");
}
}
void dupReturnValue(final int returnOpcode) {
switch (returnOpcode) {
case IRETURN:
case FRETURN:
case ARETURN:
super.visitInsn(DUP);
return;
case LRETURN:
case DRETURN:
super.visitInsn(DUP2);
return;
case RETURN:
return;
default:
throw new IllegalArgumentException("not return");
}
}
void dupValue(final Type type) {
switch (type.getSize()) {
case 1:
dup();
break;
case 2:
dup2();
break;
default:
throw new AssertionError("invalid dup");
}
}
void dupValue(final String desc) {
final int typeCode = desc.charAt(0);
switch (typeCode) {
case '[':
case 'L':
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
super.visitInsn(DUP);
break;
case 'J':
case 'D':
super.visitInsn(DUP2);
break;
default:
throw new RuntimeException("invalid signature");
}
}
// push default value of given type desc
void defaultValue(final String desc) {
final int typeCode = desc.charAt(0);
switch (typeCode) {
case '[':
case 'L':
super.visitInsn(ACONST_NULL);
break;
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
super.visitInsn(ICONST_0);
break;
case 'J':
super.visitInsn(LCONST_0);
break;
case 'F':
super.visitInsn(FCONST_0);
break;
case 'D':
super.visitInsn(DCONST_0);
break;
default:
throw new AssertionError("invalid desc " + desc);
}
}
// invokes, field get/sets
void invokeInterface(final String owner, final String method, final String desc) {
super.visitMethodInsn(INVOKEINTERFACE, owner, method, desc, true);
}
void invokeVirtual(final String owner, final String method, final String desc) {
super.visitMethodInsn(INVOKEVIRTUAL, owner, method, desc, false);
}
void invokeSpecial(final String owner, final String method, final String desc) {
super.visitMethodInsn(INVOKESPECIAL, owner, method, desc, false);
}
void invokeStatic(final String owner, final String method, final String desc) {
super.visitMethodInsn(INVOKESTATIC, owner, method, desc, false);
}
void putStatic(final String owner, final String field, final String desc) {
super.visitFieldInsn(PUTSTATIC, owner, field, desc);
}
void getStatic(final String owner, final String field, final String desc) {
super.visitFieldInsn(GETSTATIC, owner, field, desc);
}
void putField(final String owner, final String field, final String desc) {
super.visitFieldInsn(PUTFIELD, owner, field, desc);
}
void getField(final String owner, final String field, final String desc) {
super.visitFieldInsn(GETFIELD, owner, field, desc);
}
private static boolean linkLogicIsEmpty(final Type type) {
assert EMPTY_LINK_LOGIC_TYPE != null; //type is ok for null if we are a @SpecializedFunction without any attribs
return EMPTY_LINK_LOGIC_TYPE.equals(type);
}
void memberInfoArray(final String className, final List<MemberInfo> mis) {
if (mis.isEmpty()) {
pushNull();
return;
}
int pos = 0;
push(mis.size());
newObjectArray(SPECIALIZATION_TYPE);
for (final MemberInfo mi : mis) {
dup();
push(pos++);
visitTypeInsn(NEW, SPECIALIZATION_TYPE);
dup();
visitLdcInsn(new Handle(H_INVOKESTATIC, className, mi.getJavaName(), mi.getJavaDesc(), false));
final Type linkLogicClass = mi.getLinkLogicClass();
final boolean linkLogic = !linkLogicIsEmpty(linkLogicClass);
final String ctor = linkLogic ? SPECIALIZATION_INIT3 : SPECIALIZATION_INIT2;
if (linkLogic) {
visitLdcInsn(linkLogicClass);
}
visitInsn(mi.isOptimistic() ? ICONST_1 : ICONST_0);
visitInsn(mi.convertsNumericArgs() ? ICONST_1 : ICONST_0);
visitMethodInsn(INVOKESPECIAL, SPECIALIZATION_TYPE, INIT, ctor, false);
arrayStore(TYPE_SPECIALIZATION);
}
}
void computeMaxs() {
// These values are ignored as we create class writer
// with ClassWriter.COMPUTE_MAXS flag.
super.visitMaxs(Short.MAX_VALUE, Short.MAX_VALUE);
}
// debugging support - print calls
void println(final String msg) {
super.visitFieldInsn(GETSTATIC,
"java/lang/System",
"out",
"Ljava/io/PrintStream;");
super.visitLdcInsn(msg);
super.visitMethodInsn(INVOKEVIRTUAL,
"java/io/PrintStream",
"println",
"(Ljava/lang/String;)V",
false);
}
// print the object on the top of the stack
void printObject() {
super.visitFieldInsn(GETSTATIC,
"java/lang/System",
"out",
"Ljava/io/PrintStream;");
super.visitInsn(SWAP);
super.visitMethodInsn(INVOKEVIRTUAL,
"java/io/PrintStream",
"println",
"(Ljava/lang/Object;)V",
false);
}
}

View file

@ -1,87 +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.tools.nasgen;
import jdk.internal.org.objectweb.asm.AnnotationVisitor;
import jdk.internal.org.objectweb.asm.ClassVisitor;
import jdk.internal.org.objectweb.asm.FieldVisitor;
import jdk.internal.org.objectweb.asm.MethodVisitor;
/**
* A visitor that does nothing on visitXXX calls.
*
*/
public class NullVisitor extends ClassVisitor {
NullVisitor() {
super(Main.ASM_VERSION);
}
@Override
public MethodVisitor visitMethod(
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
return new MethodVisitor(Main.ASM_VERSION) {
@Override
public AnnotationVisitor visitAnnotationDefault() {
return new NullAnnotationVisitor();
}
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
return new NullAnnotationVisitor();
}
};
}
@Override
public FieldVisitor visitField(
final int access,
final String name,
final String desc,
final String signature,
final Object value) {
return new FieldVisitor(Main.ASM_VERSION) {
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
return new NullAnnotationVisitor();
}
};
}
@Override
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
return new NullAnnotationVisitor();
}
private static class NullAnnotationVisitor extends AnnotationVisitor {
NullAnnotationVisitor() {
super(Main.ASM_VERSION);
}
}
}

View file

@ -1,180 +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.tools.nasgen;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER;
import static jdk.internal.org.objectweb.asm.Opcodes.V1_7;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPE_SUFFIX;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTOBJECT_INIT_DESC;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* This class generates prototype class for a @ScriptClass annotated class.
*
*/
public class PrototypeGenerator extends ClassGenerator {
private final ScriptClassInfo scriptClassInfo;
private final String className;
private final int memberCount;
PrototypeGenerator(final ScriptClassInfo sci) {
this.scriptClassInfo = sci;
this.className = scriptClassInfo.getPrototypeClassName();
this.memberCount = scriptClassInfo.getPrototypeMemberCount();
}
byte[] getClassBytes() {
// new class extending from ScriptObject
cw.visit(V1_7, ACC_FINAL | ACC_SUPER, className, null, PROTOTYPEOBJECT_TYPE, null);
if (memberCount > 0) {
// add fields
emitFields();
// add <clinit>
emitStaticInitializer();
}
// add <init>
emitConstructor();
// add getClassName()
emitGetClassName(scriptClassInfo.getName());
cw.visitEnd();
return cw.toByteArray();
}
// --Internals only below this point
private void emitFields() {
// introduce "Function" type instance fields for each
// prototype @Function in script class info
for (MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isPrototypeFunction()) {
addFunctionField(memInfo.getJavaName());
memInfo = (MemberInfo)memInfo.clone();
memInfo.setJavaDesc(OBJECT_DESC);
addGetter(className, memInfo);
addSetter(className, memInfo);
} else if (memInfo.isPrototypeProperty()) {
if (memInfo.isStaticFinal()) {
addGetter(scriptClassInfo.getJavaName(), memInfo);
} else {
addField(memInfo.getJavaName(), memInfo.getJavaDesc());
memInfo = (MemberInfo)memInfo.clone();
memInfo.setJavaAccess(ACC_PUBLIC);
addGetter(className, memInfo);
addSetter(className, memInfo);
}
}
}
addMapField();
}
private void emitStaticInitializer() {
final MethodGenerator mi = makeStaticInitializer();
emitStaticInitPrefix(mi, className, memberCount);
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isPrototypeFunction() || memInfo.isPrototypeProperty()) {
linkerAddGetterSetter(mi, className, memInfo);
} else if (memInfo.isPrototypeGetter()) {
final MemberInfo setter = scriptClassInfo.findSetter(memInfo);
linkerAddGetterSetter(mi, scriptClassInfo.getJavaName(), memInfo, setter);
}
}
emitStaticInitSuffix(mi, className);
}
private void emitConstructor() {
final MethodGenerator mi = makeConstructor();
mi.visitCode();
mi.loadThis();
if (memberCount > 0) {
// call "super(map$)"
mi.getStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC);
mi.invokeSpecial(PROTOTYPEOBJECT_TYPE, INIT, SCRIPTOBJECT_INIT_DESC);
// initialize Function type fields
initFunctionFields(mi);
} else {
// call "super()"
mi.invokeSpecial(PROTOTYPEOBJECT_TYPE, INIT, DEFAULT_INIT_DESC);
}
mi.returnVoid();
mi.computeMaxs();
mi.visitEnd();
}
private void initFunctionFields(final MethodGenerator mi) {
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (! memInfo.isPrototypeFunction()) {
continue;
}
mi.loadThis();
newFunction(mi, scriptClassInfo.getName(), scriptClassInfo.getJavaName(), memInfo, scriptClassInfo.findSpecializations(memInfo.getJavaName()));
mi.putField(className, memInfo.getJavaName(), OBJECT_DESC);
}
}
/**
* External entry point for PrototypeGenerator if called from the command line
*
* @param args arguments, takes 1 argument which is the class to process
* @throws IOException if class cannot be read
*/
public static void main(final String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: " + PrototypeGenerator.class.getName() + " <class>");
System.exit(1);
}
final String className = args[0].replace('.', '/');
final ScriptClassInfo sci = getScriptClassInfo(className + ".class");
if (sci == null) {
System.err.println("No @ScriptClass in " + className);
System.exit(2);
throw new AssertionError(); //guard against warning that sci is null below
}
try {
sci.verify();
} catch (final Exception e) {
System.err.println(e.getMessage());
System.exit(3);
}
final PrototypeGenerator gen = new PrototypeGenerator(sci);
try (FileOutputStream fos = new FileOutputStream(className + PROTOTYPE_SUFFIX + ".class")) {
fos.write(gen.getClassBytes());
}
}
}

View file

@ -1,286 +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.tools.nasgen;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import jdk.internal.org.objectweb.asm.Type;
import jdk.nashorn.internal.tools.nasgen.MemberInfo.Kind;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJ_ANNO_PKG;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.RUNTIME_PKG;
/**
* All annotation information from a class that is annotated with
* the annotation com.sun.oracle.objects.annotations.ScriptClass.
*
*/
public final class ScriptClassInfo {
private static String getTypeDescriptor(final String pkg, final String name) {
return "L" + pkg + name + ";";
}
// descriptors for various annotations
static final String SCRIPT_CLASS_ANNO_DESC = getTypeDescriptor(OBJ_ANNO_PKG, "ScriptClass");
static final String CONSTRUCTOR_ANNO_DESC = getTypeDescriptor(OBJ_ANNO_PKG, "Constructor");
static final String FUNCTION_ANNO_DESC = getTypeDescriptor(OBJ_ANNO_PKG, "Function");
static final String GETTER_ANNO_DESC = getTypeDescriptor(OBJ_ANNO_PKG, "Getter");
static final String SETTER_ANNO_DESC = getTypeDescriptor(OBJ_ANNO_PKG, "Setter");
static final String PROPERTY_ANNO_DESC = getTypeDescriptor(OBJ_ANNO_PKG, "Property");
static final String WHERE_ENUM_DESC = getTypeDescriptor(OBJ_ANNO_PKG, "Where");
static final String LINK_LOGIC_DESC = getTypeDescriptor(OBJ_ANNO_PKG, "SpecializedFunction$LinkLogic");
static final String SPECIALIZED_FUNCTION = getTypeDescriptor(OBJ_ANNO_PKG, "SpecializedFunction");
static final Map<String, Kind> annotations = new HashMap<>();
static {
annotations.put(SCRIPT_CLASS_ANNO_DESC, Kind.SCRIPT_CLASS);
annotations.put(FUNCTION_ANNO_DESC, Kind.FUNCTION);
annotations.put(CONSTRUCTOR_ANNO_DESC, Kind.CONSTRUCTOR);
annotations.put(GETTER_ANNO_DESC, Kind.GETTER);
annotations.put(SETTER_ANNO_DESC, Kind.SETTER);
annotations.put(PROPERTY_ANNO_DESC, Kind.PROPERTY);
annotations.put(SPECIALIZED_FUNCTION, Kind.SPECIALIZED_FUNCTION);
}
// name of the script class
private String name;
// member info for script properties
private List<MemberInfo> members = Collections.emptyList();
// java class name that is annotated with @ScriptClass
private String javaName;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(final String name) {
this.name = name;
}
/**
* @return the members
*/
public List<MemberInfo> getMembers() {
return Collections.unmodifiableList(members);
}
/**
* @param members the members to set
*/
public void setMembers(final List<MemberInfo> members) {
this.members = members;
}
MemberInfo getConstructor() {
for (final MemberInfo memInfo : members) {
if (memInfo.getKind() == Kind.CONSTRUCTOR) {
return memInfo;
}
}
return null;
}
List<MemberInfo> getSpecializedConstructors() {
final List<MemberInfo> res = new LinkedList<>();
for (final MemberInfo memInfo : members) {
if (memInfo.isSpecializedConstructor()) {
assert memInfo.getKind() == Kind.SPECIALIZED_FUNCTION;
res.add(memInfo);
}
}
return Collections.unmodifiableList(res);
}
boolean isConstructorNeeded() {
// Constructor class generation is needed if we one or
// more constructor properties are defined or @Constructor
// is defined in the class.
for (final MemberInfo memInfo : members) {
if (memInfo.getKind() == Kind.CONSTRUCTOR ||
memInfo.getWhere() == Where.CONSTRUCTOR) {
return true;
}
}
return false;
}
boolean isPrototypeNeeded() {
// Prototype class generation is needed if we have at least one
// prototype property or @Constructor defined in the class.
for (final MemberInfo memInfo : members) {
if (memInfo.getWhere() == Where.PROTOTYPE || memInfo.isConstructor()) {
return true;
}
}
return false;
}
int getPrototypeMemberCount() {
int count = 0;
for (final MemberInfo memInfo : members) {
switch (memInfo.getKind()) {
case SETTER:
case SPECIALIZED_FUNCTION:
// SETTER was counted when GETTER was encountered.
// SPECIALIZED_FUNCTION was counted as FUNCTION already.
continue;
}
if (memInfo.getWhere() == Where.PROTOTYPE) {
count++;
}
}
return count;
}
int getConstructorMemberCount() {
int count = 0;
for (final MemberInfo memInfo : members) {
switch (memInfo.getKind()) {
case CONSTRUCTOR:
case SETTER:
case SPECIALIZED_FUNCTION:
// SETTER was counted when GETTER was encountered.
// Constructor and constructor SpecializedFunctions
// are not added as members and so not counted.
continue;
}
if (memInfo.getWhere() == Where.CONSTRUCTOR) {
count++;
}
}
return count;
}
int getInstancePropertyCount() {
int count = 0;
for (final MemberInfo memInfo : members) {
switch (memInfo.getKind()) {
case SETTER:
case SPECIALIZED_FUNCTION:
// SETTER was counted when GETTER was encountered.
// SPECIALIZED_FUNCTION was counted as FUNCTION already.
continue;
}
if (memInfo.getWhere() == Where.INSTANCE) {
count++;
}
}
return count;
}
MemberInfo find(final String findJavaName, final String findJavaDesc, final int findAccess) {
for (final MemberInfo memInfo : members) {
if (memInfo.getJavaName().equals(findJavaName) &&
memInfo.getJavaDesc().equals(findJavaDesc) &&
memInfo.getJavaAccess() == findAccess) {
return memInfo;
}
}
return null;
}
List<MemberInfo> findSpecializations(final String methodName) {
final List<MemberInfo> res = new LinkedList<>();
for (final MemberInfo memInfo : members) {
if (memInfo.getName().equals(methodName) &&
memInfo.getKind() == Kind.SPECIALIZED_FUNCTION) {
res.add(memInfo);
}
}
return Collections.unmodifiableList(res);
}
MemberInfo findSetter(final MemberInfo getter) {
assert getter.getKind() == Kind.GETTER : "getter expected";
final String getterName = getter.getName();
final Where getterWhere = getter.getWhere();
for (final MemberInfo memInfo : members) {
if (memInfo.getKind() == Kind.SETTER &&
getterName.equals(memInfo.getName()) &&
getterWhere == memInfo.getWhere()) {
return memInfo;
}
}
return null;
}
/**
* @return the javaName
*/
public String getJavaName() {
return javaName;
}
/**
* @param javaName the javaName to set
*/
void setJavaName(final String javaName) {
this.javaName = javaName;
}
String getConstructorClassName() {
return getJavaName() + StringConstants.CONSTRUCTOR_SUFFIX;
}
String getPrototypeClassName() {
return getJavaName() + StringConstants.PROTOTYPE_SUFFIX;
}
void verify() {
boolean constructorSeen = false;
for (final MemberInfo memInfo : getMembers()) {
if (memInfo.isConstructor()) {
if (constructorSeen) {
error("more than @Constructor method");
}
constructorSeen = true;
}
try {
memInfo.verify();
} catch (final Exception e) {
e.printStackTrace();
error(e.getMessage());
}
}
}
private void error(final String msg) throws RuntimeException {
throw new RuntimeException(javaName + " : " + msg);
}
}

View file

@ -1,365 +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.tools.nasgen;
import static jdk.nashorn.internal.tools.nasgen.ScriptClassInfo.SCRIPT_CLASS_ANNO_DESC;
import static jdk.nashorn.internal.tools.nasgen.ScriptClassInfo.WHERE_ENUM_DESC;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jdk.internal.org.objectweb.asm.AnnotationVisitor;
import jdk.internal.org.objectweb.asm.ClassReader;
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;
import jdk.internal.org.objectweb.asm.Type;
import jdk.nashorn.internal.tools.nasgen.MemberInfo.Kind;
/**
* This class collects all @ScriptClass and other annotation information from a
* compiled .class file. Enforces that @Function/@Getter/@Setter/@Constructor
* methods are declared to be 'static'.
*/
public class ScriptClassInfoCollector extends ClassVisitor {
private String scriptClassName;
private List<MemberInfo> scriptMembers;
private String javaClassName;
ScriptClassInfoCollector(final ClassVisitor visitor) {
super(Main.ASM_VERSION, visitor);
}
ScriptClassInfoCollector() {
this(new NullVisitor());
}
private void addScriptMember(final MemberInfo memInfo) {
if (scriptMembers == null) {
scriptMembers = new ArrayList<>();
}
scriptMembers.add(memInfo);
}
@Override
public void visit(final int version, final int access, final String name, final String signature,
final String superName, final String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
javaClassName = name;
}
@Override
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(Main.ASM_VERSION, delegateAV) {
@Override
public void visit(final String name, final Object value) {
if ("value".equals(name)) {
scriptClassName = (String) value;
}
super.visit(name, value);
}
};
}
return delegateAV;
}
@Override
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(Main.ASM_VERSION, delegateFV) {
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
final AnnotationVisitor delegateAV = super.visitAnnotation(descriptor, visible);
if (ScriptClassInfo.PROPERTY_ANNO_DESC.equals(descriptor)) {
final MemberInfo memInfo = new MemberInfo();
memInfo.setKind(Kind.PROPERTY);
memInfo.setJavaName(fieldName);
memInfo.setJavaDesc(fieldDesc);
memInfo.setJavaAccess(fieldAccess);
if ((fieldAccess & Opcodes.ACC_STATIC) != 0) {
memInfo.setValue(value);
}
addScriptMember(memInfo);
return new AnnotationVisitor(Main.ASM_VERSION, delegateAV) {
// These could be "null" if values are not supplied,
// in which case we have to use the default values.
private String name;
private Integer attributes;
private String clazz = "";
private Where where;
@Override
public void visit(final String annotationName, final Object annotationValue) {
switch (annotationName) {
case "name":
this.name = (String) annotationValue;
break;
case "attributes":
this.attributes = (Integer) annotationValue;
break;
case "clazz":
this.clazz = (annotationValue == null) ? "" : annotationValue.toString();
break;
default:
break;
}
super.visit(annotationName, annotationValue);
}
@Override
public void visitEnum(final String enumName, final String desc, final String enumValue) {
if ("where".equals(enumName) && WHERE_ENUM_DESC.equals(desc)) {
this.where = Where.valueOf(enumValue);
}
super.visitEnum(enumName, desc, enumValue);
}
@Override
public void visitEnd() {
super.visitEnd();
memInfo.setName(name == null ? fieldName : name);
memInfo.setAttributes(attributes == null
? MemberInfo.DEFAULT_ATTRIBUTES : attributes);
clazz = clazz.replace('.', '/');
memInfo.setInitClass(clazz);
memInfo.setWhere(where == null? Where.INSTANCE : where);
}
};
}
return delegateAV;
}
};
}
private void error(final String javaName, final String javaDesc, final String msg) {
throw new RuntimeException(scriptClassName + "." + javaName + javaDesc + " : " + msg);
}
@Override
public MethodVisitor visitMethod(final int methodAccess, final String methodName,
final String methodDesc, final String signature, final String[] exceptions) {
final MethodVisitor delegateMV = super.visitMethod(methodAccess, methodName, methodDesc,
signature, exceptions);
return new MethodVisitor(Main.ASM_VERSION, delegateMV) {
@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
final AnnotationVisitor delegateAV = super.visitAnnotation(descriptor, visible);
final Kind annoKind = ScriptClassInfo.annotations.get(descriptor);
if (annoKind != null) {
if ((methodAccess & Opcodes.ACC_STATIC) == 0) {
error(methodName, methodDesc, "nasgen method annotations cannot be on instance methods");
}
final MemberInfo memInfo = new MemberInfo();
// annoKind == GETTER or SPECIALIZED_FUNCTION
memInfo.setKind(annoKind);
memInfo.setJavaName(methodName);
memInfo.setJavaDesc(methodDesc);
memInfo.setJavaAccess(methodAccess);
addScriptMember(memInfo);
return new AnnotationVisitor(Main.ASM_VERSION, delegateAV) {
// These could be "null" if values are not supplied,
// in which case we have to use the default values.
private String name;
private Integer attributes;
private Integer arity;
private Where where;
private boolean isSpecializedConstructor;
private boolean isOptimistic;
private boolean convertsNumericArgs;
private Type linkLogicClass = MethodGenerator.EMPTY_LINK_LOGIC_TYPE;
@Override
public void visit(final String annotationName, final Object annotationValue) {
switch (annotationName) {
case "name":
this.name = (String)annotationValue;
if (name.isEmpty()) {
name = null;
}
break;
case "attributes":
this.attributes = (Integer)annotationValue;
break;
case "arity":
this.arity = (Integer)annotationValue;
break;
case "isConstructor":
assert annoKind == Kind.SPECIALIZED_FUNCTION;
this.isSpecializedConstructor = (Boolean)annotationValue;
break;
case "isOptimistic":
assert annoKind == Kind.SPECIALIZED_FUNCTION;
this.isOptimistic = (Boolean)annotationValue;
break;
case "linkLogic":
this.linkLogicClass = (Type)annotationValue;
break;
case "convertsNumericArgs":
assert annoKind == Kind.SPECIALIZED_FUNCTION;
this.convertsNumericArgs = (Boolean)annotationValue;
break;
default:
break;
}
super.visit(annotationName, annotationValue);
}
@Override
public void visitEnum(final String enumName, final String desc, final String enumValue) {
switch (enumName) {
case "where":
if (WHERE_ENUM_DESC.equals(desc)) {
this.where = Where.valueOf(enumValue);
}
break;
default:
break;
}
super.visitEnum(enumName, desc, enumValue);
}
@SuppressWarnings("fallthrough")
@Override
public void visitEnd() {
super.visitEnd();
if (memInfo.getKind() == Kind.CONSTRUCTOR) {
memInfo.setName(name == null ? scriptClassName : name);
} else {
memInfo.setName(name == null ? methodName : name);
}
memInfo.setAttributes(attributes == null ? MemberInfo.DEFAULT_ATTRIBUTES : attributes);
memInfo.setArity((arity == null)? MemberInfo.DEFAULT_ARITY : arity);
if (where == null) {
// by default @Getter/@Setter belongs to INSTANCE
// @Function belong to PROTOTYPE.
switch (memInfo.getKind()) {
case GETTER:
case SETTER:
where = Where.INSTANCE;
break;
case CONSTRUCTOR:
where = Where.CONSTRUCTOR;
break;
case FUNCTION:
where = Where.PROTOTYPE;
break;
case SPECIALIZED_FUNCTION:
where = isSpecializedConstructor? Where.CONSTRUCTOR : Where.PROTOTYPE;
//fallthru
default:
break;
}
}
memInfo.setWhere(where);
memInfo.setLinkLogicClass(linkLogicClass);
memInfo.setIsSpecializedConstructor(isSpecializedConstructor);
memInfo.setIsOptimistic(isOptimistic);
memInfo.setConvertsNumericArgs(convertsNumericArgs);
}
};
}
return delegateAV;
}
};
}
ScriptClassInfo getScriptClassInfo() {
ScriptClassInfo sci = null;
if (scriptClassName != null) {
sci = new ScriptClassInfo();
sci.setName(scriptClassName);
if (scriptMembers == null) {
scriptMembers = Collections.emptyList();
}
sci.setMembers(scriptMembers);
sci.setJavaName(javaClassName);
}
return sci;
}
/**
* External entry point for ScriptClassInfoCollector if invoked from the command line
* @param args argument vector, args contains a class for which to collect info
* @throws IOException if there were problems parsing args or class
*/
public static void main(final String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: " + ScriptClassInfoCollector.class.getName() + " <class>");
System.exit(1);
}
args[0] = args[0].replace('.', '/');
final ScriptClassInfoCollector scic = new ScriptClassInfoCollector();
try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0] + ".class"))) {
final ClassReader reader = new ClassReader(bis);
reader.accept(scic, 0);
}
final ScriptClassInfo sci = scic.getScriptClassInfo();
final PrintStream out = System.out;
if (sci != null) {
out.println("script class: " + sci.getName());
out.println("===================================");
for (final MemberInfo memInfo : sci.getMembers()) {
out.println("kind : " + memInfo.getKind());
out.println("name : " + memInfo.getName());
out.println("attributes: " + memInfo.getAttributes());
out.println("javaName: " + memInfo.getJavaName());
out.println("javaDesc: " + memInfo.getJavaDesc());
out.println("where: " + memInfo.getWhere());
out.println("=====================================");
}
} else {
out.println(args[0] + " is not a @ScriptClass");
}
}
}

View file

@ -1,298 +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.tools.nasgen;
import static jdk.internal.org.objectweb.asm.Opcodes.ALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.DUP;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESTATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.NEW;
import static jdk.internal.org.objectweb.asm.Opcodes.PUTFIELD;
import static jdk.internal.org.objectweb.asm.Opcodes.RETURN;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.$CLINIT$;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.CLINIT;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTOBJECT_TYPE;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import jdk.internal.org.objectweb.asm.AnnotationVisitor;
import jdk.internal.org.objectweb.asm.Attribute;
import jdk.internal.org.objectweb.asm.ClassReader;
import jdk.internal.org.objectweb.asm.ClassVisitor;
import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.FieldVisitor;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.util.CheckClassAdapter;
import jdk.nashorn.internal.tools.nasgen.MemberInfo.Kind;
/**
* This class instruments the java class annotated with @ScriptClass.
*
* Changes done are:
*
* 1) remove all jdk.nashorn.internal.objects.annotations.* annotations.
* 2) static final @Property fields stay here. Other @Property fields moved to
* respective classes depending on 'where' value of annotation.
* 2) add "Map" type static field named "$map".
* 3) add static initializer block to initialize map.
*/
public class ScriptClassInstrumentor extends ClassVisitor {
private final ScriptClassInfo scriptClassInfo;
private final int memberCount;
private boolean staticInitFound;
ScriptClassInstrumentor(final ClassVisitor visitor, final ScriptClassInfo sci) {
super(Main.ASM_VERSION, visitor);
if (sci == null) {
throw new IllegalArgumentException("Null ScriptClassInfo, is the class annotated?");
}
this.scriptClassInfo = sci;
this.memberCount = scriptClassInfo.getInstancePropertyCount();
}
@Override
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
if (ScriptClassInfo.annotations.containsKey(desc)) {
// ignore @ScriptClass
return null;
}
return super.visitAnnotation(desc, visible);
}
@Override
public FieldVisitor visitField(final int fieldAccess, final String fieldName,
final String fieldDesc, final String signature, final Object value) {
final MemberInfo memInfo = scriptClassInfo.find(fieldName, fieldDesc, fieldAccess);
if (memInfo != null && memInfo.getKind() == Kind.PROPERTY &&
memInfo.getWhere() != Where.INSTANCE && !memInfo.isStaticFinal()) {
// non-instance @Property fields - these have to go elsewhere unless 'static final'
return null;
}
final FieldVisitor delegateFV = super.visitField(fieldAccess, fieldName, fieldDesc,
signature, value);
return new FieldVisitor(Main.ASM_VERSION, delegateFV) {
@Override
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
if (ScriptClassInfo.annotations.containsKey(desc)) {
// ignore script field annotations
return null;
}
return fv.visitAnnotation(desc, visible);
}
@Override
public void visitAttribute(final Attribute attr) {
fv.visitAttribute(attr);
}
@Override
public void visitEnd() {
fv.visitEnd();
}
};
}
@Override
public MethodVisitor visitMethod(final int methodAccess, final String methodName,
final String methodDesc, final String signature, final String[] exceptions) {
final boolean isConstructor = INIT.equals(methodName);
final boolean isStaticInit = CLINIT.equals(methodName);
if (isStaticInit) {
staticInitFound = true;
}
final MethodGenerator delegateMV = new MethodGenerator(super.visitMethod(methodAccess, methodName, methodDesc,
signature, exceptions), methodAccess, methodName, methodDesc);
return new MethodVisitor(Main.ASM_VERSION, delegateMV) {
@Override
public void visitInsn(final int opcode) {
// call $clinit$ just before return from <clinit>
if (isStaticInit && opcode == RETURN) {
super.visitMethodInsn(INVOKESTATIC, scriptClassInfo.getJavaName(),
$CLINIT$, DEFAULT_INIT_DESC, false);
}
super.visitInsn(opcode);
}
@Override
public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, final boolean itf) {
if (isConstructor && opcode == INVOKESPECIAL &&
INIT.equals(name) && SCRIPTOBJECT_TYPE.equals(owner)) {
super.visitMethodInsn(opcode, owner, name, desc, false);
if (memberCount > 0) {
// initialize @Property fields if needed
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isInstanceProperty() && !memInfo.getInitClass().isEmpty()) {
final String clazz = memInfo.getInitClass();
super.visitVarInsn(ALOAD, 0);
super.visitTypeInsn(NEW, clazz);
super.visitInsn(DUP);
super.visitMethodInsn(INVOKESPECIAL, clazz,
INIT, DEFAULT_INIT_DESC, false);
super.visitFieldInsn(PUTFIELD, scriptClassInfo.getJavaName(),
memInfo.getJavaName(), memInfo.getJavaDesc());
}
if (memInfo.isInstanceFunction()) {
super.visitVarInsn(ALOAD, 0);
ClassGenerator.newFunction(delegateMV, scriptClassInfo.getName(), scriptClassInfo.getJavaName(), memInfo, scriptClassInfo.findSpecializations(memInfo.getJavaName()));
super.visitFieldInsn(PUTFIELD, scriptClassInfo.getJavaName(),
memInfo.getJavaName(), OBJECT_DESC);
}
}
}
} else {
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
}
@Override
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
if (ScriptClassInfo.annotations.containsKey(desc)) {
// ignore script method annotations
return null;
}
return super.visitAnnotation(desc, visible);
}
};
}
@Override
public void visitEnd() {
emitFields();
emitStaticInitializer();
emitGettersSetters();
super.visitEnd();
}
private void emitFields() {
// introduce "Function" type instance fields for each
// instance @Function in script class info
final String className = scriptClassInfo.getJavaName();
for (MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isInstanceFunction()) {
ClassGenerator.addFunctionField(cv, memInfo.getJavaName());
memInfo = (MemberInfo)memInfo.clone();
memInfo.setJavaDesc(OBJECT_DESC);
ClassGenerator.addGetter(cv, className, memInfo);
ClassGenerator.addSetter(cv, className, memInfo);
}
}
// omit addMapField() since instance classes already define a static PropertyMap field
}
void emitGettersSetters() {
if (memberCount > 0) {
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
final String className = scriptClassInfo.getJavaName();
if (memInfo.isInstanceProperty()) {
ClassGenerator.addGetter(cv, className, memInfo);
if (! memInfo.isFinal()) {
ClassGenerator.addSetter(cv, className, memInfo);
}
}
}
}
}
private void emitStaticInitializer() {
final String className = scriptClassInfo.getJavaName();
if (! staticInitFound) {
// no user written <clinit> and so create one
final MethodVisitor mv = ClassGenerator.makeStaticInitializer(this);
mv.visitCode();
mv.visitInsn(RETURN);
mv.visitMaxs(Short.MAX_VALUE, 0);
mv.visitEnd();
}
// Now generate $clinit$
final MethodGenerator mi = ClassGenerator.makeStaticInitializer(this, $CLINIT$);
ClassGenerator.emitStaticInitPrefix(mi, className, memberCount);
if (memberCount > 0) {
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isInstanceProperty() || memInfo.isInstanceFunction()) {
ClassGenerator.linkerAddGetterSetter(mi, className, memInfo);
} else if (memInfo.isInstanceGetter()) {
final MemberInfo setter = scriptClassInfo.findSetter(memInfo);
ClassGenerator.linkerAddGetterSetter(mi, className, memInfo, setter);
}
}
}
ClassGenerator.emitStaticInitSuffix(mi, className);
}
/**
* External entry point for ScriptClassInfoCollector if run from the command line
*
* @param args arguments - one argument is needed, the name of the class to collect info from
*
* @throws IOException if there are problems reading class
*/
public static void main(final String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: " + ScriptClassInstrumentor.class.getName() + " <class>");
System.exit(1);
}
final String fileName = args[0].replace('.', '/') + ".class";
final ScriptClassInfo sci = ClassGenerator.getScriptClassInfo(fileName);
if (sci == null) {
System.err.println("No @ScriptClass in " + fileName);
System.exit(2);
throw new AssertionError(); //guard against warning that sci is null below
}
try {
sci.verify();
} catch (final Exception e) {
System.err.println(e.getMessage());
System.exit(3);
}
final ClassWriter writer = ClassGenerator.makeClassWriter();
try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName))) {
final ClassReader reader = new ClassReader(bis);
final CheckClassAdapter checker = new CheckClassAdapter(writer);
final ScriptClassInstrumentor instr = new ScriptClassInstrumentor(checker, sci);
reader.accept(instr, 0);
}
try (FileOutputStream fos = new FileOutputStream(fileName)) {
fos.write(writer.toByteArray());
}
}
}

View file

@ -1,150 +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.tools.nasgen;
import java.lang.invoke.MethodHandle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import jdk.internal.org.objectweb.asm.Type;
/**
* String constants used for code generation/instrumentation.
*/
@SuppressWarnings("javadoc")
public interface StringConstants {
static final String NASHORN_INTERNAL = "jdk/nashorn/internal/";
static final String OBJ_PKG = NASHORN_INTERNAL + "objects/";
static final String OBJ_ANNO_PKG = OBJ_PKG + "annotations/";
static final String RUNTIME_PKG = NASHORN_INTERNAL + "runtime/";
static final String SCRIPTS_PKG = NASHORN_INTERNAL + "scripts/";
// standard jdk types, methods
static final Type TYPE_METHODHANDLE = Type.getType(MethodHandle.class);
static final Type TYPE_SPECIALIZATION = Type.getType("L" + RUNTIME_PKG + "Specialization;");
static final Type TYPE_SPECIALIZATION_ARRAY = Type.getType("[L" + RUNTIME_PKG + "Specialization;");
static final Type TYPE_OBJECT = Type.getType(Object.class);
static final Type TYPE_STRING = Type.getType(String.class);
static final Type TYPE_CLASS = Type.getType(Class.class);
static final Type TYPE_COLLECTION = Type.getType(Collection.class);
static final Type TYPE_COLLECTIONS = Type.getType(Collections.class);
static final Type TYPE_ARRAYLIST = Type.getType(ArrayList.class);
static final Type TYPE_LIST = Type.getType(List.class);
static final String CLINIT = "<clinit>";
static final String INIT = "<init>";
static final String DEFAULT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE);
static final String SPECIALIZATION_TYPE = TYPE_SPECIALIZATION.getInternalName();
static final String SPECIALIZATION_INIT2 = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_METHODHANDLE, Type.BOOLEAN_TYPE, Type.BOOLEAN_TYPE);
static final String SPECIALIZATION_INIT3 = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_METHODHANDLE, TYPE_CLASS, Type.BOOLEAN_TYPE, Type.BOOLEAN_TYPE);
static final String OBJECT_TYPE = TYPE_OBJECT.getInternalName();
static final String OBJECT_DESC = TYPE_OBJECT.getDescriptor();
static final String STRING_DESC = TYPE_STRING.getDescriptor();
static final String OBJECT_ARRAY_DESC = Type.getDescriptor(Object[].class);
static final String ARRAYLIST_TYPE = TYPE_ARRAYLIST.getInternalName();
static final String COLLECTION_TYPE = TYPE_COLLECTION.getInternalName();
static final String COLLECTIONS_TYPE = TYPE_COLLECTIONS.getInternalName();
// java.util.Collection.add(Object)
static final String COLLECTION_ADD = "add";
static final String COLLECTION_ADD_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, TYPE_OBJECT);
// java.util.ArrayList.<init>(int)
static final String ARRAYLIST_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
// java.util.Collections.EMPTY_LIST
static final String COLLECTIONS_EMPTY_LIST = "EMPTY_LIST";
static final String LIST_DESC = TYPE_LIST.getDescriptor();
// Nashorn types, methods
static final Type TYPE_ACCESSORPROPERTY = Type.getType("L" + RUNTIME_PKG + "AccessorProperty;");
static final Type TYPE_PROPERTYMAP = Type.getType("L" + RUNTIME_PKG + "PropertyMap;");
static final Type TYPE_PROTOTYPEOBJECT = Type.getType("L" + RUNTIME_PKG + "PrototypeObject;");
static final Type TYPE_SCRIPTFUNCTION = Type.getType("L" + RUNTIME_PKG + "ScriptFunction;");
static final Type TYPE_SCRIPTOBJECT = Type.getType("L" + RUNTIME_PKG + "ScriptObject;");
static final Type TYPE_NATIVESYMBOL = Type.getType("L" + OBJ_PKG + "NativeSymbol;");
static final Type TYPE_SYMBOL = Type.getType("L" + RUNTIME_PKG + "Symbol;");
static final String PROTOTYPE_SUFFIX = "$Prototype";
static final String CONSTRUCTOR_SUFFIX = "$Constructor";
// This field name is known to Nashorn runtime (Context).
// Synchronize the name change, if needed at all.
static final String PROPERTYMAP_FIELD_NAME = "$nasgenmap$";
static final String $CLINIT$ = "$clinit$";
// AccessorProperty
static final String ACCESSORPROPERTY_TYPE = TYPE_ACCESSORPROPERTY.getInternalName();
static final String ACCESSORPROPERTY_CREATE = "create";
static final String ACCESSORPROPERTY_CREATE_DESC =
Type.getMethodDescriptor(TYPE_ACCESSORPROPERTY, TYPE_OBJECT, Type.INT_TYPE, TYPE_METHODHANDLE, TYPE_METHODHANDLE);
// PropertyMap
static final String PROPERTYMAP_TYPE = TYPE_PROPERTYMAP.getInternalName();
static final String PROPERTYMAP_DESC = TYPE_PROPERTYMAP.getDescriptor();
static final String PROPERTYMAP_NEWMAP = "newMap";
static final String PROPERTYMAP_NEWMAP_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP, TYPE_COLLECTION);
// PrototypeObject
static final String PROTOTYPEOBJECT_TYPE = TYPE_PROTOTYPEOBJECT.getInternalName();
static final String PROTOTYPEOBJECT_SETCONSTRUCTOR = "setConstructor";
static final String PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT, TYPE_OBJECT);
// ScriptFunction
static final String SCRIPTFUNCTION_TYPE = TYPE_SCRIPTFUNCTION.getInternalName();
static final String SCRIPTFUNCTION_SETARITY = "setArity";
static final String SCRIPTFUNCTION_SETARITY_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
static final String SCRIPTFUNCTION_SETDOCUMENTATIONKEY = "setDocumentationKey";
static final String SCRIPTFUNCTION_SETDOCUMENTATIONKEY_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_STRING);
static final String SCRIPTFUNCTION_SETPROTOTYPE = "setPrototype";
static final String SCRIPTFUNCTION_SETPROTOTYPE_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT);
static final String SCRIPTFUNCTION_CREATEBUILTIN = "createBuiltin";
static final String SCRIPTFUNCTION_CREATEBUILTIN_DESC =
Type.getMethodDescriptor(TYPE_SCRIPTFUNCTION, TYPE_STRING, TYPE_METHODHANDLE);
static final String SCRIPTFUNCTION_CREATEBUILTIN_SPECS_DESC =
Type.getMethodDescriptor(TYPE_SCRIPTFUNCTION, TYPE_STRING, TYPE_METHODHANDLE, TYPE_SPECIALIZATION_ARRAY);
static final String SCRIPTFUNCTION_INIT_DESC3 =
Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_STRING, TYPE_METHODHANDLE, TYPE_SPECIALIZATION_ARRAY);
static final String SCRIPTFUNCTION_INIT_DESC4 =
Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_STRING, TYPE_METHODHANDLE, TYPE_PROPERTYMAP, TYPE_SPECIALIZATION_ARRAY);
// ScriptObject
static final String SCRIPTOBJECT_TYPE = TYPE_SCRIPTOBJECT.getInternalName();
static final String SCRIPTOBJECT_DESC = TYPE_SCRIPTOBJECT.getDescriptor();
static final String SCRIPTOBJECT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_PROPERTYMAP);
static final String GETTER_PREFIX = "G$";
static final String SETTER_PREFIX = "S$";
// ScriptObject.getClassName() method.
static final String GET_CLASS_NAME = "getClassName";
static final String GET_CLASS_NAME_DESC = Type.getMethodDescriptor(TYPE_STRING);
// NativeSymbol
static final String NATIVESYMBOL_TYPE = TYPE_NATIVESYMBOL.getInternalName();
static final String SYMBOL_DESC = TYPE_SYMBOL.getDescriptor();
static final String SYMBOL_PREFIX = "@@";
}

View file

@ -1,39 +0,0 @@
/*
* Copyright (c) 2016, 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.tools.nasgen;
/**
* Enum to tell where a Function or Property belongs.
* Note: keep this in sync. with jdk.nashorn.internal.objects.annotations.Where.
*/
public enum Where {
/** this means that the item belongs in the Constructor of an object */
CONSTRUCTOR,
/** this means that the item belongs in the Prototype of an object */
PROTOTYPE,
/** this means that the item belongs in the Instance of an object */
INSTANCE
}

View file

@ -1 +0,0 @@
This project implements an ant task to run Nashorn scripts from ant projects.

View file

@ -1,57 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2016, 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.
-->
<project name="nashorntask" default="all" basedir=".">
<target name="init">
<loadproperties srcFile="project.properties"/>
</target>
<target name="prepare" depends="init">
<mkdir dir="${nashorntask.build.classes.dir}"/>
<mkdir dir="${nashorntask.dist.dir}"/>
</target>
<target name="clean" depends="init">
<delete dir="${nashorntask.build.dir}"/>
<delete dir="${nashorntask.dist.dir}"/>
</target>
<target name="compile" depends="prepare" description="Compiles the nashorn ant tag sources">
<javac srcdir="${src.dir}"
destdir="${nashorntask.build.classes.dir}"
debug="${javac.debug}"
includeantruntime="true">
<compilerarg value="-Xlint:unchecked"/>
<compilerarg value="-Xlint:deprecation"/>
</javac>
</target>
<target name="jar" depends="compile" description="Creates nashorntask.jar">
<jar jarfile="${nashorntask.dist.jar}" basedir="${nashorntask.build.classes.dir}"/>
</target>
<target name="dist" depends="jar"/>
<target name="all" depends="dist"
description="Builds sources and generates nashorntask.jar"/>
</project>

View file

@ -1,38 +0,0 @@
#
# Copyright (c) 2016, 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.
#
application.title=nashorntask
# source and target levels
build.compiler=modern
# This directory is removed when the project is cleaned:
nashorntask.build.dir=../../../../build/nashorn/nashorntask
nashorntask.build.classes.dir=${nashorntask.build.dir}/classes
# This directory is removed when the project is cleaned:
nashorntask.dist.dir=${nashorntask.build.dir}/dist
nashorntask.dist.jar=${nashorntask.dist.dir}/nashorntask.jar
nashorntask.dist.javadoc.dir=${nashorntask.dist.dir}/javadoc
javac.debug=true
src.dir=src

View file

@ -1,76 +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.ant;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
/**
* This class implements an ant task to evaluate nashorn scripts
* from ant projects.
*/
public final class NashornTask extends Task {
// Underlying nashorn script engine
private final ScriptEngine engine;
// the current ant project
private Project project;
// the script evaluated by this task
private String script;
public NashornTask() {
final ScriptEngineManager m = new ScriptEngineManager();
this.engine = m.getEngineByName("nashorn");
}
@Override
public void setProject(Project proj) {
this.project = proj;
}
// set the script to be evaluated
public void addText(String text) {
this.script = text;
}
@Override
public void execute() {
// expose project as "project" variable
engine.put("project", project);
// expose this task as "self" variable
engine.put("self", this);
// evaluate specified script
try {
engine.eval(script);
} catch (final ScriptException se) {
throw new BuildException(se);
}
}
}

View file

@ -1,181 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project name="code-coverage" default="generate-code-coverage-report" basedir="..">
<!-- CODE COVERAGE -->
<target name="init-cc-enabled" if="${cc.enabled}">
<echo message="initialize [${jcov}] java coverage"/>
<property name="cc.report.dir" value="${cc.dir}/CC_${jcov}_report"/>
<property name="cc.merged.xml" value="${cc.dir}/CC_${jcov}_result-merged.xml"/>
<condition property="run.test.cc.jvmargs" value="${cc.dynamic.args}">
<equals arg1="${jcov}" arg2="dynamic" trim="true"/>
</condition>
<condition property="cc.generate.template" value="true">
<equals arg1="${cc.dynamic.genereate.template}" arg2="true" trim="true"/>
</condition>
<mkdir dir="${cc.dir}"/>
<mkdir dir="${build.dir}/to_be_instrumented"/>
<!-- info -->
<echo message="jcov=${jcov}"/>
<echo message="cc.generate.template=${cc.generate.template}"/>
<echo message="cc.instrument=${cc.instrument}"/>
<echo message="run.test.cc.jvmargs=${run.test.cc.jvmargs}"/>
<echo message="cc.report.dir=${cc.report.dir}"/>
<echo message="cc.merged.xml=${cc.merged.xml}"/>
</target>
<target name="init-cc-disabled" unless="${cc.enabled}">
<property name="run.test.cc.jvmargs" value=""/>
</target>
<target name="prepare-to-be-instrumented" depends="compile" description="Prepares to_be_instrumented dir">
<copy todir="${build.dir}/to_be_instrumented">
<fileset dir="${build.classes.dir}">
<include name="**/*.class"/>
</fileset>
</copy>
</target>
<target name="generate-cc-template" depends="prepare-to-be-instrumented" description="Generates code coverage template for dynamic CC" if="cc.generate.template">
<property name="cc.instrumented.path" location="${build.dir}/to_be_instrumented"/>
<java classname="com.sun.tdk.jcov.TmplGen">
<arg value="-verbose"/>
<arg line="-include ${cc.include}"/>
<arg line="-type all"/>
<arg line="-template ${cc.template}"/>
<arg value="${cc.instrumented.path}"/>
<classpath>
<pathelement location="${jcov.jar}"/>
</classpath>
</java>
<java classname="com.sun.tdk.jcov.RepGen">
<arg value="-verbose"/>
<arg line="-output ${cc.dir}/CC_template_report"/>
<arg value="${cc.template}"/>
<classpath>
<pathelement location="${jcov.jar}"/>
</classpath>
</java>
</target>
<target name="init-cc" depends="init-cc-disabled, init-cc-enabled">
<property name="run.test.cc.jvmargs" value=""/>
</target>
<target name="init-cc-cleanup" if="${cc.enabled}">
<delete dir="${cc.dir}" failonerror="false" />
<delete dir="${build.dir}/to_be_instrumented" failonerror="false" />
</target>
<target name="check-merging-files" depends="init">
<echo message="checking avalibility of ${cc.template}"/>
<condition property="nothing-to-merge" value="true">
<not>
<available file="${cc.template}"/>
</not>
</condition>
<echo message="nothing-to-merge = ${nothing-to-merge}"/>
</target>
<target name="fix-merging-files" depends="check-merging-files" if="${nothing-to-merge}">
<echo message="making pre-merge workaround due to missed template"/>
<move todir="${cc.dir}" includeemptydirs="false">
<fileset dir="${cc.dir}">
<include name="*.xml"/>
</fileset>
<mapper type="glob" from="*.xml" to="CC_${jcov}_result-merged.xml"/>
</move>
</target>
<target name="merge-code-coverage" depends="fix-merging-files" unless="${nothing-to-merge}">
<echo message="merging files"/>
<fileset dir="${cc.dir}" id="cc.xmls">
<include name="**/*_${jcov}_*.xml"/>
<include name="**/CC_template.xml"/>
</fileset>
<pathconvert pathsep=" " property="cc.all.xmls" refid="cc.xmls"/>
<echo message="merging files - ${cc.all.xmls}" />
<java classname="com.sun.tdk.jcov.Merger">
<arg value="-verbose"/>
<arg value="-output"/>
<arg value="${cc.merged.xml}"/>
<arg value="-exclude"/>
<arg value="com\.oracle\.nashorn\.runtime\.ScriptRuntime*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.javaadapters*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.objects\.annotations*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.scripts*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.lookup\.MethodHandleFactory*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.test\.framework*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.test\.models*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.ir\.debug*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.runtime\.regexp\.joni\.bench*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.runtime\.DebugLogger*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.runtime\.Timing*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.runtime\.Logging*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.runtime\.Debug*"/>
<arg value="-exclude"/>
<arg value="jdk\.nashorn\.internal\.objects\.NativeDebug*"/>
<arg line="${cc.all.xmls}"/>
<classpath>
<pathelement location="${jcov.jar}"/>
</classpath>
</java>
</target>
<target name="generate-code-coverage-report" depends="merge-code-coverage">
<java classname="com.sun.tdk.jcov.RepGen">
<arg value="-verbose"/>
<!-- <arg line ="-exclude_list CC.report.exclude"/> -->
<arg line="-output ${cc.report.dir}"/>
<arg value="${cc.merged.xml}"/>
<classpath>
<pathelement location="${jcov.jar}"/>
</classpath>
</java>
</target>
</project>

View file

@ -1,280 +0,0 @@
module:java.base
java.io
java.lang
java.lang.annotation
java.lang.invoke
java.lang.module
java.lang.ref
java.lang.reflect
java.math
java.net
java.net.spi
java.nio
java.nio.channels
java.nio.channels.spi
java.nio.charset
java.nio.charset.spi
java.nio.file
java.nio.file.attribute
java.nio.file.spi
java.security
java.security.acl
java.security.cert
java.security.interfaces
java.security.spec
java.text
java.text.spi
java.time
java.time.chrono
java.time.format
java.time.temporal
java.time.zone
java.util
java.util.concurrent
java.util.concurrent.atomic
java.util.concurrent.locks
java.util.function
java.util.jar
java.util.regex
java.util.spi
java.util.stream
java.util.zip
javax.crypto
javax.crypto.interfaces
javax.crypto.spec
javax.net
javax.net.ssl
javax.security.auth
javax.security.auth.callback
javax.security.auth.login
javax.security.auth.spi
javax.security.auth.x500
javax.security.cert
module:java.compiler
javax.annotation.processing
javax.lang.model
javax.lang.model.element
javax.lang.model.type
javax.lang.model.util
javax.tools
module:java.datatransfer
java.awt.datatransfer
module:java.desktop
java.applet
java.awt
java.awt.color
java.awt.desktop
java.awt.dnd
java.awt.event
java.awt.font
java.awt.geom
java.awt.im
java.awt.im.spi
java.awt.image
java.awt.image.renderable
java.awt.print
java.beans
java.beans.beancontext
javax.accessibility
javax.imageio
javax.imageio.event
javax.imageio.metadata
javax.imageio.plugins.bmp
javax.imageio.plugins.jpeg
javax.imageio.plugins.tiff
javax.imageio.spi
javax.imageio.stream
javax.print
javax.print.attribute
javax.print.attribute.standard
javax.print.event
javax.sound.midi
javax.sound.midi.spi
javax.sound.sampled
javax.sound.sampled.spi
javax.swing
javax.swing.border
javax.swing.colorchooser
javax.swing.event
javax.swing.filechooser
javax.swing.plaf
javax.swing.plaf.basic
javax.swing.plaf.metal
javax.swing.plaf.multi
javax.swing.plaf.nimbus
javax.swing.plaf.synth
javax.swing.table
javax.swing.text
javax.swing.text.html
javax.swing.text.html.parser
javax.swing.text.rtf
javax.swing.tree
javax.swing.undo
module:java.instrument
java.lang.instrument
module:java.logging
java.util.logging
module:java.management
java.lang.management
javax.management
javax.management.loading
javax.management.modelmbean
javax.management.monitor
javax.management.openmbean
javax.management.relation
javax.management.remote
javax.management.timer
module:java.management.rmi
javax.management.remote.rmi
module:java.naming
javax.naming
javax.naming.directory
javax.naming.event
javax.naming.ldap
javax.naming.spi
module:java.net.http
java.net.http
module:java.prefs
java.util.prefs
module:java.rmi
java.rmi
java.rmi.activation
java.rmi.dgc
java.rmi.registry
java.rmi.server
javax.rmi.ssl
module:java.scripting
javax.script
module:java.se
module:java.security.jgss
javax.security.auth.kerberos
org.ietf.jgss
module:java.security.sasl
javax.security.sasl
module:java.smartcardio
javax.smartcardio
module:java.sql
java.sql
javax.sql
module:java.sql.rowset
javax.sql.rowset
javax.sql.rowset.serial
javax.sql.rowset.spi
module:java.transaction.xa
javax.transaction.xa
module:java.xml
javax.xml
javax.xml.catalog
javax.xml.datatype
javax.xml.namespace
javax.xml.parsers
javax.xml.stream
javax.xml.stream.events
javax.xml.stream.util
javax.xml.transform
javax.xml.transform.dom
javax.xml.transform.sax
javax.xml.transform.stax
javax.xml.transform.stream
javax.xml.validation
javax.xml.xpath
org.w3c.dom
org.w3c.dom.bootstrap
org.w3c.dom.events
org.w3c.dom.ls
org.w3c.dom.ranges
org.w3c.dom.traversal
org.w3c.dom.views
org.xml.sax
org.xml.sax.ext
org.xml.sax.helpers
module:java.xml.crypto
javax.xml.crypto
javax.xml.crypto.dom
javax.xml.crypto.dsig
javax.xml.crypto.dsig.dom
javax.xml.crypto.dsig.keyinfo
javax.xml.crypto.dsig.spec
module:jdk.accessibility
com.sun.java.accessibility.util
module:jdk.attach
com.sun.tools.attach
com.sun.tools.attach.spi
module:jdk.charsets
module:jdk.compiler
com.sun.source.doctree
com.sun.source.tree
com.sun.source.util
com.sun.tools.javac
module:jdk.crypto.cryptoki
module:jdk.crypto.ec
module:jdk.dynalink
jdk.dynalink
jdk.dynalink.beans
jdk.dynalink.linker
jdk.dynalink.linker.support
jdk.dynalink.support
module:jdk.editpad
module:jdk.hotspot.agent
module:jdk.httpserver
com.sun.net.httpserver
com.sun.net.httpserver.spi
module:jdk.jartool
com.sun.jarsigner
jdk.security.jarsigner
module:jdk.javadoc
com.sun.javadoc
com.sun.tools.javadoc
jdk.javadoc.doclet
module:jdk.jcmd
module:jdk.jconsole
com.sun.tools.jconsole
module:jdk.jdeps
module:jdk.jdi
com.sun.jdi
com.sun.jdi.connect
com.sun.jdi.connect.spi
com.sun.jdi.event
com.sun.jdi.request
module:jdk.jdwp.agent
module:jdk.jfr
jdk.jfr
jdk.jfr.consumer
module:jdk.jlink
module:jdk.jshell
jdk.jshell
jdk.jshell.execution
jdk.jshell.spi
jdk.jshell.tool
module:jdk.jsobject
netscape.javascript
module:jdk.jstatd
module:jdk.localedata
module:jdk.management
com.sun.management
module:jdk.management.agent
module:jdk.management.jfr
jdk.management.jfr
module:jdk.naming.dns
module:jdk.naming.rmi
module:jdk.net
jdk.net
jdk.nio
module:jdk.scripting.nashorn
jdk.nashorn.api.scripting
jdk.nashorn.api.tree
module:jdk.sctp
com.sun.nio.sctp
module:jdk.security.auth
com.sun.security.auth
com.sun.security.auth.callback
com.sun.security.auth.login
com.sun.security.auth.module
module:jdk.security.jgss
com.sun.security.jgss
module:jdk.xml.dom
org.w3c.dom.css
org.w3c.dom.html
org.w3c.dom.stylesheets
org.w3c.dom.xpath
module:jdk.zipfs

View file

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<excludeList>
</excludeList>

View file

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<excludeList>
<test id="JDK-8014647.js" />
<test id="javaclassoverrides.js" />
<test id="JDK-8020809.js" />
</excludeList>

View file

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project basedir=".." name="nashorn-IDE">
<target name="debug-selected-file-in-src">
<fail unless="test.class">Must set property 'debug.class'</fail>
<nbjpdastart addressproperty="jpda.address" name="nashorn" transport="dt_socket">
<classpath path="${run.test.classpath}"/>
</nbjpdastart>
<ant antfile="build.xml" inheritall="false" target="test">
<property name="test.class" value="${test.class}"/>
<property name="debug.test.jvmargs" value="-Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
</ant>
</target>
</project>

View file

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project basedir="../.." name="nashorn-IDE">
<import file="../build.xml"/>
<!-- TODO: edit the following target according to your needs -->
<!-- (more info: http://www.netbeans.org/kb/articles/freeform-config.html#debugj2se) -->
<target depends="jar" description="Run the shell with a sample script" name="debug-nb">
<nbjpdastart addressproperty="jpda.address" name="nashorn" transport="dt_socket">
<classpath path="${run.test.classpath}"/>
</nbjpdastart>
<java classname="jdk.nashorn.tools.Shell" classpath="${run.test.classpath}" dir="samples" fork="true">
<jvmarg line="-Dnashorn.optimistic"/>
<jvmarg line="${nashorn.override.path}"/>
<jvmarg line="${run.test.jvmargs}"/>
<jvmarg value="-Xdebug"/>
<jvmarg value="-Xrunjdwp:transport=dt_socket,address=${jpda.address}"/>
</java>
</target>
</project>

View file

@ -1,179 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><project name="jdk" basedir=".">
<!--
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.
-->
<description>
Permits selection of a JDK to use when building and running project.
See: http://www.netbeans.org/issues/show_bug.cgi?id=64160
</description>
<target name="-jdk-pre-preinit">
<condition property="nbjdk.active-or-nbjdk.home">
<or>
<and>
<isset property="nbjdk.active"/>
<not>
<equals arg1="${nbjdk.active}" arg2="default_platform"/>
</not>
</and>
<and>
<isset property="nbjdk.home"/>
<not>
<isset property="nbjdk.home.defaulted"/>
</not>
</and>
</or>
</condition>
</target>
<target xmlns:common="http://java.netbeans.org/freeform/jdk.xml" name="-jdk-preinit" depends="-jdk-pre-preinit" if="nbjdk.active-or-nbjdk.home">
<macrodef name="property" uri="http://java.netbeans.org/freeform/jdk.xml">
<attribute name="name"/>
<attribute name="value"/>
<sequential>
<property name="@{name}" value="${@{value}}"/>
</sequential>
</macrodef>
<common:property name="nbjdk.home" value="platforms.${nbjdk.active}.home"/>
<common:property name="nbjdk.javac.tmp" value="platforms.${nbjdk.active}.javac"/>
<condition property=".exe" value=".exe">
<os family="windows"/>
</condition>
<property name=".exe" value=""/>
<condition property="nbjdk.javac" value="${nbjdk.home}/bin/javac${.exe}">
<equals arg1="${nbjdk.javac.tmp}" arg2="$${platforms.${nbjdk.active}.javac}"/>
</condition>
<property name="nbjdk.javac" value="${nbjdk.javac.tmp}"/>
<common:property name="nbjdk.java.tmp" value="platforms.${nbjdk.active}.java"/>
<condition property="nbjdk.java" value="${nbjdk.home}/bin/java${.exe}">
<equals arg1="${nbjdk.java.tmp}" arg2="$${platforms.${nbjdk.active}.java}"/>
</condition>
<property name="nbjdk.java" value="${nbjdk.java.tmp}"/>
<common:property name="nbjdk.javadoc.tmp" value="platforms.${nbjdk.active}.javadoc"/>
<condition property="nbjdk.javadoc" value="${nbjdk.home}/bin/javadoc${.exe}">
<equals arg1="${nbjdk.javadoc.tmp}" arg2="$${platforms.${nbjdk.active}.javadoc}"/>
</condition>
<property name="nbjdk.javadoc" value="${nbjdk.javadoc.tmp}"/>
<common:property name="nbjdk.bootclasspath.tmp" value="platforms.${nbjdk.active}.bootclasspath"/>
<condition property="nbjdk.bootclasspath" value="${nbjdk.home}/jre/lib/rt.jar">
<equals arg1="${nbjdk.bootclasspath.tmp}" arg2="$${platforms.${nbjdk.active}.bootclasspath}"/>
</condition>
<property name="nbjdk.bootclasspath" value="${nbjdk.bootclasspath.tmp}"/>
<condition property="nbjdk.valid">
<and>
<available file="${nbjdk.home}" type="dir"/>
<available file="${nbjdk.javac}" type="file"/>
<available file="${nbjdk.java}" type="file"/>
<available file="${nbjdk.javadoc}" type="file"/>
</and>
</condition>
<echo level="verbose">nbjdk.active=${nbjdk.active} nbjdk.home=${nbjdk.home} nbjdk.java=${nbjdk.java} nbjdk.javac=${nbjdk.javac} nbjdk.javadoc=${nbjdk.javadoc} nbjdk.bootclasspath=${nbjdk.bootclasspath} nbjdk.valid=${nbjdk.valid} have-jdk-1.4=${have-jdk-1.4} have-jdk-1.5=${have-jdk-1.5}</echo>
</target>
<target name="-jdk-warn" depends="-jdk-preinit" if="nbjdk.active-or-nbjdk.home" unless="nbjdk.valid">
<property name="jdkhome.presumed" location="${java.home}/.."/>
<echo level="warning">Warning: nbjdk.active=${nbjdk.active} or nbjdk.home=${nbjdk.home} is an invalid Java platform; ignoring and using ${jdkhome.presumed}</echo>
</target>
<target name="-jdk-presetdef-basic" depends="-jdk-preinit" if="nbjdk.valid" unless="nbjdk.presetdef.basic.done">
<macrodef name="javac-presetdef">
<attribute name="javacval"/>
<sequential>
<presetdef name="javac">
<javac fork="yes" executable="@{javacval}"/>
</presetdef>
</sequential>
</macrodef>
<javac-presetdef javacval="${nbjdk.javac}"/>
<macrodef name="java-presetdef">
<attribute name="javaval"/>
<sequential>
<presetdef name="java">
<java fork="yes" jvm="@{javaval}"/>
</presetdef>
</sequential>
</macrodef>
<java-presetdef javaval="${nbjdk.java}"/>
<macrodef name="javadoc-presetdef">
<attribute name="javadocval"/>
<sequential>
<presetdef name="javadoc">
<javadoc executable="@{javadocval}"/>
</presetdef>
</sequential>
</macrodef>
<javadoc-presetdef javadocval="${nbjdk.javadoc}"/>
<macrodef name="junit-presetdef">
<attribute name="javaval"/>
<sequential>
<presetdef name="junit">
<junit fork="yes" jvm="@{javaval}"/>
</presetdef>
</sequential>
</macrodef>
<junit-presetdef javaval="${nbjdk.java}"/>
<property name="nbjdk.presetdef.basic.done" value="true"/>
</target>
<target name="-jdk-presetdef-nbjpdastart" depends="-jdk-preinit" if="nbjdk.valid" unless="nbjdk.presetdef.nbjpdastart.done">
<macrodef name="nbjpdastart-presetdef">
<attribute name="bootcpval"/>
<sequential>
<presetdef name="nbjpdastart">
<nbjpdastart>
<bootclasspath>
<path path="@{bootcpval}"/>
</bootclasspath>
</nbjpdastart>
</presetdef>
</sequential>
</macrodef>
<nbjpdastart-presetdef bootcpval="${nbjdk.bootclasspath}"/>
<property name="nbjdk.presetdef.nbjpdastart.done" value="true"/>
</target>
<target name="-jdk-default" unless="nbjdk.active-or-nbjdk.home">
<property name="java.home.parent" location="${java.home}/.."/>
<condition property="nbjdk.home" value="${java.home.parent}">
<available file="${java.home.parent}/lib/tools.jar" type="file"/>
</condition>
<condition property="nbjdk.home" value="${java.home}">
<available file="${java.home}/lib/tools.jar" type="file"/>
</condition>
<condition property="nbjdk.home" value="/Library/Java/Home">
<available file="/Library/Java/Home" type="dir"/>
</condition>
<property name="nbjdk.home" location="${java.home.parent}"/>
<property name="nbjdk.home.defaulted" value="true"/>
</target>
<target name="-jdk-init" depends="-jdk-preinit,-jdk-warn,-jdk-presetdef-basic,-jdk-default"/>
</project>

View file

@ -1,24 +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.
#
# 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.
#
nbjdk.active=JDK_9

View file

@ -1,48 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project basedir="..">
<property file="../global.properties"/>
<property file="nbproject/nbjdk.properties"/>
<property location="${netbeans.user}/build.properties" name="user.properties.file"/>
<property file="${user.properties.file}"/>
<import file="jdk.xml"/>
<target depends="-jdk-init" name="jar">
<ant inheritall="false" target="jar"/>
</target>
<target depends="-jdk-init" name="clean">
<ant inheritall="false" target="clean"/>
</target>
<target depends="-jdk-init" name="javadoc">
<ant inheritall="false" target="javadoc"/>
</target>
<target depends="-jdk-init" name="test">
<ant inheritall="false" target="test"/>
</target>
<target depends="-jdk-init" name="run">
<ant inheritall="false" target="run"/>
</target>
<target depends="-jdk-init,-jdk-presetdef-nbjpdastart" name="debug-nb">
<ant antfile="nbproject/ide-targets.xml" inheritall="false" target="debug-nb"/>
</target>
</project>

View file

@ -1,212 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.ant.freeform</type>
<configuration>
<general-data xmlns="http://www.netbeans.org/ns/freeform-project/1">
<name>nashorn</name>
</general-data>
<general-data xmlns="http://www.netbeans.org/ns/freeform-project/2">
<!-- Do not use Project Properties customizer when editing this file manually. -->
<name>nashorn</name>
<properties/>
<folders>
<source-folder>
<label>nashorn</label>
<location>.</location>
<encoding>UTF-8</encoding>
</source-folder>
<source-folder>
<label>../test/src</label>
<location>../test/src</location>
</source-folder>
<source-folder>
<label>../buildtools/nasgen/src</label>
<location>../buildtools/nasgen/src</location>
</source-folder>
<source-folder>
<label>../src/jdk.scripting.nashorn/share/classes</label>
<location>../src/jdk.scripting.nashorn/share/classes</location>
</source-folder>
<source-folder>
<label>../src/jdk.scripting.nashorn.shell/share/classes</label>
<location>../src/jdk.scripting.nashorn.shell/share/classes</location>
</source-folder>
<source-folder>
<label>../test/src</label>
<type>java</type>
<location>../test/src</location>
<encoding>UTF-8</encoding>
</source-folder>
<source-folder>
<label>../buildtools/nasgen/src</label>
<type>java</type>
<location>../buildtools/nasgen/src</location>
<encoding>UTF-8</encoding>
</source-folder>
<source-folder>
<label>../src/jdk.scripting.nashorn/share/classes</label>
<type>java</type>
<location>../src/jdk.scripting.nashorn/share/classes</location>
<encoding>UTF-8</encoding>
</source-folder>
<source-folder>
<label>../src/jdk.scripting.nashorn.shell/share/classes</label>
<type>java</type>
<location>../src/jdk.scripting.nashorn.shell/share/classes</location>
<encoding>UTF-8</encoding>
</source-folder>
<source-folder>
<label>../src/jdk.dynalink/share/classes</label>
<type>java</type>
<location>../src/jdk.dynalink/share/classes</location>
<encoding>UTF-8</encoding>
</source-folder>
<source-folder>
<label>../src/jdk.dynalink/share/classes</label>
<location>../src/jdk.dynalink/share/classes</location>
</source-folder>
</folders>
<ide-actions>
<action name="build">
<script>nbproject/nbjdk.xml</script>
<target>jar</target>
</action>
<action name="clean">
<script>nbproject/nbjdk.xml</script>
<target>clean</target>
</action>
<action name="javadoc">
<script>nbproject/nbjdk.xml</script>
<target>javadoc</target>
</action>
<action name="test">
<script>nbproject/nbjdk.xml</script>
<target>test</target>
</action>
<action name="rebuild">
<script>nbproject/nbjdk.xml</script>
<target>clean</target>
<target>jar</target>
</action>
<action name="run">
<script>nbproject/nbjdk.xml</script>
<target>run</target>
</action>
<action name="debug">
<script>nbproject/nbjdk.xml</script>
<target>debug-nb</target>
</action>
<action name="run.single">
<script>build.xml</script>
<target>test</target>
<context>
<property>test.class</property>
<folder>../test/src</folder>
<pattern>\.java$</pattern>
<format>relative-path-noext</format>
<arity>
<one-file-only/>
</arity>
</context>
</action>
<action name="debug.single">
<script>nbproject/ide-file-targets.xml</script>
<target>debug-selected-file-in-src</target>
<context>
<property>test.class</property>
<folder>../test/src</folder>
<pattern>\.java$</pattern>
<format>relative-path-noext</format>
<arity>
<one-file-only/>
</arity>
</context>
</action>
</ide-actions>
<view>
<items>
<source-folder style="packages">
<label>../test/src</label>
<location>../test/src</location>
</source-folder>
<source-folder style="packages">
<label>../buildtools/nasgen/src</label>
<location>../buildtools/nasgen/src</location>
</source-folder>
<source-folder style="packages">
<label>../src/jdk.scripting.nashorn/share/classes</label>
<location>../src/jdk.scripting.nashorn/share/classes</location>
</source-folder>
<source-folder style="packages">
<label>../src/jdk.scripting.nashorn.shell/share/classes</label>
<location>../src/jdk.scripting.nashorn.shell/share/classes</location>
</source-folder>
<source-folder style="packages">
<label>../src/jdk.dynalink/share/classes</label>
<location>../src/jdk.dynalink/share/classes</location>
</source-folder>
<source-file>
<location>build.xml</location>
</source-file>
</items>
<context-menu>
<ide-action name="build"/>
<ide-action name="rebuild"/>
<ide-action name="clean"/>
<ide-action name="javadoc"/>
<ide-action name="run"/>
<ide-action name="test"/>
<ide-action name="debug"/>
</context-menu>
</view>
<subprojects/>
</general-data>
<java-data xmlns="http://www.netbeans.org/ns/freeform-project-java/4">
<compilation-unit>
<package-root>../test/src</package-root>
<unit-tests/>
<classpath mode="compile">../test/lib/testng.jar:../build/classes:../src/jdk.scripting.nashorn/share/classes</classpath>
<source-level>1.8</source-level>
</compilation-unit>
<compilation-unit>
<package-root>../buildtools/nasgen/src</package-root>
<classpath mode="compile">../build/classes:../src</classpath>
<source-level>1.8</source-level>
</compilation-unit>
<compilation-unit>
<package-root>../src/jdk.scripting.nashorn/share/classes</package-root>
<source-level>1.8</source-level>
</compilation-unit>
<compilation-unit>
<package-root>../src/jdk.scripting.nashorn.shell/share/classes</package-root>
<source-level>1.8</source-level>
</compilation-unit>
<compilation-unit>
<package-root>../src/jdk.dynalink/share/classes</package-root>
<source-level>1.8</source-level>
</compilation-unit>
</java-data>
</configuration>
</project>

View file

@ -1,492 +0,0 @@
#
# Copyright (c) 2010, 2018, 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.
#
application.title=nashorn
# location of JDK embedded ASM sources
jdk.java.base.dir=src/java.base/share/classes
jdk.asm.src.dir=${jdk.java.base.dir}/jdk/internal/org/objectweb/asm
# location of JDK embedded jline sources
jdk.jline.src.dir=src/jdk.internal.le/share/classes
# source and target levels
build.compiler=modern
jdk.build.dir=build
nashorn.make.dir=make/nashorn
javadoc.base.url=https://docs.oracle.com/en/java/javase/11/docs/api/
javadoc.element.list=make/nashorn
javadoc.option=\
-tag "implSpec:a:Implementation Requirements:" \
-tag "implNote:a:Implementation Note:" \
-tag "moduleGraph:a:Module Graph"
# nashorn version information
nashorn.version=0.1
nashorn.fullversion=0.1
nashorn.product.name=Oracle Nashorn
# This directory is removed when the project is cleaned:
build.dir=${jdk.build.dir}/nashorn
build.classes.dir=${build.dir}/classes
build.zip=${build.dir}/nashorn.zip
build.gzip=${build.dir}/nashorn.tar.gz
nashorn.override.option=\
--patch-module jdk.scripting.nashorn=${build.classes.dir}/jdk.scripting.nashorn \
--patch-module jdk.scripting.nashorn.shell=${build.classes.dir}/jdk.scripting.nashorn.shell \
--patch-module jdk.dynalink=${build.classes.dir}/jdk.dynalink
# project directory of <nashorn> ant task
nashorntask.dir=${nashorn.make.dir}/buildtools/nashorntask
nashorntask.dist.dir=${build.dir}/nashorntask/dist
# nashorn Shell tool
nashorn.shell.tool=jdk.nashorn.tools.Shell
# nasgen tool
nasgen.tool=jdk.nashorn.internal.tools.nasgen.Main
nasgen.module.imports=\
--add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED \
--add-exports java.base/jdk.internal.org.objectweb.asm.util=ALL-UNNAMED
# parallel test runner tool
parallel.test.runner=jdk.nashorn.internal.test.framework.ParallelTestRunner
# test classes directory
build.test.classes.dir=${build.dir}/test/classes
# nashorn test jar - internal tests jar and api tests jar
nashorn.internal.tests.jar=${build.dir}/nashorn-internal-tests.jar
nashorn.api.tests.jar=${build.dir}/nashorn-api-tests.jar
# test results directory
build.test.results.dir=${build.dir}/test/reports
build.nosecurity.test.results.dir=${build.dir}/test/nosecurity/reports
build.nooptimistic.test.results.dir=${build.dir}/test/nooptimistic/reports
# This directory is removed when the project is cleaned:
dist.dir=build/nashorn/dist
dynalink.jar=${dist.dir}/dynalink.jar
nashorn.jar=${dist.dir}/nashorn.jar
jjs.jar=${dist.dir}/jjs.jar
dist.javadoc.dir=${dist.dir}/javadoc
dist.nashornapi.javadoc.dir=${dist.javadoc.dir}/nashornapi
dist.dynalinkapi.javadoc.dir=${dist.javadoc.dir}/dynalinkapi
# configuration for flight recorder
run.test.jvmargs.jfr=XX:StartFlightRecording=disk=true,dumponexit=true,dumponexitpath=${build.dir},stackdepth=128
# test library location
test.lib=test/nashorn/lib
# jars refererred
file.reference.testng.jar=${test.lib}${file.separator}testng-6.8.jar
file.reference.jcommander.jar=${test.lib}${file.separator}jcommander-1.27.jar
file.reference.bsh.jar=${test.lib}${file.separator}bsh-2.0b4.jar
file.reference.snakeyaml.jar=${test.lib}${file.separator}snakeyaml-1.6.jar
file.reference.asmtools.jar=${test.lib}${file.separator}asmtools-60.jar
# TestNG ant task classpath
testng.ant.classpath=\
${file.reference.testng.jar}${path.separator}\
${file.reference.jcommander.jar}${path.separator}\
${file.reference.bsh.jar}${path.separator}\
${file.reference.snakeyaml.jar}${path.separator}
# Set testng verbose level
# From TestNG docs: "the verbosity level (0 to 10 where 10 is most detailed)
# Actually, this is a lie: you can specify -1 and this will put TestNG in
# debug mode (no longer slicing off stack traces and all)."
testng.verbose=2
# TestNG listeners - we want to replace TestNG's own JUnit
# reporter, but want everything else provided by default
# Unfortunately, we've to clone the other default reporters here.
testng.listeners=\
org.testng.reporters.SuiteHTMLReporter, \
org.testng.reporters.TestHTMLReporter, \
org.testng.reporters.jq.Main, \
org.testng.reporters.FailedReporter, \
org.testng.reporters.XMLReporter \
org.testng.reporters.EmailableReporter, \
jdk.nashorn.internal.test.framework.JSJUnitReportReporter
javac.debug=true
javac.encoding=ascii
javac.test.classpath=\
${build.test.classes.dir}${path.separator}\
${file.reference.testng.jar}${path.separator}\
${file.reference.jcommander.jar}${path.separator}\
${file.reference.bsh.jar}${path.separator}\
${file.reference.snakeyaml.jar}
test.module.imports.compile.time=\
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.ir=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.codegen=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.parser=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.objects=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.doubleconv=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.linker=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.events=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.options=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.regexp=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.regexp.joni=ALL-UNNAMED \
--add-exports jdk.scripting.nashorn/jdk.nashorn.tools=ALL-UNNAMED \
--add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED
test.module.imports.runtime=\
${test.module.imports.compile.time} \
--add-opens jdk.scripting.nashorn/jdk.nashorn.internal.runtime=ALL-UNNAMED \
--add-opens jdk.scripting.nashorn/jdk.nashorn.internal.runtime.doubleconv=ALL-UNNAMED
meta.inf.dir=${nashorn.module.src.dir}/META-INF
run.classpath=\
${build.classes.dir}
# test scripts to run
test.dir=test/nashorn
test.nosecurity.dir=${test.dir}/script/nosecurity
test.script.dir=${test.dir}/script
test.basic.dir=${test.script.dir}/basic
test.maptests.dir=${test.script.dir}/maptests
test.error.dir=${test.script.dir}/error
test.sandbox.dir=${test.script.dir}/sandbox
test.trusted.dir=${test.script.dir}/trusted
test.external.dir=${test.script.dir}/external
test262.dir=${test.external.dir}/test262
test262.suite.dir=${test262.dir}/test/suite
testjfx.dir=${test.script.dir}/jfx
testmarkdown.dir=${test.script.dir}/markdown
test-sys-prop.test.dir=${test.dir}
test-sys-prop.test.js.roots=${test.basic.dir} ${test.maptests.dir} ${test.error.dir} ${test.sandbox.dir} ${test.trusted.dir}
test-sys-prop.test262.suite.dir=${test262.suite.dir}
test-sys-prop.es5conform.testcases.dir=${test.external.dir}/ES5Conform/TestCases
test-sys-prop.test.basic.dir=${test.basic.dir}
test-sys-prop.test.external.dir=${test.external.dir}
test-sys-prop.test.maptests.dir=${test.maptests.dir}
test-sys-prop.test.sandbox.dir=${test.sandbox.dir}
test-sys-prop.test.trusted.dir=${test.trusted.dir}
test-sys-prop-no-security.test.dir=${test.dir}
test-sys-prop-no-security.test.js.roots=${test.nosecurity.dir}
# framework root for our script tests
test-sys-prop.test.js.framework=${test.script.dir}/assert.js
test-sys-prop-no-security.test.js.framework=${test.script.dir}/assert.js
# Control the verbosity of ParserTest
test-sys-prop.parsertest.verbose=false
# turn on/off scripting mode for parser tests
test-sys-prop.parsertest.scripting=true
test-sys-prop.parserapitest.verbose=false
# turn on/off test262 scripts for parser tests
test-sys-prop.parsertest.test262=false
test-sys-prop.parserapitest.test262=false
# Control the verbosity of the CompilerTest
test-sys-prop.compilertest.verbose=false
# turn on/off scripting mode for compiler tests
test-sys-prop.compilertest.scripting=true
# turn on/off test262 scripts for compiler tests
test-sys-prop.compilertest.test262=false
# test directory to be excluded.
test-sys-prop.test.js.exclude.dir=${test.script.dir}/currently-failing ${test.external.dir}
# run everything that's js in here, without checking file headers for test annotations
test-sys-prop.test.js.unchecked.dir=${test262.dir}
# test root for octane
octane-test-sys-prop.test.js.roots=${test.external.dir}/octane/
# run octane benchmars in separate processes? (recommended)
octane-test-sys-prop.separate.process=true
# framework root for octane
octane-test-sys-prop.test.js.framework=${test.basic.dir}/run-octane.js
# test root for sunspider
sunspider-test-sys-prop.test.js.roots=${test.external.dir}/sunspider/tests/sunspider-1.0.2/
# framework root for sunspider
sunspider-test-sys-prop.test.js.framework=${test.basic.dir}/runsunspider.js
# list of tests to be excluded
sunspider-test-sys-prop.test.js.exclude.list=
# execute our script tests in shared nashorn context or not?
test-sys-prop.test.js.shared.context=false
# execute test262 tests in shared nashorn context or not?
test262-test-sys-prop.test.js.shared.context=true
# test262 test root
test262-test-sys-prop.test.js.roots=${test262.suite.dir}
# test262 enable/disable strict mode tests
test262-test-sys-prop.test.js.enable.strict.mode=true
# file containing test262 tests to be excluded
# test262-test-sys-prop.test.js.excludes.file=${test262.dir}/test/config/excludelist.xml
# list of test262 files to be excluded
test262-test-sys-prop.test.js.exclude.list=\
${test262.suite.dir}/ch07/7.4/S7.4_A6.js \
${test262.suite.dir}/ch07/7.8/7.8.5/S7.8.5_A1.4_T2.js \
${test262.suite.dir}/ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-170.js
# 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-test-sys-prop.test.failed.list.file=${build.dir}/test/failedTests
# test262 test frameworks
test262-test-sys-prop.test.js.framework=\
--class-cache-size=10 \
--no-java \
--no-typed-arrays \
-timezone=PST \
${test.script.dir}/test262.js \
${test262.dir}/test/harness/framework.js \
${test262.dir}/test/harness/sta.js
# testmarkdown test root
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
# framework root for markdown script tests
testmarkdown-test-sys-prop.test.js.framework=\
${test.script.dir}${file.separator}markdown.js
# testjfx test root
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
# framework root for our script tests
testjfx-test-sys-prop.test.js.framework=\
-fx \
${test.script.dir}${file.separator}jfx.js
file.reference.jemmyfx.jar=${test.lib}${file.separator}JemmyFX.jar
file.reference.jemmycore.jar=${test.lib}${file.separator}JemmyCore.jar
file.reference.jemmyawtinput.jar=${test.lib}${file.separator}JemmyAWTInput.jar
file.reference.jfxrt.jar=${java.home}${file.separator}lib${file.separator}ext${file.separator}jfxrt.jar
testjfx.run.test.classpath=\
${file.reference.jemmyfx.jar}${path.separator}\
${file.reference.jemmycore.jar}${path.separator}\
${file.reference.jemmyawtinput.jar}${path.separator}\
${file.reference.testng.jar}${path.separator}\
${file.reference.jcommander.jar}${path.separator}\
${file.reference.bsh.jar}${path.separator}\
${file.reference.snakeyaml.jar}${path.separator}\
${nashorn.internal.tests.jar}${path.separator}\
${nashorn.api.tests.jar}
# testjfx VM options for script tests with @fork option
testjfx-test-sys-prop.test.fork.jvm.options=${run.test.jvmargs.main} -Xmx${run.test.xmx} -cp ${testjfx.run.test.classpath}
run.test.classpath=\
${file.reference.testng.jar}${path.separator}\
${file.reference.jcommander.jar}${path.separator}\
${file.reference.bsh.jar}${path.separator}\
${file.reference.snakeyaml.jar}${path.separator}\
${nashorn.internal.tests.jar}${path.separator}\
${nashorn.api.tests.jar}
dynalink.module.src.dir=src/jdk.dynalink/share/classes
dynalink.module.classes.dir=${build.classes.dir}/jdk.dynalink
nashorn.module.src.dir=src/jdk.scripting.nashorn/share/classes
nashorn.module.classes.dir=${build.classes.dir}/jdk.scripting.nashorn
nashorn.shell.module.src.dir=src/jdk.scripting.nashorn.shell/share/classes
nashorn.shell.module.classes.dir=${build.classes.dir}/jdk.scripting.nashorn.shell
src.dir=${dynalink.module.src.dir}${path.separator}\
${nashorn.module.src.dir}${path.separator}\
${nashorn.shell.module.src.dir}${path.separator}\
${jdk.jline.src.dir}
test.src.dir=test/nashorn/src
# -Xmx is used for all tests, -Xms only for octane benchmark
run.test.xmx=2G
run.test.xms=2G
# uncomment this jfr.args to enable flight recordings. the stack needs to be cranked up to 1024 frames,
# or everything will as of the now drown in lambda forms and be cut off.
#
#jfr.args=-XX:StartFlightRecording=disk=true,dumponexit=true,dumponexitpath="test_suite.jfr",stackdepth=1024
jfr.args=
run.test.user.language=tr
run.test.user.country=TR
run.test.jvmargs.common=\
-server \
${test.module.imports.runtime} \
${run.test.jvmargs.external} \
--add-modules jdk.scripting.nashorn.shell \
${nashorn.override.option} \
-Dfile.encoding=UTF-8 \
-Duser.language=${run.test.user.language} \
-Duser.country=${run.test.user.country} \
-Dnashorn.typeInfo.cacheDir=${build.dir}${file.separator}test${file.separator}type_info_cache \
-Dnashorn.args.prepend=--no-deprecation-warning \
${jfr.args} \
-XX:+HeapDumpOnOutOfMemoryError
# turn on assertions for tests
run.test.jvmargs.main=${run.test.jvmargs.common} -esa -ea
# Extra jvmargs that might be useful for debugging
# and performance improvements/monitoring
#
# -XX:+UnlockDiagnosticVMOptions
#
# turn off compressed class pointers in metaspace
# -XX:-UseCompressedKlassPointers
#
# dump the heap after every GC
# -XX:+PrintHeapAtGC
#
# manually set a metaspace size for class data
# -XX:ClassMetaspaceSize=300M
#
# print out methods compiled
# -XX:+PrintCompilation
#
# print all compiled nmethods with oopmaps and lots of other info
# -XX:+PrintNMethods
#
# activate the generic "UseNewCode" flag to test whatever functionality
# lies behind it. This is the preferred way to test a, yet flagless,
# feature in HotSpot - for example, the uncommon trap placement fix
# was hidden behind this flag before it became the default
#
# -XX:+UnlockDiagnosticVMOptions -XX:+UseNewCode
#
# Crank up the type profile level to 222, which has some warmup
# penalties, but produces much better code for JavaScript, where better
# and more intrusive type profiling is required to get rid of
# a large amount of unnecessary guard code, that could not otherwise
# be eliminated
#
# -XX:TypeProfileLevel=222
#
# Use best known performance options for octane
run.test.jvmargs.octane.main=${run.test.jvmargs.common} -XX:TypeProfileLevel=222
# Security manager args - make sure that we run with the nashorn.policy that the build creates
run.test.jvmsecurityargs=-Xverify:all -Djava.security.manager -Djava.security.policy=${build.dir}/nashorn.policy -Djava.security.properties=${build.dir}/nashorn.security.properties
# VM options for script tests with @fork option
test-sys-prop.test.fork.jvm.options=${run.test.jvmargs.main} -Xmx${run.test.xmx} ${run.test.jvmsecurityargs} -cp ${run.test.classpath}
# VM options for no-security script tests with @fork option - same as above but without jvmsecurityargs
test-sys-prop-no-security.test.fork.jvm.options=${run.test.jvmargs.main} -Xmx${run.test.xmx} -cp ${run.test.classpath}
# path of rhino.jar for benchmarks
rhino.dir=
rhino.jar=${rhino.dir}/js.jar
v8.shell=d8
# How many iterations should 'ant octane' run for each
# benchmark
octane.iterations=25
# List of octane tests to run, as properties prefixed with
# "octane.benchmark." mapping to the benchmark name in
# the test harness
#
# Octane tests that are disabled should have their entire line
# commented out Tests may be disabled for functionality reasons when
# they have bugs or when the runtime doesn't handle them (yet)
octane.benchmark.box2d=box2d
#octane.benchmark.code-load=code-load
octane.benchmark.crypto=crypto
octane.benchmark.deltablue=deltablue
octane.benchmark.earley-boyer=earley-boyer
octane.benchmark.gbemu=gbemu
octane.benchmark.navier-stokes=navier-stokes
octane.benchmark.mandreel=mandreel
octane.benchmark.pdfjs=pdfjs
octane.benchmark.raytrace=raytrace
octane.benchmark.regexp=regexp
octane.benchmark.richards=richards
octane.benchmark.splay=splay
#octane.benchmark.typescript=typescript
#octane.benchmark.zlib=zlib
#path to rhino jar file
octaneperf-sys-prop.rhino.jar=${rhino.jar}
#timeout for performance tests in minutes
octaneperf-sys-prop.timeout.value=10
#how many iterations to run sunspider after warmup
sunspider.iterations=3000
#################
# code coverage #
#################
#enable/disable code coverage; please redifine in the ${user.home}/.nashorn.project.local.properties
make.code.coverage=false
#type of codecoverage; one of static or dynamic. Now only dynamic is supported
jcov=dynamic
#naming of CC results
#NB directory specified in the cc.dir will be cleaned up!!!
cc.dir=${build.dir}/Codecoverage_Nashorn
cc.result.file.name=CC_${jcov}_nashorn.xml
#dynamic CC parameters; please redefine in the ${user.home}/.nashorn.project.local.properties
jcov2.lib.dir=${build.dir}/jcov2/lib
jcov.jar=${jcov2.lib.dir}/jcov.jar
cc.include=jdk\.nashorn\.*
cc.exclude=jdk\.nashorn\.internal\.scripts\.*
cc.dynamic.genereate.template=true
cc.template=${cc.dir}/CC_template.xml
cc.dynamic.args=-javaagent:${jcov.jar}=include=${cc.include},exclude=${cc.exclude},type=all,verbose=0,file=${cc.dir}/${cc.result.file.name}

View file

@ -102,7 +102,6 @@ static const char* modules[] = {
"java.base", "java.base",
"java.logging", "java.logging",
"jdk.compiler", "jdk.compiler",
"jdk.scripting.nashorn",
"jdk.internal.vm.ci", "jdk.internal.vm.ci",
"jdk.internal.vm.compiler" "jdk.internal.vm.compiler"
}; };

View file

@ -172,19 +172,14 @@ module java.base {
exports jdk.internal.org.objectweb.asm to exports jdk.internal.org.objectweb.asm to
jdk.jartool, jdk.jartool,
jdk.jfr, jdk.jfr,
jdk.jlink, jdk.jlink;
jdk.scripting.nashorn;
exports jdk.internal.org.objectweb.asm.tree to exports jdk.internal.org.objectweb.asm.tree to
jdk.jfr, jdk.jfr,
jdk.jlink; jdk.jlink;
exports jdk.internal.org.objectweb.asm.util to exports jdk.internal.org.objectweb.asm.util to
jdk.jfr, jdk.jfr;
jdk.scripting.nashorn;
exports jdk.internal.org.objectweb.asm.commons to exports jdk.internal.org.objectweb.asm.commons to
jdk.jfr, jdk.jfr;
jdk.scripting.nashorn;
exports jdk.internal.org.objectweb.asm.signature to
jdk.scripting.nashorn;
exports jdk.internal.org.xml.sax to exports jdk.internal.org.xml.sax to
jdk.jfr; jdk.jfr;
exports jdk.internal.org.xml.sax.helpers to exports jdk.internal.org.xml.sax.helpers to
@ -204,8 +199,6 @@ module java.base {
jdk.jfr, jdk.jfr,
jdk.jshell, jdk.jshell,
jdk.nio.mapmode, jdk.nio.mapmode,
jdk.scripting.nashorn,
jdk.scripting.nashorn.shell,
jdk.unsupported, jdk.unsupported,
jdk.internal.vm.ci, jdk.internal.vm.ci,
jdk.incubator.foreign; jdk.incubator.foreign;
@ -230,7 +223,6 @@ module java.base {
java.sql.rowset, java.sql.rowset,
jdk.dynalink, jdk.dynalink,
jdk.internal.vm.ci, jdk.internal.vm.ci,
jdk.scripting.nashorn,
jdk.unsupported; jdk.unsupported;
exports jdk.internal.vm to exports jdk.internal.vm to
jdk.internal.jvmstat, jdk.internal.jvmstat,

View file

@ -113,8 +113,7 @@ module jdk.compiler {
jdk.javadoc, jdk.javadoc,
jdk.jshell; jdk.jshell;
exports jdk.internal.shellsupport.doc to exports jdk.internal.shellsupport.doc to
jdk.jshell, jdk.jshell;
jdk.scripting.nashorn.shell;
uses javax.annotation.processing.Processor; uses javax.annotation.processing.Processor;
uses com.sun.source.util.Plugin; uses com.sun.source.util.Plugin;

View file

@ -33,9 +33,7 @@ module jdk.internal.ed {
exports jdk.internal.editor.spi to exports jdk.internal.editor.spi to
jdk.editpad, jdk.editpad,
jdk.jshell, jdk.jshell;
jdk.scripting.nashorn.shell;
exports jdk.internal.editor.external to exports jdk.internal.editor.external to
jdk.jshell, jdk.jshell;
jdk.scripting.nashorn.shell;
} }

View file

@ -30,31 +30,22 @@
*/ */
module jdk.internal.le { module jdk.internal.le {
exports jdk.internal.org.jline.keymap to exports jdk.internal.org.jline.keymap to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
exports jdk.internal.org.jline.reader to exports jdk.internal.org.jline.reader to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
exports jdk.internal.org.jline.reader.impl to exports jdk.internal.org.jline.reader.impl to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
exports jdk.internal.org.jline.reader.impl.completer to exports jdk.internal.org.jline.reader.impl.completer to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
exports jdk.internal.org.jline.reader.impl.history to exports jdk.internal.org.jline.reader.impl.history to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
exports jdk.internal.org.jline.terminal.impl to exports jdk.internal.org.jline.terminal.impl to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
exports jdk.internal.org.jline.terminal to exports jdk.internal.org.jline.terminal to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
exports jdk.internal.org.jline.utils to exports jdk.internal.org.jline.utils to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
exports jdk.internal.org.jline.terminal.spi to exports jdk.internal.org.jline.terminal.spi to
jdk.scripting.nashorn.shell,
jdk.jshell; jdk.jshell;
uses jdk.internal.org.jline.terminal.spi.JnaSupport; uses jdk.internal.org.jline.terminal.spi.JnaSupport;

View file

@ -1,186 +0,0 @@
/*
* Copyright (c) 2015, 2018, 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.tools.jjs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Writer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import jdk.internal.org.jline.reader.Candidate;
import jdk.internal.org.jline.reader.CompletingParsedLine;
import jdk.internal.org.jline.reader.EOFError;
import jdk.internal.org.jline.reader.History;
import jdk.internal.org.jline.reader.LineReader;
import jdk.internal.org.jline.reader.LineReader.Option;
import jdk.internal.org.jline.reader.LineReaderBuilder;
import jdk.internal.org.jline.reader.Parser;
import jdk.internal.org.jline.reader.Parser.ParseContext;
import jdk.internal.org.jline.reader.Widget;
import jdk.internal.org.jline.reader.impl.LineReaderImpl;
import jdk.internal.org.jline.reader.impl.completer.ArgumentCompleter.ArgumentLine;
import jdk.internal.org.jline.terminal.Attributes.LocalFlag;
import jdk.internal.org.jline.terminal.Terminal;
class Console implements AutoCloseable {
private static final String DOCUMENTATION_SHORTCUT = "\033\133\132"; //Shift-TAB
private final LineReader in;
private final File historyFile;
Console(final InputStream cmdin, final PrintStream cmdout, final File historyFile,
final NashornCompleter completer, final Function<String, String> docHelper) throws IOException {
this.historyFile = historyFile;
Parser parser = (line, cursor, context) -> {
if (context == ParseContext.COMPLETE) {
List<Candidate> candidates = new ArrayList<>();
int anchor = completer.complete(line, cursor, candidates);
anchor = Math.min(anchor, line.length());
return new CompletionLine(line.substring(anchor), cursor, candidates);
} else if (!completer.isComplete(line)) {
throw new EOFError(cursor, cursor, line);
}
return new ArgumentLine(line, cursor);
};
in = LineReaderBuilder.builder()
.option(Option.DISABLE_EVENT_EXPANSION, true)
.completer((in, line, candidates) -> candidates.addAll(((CompletionLine) line).candidates))
.parser(parser)
.build();
if (historyFile.exists()) {
StringBuilder line = new StringBuilder();
for (String h : Files.readAllLines(historyFile.toPath())) {
if (line.length() > 0) {
line.append("\n");
}
line.append(h);
try {
parser.parse(line.toString(), line.length());
in.getHistory().add(line.toString());
line.delete(0, line.length());
} catch (EOFError e) {
//continue;
}
}
if (line.length() > 0) {
in.getHistory().add(line.toString());
}
}
Runtime.getRuntime().addShutdownHook(new Thread((Runnable)this::saveHistory));
bind(DOCUMENTATION_SHORTCUT, ()->showDocumentation(docHelper));
}
String readLine(final String prompt, final String continuationPrompt) throws IOException {
in.setVariable(LineReader.SECONDARY_PROMPT_PATTERN, continuationPrompt);
return in.readLine(prompt);
}
String readUserLine(final String prompt) throws IOException {
Parser prevParser = in.getParser();
try {
((LineReaderImpl) in).setParser((line, cursor, context) -> new ArgumentLine(line, cursor));
return in.readLine(prompt);
} finally {
((LineReaderImpl) in).setParser(prevParser);
}
}
@Override
public void close() {
saveHistory();
}
private void saveHistory() {
try (Writer out = Files.newBufferedWriter(historyFile.toPath())) {
String lineSeparator = System.getProperty("line.separator");
out.write(StreamSupport.stream(getHistory().spliterator(), false)
.map(e -> e.line())
.collect(Collectors.joining(lineSeparator)));
} catch (final IOException exp) {}
}
History getHistory() {
return in.getHistory();
}
boolean terminalEditorRunning() {
Terminal terminal = in.getTerminal();
return !terminal.getAttributes().getLocalFlag(LocalFlag.ICANON);
}
void suspend() {
}
void resume() {
}
private void bind(String shortcut, Widget action) {
in.getKeyMaps().get(LineReader.MAIN).bind(action, shortcut);
}
private boolean showDocumentation(final Function<String, String> docHelper) {
final String buffer = in.getBuffer().toString();
final int cursor = in.getBuffer().cursor();
final String doc = docHelper.apply(buffer.substring(0, cursor));
if (doc != null) {
in.getTerminal().writer().println();
in.printAbove(doc);
return true;
} else {
return false;
}
}
private static final class CompletionLine extends ArgumentLine implements CompletingParsedLine {
public final List<Candidate> candidates;
public CompletionLine(String word, int cursor, List<Candidate> candidates) {
super(word, cursor);
this.candidates = candidates;
}
public CharSequence escape(CharSequence candidate, boolean complete) {
return candidate;
}
public int rawWordCursor() {
return word().length();
}
public int rawWordLength() {
return word().length();
}
}
}

View file

@ -1,147 +0,0 @@
/*
* Copyright (c) 2015, 2017, 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.tools.jjs;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import java.util.ServiceLoader;
import jdk.nashorn.api.scripting.AbstractJSObject;
import jdk.internal.editor.spi.BuildInEditorProvider;
import jdk.nashorn.internal.runtime.JSType;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
/*
* "edit" top level script function which shows an external Window
* for editing and evaluating scripts from it.
*/
final class EditObject extends AbstractJSObject {
private static final Set<String> props;
static {
final HashSet<String> s = new HashSet<>();
s.add("editor");
props = Collections.unmodifiableSet(s);
}
private final Console console;
private final Consumer<String> errorHandler;
private final Consumer<String> evaluator;
private String editor;
EditObject(final Console console, final Consumer<String> errorHandler,
final Consumer<String> evaluator) {
this.console = console;
this.errorHandler = errorHandler;
this.evaluator = evaluator;
}
@Override
public Object getDefaultValue(final Class<?> hint) {
if (hint == String.class) {
return toString();
}
return UNDEFINED;
}
@Override
public String toString() {
return "function edit() { [native code] }";
}
@Override
public Set<String> keySet() {
return props;
}
@Override
public Object getMember(final String name) {
if (name.equals("editor")) {
return editor;
}
return UNDEFINED;
}
@Override
public void setMember(final String name, final Object value) {
if (name.equals("editor")) {
this.editor = value != null && value != UNDEFINED? JSType.toString(value) : "";
}
}
// called whenever user 'saves' script in editor
class SaveHandler implements Consumer<String> {
private String lastStr; // last seen code
SaveHandler(final String str) {
this.lastStr = str;
}
@Override
public void accept(final String str) {
// ignore repeated save of the same code!
if (! str.equals(lastStr)) {
this.lastStr = str;
// evaluate the new code
evaluator.accept(str);
}
}
}
@Override
public Object call(final Object thiz, final Object... args) {
final String initText = args.length > 0? JSType.toString(args[0]) : "";
final SaveHandler saveHandler = new SaveHandler(initText);
if (editor != null && !editor.isEmpty()) {
ExternalEditor.edit(editor, errorHandler, initText, saveHandler, console);
} else {
try {
ServiceLoader<BuildInEditorProvider> sl
= ServiceLoader.load(BuildInEditorProvider.class);
//find the highest ranking provider
BuildInEditorProvider provider = null;
for (BuildInEditorProvider p : sl){
if (provider == null || p.rank() > provider.rank()) {
provider = p;
}
}
if (provider != null) {
provider.edit(null, initText, saveHandler, errorHandler);
} else {
errorHandler.accept(Main.getMessage("jjs.err.no.builtin.editor"));
}
} catch (RuntimeException ex) {
errorHandler.accept(Main.getMessage("jjs.err.cant.launch.editor"));
}
}
return UNDEFINED;
}
@Override
public boolean isFunction() {
return true;
}
}

View file

@ -1,152 +0,0 @@
/*
* Copyright (c) 2015, 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.tools.jjs;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
import java.util.function.Consumer;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
final class ExternalEditor {
private final Consumer<String> errorHandler;
private final Consumer<String> saveHandler;
private final Console input;
private WatchService watcher;
private Thread watchedThread;
private Path dir;
private Path tmpfile;
ExternalEditor(final Consumer<String> errorHandler, final Consumer<String> saveHandler, final Console input) {
this.errorHandler = errorHandler;
this.saveHandler = saveHandler;
this.input = input;
}
private void edit(final String cmd, final String initialText) {
try {
setupWatch(initialText);
launch(cmd);
} catch (IOException ex) {
errorHandler.accept(ex.getMessage());
}
}
/**
* Creates a WatchService and registers the given directory
*/
private void setupWatch(final String initialText) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.dir = Files.createTempDirectory("REPL");
this.tmpfile = Files.createTempFile(dir, null, ".js");
Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
dir.register(watcher,
ENTRY_CREATE,
ENTRY_DELETE,
ENTRY_MODIFY);
watchedThread = new Thread(() -> {
for (;;) {
WatchKey key;
try {
key = watcher.take();
} catch (final ClosedWatchServiceException ex) {
break;
} catch (final InterruptedException ex) {
continue; // tolerate an intrupt
}
if (!key.pollEvents().isEmpty()) {
if (!input.terminalEditorRunning()) {
saveFile();
}
}
boolean valid = key.reset();
if (!valid) {
errorHandler.accept("Invalid key");
break;
}
}
});
watchedThread.start();
}
private void launch(final String cmd) throws IOException {
ProcessBuilder pb = new ProcessBuilder(cmd, tmpfile.toString());
pb = pb.inheritIO();
try {
input.suspend();
Process process = pb.start();
process.waitFor();
} catch (final IOException ex) {
errorHandler.accept("process IO failure: " + ex.getMessage());
} catch (final InterruptedException ex) {
errorHandler.accept("process interrupt: " + ex.getMessage());
} finally {
try {
watcher.close();
watchedThread.join(); //so that saveFile() is finished.
saveFile();
} catch (InterruptedException ex) {
errorHandler.accept("process interrupt: " + ex.getMessage());
} finally {
input.resume();
}
}
}
private void saveFile() {
List<String> lines;
try {
lines = Files.readAllLines(tmpfile);
} catch (final IOException ex) {
errorHandler.accept("Failure read edit file: " + ex.getMessage());
return ;
}
StringBuilder sb = new StringBuilder();
for (String ln : lines) {
sb.append(ln);
sb.append('\n');
}
saveHandler.accept(sb.toString());
}
static void edit(final String cmd, final Consumer<String> errorHandler, final String initialText,
final Consumer<String> saveHandler, final Console input) {
ExternalEditor ed = new ExternalEditor(errorHandler, saveHandler, input);
ed.edit(cmd, initialText);
}
}

View file

@ -1,212 +0,0 @@
/*
* Copyright (c) 2015, 2018, 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.tools.jjs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import jdk.internal.org.jline.reader.History;
import jdk.nashorn.api.scripting.AbstractJSObject;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.internal.runtime.JSType;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
/*
* A script friendly object that exposes history of commands to scripts.
*/
final class HistoryObject extends AbstractJSObject {
private static final Set<String> props;
static {
final HashSet<String> s = new HashSet<>();
s.add("clear");
s.add("forEach");
s.add("load");
s.add("print");
s.add("save");
s.add("size");
s.add("toString");
props = Collections.unmodifiableSet(s);
}
private final History hist;
private final PrintWriter err;
private final Consumer<String> evaluator;
HistoryObject(final History hist, final PrintWriter err,
final Consumer<String> evaluator) {
this.hist = hist;
this.err = err;
this.evaluator = evaluator;
}
@Override
public boolean isFunction() {
return true;
}
@Override
public Object call(final Object thiz, final Object... args) {
if (args.length > 0) {
int index = JSType.toInteger(args[0]);
if (index < 0) {
index += (hist.size() - 1);
} else {
index--;
}
if (index >= 0 && index < (hist.size() - 1)) {
final CharSequence src = hist.get(index);
var it = hist.iterator();
while (it.hasNext()) {
it.next();
}
it.remove();
hist.add(src.toString());
err.println(src);
evaluator.accept(src.toString());
} else {
var it = hist.iterator();
while (it.hasNext()) {
it.next();
}
it.remove();
err.println("no history entry @ " + (index + 1));
}
}
return UNDEFINED;
}
@Override
public Object getMember(final String name) {
switch (name) {
case "clear":
return (Runnable) () -> {
try {
hist.purge();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
};
case "forEach":
return (Function<JSObject, Object>)this::iterate;
case "load":
return (Consumer<Object>)this::load;
case "print":
return (Runnable)this::print;
case "save":
return (Consumer<Object>)this::save;
case "size":
return hist.size();
case "toString":
return (Supplier<String>)this::toString;
}
return UNDEFINED;
}
@Override
public Object getDefaultValue(final Class<?> hint) {
if (hint == String.class) {
return toString();
}
return UNDEFINED;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder();
for (History.Entry e : hist) {
buf.append(e.line()).append('\n');
}
return buf.toString();
}
@Override
public Set<String> keySet() {
return props;
}
private void save(final Object obj) {
final File file = getFile(obj);
try (final PrintWriter pw = new PrintWriter(file)) {
for (History.Entry e : hist) {
pw.println(e.line());
}
} catch (final IOException exp) {
throw new RuntimeException(exp);
}
}
private void load(final Object obj) {
final File file = getFile(obj);
String item = null;
try (final BufferedReader r = new BufferedReader(new FileReader(file))) {
while ((item = r.readLine()) != null) {
hist.add(item);
}
} catch (final IOException exp) {
throw new RuntimeException(exp);
}
}
private void print() {
for (History.Entry e : hist) {
System.out.printf("%3d %s\n", e.index() + 1, e.line());
}
}
private Object iterate(final JSObject func) {
for (History.Entry e : hist) {
if (JSType.toBoolean(func.call(this, e.line().toString()))) {
break; // return true from callback to skip iteration
}
}
return UNDEFINED;
}
private static File getFile(final Object obj) {
File file = null;
if (obj instanceof String) {
file = new File((String)obj);
} else if (obj instanceof File) {
file = (File)obj;
} else {
throw typeError("not.a.file", JSType.toString(obj));
}
return file;
}
}

View file

@ -1,160 +0,0 @@
/*
* Copyright (c) 2017, 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.tools.jjs;
import java.io.IOException;
import java.io.File;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager.Location;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import jdk.nashorn.internal.runtime.Context;
/**
* A javac package helper that uses javac to complete package names.
*/
final class JavacPackagesHelper extends PackagesHelper {
// JavaCompiler may be null on certain platforms (eg. JRE)
private static final JavaCompiler compiler;
static {
// Use javac only if security manager is not around!
compiler = System.getSecurityManager() == null? ToolProvider.getSystemJavaCompiler() : null;
}
/**
* Is this class available?
*
* @return true if javac is available
*/
static boolean isAvailable() {
return compiler != null;
}
private final boolean modulePathSet;
private final StandardJavaFileManager fm;
private final Set<JavaFileObject.Kind> fileKinds;
/**
* Construct a new JavacPackagesHelper.
*
* @param context the current Nashorn Context
*/
JavacPackagesHelper(final Context context) throws IOException {
super(context);
final String modulePath = context.getEnv()._module_path;
this.modulePathSet = modulePath != null && !modulePath.isEmpty();
if (isAvailable()) {
final String classPath = context.getEnv()._classpath;
fm = compiler.getStandardFileManager(null, null, null);
fileKinds = EnumSet.of(JavaFileObject.Kind.CLASS);
if (this.modulePathSet) {
fm.setLocation(StandardLocation.MODULE_PATH, getFiles(modulePath));
}
if (classPath != null && !classPath.isEmpty()) {
fm.setLocation(StandardLocation.CLASS_PATH, getFiles(classPath));
} else {
// no classpath set. Make sure that it is empty and not any default like "."
fm.setLocation(StandardLocation.CLASS_PATH, Collections.<File>emptyList());
}
} else {
// javac is not available - caller should have checked!
throw new IllegalStateException("JavacPackagesHelper is not available!");
}
}
@Override
void close() throws IOException {
if (fm != null) {
fm.close();
}
}
@Override
Set<String> listPackage(final String pkg) throws IOException {
final Set<String> props = new HashSet<>();
listPackage(StandardLocation.PLATFORM_CLASS_PATH, pkg, props);
if (this.modulePathSet) {
for (Set<Location> locs : fm.listLocationsForModules(StandardLocation.MODULE_PATH)) {
for (Location loc : locs) {
listPackage(loc, pkg, props);
}
}
}
listPackage(StandardLocation.CLASS_PATH, pkg, props);
return props;
}
private void listPackage(final Location loc, final String pkg, final Set<String> props)
throws IOException {
for (JavaFileObject file : fm.list(loc, pkg, fileKinds, true)) {
final String binaryName = fm.inferBinaryName(loc, file);
// does not start with the given package prefix
if (!binaryName.startsWith(pkg + ".")) {
continue;
}
final int nextDot = binaryName.indexOf('.', pkg.length() + 1);
final int start = pkg.length() + 1;
if (nextDot != -1) {
// subpackage - eg. "regex" for "java.util"
final String pkgName = binaryName.substring(start, nextDot);
if (isPackageAccessible(binaryName.substring(0, nextDot))) {
props.add(binaryName.substring(start, nextDot));
}
} else {
// class - filter out nested, inner, anonymous, local classes.
// Dynalink supported public nested classes as properties of
// StaticClass object anyway. We don't want to expose those
// "$" internal names as properties of package object.
final String clsName = binaryName.substring(start);
if (clsName.indexOf('$') == -1 && isClassAccessible(binaryName)) {
props.add(clsName);
}
}
}
}
// return list of File objects for the given class path
private static List<File> getFiles(final String classPath) {
return Stream.of(classPath.split(File.pathSeparator))
.map(File::new)
.collect(Collectors.toList());
}
}

View file

@ -1,90 +0,0 @@
/*
* Copyright (c) 2017, 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.tools.jjs;
import java.io.IOException;
import java.net.URI;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;
import jdk.nashorn.internal.runtime.Context;
/**
* A java packages helper that uses jrt file system.
*/
final class JrtPackagesHelper extends PackagesHelper {
private final FileSystem jrtfs;
/**
* Construct a new JrtPackagesHelper.
*
* @param context the current Nashorn Context
*/
JrtPackagesHelper(final Context context) throws IOException {
super(context);
jrtfs = FileSystems.getFileSystem(URI.create("jrt:/"));
}
@Override
void close() throws IOException {
}
@Override
Set<String> listPackage(final String pkg) throws IOException {
final Set<String> props = new HashSet<>();
// look for the /packages/<package_name> directory
Path pkgDir = jrtfs.getPath("/packages/" + pkg);
if (Files.exists(pkgDir)) {
String pkgSlashName = pkg.replace('.', '/');
try (DirectoryStream<Path> ds = Files.newDirectoryStream(pkgDir)) {
// it has module links under which this package occurs
for (Path mod : ds) {
// get the package directory under /modules
Path pkgUnderMod = jrtfs.getPath(mod.toString() + "/" + pkgSlashName);
try (DirectoryStream<Path> ds2 = Files.newDirectoryStream(pkgUnderMod)) {
for (Path p : ds2) {
String str = p.getFileName().toString();
// get rid of ".class", if any
if (str.endsWith(".class")) {
final String clsName = str.substring(0, str.length() - ".class".length());
if (clsName.indexOf('$') == -1 && isClassAccessible(pkg + "." + clsName)) {
props.add(str);
}
} else if (isPackageAccessible(pkg + "." + str)) {
props.add(str);
}
}
}
}
}
}
return props;
}
}

View file

@ -1,321 +0,0 @@
/*
* Copyright (c) 2015, 2018, 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.tools.jjs;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.function.Consumer;
import jdk.internal.org.jline.reader.UserInterruptException;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.objects.NativeJava;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.NativeJavaPackage;
import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.ScriptEnvironment;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptingFunctions;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.Source;
import jdk.nashorn.tools.Shell;
/**
* Interactive command line Shell for Nashorn.
*/
@Deprecated(since="11", forRemoval=true)
public final class Main extends Shell {
private Main() {}
private static final String DOC_PROPERTY_NAME = "__doc__";
static final boolean DEBUG = Boolean.getBoolean("nashorn.jjs.debug");
// file where history is persisted.
private static final File HIST_FILE = new File(new File(System.getProperty("user.home")), ".jjs.history");
/**
* Main entry point with the default input, output and error streams.
*
* @param args The command line arguments
*/
public static void main(final String[] args) {
try {
final int exitCode = main(System.in, System.out, System.err, args);
if (exitCode != SUCCESS) {
System.exit(exitCode);
}
} catch (final IOException e) {
System.err.println(e); //bootstrapping, Context.err may not exist
System.exit(IO_ERROR);
}
}
/**
* Starting point for executing a {@code Shell}. Starts a shell with the
* given arguments and streams and lets it run until exit.
*
* @param in input stream for Shell
* @param out output stream for Shell
* @param err error stream for Shell
* @param args arguments to Shell
*
* @return exit code
*
* @throws IOException if there's a problem setting up the streams
*/
public static int main(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException {
return new Main().run(in, out, err, args);
}
/**
* read-eval-print loop for Nashorn shell.
*
* @param context the nashorn context
* @param global global scope object to use
* @return return code
*/
protected int readEvalPrint(final Context context, final Global global) {
final ScriptEnvironment env = context.getEnv();
final String prompt = bundle.getString("shell.prompt");
final String prompt2 = bundle.getString("shell.prompt2");
final PrintWriter err = context.getErr();
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
final PropertiesHelper propsHelper = new PropertiesHelper(context);
if (globalChanged) {
Context.setGlobal(global);
}
// jjs.js is read and evaluated. The result of the evaluation is an "exports" object. This is done
// to avoid polluting javascript global scope. These are internal funtions are retrieved from the
// 'exports' object and used from here.
final ScriptObject jjsObj = (ScriptObject)context.eval(global, readJJSScript(), global, "<jjs.js>");
final boolean isHeadless = (boolean) ScriptRuntime.apply((ScriptFunction) jjsObj.get("isHeadless"), null);
final ScriptFunction fileChooserFunc = isHeadless? null : (ScriptFunction) jjsObj.get("chooseFile");
final NashornCompleter completer = new NashornCompleter(context, global, this, propsHelper, fileChooserFunc);
final ScriptFunction browseFunc = isHeadless? null : (ScriptFunction) jjsObj.get("browse");
final ScriptFunction javadoc = (ScriptFunction) jjsObj.get("javadoc");
try (final Console in = new Console(System.in, System.out, HIST_FILE, completer,
str -> {
try {
final Object res = context.eval(global, str, global, "<shell>");
if (res != null && res != UNDEFINED) {
// Special case Java types: show the javadoc for the class.
if (!isHeadless && NativeJava.isType(UNDEFINED, res)) {
final String typeName = NativeJava.typeName(UNDEFINED, res).toString();
final String url = typeName.replace('.', '/').replace('$', '.') + ".html";
openBrowserForJavadoc(browseFunc, url);
} else if (!isHeadless && res instanceof NativeJavaPackage) {
final String pkgName = ((NativeJavaPackage)res).getName();
final String url = pkgName.replace('.', '/') + "/package-summary.html";
openBrowserForJavadoc(browseFunc, url);
} else if (NativeJava.isJavaMethod(UNDEFINED, res)) {
ScriptRuntime.apply(javadoc, UNDEFINED, res);
return ""; // javadoc function already prints javadoc
} else if (res instanceof ScriptObject) {
final ScriptObject sobj = (ScriptObject)res;
if (sobj.has(DOC_PROPERTY_NAME)) {
return toString(sobj.get(DOC_PROPERTY_NAME), global);
} else if (sobj instanceof ScriptFunction) {
return ((ScriptFunction)sobj).getDocumentation();
}
}
// FIXME: better than toString for other cases?
return toString(res, global);
}
} catch (Exception ignored) {
}
return null;
})) {
global.addShellBuiltins();
// redefine readLine to use jline Console's readLine!
ScriptingFunctions.setReadLineHelper(str-> {
try {
return in.readUserLine(str);
} catch (final IOException ioExp) {
throw new UncheckedIOException(ioExp);
}
});
if (System.getSecurityManager() == null) {
final Consumer<String> evaluator = str -> {
// could be called from different thread (GUI), we need to handle Context set/reset
final Global _oldGlobal = Context.getGlobal();
final boolean _globalChanged = (_oldGlobal != global);
if (_globalChanged) {
Context.setGlobal(global);
}
try {
evalImpl(context, global, str, err, env._dump_on_error);
} finally {
if (_globalChanged) {
Context.setGlobal(_oldGlobal);
}
}
};
// expose history object for reflecting on command line history
global.addOwnProperty("history", Property.NOT_ENUMERABLE, new HistoryObject(in.getHistory(), err, evaluator));
// 'edit' command
global.addOwnProperty("edit", Property.NOT_ENUMERABLE, new EditObject(in, err::println, evaluator));
}
while (true) {
String source;
try {
source = in.readLine(prompt, prompt2);
} catch (final IOException ioe) {
err.println(ioe.toString());
if (env._dump_on_error) {
ioe.printStackTrace(err);
}
return IO_ERROR;
} catch (final UserInterruptException ex) {
break;
}
if (source == null) {
break;
}
if (source.isEmpty()) {
continue;
}
try {
final Object res = context.eval(global, source, global, "<shell>");
if (res != UNDEFINED) {
err.println(toString(res, global));
}
} catch (final Exception exp) {
// Is this a ECMAScript SyntaxError at last column (of the single line)?
// If so, it is because parser expected more input but got EOF. Try to
// to more lines from the user (multiline edit support).
if (completer.isSyntaxErrorAt(exp, 1, source.length())) {
final String fullSrc = completer.readMoreLines(source, exp, in, prompt2, err);
// check if we succeeded in getting complete code.
if (fullSrc != null && !fullSrc.isEmpty()) {
evalImpl(context, global, fullSrc, err, env._dump_on_error);
} // else ignore, error reported already by 'completer.readMoreLines'
} else {
// can't read more lines to have parseable/complete code.
err.println(exp);
if (env._dump_on_error) {
exp.printStackTrace(err);
}
}
}
}
} catch (final Exception e) {
err.println(e);
if (env._dump_on_error) {
e.printStackTrace(err);
}
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
try {
propsHelper.close();
} catch (final Exception exp) {
if (DEBUG) {
exp.printStackTrace();
}
}
}
return SUCCESS;
}
static String getMessage(final String id) {
return bundle.getString(id);
}
private void evalImpl(final Context context, final Global global, final String source,
final PrintWriter err, final boolean doe) {
try {
final Object res = context.eval(global, source, global, "<shell>");
if (res != UNDEFINED) {
err.println(toString(res, global));
}
} catch (final Exception e) {
err.println(e);
if (doe) {
e.printStackTrace(err);
}
}
}
private static String JAVADOC_BASE = "https://docs.oracle.com/javase/%d/docs/api/";
private static void openBrowserForJavadoc(ScriptFunction browse, String relativeUrl) {
try {
final URI uri = new URI(String.format(JAVADOC_BASE, Runtime.version().feature()) + relativeUrl);
ScriptRuntime.apply(browse, null, uri);
} catch (Exception ignored) {
}
}
private static String readJJSScript() {
return AccessController.doPrivileged(
new PrivilegedAction<String>() {
@Override
public String run() {
try {
final InputStream resStream = Main.class.getResourceAsStream("resources/jjs.js");
if (resStream == null) {
throw new RuntimeException("resources/jjs.js is missing!");
}
return new String(Source.readFully(resStream));
} catch (final IOException exp) {
throw new RuntimeException(exp);
}
}
});
}
}

View file

@ -1,441 +0,0 @@
/*
* Copyright (c) 2015, 2018, 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.tools.jjs;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import jdk.internal.org.jline.reader.Candidate;
import jdk.internal.org.jline.reader.Completer;
import jdk.internal.org.jline.reader.LineReader;
import jdk.internal.org.jline.reader.ParsedLine;
import jdk.internal.org.jline.reader.UserInterruptException;
import jdk.nashorn.api.tree.AssignmentTree;
import jdk.nashorn.api.tree.BinaryTree;
import jdk.nashorn.api.tree.CompilationUnitTree;
import jdk.nashorn.api.tree.CompoundAssignmentTree;
import jdk.nashorn.api.tree.ConditionalExpressionTree;
import jdk.nashorn.api.tree.ExpressionTree;
import jdk.nashorn.api.tree.ExpressionStatementTree;
import jdk.nashorn.api.tree.FunctionCallTree;
import jdk.nashorn.api.tree.IdentifierTree;
import jdk.nashorn.api.tree.InstanceOfTree;
import jdk.nashorn.api.tree.MemberSelectTree;
import jdk.nashorn.api.tree.NewTree;
import jdk.nashorn.api.tree.SimpleTreeVisitorES5_1;
import jdk.nashorn.api.tree.Tree;
import jdk.nashorn.api.tree.UnaryTree;
import jdk.nashorn.api.tree.Parser;
import jdk.nashorn.api.scripting.NashornException;
import jdk.nashorn.tools.PartialParser;
import jdk.nashorn.internal.objects.NativeSyntaxError;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.runtime.ECMAException;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ScriptEnvironment;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptRuntime;
/**
* A simple source completer for nashorn. Handles code completion for
* expressions as well as handles incomplete single line code.
*/
final class NashornCompleter {
private final Context context;
private final Global global;
private final ScriptEnvironment env;
private final PartialParser partialParser;
private final PropertiesHelper propsHelper;
private final ScriptFunction fileChooserFunc;
private final Parser parser;
private static final boolean BACKSLASH_FILE_SEPARATOR = File.separatorChar == '\\';
NashornCompleter(final Context context, final Global global,
final PartialParser partialParser, final PropertiesHelper propsHelper,
final ScriptFunction fileChooserFunc) {
this.context = context;
this.global = global;
this.env = context.getEnv();
this.partialParser = partialParser;
this.propsHelper = propsHelper;
this.fileChooserFunc = fileChooserFunc;
this.parser = createParser(env);
}
/**
* Is this a ECMAScript SyntaxError thrown for parse issue at the given line and column?
*
* @param exp Throwable to check
* @param line line number to check
* @param column column number to check
*
* @return true if the given Throwable is a ECMAScript SyntaxError at given line, column
*/
boolean isSyntaxErrorAt(final Throwable exp, final int line, final int column) {
if (exp instanceof ECMAException) {
final ECMAException eexp = (ECMAException)exp;
if (eexp.getThrown() instanceof NativeSyntaxError) {
return isParseErrorAt(eexp.getCause(), line, column);
}
}
return false;
}
/**
* Is this a parse error at the given line and column?
*
* @param exp Throwable to check
* @param line line number to check
* @param column column number to check
*
* @return true if the given Throwable is a parser error at given line, column
*/
boolean isParseErrorAt(final Throwable exp, final int line, final int column) {
if (exp instanceof NashornException) {
final NashornException nexp = (NashornException)exp;
return nexp.getLineNumber() == line && nexp.getColumnNumber() == column;
}
return false;
}
/**
* Read more lines of code if we got SyntaxError at EOF and we can it fine by
* by reading more lines of code from the user. This is used for multiline editing.
*
* @param firstLine First line of code from the user
* @param exp Exception thrown by evaluting first line code
* @param in Console to get read more lines from the user
* @param prompt Prompt to be printed to read more lines from the user
* @param err PrintWriter to print any errors in the proecess of reading
*
* @return Complete code read from the user including the first line. This is null
* if any error or the user discarded multiline editing by Ctrl-C.
*/
String readMoreLines(final String firstLine, final Exception exp, final Console in,
final String prompt, final PrintWriter err) {
int line = 1;
final StringBuilder buf = new StringBuilder(firstLine);
while (true) {
buf.append('\n');
String curLine = null;
try {
curLine = in.readLine(prompt, prompt);
buf.append(curLine);
line++;
} catch (final Throwable th) {
if (th instanceof UserInterruptException) {
// Ctrl-C from user - discard the whole thing silently!
return null;
} else {
// print anything else -- but still discard the code
err.println(th);
if (env._dump_on_error) {
th.printStackTrace(err);
}
return null;
}
}
final String allLines = buf.toString();
try {
parser.parse("<shell>", allLines, null);
} catch (final Exception pexp) {
// Do we have a parse error at the end of current line?
// If so, read more lines from the console.
if (isParseErrorAt(pexp, line, curLine.length())) {
continue;
} else {
// print anything else and bail out!
err.println(pexp);
if (env._dump_on_error) {
pexp.printStackTrace(err);
}
return null;
}
}
// We have complete parseable code!
return buf.toString();
}
}
public boolean isComplete(String input) {
try {
parser.parse("<shell>", input, null);
} catch (final Exception pexp) {
// Do we have a parse error at the end of current line?
// If so, read more lines from the console.
int line = input.split("\n").length;
int lastLineLen = input.length() - (input.lastIndexOf("\n") + 1);
if (isParseErrorAt(pexp, line, lastLineLen)) {
return false;
}
}
return true;
}
// Pattern to match a unfinished member selection expression. object part and "."
// but property name missing pattern.
private static final Pattern SELECT_PROP_MISSING = Pattern.compile(".*\\.\\s*");
// Pattern to match load call
private static final Pattern LOAD_CALL = Pattern.compile("\\s*load\\s*\\(\\s*");
public int complete(String test, int cursor, List<Candidate> candidates) {
// check that cursor is at the end of test string. Do not complete in the middle!
if (cursor != test.length()) {
return cursor;
}
// get the start of the last expression embedded in the given code
// using the partial parsing support - so that we can complete expressions
// inside statements, function call argument lists, array index etc.
final int exprStart = partialParser.getLastExpressionStart(context, test);
if (exprStart == -1) {
return cursor;
}
// extract the last expression string
final String exprStr = test.substring(exprStart);
// do we have an incomplete member selection expression that misses property name?
final boolean endsWithDot = SELECT_PROP_MISSING.matcher(exprStr).matches();
// If this is an incomplete member selection, then it is not legal code.
// Make it legal by adding a random property name "x" to it.
final String completeExpr = endsWithDot? exprStr + "x" : exprStr;
final ExpressionTree topExpr = getTopLevelExpression(parser, completeExpr);
if (topExpr == null) {
// Special case for load call that looks like "load(" with optional whitespaces.
// If we have a fileChooserFunc then call it, so that the user can select a file.
if (fileChooserFunc != null && LOAD_CALL.matcher(test).matches()) {
String name = readFileName(context.getErr());
if (name != null) {
// handle '\' file separator
if (BACKSLASH_FILE_SEPARATOR) {
name = name.replace("\\", "\\\\");
}
candidates.add(createCandidate("\"" + name + "\")"));
return cursor + name.length() + 3;
}
}
// did not parse to be a top level expression, no suggestions!
return cursor;
}
// Find 'right most' expression of the top level expression
final Tree rightMostExpr = getRightMostExpression(topExpr);
if (rightMostExpr instanceof MemberSelectTree) {
return completeMemberSelect(exprStr, cursor, candidates, (MemberSelectTree)rightMostExpr, endsWithDot);
} else if (rightMostExpr instanceof IdentifierTree) {
return completeIdentifier(exprStr, cursor, candidates, (IdentifierTree)rightMostExpr);
} else {
// expression that we cannot handle for completion
return cursor;
}
}
// Internals only below this point
// read file name from the user using by showing a swing file chooser diablog
private String readFileName(final PrintWriter err) {
try {
final Object res = ScriptRuntime.apply(fileChooserFunc, null);
return res instanceof String? (String)res : null;
} catch (final Exception e) {
err.println(e);
if (Main.DEBUG) {
e.printStackTrace();
}
}
return null;
}
// fill properties of the incomplete member expression
private int completeMemberSelect(final String exprStr, final int cursor, final List<Candidate> candidates,
final MemberSelectTree select, final boolean endsWithDot) {
final ExpressionTree objExpr = select.getExpression();
final String objExprCode = exprStr.substring((int)objExpr.getStartPosition(), (int)objExpr.getEndPosition());
// try to evaluate the object expression part as a script
Object obj = null;
try {
obj = context.eval(global, objExprCode, global, "<suggestions>");
} catch (Exception exp) {
// throw away the exception - this is during tab-completion
if (Main.DEBUG) {
exp.printStackTrace();
}
}
if (obj != null && obj != ScriptRuntime.UNDEFINED) {
if (endsWithDot) {
// no user specified "prefix". List all properties of the object
propsHelper.getProperties(obj).stream().map(this::createCandidate).forEach(candidates::add);
return cursor;
} else {
// list of properties matching the user specified prefix
final String prefix = select.getIdentifier();
propsHelper.getProperties(obj, prefix).stream().map(this::createCandidate).forEach(candidates::add);
return cursor - prefix.length();
}
}
return cursor;
}
// fill properties for the given (partial) identifer
private int completeIdentifier(final String test, final int cursor, final List<Candidate> candidates,
final IdentifierTree ident) {
final String name = ident.getName();
propsHelper.getProperties(global, name).stream().map(this::createCandidate).forEach(candidates::add);
return cursor - name.length();
}
// returns ExpressionTree if the given code parses to a top level expression.
// Or else returns null.
private ExpressionTree getTopLevelExpression(final Parser parser, final String code) {
try {
final CompilationUnitTree cut = parser.parse("<code>", code, null);
final List<? extends Tree> stats = cut.getSourceElements();
if (stats.size() == 1) {
final Tree stat = stats.get(0);
if (stat instanceof ExpressionStatementTree) {
return ((ExpressionStatementTree)stat).getExpression();
}
}
} catch (final NashornException ignored) {
// ignore any parser error. This is for completion anyway!
// And user will get that error later when the expression is evaluated.
}
return null;
}
// get the right most expreesion of the given expression
private Tree getRightMostExpression(final ExpressionTree expr) {
return expr.accept(new SimpleTreeVisitorES5_1<Tree, Void>() {
@Override
public Tree visitAssignment(final AssignmentTree at, final Void v) {
return getRightMostExpression(at.getExpression());
}
@Override
public Tree visitCompoundAssignment(final CompoundAssignmentTree cat, final Void v) {
return getRightMostExpression(cat.getExpression());
}
@Override
public Tree visitConditionalExpression(final ConditionalExpressionTree cet, final Void v) {
return getRightMostExpression(cet.getFalseExpression());
}
@Override
public Tree visitBinary(final BinaryTree bt, final Void v) {
return getRightMostExpression(bt.getRightOperand());
}
@Override
public Tree visitIdentifier(final IdentifierTree ident, final Void v) {
return ident;
}
@Override
public Tree visitInstanceOf(final InstanceOfTree it, final Void v) {
return it.getType();
}
@Override
public Tree visitMemberSelect(final MemberSelectTree select, final Void v) {
return select;
}
@Override
public Tree visitNew(final NewTree nt, final Void v) {
final ExpressionTree call = nt.getConstructorExpression();
if (call instanceof FunctionCallTree) {
final ExpressionTree func = ((FunctionCallTree)call).getFunctionSelect();
// Is this "new Foo" or "new obj.Foo" with no user arguments?
// If so, we may be able to do completion of constructor name.
if (func.getEndPosition() == nt.getEndPosition()) {
return func;
}
}
return null;
}
@Override
public Tree visitUnary(final UnaryTree ut, final Void v) {
return getRightMostExpression(ut.getExpression());
}
}, null);
}
// create a Parser instance that uses compatible command line options of the
// current ScriptEnvironment being used for REPL.
private static Parser createParser(final ScriptEnvironment env) {
final List<String> args = new ArrayList<>();
if (env._const_as_var) {
args.add("--const-as-var");
}
if (env._no_syntax_extensions) {
args.add("-nse");
}
if (env._scripting) {
args.add("-scripting");
}
if (env._strict) {
args.add("-strict");
}
if (env._es6) {
args.add("--language=es6");
}
return Parser.create(args.toArray(new String[0]));
}
private Candidate createCandidate(String value) {
return new Candidate(value, value, null, null, null, null, false);
}
}

View file

@ -1,143 +0,0 @@
/*
* Copyright (c) 2015, 2016, 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.tools.jjs;
import java.lang.reflect.Modifier;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jdk.nashorn.internal.runtime.Context;
/**
* Abstract helper class to compute properties of a Java package object. Properties of
* package object are (simple) top level class names in that java package and
* immediate subpackages of that package.
*/
abstract class PackagesHelper {
private final Context context;
/**
* Construct a new PackagesHelper.
*
* @param context the current Nashorn Context
*/
PackagesHelper(final Context context) throws IOException {
this.context = context;
}
static PackagesHelper create(final Context context) throws IOException {
return isJavacHelperAvailable()? new JavacPackagesHelper(context) : new JrtPackagesHelper(context);
}
// LRU cache for java package properties lists
private final LinkedHashMap<String, List<String>> propsCache =
new LinkedHashMap<String, List<String>>(32, 0.75f, true) {
private static final int CACHE_SIZE = 100;
private static final long serialVersionUID = 1;
@Override
protected boolean removeEldestEntry(final Map.Entry<String, List<String>> eldest) {
return size() > CACHE_SIZE;
}
};
/**
* Return the list of properties of the given Java package or package prefix
*
* @param pkg Java package name or package prefix name
* @return the list of properties of the given Java package or package prefix
*/
final List<String> getPackageProperties(final String pkg) {
// check the cache first
if (propsCache.containsKey(pkg)) {
return propsCache.get(pkg);
}
try {
// make sorted list of properties
final List<String> props = new ArrayList<>(listPackage(pkg));
Collections.sort(props);
propsCache.put(pkg, props);
return props;
} catch (final IOException exp) {
if (Main.DEBUG) {
exp.printStackTrace();
}
return Collections.<String>emptyList();
}
}
/**
* Close resources (like file system) used, if any.
*/
abstract void close() throws IOException;
/**
* Return the set of properties of a given package object.
*
* @param pkg package start string
* @return set of properties of the given Java package
*/
abstract Set<String> listPackage(final String pkg) throws IOException;
final boolean isClassAccessible(final String className) {
try {
final Class<?> clz = context.findClass(className);
return Modifier.isPublic(clz.getModifiers());
} catch (final ClassNotFoundException cnfe) {
}
return false;
}
final boolean isPackageAccessible(final String pkgName) {
try {
Context.checkPackageAccess(pkgName);
return true;
} catch (final SecurityException se) {
return false;
}
}
private static boolean isJavacHelperAvailable() {
try {
boolean result = JavacPackagesHelper.isAvailable();
if (Main.DEBUG && !result) {
System.err.println("javac packages helper is not available");
}
return result;
} catch (final LinkageError err) {
if (Main.DEBUG) {
System.err.println("javac packages helper is not available");
err.printStackTrace();
}
return false;
}
}
}

View file

@ -1,203 +0,0 @@
/*
* Copyright (c) 2015, 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.tools.jjs;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.WeakHashMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.NativeJavaPackage;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.objects.NativeJava;
/*
* A helper class to get properties of a given object for source code completion.
*/
final class PropertiesHelper {
// Java package properties helper, may be null
private PackagesHelper pkgsHelper;
// cached properties list
private final WeakHashMap<Object, List<String>> propsCache = new WeakHashMap<>();
/**
* Construct a new PropertiesHelper.
*
* @param context the current nashorn Context
*/
PropertiesHelper(final Context context) {
try {
this.pkgsHelper = PackagesHelper.create(context);
} catch (final IOException exp) {
if (Main.DEBUG) {
exp.printStackTrace();
}
this.pkgsHelper = null;
}
}
void close() throws Exception {
propsCache.clear();
pkgsHelper.close();
}
/**
* returns the list of properties of the given object.
*
* @param obj object whose property list is returned
* @return the list of properties of the given object
*/
List<String> getProperties(final Object obj) {
assert obj != null && obj != ScriptRuntime.UNDEFINED;
// wrap JS primitives as objects before gettting properties
if (JSType.isPrimitive(obj)) {
return getProperties(JSType.toScriptObject(obj));
}
// Handle Java package prefix case first. Should do it before checking
// for its super class ScriptObject!
if (obj instanceof NativeJavaPackage) {
if (pkgsHelper != null) {
return pkgsHelper.getPackageProperties(((NativeJavaPackage)obj).getName());
} else {
return Collections.<String>emptyList();
}
}
// script object - all inherited and non-enumerable, non-index properties
if (obj instanceof ScriptObject) {
final ScriptObject sobj = (ScriptObject)obj;
final PropertyMap pmap = sobj.getMap();
if (propsCache.containsKey(pmap)) {
return propsCache.get(pmap);
}
final String[] keys = sobj.getAllKeys();
List<String> props = Arrays.asList(keys);
props = props.stream()
.filter(s -> Character.isJavaIdentifierStart(s.charAt(0)))
.collect(Collectors.toList());
Collections.sort(props);
// cache properties against the PropertyMap
propsCache.put(pmap, props);
return props;
}
// java class case - don't refer to StaticClass directly
if (NativeJava.isType(ScriptRuntime.UNDEFINED, obj)) {
if (propsCache.containsKey(obj)) {
return propsCache.get(obj);
}
final List<String> props = NativeJava.getProperties(obj);
Collections.sort(props);
// cache properties against the StaticClass representing the class
propsCache.put(obj, props);
return props;
}
// any other Java object
final Class<?> clazz = obj.getClass();
if (propsCache.containsKey(clazz)) {
return propsCache.get(clazz);
}
final List<String> props = NativeJava.getProperties(obj);
Collections.sort(props);
// cache properties against the Class object
propsCache.put(clazz, props);
return props;
}
// This method creates a regex Pattern to use to do CamelCase
// matching. The pattern is derived from user supplied string
// containing one or more upper case characters in it.
private static Pattern makeCamelCasePattern(final String str) {
assert !str.isEmpty();
final char[] chars = str.toCharArray();
final StringBuilder buf = new StringBuilder();
boolean seenUpperCase = false;
// Skip first char for case check. Even if it is upper case,
// we do not want to put lower case matching pattern before
// the first letter!
buf.append(chars[0]);
for (int idx = 1; idx < chars.length; idx++) {
final char ch = chars[idx];
if (ch >= 'A' && ch <= 'Z') {
seenUpperCase = true;
buf.append("[^A-Z]*");
}
buf.append(ch);
}
if (seenUpperCase) {
// match anything at the end!
buf.append(".*");
try {
return Pattern.compile(buf.toString());
} catch (Exception exp) {
}
}
return null;
}
/**
* Returns the list of properties of the given object that start with the given prefix.
*
* @param obj object whose property list is returned
* @param prefix property prefix to be matched
* @return the list of properties of the given object
*/
List<String> getProperties(final Object obj, final String prefix) {
assert prefix != null && !prefix.isEmpty();
List<String> allProps = getProperties(obj);
List<String> props = allProps.stream()
.filter(s -> s.startsWith(prefix))
.collect(Collectors.toList());
// If no match, try CamelCase completion..
if (props.isEmpty()) {
final Pattern pat = makeCamelCasePattern(prefix);
if (pat != null) {
return allProps.stream()
.filter(s -> pat.matcher(s).matches())
.collect(Collectors.toList());
}
}
return props;
}
}

View file

@ -1,147 +0,0 @@
/*
* Copyright (c) 2017, 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.
*/
(function () {
// Check if java.desktop module is available and we're running in non-headless mode.
// We access AWT via script to avoid direct dependency on java.desktop module.
function isHeadless() {
var GraphicsEnvironment = java.awt.GraphicsEnvironment;
return Java.isType(GraphicsEnvironment)? GraphicsEnvironment.isHeadless() : true;
}
// Function that shows a JFileChooser dialog and returns the file name chosen (if chosen).
// We access swing from script to avoid direct dependency on java.desktop module.
function chooseFile() {
var JFileChooser = javax.swing.JFileChooser;
if (!Java.isType(JFileChooser)) {
return null;
}
var ExtensionFilter = javax.swing.filechooser.FileNameExtensionFilter;
function run() {
var chooser = new JFileChooser();
chooser.fileFilter = new ExtensionFilter('JavaScript Files', 'js');
var retVal = chooser.showOpenDialog(null);
return retVal == JFileChooser.APPROVE_OPTION ?
chooser.selectedFile.absolutePath : null;
}
var FutureTask = java.util.concurrent.FutureTask;
var fileChooserTask = new FutureTask(run);
javax.swing.SwingUtilities.invokeLater(fileChooserTask);
return fileChooserTask.get();
}
// Function that opens up the desktop browser application with the given URI.
// We access AWT from script to avoid direct dependency on java.desktop module.
function browse(uri) {
var Desktop = java.awt.Desktop;
if (Java.isType(Desktop)) {
Desktop.desktop.browse(uri);
}
}
function printDoc(list) {
list.forEach(function(doc) {
print();
print(doc.signature());
print();
print(doc.javadoc());
});
}
var JShell = null;
var jshell = null;
function javadoc(obj) {
var str = String(obj);
if (!JShell) {
// first time - resolve JShell class
JShell = Packages.jdk.jshell.JShell;
// if JShell class is available, create an instance
jshell = Java.isType(JShell)? JShell.create() : null;
}
if (!jshell) {
// we don't have jshell. Just print the default!
return print(str);
}
/*
* A java method object's String representation looks something like this:
*
* For an overloaded method:
*
* [jdk.dynalink.beans.OverloadedDynamicMethod
* String java.lang.System.getProperty(String,String)
* String java.lang.System.getProperty(String)
* ]
*
* For a non-overloaded method:
*
* [jdk.dynalink.beans.SimpleDynamicMethod void java.lang.System.exit(int)]
*
* jshell expects "java.lang.System.getProperty(" or "java.lang.System.exit("
* to retrieve the javadoc comment(s) for the method.
*/
var javaCode = str.split(" ")[2]; // stuff after second whitespace char
javaCode = javaCode.substring(0, javaCode.indexOf('(') + 1); // strip argument types
try {
var analysis = jshell.sourceCodeAnalysis();
var docList = analysis.documentation(javaCode, javaCode.length, true);
if (!docList.isEmpty()) {
return printDoc(docList);
}
/*
* May be the method is a Java instance method. In such a case, jshell expects
* a valid starting portion of an instance method call expression. We cast null
* to Java object and call method on it. i.e., We pass something like this:
*
* "((java.io.PrintStream)null).println("
*/
var javaType = javaCode.substring(0, javaCode.lastIndexOf('.'));
javaCode = "((" + javaType + ")null)" + javaCode.substring(javaCode.lastIndexOf('.'));
docList = analysis.documentation(javaCode, javaCode.length, true);
if (!docList.isEmpty()) {
return printDoc(docList);
}
} catch (e) {
}
print(str);
}
return {
isHeadless: isHeadless,
chooseFile: chooseFile,
browse: browse,
javadoc: javadoc
};
})();

View file

@ -1,45 +0,0 @@
/*
* Copyright (c) 2014, 2019, 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.
*/
/**
* Defines Nashorn shell module.
*
* <p>This module includes the command line tool <em>{@index jjs jjs tool}</em>
* to invoke the Nashorn engine.
*
* @toolGuide jjs
*
* @moduleGraph
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
module jdk.scripting.nashorn.shell {
requires static java.compiler;
requires jdk.internal.le;
requires jdk.scripting.nashorn;
requires jdk.internal.ed;
uses jdk.internal.editor.spi.BuildInEditorProvider;
}

View file

@ -1,247 +0,0 @@
.\" Copyright (c) 1994, 2019, 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.
.\"
.\" Automatically generated by Pandoc 2.3.1
.\"
.TH "JJS" "1" "2020" "JDK 14" "JDK Commands"
.hy
.SH NAME
.PP
jjs \- command\-line tool to invoke the Nashorn engine
.SH SYNOPSIS
.PP
\f[B]Note:\f[R] The \f[CB]jjs\f[R] tool and the Nashorn engine are
deprecated in JDK 11 in preparation for removal in a future release.
.PP
\f[CB]jjs\f[R] [\f[I]options\f[R]] \f[I]script\-files\f[R] [\f[CB]\-\-\f[R]
\f[I]arguments\f[R]]
.TP
.B \f[I]options\f[R]
This represents one or more options of the \f[CB]jjs\f[R] command,
separated by spaces.
See \f[B]Options for the jjs Command\f[R].
.RS
.RE
.TP
.B \f[I]script\-files\f[R]
This represents one or more script files that you want to interpret
using the Nashorn engine, separated by spaces.
If no files are specified, then an interactive shell is started.
.RS
.RE
.TP
.B \f[I]arguments\f[R]
All values after the double hyphen marker (\f[CB]\-\-\f[R]) are passed
through to the script or the interactive shell as arguments.
These values can be accessed by using the \f[CB]arguments\f[R] property.
.RS
.RE
.SH DESCRIPTION
.PP
The \f[CB]jjs\f[R] command\-line tool is used to invoke the Nashorn
engine.
You can use it to interpret one or several script files, or to run an
interactive shell.
.SH OPTIONS FOR THE JJS COMMAND
.PP
The options of the \f[CB]jjs\f[R] command control the conditions under
which scripts are interpreted by Nashorn engine.
.TP
.B \f[CB]\-D\f[R]\f[I]name\f[R]\f[CB]=\f[R]\f[I]value\f[R]
Sets a system property to be passed to the script by assigning a value
to a property name.
The following example shows how to invoke Nashorn engine in interactive
mode and assign \f[CB]myValue\f[R] to the property named \f[CB]myKey\f[R]:
.RS
.IP
.nf
\f[CB]
>>\ jjs\ \-DmyKey=myValue
jjs>\ java.lang.System.getProperty("myKey")
myValue
jjs>
\f[R]
.fi
.PP
This option can be repeated to set multiple properties.
.RE
.TP
.B \f[CB]\-\-add\-modules\f[R] \f[I]modules\f[R]
Specifies the root user Java modules.
.RS
.RE
.TP
.B \f[CB]\-cp\f[R] \f[I]path\f[R] or \f[CB]\-classpath\f[R] \f[I]path\f[R]
Specifies the path to the supporting class files.
To set multiple paths, the option can be repeated, or you can separate
each path with the following character:
.RS
.IP \[bu] 2
\f[B]Oracle Solaris, Linux, and OS X:\f[R] Colon (\f[CB]:\f[R])
.IP \[bu] 2
\f[B]Windows:\f[R] Semicolon (\f[CB];\f[R])
.RE
.TP
.B \f[CB]\-doe=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]] or \f[CB]\-dump\-on\-error=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]]
Provides a full stack trace when an error occurs.
By default, only a brief error message is printed.
The default parameter is \f[CB]false\f[R].
.RS
.RE
.TP
.B \f[CB]\-fv=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]] or \f[CB]\-fullversion=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]]
Prints the full Nashorn version string.
The default parameter is \f[CB]false\f[R].
.RS
.RE
.TP
.B \f[CB]\-fx=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]]
Launches the script as a JavaFX application.
The default parameter is \f[CB]false\f[R].
.RS
.PP
\f[B]Note:\f[R]
.PP
You must explicitly add the JavaFX modules to launch the script as a
JavaFX application.
The following example specifies the location of the JavaFX modules and
adds them with the \f[CB]\-\-module\-path\f[R] and
\f[CB]\-\-add\-modules\f[R] options:
.IP
.nf
\f[CB]
jjs\ \-fx\ \-\-module\-path\ /SOMEDIR/javafx\-sdk\-11/lib\ \-\-add\-modules\ javafx.controls\ HelloWorld.js
\f[R]
.fi
.PP
The following example uses the \f[CB]jlink\f[R] command to create a custom
runtime image that contains the JavaFX modules.
The example then launches a script as a JavaFX application without
specifying the JavaFX modules in the \f[CB]jjs\f[R] command:
.IP
.nf
\f[CB]
jlink\ \-\-module\-path\ /SOMEDIR/javafx\-jmods\-11\ \-\-add\-modules\ jdk.scripting.nashorn,jdk.scripting.nashorn.shell,javafx.controls\ \-\-output\ /SOMEDIR/myjdk
/SOMEDIR/myjdk/bin/jjs\ \-fx\ HelloWorld.js
\f[R]
.fi
.PP
If you don\[aq]t explicitly specify the JavaFX modules, then the
\f[CB]jjs\f[R] command prints a message and exits:
.IP
.nf
\f[CB]
jjs\ \-fx\ HelloWorld.js
JavaFX\ is\ not\ available.
\f[R]
.fi
.RE
.TP
.B \f[CB]\-h\f[R] or \f[CB]\-help\f[R]
Prints the list of options and their descriptions.
.RS
.RE
.TP
.B \f[CB]\-\-language=\f[R][\f[CB]es5\f[R]|\f[CB]es6\f[R]]
Specifies the ECMAScript language version.
The default version is ES5.
.RS
.RE
.TP
.B \f[CB]\-\-module\-path\f[R] \f[I]path\f[R]
Specifies where to find user Java modules.
.RS
.RE
.TP
.B \f[CB]\-ot=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]] or \f[CB]\-optimistic\-types=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]]
Enables or disables optimistic type assumptions with deoptimizing
recompilation.
This makes the compiler try, for any program symbol whose type can\[aq]t
be proven at compile time, to type it as narrowly and primitively as
possible.
If the runtime encounters an error because the symbol type is too
narrow, then a wider method is generated until a steady stage is
reached.
While this produces as optimal Java bytecode as possible, erroneous type
guesses will lead to longer warmup.
Optimistic typing is currently enabled by default, but it can be
disabled for faster startup performance.
The default parameter is \f[CB]true\f[R].
.RS
.RE
.TP
.B \f[CB]\-scripting=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]]
Enables a shell scripting features.
The default parameter is \f[CB]true\f[R].
.RS
.RE
.TP
.B \f[CB]\-strict=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]]
Enables a strict mode, which enforces stronger adherence to the standard
(ECMAScript Edition 5.1), making it easier to detect common coding
errors.
The default parameter is \f[CB]false\f[R].
.RS
.RE
.TP
.B \f[CB]\-t=\f[R]\f[I]zone\f[R] or \f[CB]\-timezone=\f[R]\f[I]zone\f[R]
Sets the specified time zone for script execution.
It overrides the time zone set in the OS and used by the \f[CB]Date\f[R]
object.
The default \f[I]zone\f[R] is \f[CB]America/Los_Angeles\f[R].
.RS
.RE
.TP
.B \f[CB]\-v=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]] or\f[CB]\-version=\f[R][\f[CB]true\f[R]|\f[CB]false\f[R]]
Prints the Nashorn version string.
The default parameter is \f[CB]false\f[R].
.RS
.RE
.SH EXAMPLE OF RUNNING A SCRIPT WITH NASHORN
.IP
.nf
\f[CB]
jjs\ script.js
\f[R]
.fi
.SH EXAMPLE OF RUNNING NASHORN IN INTERACTIVE MODE
.IP
.nf
\f[CB]
>>\ jjs
jjs>\ println("Hello,\ World!")
Hello,\ World!
jjs>\ quit()
>>
\f[R]
.fi
.SH EXAMPLE OF PASSING ARGUMENTS TO NASHORN
.IP
.nf
\f[CB]
>>\ jjs\ \-\-\ a\ b\ c
jjs>\ arguments.join(",\ ")
a,\ b,\ c
jjs>
\f[R]
.fi

View file

@ -1,61 +0,0 @@
/*
* Copyright (c) 2016, 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.
*/
package jdk.nashorn.api.linker;
import java.util.List;
import jdk.dynalink.linker.GuardingDynamicLinker;
import jdk.dynalink.linker.GuardingDynamicLinkerExporter;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
/**
* This linker exporter is a service provider that exports Nashorn Dynalink
* linkers to external users. Other language runtimes that use Dynalink
* can use the linkers exported by this provider to support tight integration
* of Nashorn objects.
*/
@Deprecated(since="11", forRemoval=true)
public final class NashornLinkerExporter extends GuardingDynamicLinkerExporter {
/**
* The default constructor.
*/
public NashornLinkerExporter() {}
/**
* Returns a list of exported nashorn specific linkers.
*
* @return list of exported nashorn specific linkers
*/
@Override
public List<GuardingDynamicLinker> get() {
return Bootstrap.getExposedLinkers();
}
}

View file

@ -1,230 +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.api.scripting;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
/**
* This is the base class for nashorn ScriptObjectMirror class.
*
* This class can also be subclassed by an arbitrary Java class. Nashorn will
* treat objects of such classes just like nashorn script objects. Usual nashorn
* operations like obj[i], obj.foo, obj.func(), delete obj.foo will be delegated
* to appropriate method call of this class.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
public abstract class AbstractJSObject implements JSObject {
/**
* The default constructor.
*/
public AbstractJSObject() {}
/**
* @implSpec This implementation always throws UnsupportedOperationException
*/
@Override
public Object call(final Object thiz, final Object... args) {
throw new UnsupportedOperationException("call");
}
/**
* @implSpec This implementation always throws UnsupportedOperationException
*/
@Override
public Object newObject(final Object... args) {
throw new UnsupportedOperationException("newObject");
}
/**
* @implSpec This imlementation always throws UnsupportedOperationException
*/
@Override
public Object eval(final String s) {
throw new UnsupportedOperationException("eval");
}
/**
* @implSpec This implementation always returns null
*/
@Override
public Object getMember(final String name) {
Objects.requireNonNull(name);
return null;
}
/**
* @implSpec This implementation always returns null
*/
@Override
public Object getSlot(final int index) {
return null;
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean hasMember(final String name) {
Objects.requireNonNull(name);
return false;
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean hasSlot(final int slot) {
return false;
}
/**
* @implSpec This implementation is a no-op
*/
@Override
public void removeMember(final String name) {
Objects.requireNonNull(name);
//empty
}
/**
* @implSpec This implementation is a no-op
*/
@Override
public void setMember(final String name, final Object value) {
Objects.requireNonNull(name);
//empty
}
/**
* @implSpec This implementation is a no-op
*/
@Override
public void setSlot(final int index, final Object value) {
//empty
}
// property and value iteration
/**
* @implSpec This implementation returns empty set
*/
@Override
public Set<String> keySet() {
return Collections.emptySet();
}
/**
* @implSpec This implementation returns empty set
*/
@Override
public Collection<Object> values() {
return Collections.emptySet();
}
// JavaScript instanceof check
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean isInstance(final Object instance) {
return false;
}
@Override
public boolean isInstanceOf(final Object clazz) {
if (clazz instanceof JSObject) {
return ((JSObject)clazz).isInstance(this);
}
return false;
}
@Override
public String getClassName() {
return getClass().getName();
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean isFunction() {
return false;
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean isStrictFunction() {
return false;
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean isArray() {
return false;
}
/**
* Returns this object's numeric value.
*
* @return this object's numeric value.
* @deprecated use {@link #getDefaultValue(Class)} with {@link Number} hint instead.
*/
@Override @Deprecated
public double toNumber() {
return Double.NaN;
}
/**
* When passed an {@link AbstractJSObject}, invokes its {@link #getDefaultValue(Class)} method. When passed any
* other {@link JSObject}, it will obtain its {@code [[DefaultValue]]} method as per ECMAScript 5.1 section
* 8.6.2.
*
* @param jsobj the {@link JSObject} whose {@code [[DefaultValue]]} is obtained.
* @param hint the type hint. Should be either {@code null}, {@code Number.class} or {@code String.class}.
* @return this object's default value.
* @throws UnsupportedOperationException if the conversion can't be performed. The engine will convert this
* exception into a JavaScript {@code TypeError}.
* @deprecated use {@link JSObject#getDefaultValue(Class)} instead.
*/
@Deprecated
public static Object getDefaultValue(final JSObject jsobj, final Class<?> hint) {
return jsobj.getDefaultValue(hint);
}
}

View file

@ -1,47 +0,0 @@
/*
* 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.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
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);
}

View file

@ -1,55 +0,0 @@
/*
* Copyright (c) 2015, 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;
import jdk.nashorn.internal.runtime.JSType;
/**
* Default implementation of {@link JSObject#getDefaultValue(Class)}. Isolated into a separate class mostly so
* that we can have private static instances of function name arrays, something we couldn't declare without it
* being visible in {@link JSObject} interface.
*/
class DefaultValueImpl {
private static final String[] DEFAULT_VALUE_FNS_NUMBER = new String[] { "valueOf", "toString" };
private static final String[] DEFAULT_VALUE_FNS_STRING = new String[] { "toString", "valueOf" };
static Object getDefaultValue(final JSObject jsobj, final Class<?> hint) throws UnsupportedOperationException {
final boolean isNumber = hint == null || hint == Number.class;
for(final String methodName: isNumber ? DEFAULT_VALUE_FNS_NUMBER : DEFAULT_VALUE_FNS_STRING) {
final Object objMember = jsobj.getMember(methodName);
if (objMember instanceof JSObject) {
final JSObject member = (JSObject)objMember;
if (member.isFunction()) {
final Object value = member.call(jsobj);
if (JSType.isPrimitive(value)) {
return value;
}
}
}
}
throw new UnsupportedOperationException(isNumber ? "cannot.get.default.number" : "cannot.get.default.string");
}
}

View file

@ -1,185 +0,0 @@
/*
* Copyright (c) 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.api.scripting;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Formatter is a class to get the type conversion between javascript types and
* java types for the format (sprintf) method working.
*
* <p>In javascript the type for numbers can be different from the format type
* specifier. For format type '%d', '%o', '%x', '%X' double need to be
* converted to integer. For format type 'e', 'E', 'f', 'g', 'G', 'a', 'A'
* integer needs to be converted to double.
*
* <p>Format type "%c" and javascript string needs special handling.
*
* <p>The javascript date objects can be handled if they are type double (the
* related javascript code will convert with Date.getTime() to double). So
* double date types are converted to long.
*
* <p>Pattern and the logic for parameter position: java.util.Formatter
*
*/
final class Formatter {
private Formatter() {
}
/**
* Method which converts javascript types to java types for the
* String.format method (jrunscript function sprintf).
*
* @param format a format string
* @param args arguments referenced by the format specifiers in format
* @return a formatted string
*/
static String format(final String format, final Object[] args) {
final Matcher m = FS_PATTERN.matcher(format);
int positionalParameter = 1;
while (m.find()) {
int index = index(m.group(1));
final boolean previous = isPreviousArgument(m.group(2));
final char conversion = m.group(6).charAt(0);
// skip over some formats
if (index < 0 || previous
|| conversion == 'n' || conversion == '%') {
continue;
}
// index 0 here means take a positional parameter
if (index == 0) {
index = positionalParameter++;
}
// out of index, String.format will handle
if (index > args.length) {
continue;
}
// current argument
final Object arg = args[index - 1];
// for date we convert double to long
if (m.group(5) != null) {
// convert double to long
if (arg instanceof Double) {
args[index - 1] = ((Double) arg).longValue();
}
} else {
// we have to convert some types
switch (conversion) {
case 'd':
case 'o':
case 'x':
case 'X':
if (arg instanceof Double) {
// convert double to long
args[index - 1] = ((Double) arg).longValue();
} else if (arg instanceof String
&& ((String) arg).length() > 0) {
// convert string (first character) to int
args[index - 1] = (int) ((String) arg).charAt(0);
}
break;
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
case 'a':
case 'A':
if (arg instanceof Integer) {
// convert integer to double
args[index - 1] = ((Integer) arg).doubleValue();
}
break;
case 'c':
if (arg instanceof Double) {
// convert double to integer
args[index - 1] = ((Double) arg).intValue();
} else if (arg instanceof String
&& ((String) arg).length() > 0) {
// get the first character from string
args[index - 1] = (int) ((String) arg).charAt(0);
}
break;
default:
break;
}
}
}
return String.format(format, args);
}
/**
* Method to parse the integer of the argument index.
*
* @param s string to parse
* @return -1 if parsing failed, 0 if string is null, > 0 integer
*/
private static int index(final String s) {
int index = -1;
if (s != null) {
try {
index = Integer.parseInt(s.substring(0, s.length() - 1));
} catch (final NumberFormatException e) {
//ignored
}
} else {
index = 0;
}
return index;
}
/**
* Method to check if a string contains '&lt;'. This is used to find out if
* previous parameter is used.
*
* @param s string to check
* @return true if '&lt;' is in the string, else false
*/
private static boolean isPreviousArgument(final String s) {
return (s != null && s.indexOf('<') >= 0);
}
// %[argument_index$][flags][width][.precision][t]conversion
private static final String formatSpecifier =
"%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";
// compiled format string
private static final Pattern FS_PATTERN;
static {
FS_PATTERN = Pattern.compile(formatSpecifier);
}
}

View file

@ -1,214 +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.api.scripting;
import java.util.Collection;
import java.util.Set;
import jdk.nashorn.internal.runtime.JSType;
/**
* This interface can be implemented by an arbitrary Java class. Nashorn will
* treat objects of such classes just like nashorn script objects. Usual nashorn
* operations like obj[i], obj.foo, obj.func(), delete obj.foo will be delegated
* to appropriate method call of this interface.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
public interface JSObject {
/**
* Call this object as a JavaScript function. This is equivalent to
* 'func.apply(thiz, args)' in JavaScript.
*
* @param thiz 'this' object to be passed to the function. This may be null.
* @param args arguments to method
* @return result of call
*/
public Object call(final Object thiz, final Object... args);
/**
* Call this 'constructor' JavaScript function to create a new object.
* This is equivalent to 'new func(arg1, arg2...)' in JavaScript.
*
* @param args arguments to method
* @return result of constructor call
*/
public Object newObject(final Object... args);
/**
* Evaluate a JavaScript expression.
*
* @param s JavaScript expression to evaluate
* @return evaluation result
*/
public Object eval(final String s);
/**
* Retrieves a named member of this JavaScript object.
*
* @param name of member
* @return member
* @throws NullPointerException if name is null
*/
public Object getMember(final String name);
/**
* Retrieves an indexed member of this JavaScript object.
*
* @param index index slot to retrieve
* @return member
*/
public Object getSlot(final int index);
/**
* Does this object have a named member?
*
* @param name name of member
* @return true if this object has a member of the given name
*/
public boolean hasMember(final String name);
/**
* Does this object have a indexed property?
*
* @param slot index to check
* @return true if this object has a slot
*/
public boolean hasSlot(final int slot);
/**
* Remove a named member from this JavaScript object
*
* @param name name of the member
* @throws NullPointerException if name is null
*/
public void removeMember(final String name);
/**
* Set a named member in this JavaScript object
*
* @param name name of the member
* @param value value of the member
* @throws NullPointerException if name is null
*/
public void setMember(final String name, final Object value);
/**
* Set an indexed member in this JavaScript object
*
* @param index index of the member slot
* @param value value of the member
*/
public void setSlot(final int index, final Object value);
// property and value iteration
/**
* Returns the set of all property names of this object.
*
* @return set of property names
*/
public Set<String> keySet();
/**
* Returns the set of all property values of this object.
*
* @return set of property values.
*/
public Collection<Object> values();
// JavaScript instanceof check
/**
* Checking whether the given object is an instance of 'this' object.
*
* @param instance instance to check
* @return true if the given 'instance' is an instance of this 'function' object
*/
public boolean isInstance(final Object instance);
/**
* Checking whether this object is an instance of the given 'clazz' object.
*
* @param clazz clazz to check
* @return true if this object is an instance of the given 'clazz'
*/
public boolean isInstanceOf(final Object clazz);
/**
* ECMA [[Class]] property
*
* @return ECMA [[Class]] property value of this object
*/
public String getClassName();
/**
* Is this a function object?
*
* @return if this mirror wraps a ECMAScript function instance
*/
public boolean isFunction();
/**
* Is this a 'use strict' function object?
*
* @return true if this mirror represents a ECMAScript 'use strict' function
*/
public boolean isStrictFunction();
/**
* Is this an array object?
*
* @return if this mirror wraps a ECMAScript array object
*/
public boolean isArray();
/**
* Returns this object's numeric value.
*
* @return this object's numeric value.
* @deprecated use {@link #getDefaultValue(Class)} with {@link Number} hint instead.
*/
@Deprecated
default double toNumber() {
return JSType.toNumber(JSType.toPrimitive(this, Number.class));
}
/**
* Implements this object's {@code [[DefaultValue]]} method as per ECMAScript 5.1 section 8.6.2.
*
* @param hint the type hint. Should be either {@code null}, {@code Number.class} or {@code String.class}.
* @return this object's default value.
* @throws UnsupportedOperationException if the conversion can't be performed. The engine will convert this
* exception into a JavaScript {@code TypeError}.
*/
default Object getDefaultValue(final Class<?> hint) throws UnsupportedOperationException {
return DefaultValueImpl.getDefaultValue(this, hint);
}
}

View file

@ -1,300 +0,0 @@
/*
* Copyright (c) 2010, 2016, 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;
import java.util.ArrayList;
import java.util.List;
import jdk.nashorn.internal.codegen.CompilerConstants;
import jdk.nashorn.internal.runtime.ECMAErrors;
import jdk.nashorn.internal.runtime.ScriptObject;
/**
* This is base exception for all Nashorn exceptions. These originate from
* user's ECMAScript code. Example: script parse errors, exceptions thrown from
* scripts. Note that ScriptEngine methods like "eval", "invokeMethod",
* "invokeFunction" will wrap this as ScriptException and throw it. But, there
* are cases where user may need to access this exception (or implementation
* defined subtype of this). For example, if java interface is implemented by a
* script object or Java access to script object properties via java.util.Map
* interface. In these cases, user code will get an instance of this or
* implementation defined subclass.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
@SuppressWarnings("serial")
public abstract class NashornException extends RuntimeException {
private static final long serialVersionUID = 1L;
// script file name
private String fileName;
// script line number
private int line;
// are the line and fileName unknown?
private boolean lineAndFileNameUnknown;
// script column number
private int column;
// underlying ECMA error object - lazily initialized
private Object ecmaError;
/**
* Constructor to initialize error message, file name, line and column numbers.
*
* @param msg exception message
* @param fileName file name
* @param line line number
* @param column column number
*/
protected NashornException(final String msg, final String fileName, final int line, final int column) {
this(msg, null, fileName, line, column);
}
/**
* Constructor to initialize error message, cause exception, file name, line and column numbers.
*
* @param msg exception message
* @param cause exception cause
* @param fileName file name
* @param line line number
* @param column column number
*/
protected NashornException(final String msg, final Throwable cause, final String fileName, final int line, final int column) {
super(msg, cause == null ? null : cause);
this.fileName = fileName;
this.line = line;
this.column = column;
}
/**
* Constructor to initialize error message and cause exception.
*
* @param msg exception message
* @param cause exception cause
*/
protected NashornException(final String msg, final Throwable cause) {
super(msg, cause == null ? null : cause);
// Hard luck - no column number info
this.column = -1;
// We can retrieve the line number and file name from the stack trace if needed
this.lineAndFileNameUnknown = true;
}
/**
* Get the source file name for this {@code NashornException}
*
* @return the file name
*/
public final String getFileName() {
ensureLineAndFileName();
return fileName;
}
/**
* Set the source file name for this {@code NashornException}
*
* @param fileName the file name
*/
public final void setFileName(final String fileName) {
this.fileName = fileName;
lineAndFileNameUnknown = false;
}
/**
* Get the line number for this {@code NashornException}
*
* @return the line number
*/
public final int getLineNumber() {
ensureLineAndFileName();
return line;
}
/**
* Set the line number for this {@code NashornException}
*
* @param line the line number
*/
public final void setLineNumber(final int line) {
lineAndFileNameUnknown = false;
this.line = line;
}
/**
* Get the column for this {@code NashornException}
*
* @return the column number
*/
public final int getColumnNumber() {
return column;
}
/**
* Set the column for this {@code NashornException}
*
* @param column the column number
*/
public final void setColumnNumber(final int column) {
this.column = column;
}
/**
* Returns array javascript stack frames from the given exception object.
*
* @param exception exception from which stack frames are retrieved and filtered
* @return array of javascript stack frames
*/
public static StackTraceElement[] getScriptFrames(final Throwable exception) {
final StackTraceElement[] frames = exception.getStackTrace();
final List<StackTraceElement> filtered = new ArrayList<>();
for (final StackTraceElement st : frames) {
if (ECMAErrors.isScriptFrame(st)) {
final String className = "<" + st.getFileName() + ">";
String methodName = st.getMethodName();
if (methodName.equals(CompilerConstants.PROGRAM.symbolName())) {
methodName = "<program>";
} else {
methodName = stripMethodName(methodName);
}
filtered.add(new StackTraceElement(className, methodName,
st.getFileName(), st.getLineNumber()));
}
}
return filtered.toArray(new StackTraceElement[0]);
}
private static String stripMethodName(final String methodName) {
String name = methodName;
final int nestedSeparator = name.lastIndexOf(CompilerConstants.NESTED_FUNCTION_SEPARATOR.symbolName());
if (nestedSeparator >= 0) {
name = name.substring(nestedSeparator + 1);
}
final int idSeparator = name.indexOf(CompilerConstants.ID_FUNCTION_SEPARATOR.symbolName());
if (idSeparator >= 0) {
name = name.substring(0, idSeparator);
}
return name.contains(CompilerConstants.ANON_FUNCTION_PREFIX.symbolName()) ? "<anonymous>" : name;
}
/**
* Return a formatted script stack trace string with frames information separated by '\n'
*
* @param exception exception for which script stack string is returned
* @return formatted stack trace string
*/
public static String getScriptStackString(final Throwable exception) {
final StringBuilder buf = new StringBuilder();
final StackTraceElement[] frames = getScriptFrames(exception);
for (final StackTraceElement st : frames) {
buf.append("\tat ");
buf.append(st.getMethodName());
buf.append(" (");
buf.append(st.getFileName());
buf.append(':');
buf.append(st.getLineNumber());
buf.append(")\n");
}
final int len = buf.length();
// remove trailing '\n'
if (len > 0) {
assert buf.charAt(len - 1) == '\n';
buf.deleteCharAt(len - 1);
}
return buf.toString();
}
/**
* Get the thrown object. Subclass responsibility
* @return thrown object
*/
protected Object getThrown() {
return null;
}
/**
* Initialization function for ECMA errors. Stores the error
* in the ecmaError field of this class. It is only initialized
* once, and then reused
*
* @param global the global
* @return initialized exception
*/
NashornException initEcmaError(final ScriptObject global) {
if (ecmaError != null) {
return this; // initialized already!
}
final Object thrown = getThrown();
if (thrown instanceof ScriptObject) {
setEcmaError(ScriptObjectMirror.wrap(thrown, global));
} else {
setEcmaError(thrown);
}
return this;
}
/**
* Return the underlying ECMA error object, if available.
*
* @return underlying ECMA Error object's mirror or whatever was thrown
* from script such as a String, Number or a Boolean.
*/
public Object getEcmaError() {
return ecmaError;
}
/**
* Return the underlying ECMA error object, if available.
*
* @param ecmaError underlying ECMA Error object's mirror or whatever was thrown
* from script such as a String, Number or a Boolean.
*/
public void setEcmaError(final Object ecmaError) {
this.ecmaError = ecmaError;
}
private void ensureLineAndFileName() {
if (lineAndFileNameUnknown) {
for (final StackTraceElement ste : getStackTrace()) {
if (ECMAErrors.isScriptFrame(ste)) {
// Whatever here is compiled from JavaScript code
fileName = ste.getFileName();
line = ste.getLineNumber();
return;
}
}
lineAndFileNameUnknown = false;
}
}
}

View file

@ -1,576 +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.api.scripting;
import static jdk.nashorn.internal.runtime.Source.sourceFor;
import java.io.IOException;
import java.io.Reader;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Objects;
import java.util.ResourceBundle;
import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
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;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.Source;
import jdk.nashorn.internal.runtime.linker.JavaAdapterFactory;
import jdk.nashorn.internal.runtime.options.Options;
/**
* JSR-223 compliant script engine for Nashorn. Instances are not created directly, but rather returned through
* {@link NashornScriptEngineFactory#getScriptEngine()}. Note that this engine implements the {@link Compilable} and
* {@link Invocable} interfaces, allowing for efficient precompilation and repeated execution of scripts.
* @see NashornScriptEngineFactory
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
public final class NashornScriptEngine extends AbstractScriptEngine implements Compilable, Invocable {
/**
* Key used to associate Nashorn global object mirror with arbitrary Bindings instance.
*/
public static final String NASHORN_GLOBAL = "nashorn.global";
// commonly used access control context objects
private static AccessControlContext createPermAccCtxt(final String permName) {
final Permissions perms = new Permissions();
perms.add(new RuntimePermission(permName));
return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
}
private static final AccessControlContext CREATE_CONTEXT_ACC_CTXT = createPermAccCtxt(Context.NASHORN_CREATE_CONTEXT);
private static final AccessControlContext CREATE_GLOBAL_ACC_CTXT = createPermAccCtxt(Context.NASHORN_CREATE_GLOBAL);
// the factory that created this engine
private final ScriptEngineFactory factory;
// underlying nashorn Context - 1:1 with engine instance
private final Context nashornContext;
// do we want to share single Nashorn global instance across ENGINE_SCOPEs?
private final boolean _global_per_engine;
// This is the initial default Nashorn global object.
// This is used as "shared" global if above option is true.
private final Global global;
// Nashorn script engine error message management
private static final String MESSAGES_RESOURCE = "jdk.nashorn.api.scripting.resources.Messages";
private static final ResourceBundle MESSAGES_BUNDLE;
static {
MESSAGES_BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, Locale.getDefault());
}
// helper to get Nashorn script engine error message
private static String getMessage(final String msgId, final String... args) {
try {
return new MessageFormat(MESSAGES_BUNDLE.getString(msgId)).format(args);
} catch (final java.util.MissingResourceException e) {
throw new RuntimeException("no message resource found for message id: "+ msgId);
}
}
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);
// throw ParseException on first error from script
final ErrorManager errMgr = new Context.ThrowErrorManager();
// create new Nashorn Context
this.nashornContext = AccessController.doPrivileged(new PrivilegedAction<Context>() {
@Override
public Context run() {
try {
return new Context(options, errMgr, appLoader, classFilter);
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
}
throw e;
}
}
}, CREATE_CONTEXT_ACC_CTXT);
if (!nashornContext.getEnv()._no_deprecation_warning) {
System.err.println("Warning: Nashorn engine is planned to be removed from a future JDK release");
}
// cache this option that is used often
this._global_per_engine = nashornContext.getEnv()._global_per_engine;
// create new global object
this.global = createNashornGlobal();
// set the default ENGINE_SCOPE object for the default context
context.setBindings(new ScriptObjectMirror(global, global), ScriptContext.ENGINE_SCOPE);
}
@Override
public Object eval(final Reader reader, final ScriptContext ctxt) throws ScriptException {
return evalImpl(makeSource(reader, ctxt), ctxt);
}
@Override
public Object eval(final String script, final ScriptContext ctxt) throws ScriptException {
return evalImpl(makeSource(script, ctxt), ctxt);
}
@Override
public ScriptEngineFactory getFactory() {
return factory;
}
@Override
public Bindings createBindings() {
if (_global_per_engine) {
// just create normal SimpleBindings.
// We use same 'global' for all Bindings.
return new SimpleBindings();
}
return createGlobalMirror();
}
// Compilable methods
@Override
public CompiledScript compile(final Reader reader) throws ScriptException {
return asCompiledScript(makeSource(reader, context));
}
@Override
public CompiledScript compile(final String str) throws ScriptException {
return asCompiledScript(makeSource(str, context));
}
// Invocable methods
@Override
public Object invokeFunction(final String name, final Object... args)
throws ScriptException, NoSuchMethodException {
return invokeImpl(null, name, args);
}
@Override
public Object invokeMethod(final Object thiz, final String name, final Object... args)
throws ScriptException, NoSuchMethodException {
if (thiz == null) {
throw new IllegalArgumentException(getMessage("thiz.cannot.be.null"));
}
return invokeImpl(thiz, name, args);
}
@Override
public <T> T getInterface(final Class<T> clazz) {
return getInterfaceInner(null, clazz);
}
@Override
public <T> T getInterface(final Object thiz, final Class<T> clazz) {
if (thiz == null) {
throw new IllegalArgumentException(getMessage("thiz.cannot.be.null"));
}
return getInterfaceInner(thiz, clazz);
}
// Implementation only below this point
private static Source makeSource(final Reader reader, final ScriptContext ctxt) throws ScriptException {
try {
return sourceFor(getScriptName(ctxt), reader);
} catch (final IOException e) {
throw new ScriptException(e);
}
}
private static Source makeSource(final String src, final ScriptContext ctxt) {
return sourceFor(getScriptName(ctxt), src);
}
private static String getScriptName(final ScriptContext ctxt) {
final Object val = ctxt.getAttribute(ScriptEngine.FILENAME);
return (val != null) ? val.toString() : "<eval>";
}
private <T> T getInterfaceInner(final Object thiz, final Class<T> clazz) {
assert !(thiz instanceof ScriptObject) : "raw ScriptObject not expected here";
if (clazz == null || !clazz.isInterface()) {
throw new IllegalArgumentException(getMessage("interface.class.expected"));
}
// perform security access check as early as possible
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (! Modifier.isPublic(clazz.getModifiers())) {
throw new SecurityException(getMessage("implementing.non.public.interface", clazz.getName()));
}
Context.checkPackageAccess(clazz);
}
ScriptObject realSelf = null;
Global realGlobal = null;
if(thiz == null) {
// making interface out of global functions
realSelf = realGlobal = getNashornGlobalFrom(context);
} else if (thiz instanceof ScriptObjectMirror) {
final ScriptObjectMirror mirror = (ScriptObjectMirror)thiz;
realSelf = mirror.getScriptObject();
realGlobal = mirror.getHomeGlobal();
if (! isOfContext(realGlobal, nashornContext)) {
throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
}
}
if (realSelf == null) {
throw new IllegalArgumentException(getMessage("interface.on.non.script.object"));
}
try {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != realGlobal);
try {
if (globalChanged) {
Context.setGlobal(realGlobal);
}
if (! isInterfaceImplemented(clazz, realSelf)) {
return null;
}
return clazz.cast(JavaAdapterFactory.getConstructor(realSelf.getClass(), clazz,
MethodHandles.publicLookup()).invoke(realSelf));
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
} catch(final RuntimeException|Error e) {
throw e;
} catch(final Throwable t) {
throw new RuntimeException(t);
}
}
// Retrieve nashorn Global object for a given ScriptContext object
private Global getNashornGlobalFrom(final ScriptContext ctxt) {
if (_global_per_engine) {
// shared single global object for all ENGINE_SCOPE Bindings
return global;
}
final Bindings bindings = ctxt.getBindings(ScriptContext.ENGINE_SCOPE);
// is this Nashorn's own Bindings implementation?
if (bindings instanceof ScriptObjectMirror) {
final Global glob = globalFromMirror((ScriptObjectMirror)bindings);
if (glob != null) {
return glob;
}
}
// Arbitrary user Bindings implementation. Look for NASHORN_GLOBAL in it!
final Object scope = bindings.get(NASHORN_GLOBAL);
if (scope instanceof ScriptObjectMirror) {
final Global glob = globalFromMirror((ScriptObjectMirror)scope);
if (glob != null) {
return glob;
}
}
// We didn't find associated nashorn global mirror in the Bindings given!
// Create new global instance mirror and associate with the Bindings.
final ScriptObjectMirror mirror = createGlobalMirror();
bindings.put(NASHORN_GLOBAL, mirror);
// Since we created this global explicitly for the non-default script context we set the
// current script context in global permanently so that invokes work as expected. See JDK-8150219
mirror.getHomeGlobal().setInitScriptContext(ctxt);
return mirror.getHomeGlobal();
}
// Retrieve nashorn Global object from a given ScriptObjectMirror
private Global globalFromMirror(final ScriptObjectMirror mirror) {
final ScriptObject sobj = mirror.getScriptObject();
if (sobj instanceof Global && isOfContext((Global)sobj, nashornContext)) {
return (Global)sobj;
}
return null;
}
// Create a new ScriptObjectMirror wrapping a newly created Nashorn Global object
private ScriptObjectMirror createGlobalMirror() {
final Global newGlobal = createNashornGlobal();
return new ScriptObjectMirror(newGlobal, newGlobal);
}
// Create a new Nashorn Global object
private Global createNashornGlobal() {
final Global newGlobal = AccessController.doPrivileged(new PrivilegedAction<Global>() {
@Override
public Global run() {
try {
return nashornContext.newGlobal();
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
}
throw e;
}
}
}, CREATE_GLOBAL_ACC_CTXT);
nashornContext.initGlobal(newGlobal, this);
return newGlobal;
}
private Object invokeImpl(final Object selfObject, final String name, final Object... args) throws ScriptException, NoSuchMethodException {
Objects.requireNonNull(name);
assert !(selfObject instanceof ScriptObject) : "raw ScriptObject not expected here";
Global invokeGlobal = null;
ScriptObjectMirror selfMirror = null;
if (selfObject instanceof ScriptObjectMirror) {
selfMirror = (ScriptObjectMirror)selfObject;
if (! isOfContext(selfMirror.getHomeGlobal(), nashornContext)) {
throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
}
invokeGlobal = selfMirror.getHomeGlobal();
} else if (selfObject == null) {
// selfObject is null => global function call
final Global ctxtGlobal = getNashornGlobalFrom(context);
invokeGlobal = ctxtGlobal;
selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(ctxtGlobal, ctxtGlobal);
}
if (selfMirror != null) {
try {
return ScriptObjectMirror.translateUndefined(selfMirror.callMember(name, args));
} catch (final Exception e) {
final Throwable cause = e.getCause();
if (cause instanceof NoSuchMethodException) {
throw (NoSuchMethodException)cause;
}
throwAsScriptException(e, invokeGlobal);
throw new AssertionError("should not reach here");
}
}
// Non-script object passed as selfObject
throw new IllegalArgumentException(getMessage("interface.on.non.script.object"));
}
private Object evalImpl(final Source src, final ScriptContext ctxt) throws ScriptException {
return evalImpl(compileImpl(src, ctxt), ctxt);
}
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt) throws ScriptException {
return evalImpl(script, ctxt, getNashornGlobalFrom(ctxt));
}
private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != ctxtGlobal);
try {
if (globalChanged) {
Context.setGlobal(ctxtGlobal);
}
final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
ctxtGlobal.setScriptContext(ctxt);
try {
return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
} finally {
ctxtGlobal.setScriptContext(oldCtxt);
}
} catch (final Exception e) {
throwAsScriptException(e, ctxtGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
if (script == null) {
return null;
}
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != ctxtGlobal);
try {
if (globalChanged) {
Context.setGlobal(ctxtGlobal);
}
final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
ctxtGlobal.setScriptContext(ctxt);
try {
return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
} finally {
ctxtGlobal.setScriptContext(oldCtxt);
}
} catch (final Exception e) {
throwAsScriptException(e, ctxtGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
private static void throwAsScriptException(final Exception e, final Global global) throws ScriptException {
if (e instanceof ScriptException) {
throw (ScriptException)e;
} else if (e instanceof NashornException) {
final NashornException ne = (NashornException)e;
final ScriptException se = new ScriptException(
ne.getMessage(), ne.getFileName(),
ne.getLineNumber(), ne.getColumnNumber());
ne.initEcmaError(global);
se.initCause(e);
throw se;
} else if (e instanceof RuntimeException) {
throw (RuntimeException)e;
} else {
// wrap any other exception as ScriptException
throw new ScriptException(e);
}
}
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
final Context.MultiGlobalCompiledScript mgcs;
final ScriptFunction func;
final Global oldGlobal = Context.getGlobal();
final Global newGlobal = getNashornGlobalFrom(context);
final boolean globalChanged = (oldGlobal != newGlobal);
try {
if (globalChanged) {
Context.setGlobal(newGlobal);
}
mgcs = nashornContext.compileScript(source);
func = mgcs.getFunction(newGlobal);
} catch (final Exception e) {
throwAsScriptException(e, newGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
return new CompiledScript() {
@Override
public Object eval(final ScriptContext ctxt) throws ScriptException {
final Global globalObject = getNashornGlobalFrom(ctxt);
// Are we running the script in the same global in which it was compiled?
if (func.getScope() == globalObject) {
return evalImpl(func, ctxt, globalObject);
}
// different global
return evalImpl(mgcs, ctxt, globalObject);
}
@Override
public ScriptEngine getEngine() {
return NashornScriptEngine.this;
}
};
}
private ScriptFunction compileImpl(final Source source, final ScriptContext ctxt) throws ScriptException {
return compileImpl(source, getNashornGlobalFrom(ctxt));
}
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != newGlobal);
try {
if (globalChanged) {
Context.setGlobal(newGlobal);
}
return nashornContext.compileScript(source, newGlobal);
} catch (final Exception e) {
throwAsScriptException(e, newGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
private static boolean isInterfaceImplemented(final Class<?> iface, final ScriptObject sobj) {
for (final Method method : iface.getMethods()) {
// ignore methods of java.lang.Object class
if (method.getDeclaringClass() == Object.class) {
continue;
}
// skip check for default methods - non-abstract, interface methods
if (! Modifier.isAbstract(method.getModifiers())) {
continue;
}
final Object obj = sobj.get(method.getName());
if (! (obj instanceof ScriptFunction)) {
return false;
}
}
return true;
}
private static boolean isOfContext(final Global global, final Context context) {
return global.isOfContext(context);
}
}

View file

@ -1,289 +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.api.scripting;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.Version;
/**
* JSR-223 compliant script engine factory for Nashorn. The engine answers for:
* <ul>
* <li>names {@code "nashorn"}, {@code "Nashorn"}, {@code "js"}, {@code "JS"}, {@code "JavaScript"},
* {@code "javascript"}, {@code "ECMAScript"}, and {@code "ecmascript"};</li>
* <li>MIME types {@code "application/javascript"}, {@code "application/ecmascript"}, {@code "text/javascript"}, and
* {@code "text/ecmascript"};</li>
* <li>as well as for the extension {@code "js"}.</li>
* </ul>
* Programs executing in engines created using {@link #getScriptEngine(String[])} will have the passed arguments
* accessible as a global variable named {@code "arguments"}.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
public final class NashornScriptEngineFactory implements ScriptEngineFactory {
@Override
public String getEngineName() {
return (String) getParameter(ScriptEngine.ENGINE);
}
@Override
public String getEngineVersion() {
return (String) getParameter(ScriptEngine.ENGINE_VERSION);
}
@Override
public List<String> getExtensions() {
return Collections.unmodifiableList(extensions);
}
@Override
public String getLanguageName() {
return (String) getParameter(ScriptEngine.LANGUAGE);
}
@Override
public String getLanguageVersion() {
return (String) getParameter(ScriptEngine.LANGUAGE_VERSION);
}
@Override
public String getMethodCallSyntax(final String obj, final String method, final String... args) {
final StringBuilder sb = new StringBuilder().
append(Objects.requireNonNull(obj)).append('.').
append(Objects.requireNonNull(method)).append('(');
final int len = args.length;
if (len > 0) {
sb.append(Objects.requireNonNull(args[0]));
}
for (int i = 1; i < len; i++) {
sb.append(',').append(Objects.requireNonNull(args[i]));
}
sb.append(')');
return sb.toString();
}
@Override
public List<String> getMimeTypes() {
return Collections.unmodifiableList(mimeTypes);
}
@Override
public List<String> getNames() {
return Collections.unmodifiableList(names);
}
@Override
public String getOutputStatement(final String toDisplay) {
return "print(" + toDisplay + ")";
}
@Override
public Object getParameter(final String key) {
switch (key) {
case ScriptEngine.NAME:
return "javascript";
case ScriptEngine.ENGINE:
return "Oracle Nashorn";
case ScriptEngine.ENGINE_VERSION:
return Version.version();
case ScriptEngine.LANGUAGE:
return "ECMAScript";
case ScriptEngine.LANGUAGE_VERSION:
return "ECMA - 262 Edition 5.1";
case "THREADING":
// The engine implementation is not thread-safe. Can't be
// used to execute scripts concurrently on multiple threads.
return null;
default:
return null;
}
}
@Override
public String getProgram(final String... statements) {
Objects.requireNonNull(statements);
final StringBuilder sb = new StringBuilder();
for (final String statement : statements) {
sb.append(Objects.requireNonNull(statement)).append(';');
}
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, DEFAULT_OPTIONS, getAppClassLoader(), null);
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
}
throw e;
}
}
/**
* Create a new Script engine initialized with the given class loader.
*
* @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) {
return newEngine(DEFAULT_OPTIONS, appLoader, null);
}
/**
* Create a new Script engine initialized with the 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) {
return newEngine(DEFAULT_OPTIONS, getAppClassLoader(), Objects.requireNonNull(classFilter));
}
/**
* Create a new Script engine initialized with the given arguments.
*
* @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) {
return newEngine(Objects.requireNonNull(args), getAppClassLoader(), null);
}
/**
* Create a new Script engine initialized with the given arguments and the given class loader.
*
* @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) {
return newEngine(Objects.requireNonNull(args), appLoader, null);
}
/**
* Create a new Script engine initialized with the given arguments, class loader and class filter.
*
* @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) {
return newEngine(Objects.requireNonNull(args), appLoader, Objects.requireNonNull(classFilter));
}
private ScriptEngine newEngine(final String[] args, final ClassLoader appLoader, final ClassFilter classFilter) {
checkConfigPermission();
try {
return new NashornScriptEngine(this, args, appLoader, classFilter);
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
}
throw e;
}
}
// -- Internals only below this point
private static void checkConfigPermission() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission(Context.NASHORN_SET_CONFIG));
}
}
private static final List<String> names;
private static final List<String> mimeTypes;
private static final List<String> extensions;
static {
names = immutableList(
"nashorn", "Nashorn",
"js", "JS",
"JavaScript", "javascript",
"ECMAScript", "ecmascript"
);
mimeTypes = immutableList(
"application/javascript",
"application/ecmascript",
"text/javascript",
"text/ecmascript"
);
extensions = immutableList("js");
}
private static List<String> immutableList(final String... elements) {
return Collections.unmodifiableList(Arrays.asList(elements));
}
private static ClassLoader getAppClassLoader() {
// Revisit: script engine implementation needs the capability to
// find the class loader of the context in which the script engine
// is running so that classes will be found and loaded properly
final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
return (ccl == null)? NashornScriptEngineFactory.class.getClassLoader() : ccl;
}
}

View file

@ -1,925 +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.api.scripting;
import java.nio.ByteBuffer;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.script.Bindings;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.runtime.ConsString;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ECMAException;
import jdk.nashorn.internal.runtime.JSONListAdapter;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.arrays.ArrayData;
import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
/**
* Mirror object that wraps a given Nashorn Script object.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
public final class ScriptObjectMirror extends AbstractJSObject implements Bindings {
private static AccessControlContext getContextAccCtxt() {
final Permissions perms = new Permissions();
perms.add(new RuntimePermission(Context.NASHORN_GET_CONTEXT));
return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
}
private static final AccessControlContext GET_CONTEXT_ACC_CTXT = getContextAccCtxt();
private final ScriptObject sobj;
private final Global global;
private final boolean strict;
private final boolean jsonCompatible;
@Override
public boolean equals(final Object other) {
if (other instanceof ScriptObjectMirror) {
return sobj.equals(((ScriptObjectMirror)other).sobj);
}
return false;
}
@Override
public int hashCode() {
return sobj.hashCode();
}
@Override
public String toString() {
return inGlobal(new Callable<String>() {
@Override
public String call() {
return ScriptRuntime.safeToString(sobj);
}
});
}
// JSObject methods
@Override
public Object call(final Object thiz, final Object... args) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
if (sobj instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
final Object self = globalChanged? wrapLikeMe(thiz, oldGlobal) : thiz;
return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)sobj, unwrap(self, global), unwrapArray(modArgs, global)));
}
throw new RuntimeException("not a function: " + toString());
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object newObject(final Object... args) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
if (sobj instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
return wrapLikeMe(ScriptRuntime.construct((ScriptFunction)sobj, unwrapArray(modArgs, global)));
}
throw new RuntimeException("not a constructor: " + toString());
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object eval(final String s) {
return inGlobal(new Callable<Object>() {
@Override
public Object call() {
final Context context = AccessController.doPrivileged(
new PrivilegedAction<Context>() {
@Override
public Context run() {
return Context.getContext();
}
}, GET_CONTEXT_ACC_CTXT);
return wrapLikeMe(context.eval(global, s, sobj, null));
}
});
}
/**
* Call member function
* @param functionName function name
* @param args arguments
* @return return value of function
*/
public Object callMember(final String functionName, final Object... args) {
Objects.requireNonNull(functionName);
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
final Object val = sobj.get(functionName);
if (val instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)val, sobj, unwrapArray(modArgs, global)));
} else if (val instanceof JSObject && ((JSObject)val).isFunction()) {
return ((JSObject)val).call(sobj, args);
}
throw new NoSuchMethodException("No such function " + functionName);
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object getMember(final String name) {
Objects.requireNonNull(name);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.get(name));
}
});
}
@Override
public Object getSlot(final int index) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.get(index));
}
});
}
@Override
public boolean hasMember(final String name) {
Objects.requireNonNull(name);
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.has(name);
}
});
}
@Override
public boolean hasSlot(final int slot) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.has(slot);
}
});
}
@Override
public void removeMember(final String name) {
remove(Objects.requireNonNull(name));
}
@Override
public void setMember(final String name, final Object value) {
put(Objects.requireNonNull(name), value);
}
@Override
public void setSlot(final int index, final Object value) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.set(index, unwrap(value, global), getCallSiteFlags());
return null;
}
});
}
/**
* Nashorn extension: setIndexedPropertiesToExternalArrayData.
* set indexed properties be exposed from a given nio ByteBuffer.
*
* @param buf external buffer - should be a nio ByteBuffer
*/
public void setIndexedPropertiesToExternalArrayData(final ByteBuffer buf) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.setArray(ArrayData.allocate(buf));
return null;
}
});
}
@Override
public boolean isInstance(final Object instance) {
if (! (instance instanceof ScriptObjectMirror)) {
return false;
}
final ScriptObjectMirror mirror = (ScriptObjectMirror)instance;
// if not belongs to my global scope, return false
if (global != mirror.global) {
return false;
}
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isInstance(mirror.sobj);
}
});
}
@Override
public String getClassName() {
return sobj.getClassName();
}
@Override
public boolean isFunction() {
return sobj instanceof ScriptFunction;
}
@Override
public boolean isStrictFunction() {
return isFunction() && ((ScriptFunction)sobj).isStrict();
}
@Override
public boolean isArray() {
return sobj.isArray();
}
// javax.script.Bindings methods
@Override
public void clear() {
inGlobal(new Callable<Object>() {
@Override public Object call() {
sobj.clear(strict);
return null;
}
});
}
@Override
public boolean containsKey(final Object key) {
checkKey(key);
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.containsKey(key);
}
});
}
@Override
public boolean containsValue(final Object value) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.containsValue(unwrap(value, global));
}
});
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return inGlobal(new Callable<Set<Map.Entry<String, Object>>>() {
@Override public Set<Map.Entry<String, Object>> call() {
final Iterator<String> iter = sobj.propertyIterator();
final Set<Map.Entry<String, Object>> entries = new LinkedHashSet<>();
while (iter.hasNext()) {
final String key = iter.next();
final Object value = translateUndefined(wrapLikeMe(sobj.get(key)));
entries.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
}
return Collections.unmodifiableSet(entries);
}
});
}
@Override
public Object get(final Object key) {
checkKey(key);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return translateUndefined(wrapLikeMe(sobj.get(key)));
}
});
}
@Override
public boolean isEmpty() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isEmpty();
}
});
}
@Override
public Set<String> keySet() {
return inGlobal(new Callable<Set<String>>() {
@Override public Set<String> call() {
final Iterator<String> iter = sobj.propertyIterator();
final Set<String> keySet = new LinkedHashSet<>();
while (iter.hasNext()) {
keySet.add(iter.next());
}
return Collections.unmodifiableSet(keySet);
}
});
}
@Override
public Object put(final String key, final Object value) {
checkKey(key);
final ScriptObject oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value;
return translateUndefined(wrapLikeMe(sobj.put(key, unwrap(modValue, global), strict)));
}
});
}
@Override
public void putAll(final Map<? extends String, ? extends Object> map) {
Objects.requireNonNull(map);
final ScriptObject oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
inGlobal(new Callable<Object>() {
@Override public Object call() {
for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
final Object value = entry.getValue();
final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value;
final String key = entry.getKey();
checkKey(key);
sobj.set(key, unwrap(modValue, global), getCallSiteFlags());
}
return null;
}
});
}
@Override
public Object remove(final Object key) {
checkKey(key);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return translateUndefined(wrapLikeMe(sobj.remove(key, strict)));
}
});
}
/**
* Delete a property from this object.
*
* @param key the property to be deleted
*
* @return if the delete was successful or not
*/
public boolean delete(final Object key) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.delete(unwrap(key, global), strict);
}
});
}
@Override
public int size() {
return inGlobal(new Callable<Integer>() {
@Override public Integer call() {
return sobj.size();
}
});
}
@Override
public Collection<Object> values() {
return inGlobal(new Callable<Collection<Object>>() {
@Override public Collection<Object> call() {
final List<Object> values = new ArrayList<>(size());
final Iterator<Object> iter = sobj.valueIterator();
while (iter.hasNext()) {
values.add(translateUndefined(wrapLikeMe(iter.next())));
}
return Collections.unmodifiableList(values);
}
});
}
// Support for ECMAScript Object API on mirrors
/**
* Return the __proto__ of this object.
* @return __proto__ object.
*/
public Object getProto() {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.getProto());
}
});
}
/**
* Set the __proto__ of this object.
* @param proto new proto for this object
*/
public void setProto(final Object proto) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.setPrototypeOf(unwrap(proto, global));
return null;
}
});
}
/**
* ECMA 8.12.1 [[GetOwnProperty]] (P)
*
* @param key property key
*
* @return Returns the Property Descriptor of the named own property of this
* object, or undefined if absent.
*/
public Object getOwnPropertyDescriptor(final String key) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.getOwnPropertyDescriptor(key));
}
});
}
/**
* return an array of own property keys associated with the object.
*
* @param all True if to include non-enumerable keys.
* @return Array of keys.
*/
public String[] getOwnKeys(final boolean all) {
return inGlobal(new Callable<String[]>() {
@Override public String[] call() {
return sobj.getOwnKeys(all);
}
});
}
/**
* Flag this script object as non extensible
*
* @return the object after being made non extensible
*/
public ScriptObjectMirror preventExtensions() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.preventExtensions();
return ScriptObjectMirror.this;
}
});
}
/**
* Check if this script object is extensible
* @return true if extensible
*/
public boolean isExtensible() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isExtensible();
}
});
}
/**
* ECMAScript 15.2.3.8 - seal implementation
* @return the sealed script object
*/
public ScriptObjectMirror seal() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.seal();
return ScriptObjectMirror.this;
}
});
}
/**
* Check whether this script object is sealed
* @return true if sealed
*/
public boolean isSealed() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isSealed();
}
});
}
/**
* ECMA 15.2.39 - freeze implementation. Freeze this script object
* @return the frozen script object
*/
public ScriptObjectMirror freeze() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.freeze();
return ScriptObjectMirror.this;
}
});
}
/**
* Check whether this script object is frozen
* @return true if frozen
*/
public boolean isFrozen() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isFrozen();
}
});
}
/**
* Utility to check if given object is ECMAScript undefined value
*
* @param obj object to check
* @return true if 'obj' is ECMAScript undefined value
*/
public static boolean isUndefined(final Object obj) {
return obj == ScriptRuntime.UNDEFINED;
}
/**
* Utility to convert this script object to the given type.
*
* @param <T> destination type to convert to
* @param type destination type to convert to
* @return converted object
*/
public <T> T to(final Class<T> type) {
return inGlobal(new Callable<T>() {
@Override
public T call() {
return type.cast(ScriptUtils.convert(sobj, type));
}
});
}
/**
* Make a script object mirror on given object if needed.
*
* @param obj object to be wrapped/converted
* @param homeGlobal global to which this object belongs.
* @return wrapped/converted object
*/
public static Object wrap(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, false);
}
/**
* Make a script object mirror on given object if needed. The created wrapper will implement
* the Java {@code List} interface if {@code obj} is a JavaScript {@code Array} object;
* this is compatible with Java JSON libraries expectations. Arrays retrieved through its
* properties (transitively) will also implement the list interface.
*
* @param obj object to be wrapped/converted
* @param homeGlobal global to which this object belongs.
* @return wrapped/converted object
*/
public static Object wrapAsJSONCompatible(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, true);
}
/**
* Make a script object mirror on given object if needed.
*
* @param obj object to be wrapped/converted
* @param homeGlobal global to which this object belongs.
* @param jsonCompatible if true, the created wrapper will implement the Java {@code List} interface if
* {@code obj} is a JavaScript {@code Array} object. Arrays retrieved through its properties (transitively)
* will also implement the list interface.
* @return wrapped/converted object
*/
private static Object wrap(final Object obj, final Object homeGlobal, final boolean jsonCompatible) {
if(obj instanceof ScriptObject) {
if (!(homeGlobal instanceof Global)) {
return obj;
}
final ScriptObject sobj = (ScriptObject)obj;
final Global global = (Global)homeGlobal;
final ScriptObjectMirror mirror = new ScriptObjectMirror(sobj, global, jsonCompatible);
if (jsonCompatible && sobj.isArray()) {
return new JSONListAdapter(mirror, global);
}
return mirror;
} else if(obj instanceof ConsString) {
return obj.toString();
} else if (jsonCompatible && obj instanceof ScriptObjectMirror) {
// Since choosing JSON compatible representation is an explicit decision on user's part, if we're asked to
// wrap a mirror that was not JSON compatible, explicitly create its compatible counterpart following the
// principle of least surprise.
return ((ScriptObjectMirror)obj).asJSONCompatible();
}
return obj;
}
/**
* Wraps the passed object with the same jsonCompatible flag as this mirror.
* @param obj the object
* @param homeGlobal the object's home global.
* @return a wrapper for the object.
*/
private Object wrapLikeMe(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, jsonCompatible);
}
/**
* Wraps the passed object with the same home global and jsonCompatible flag as this mirror.
* @param obj the object
* @return a wrapper for the object.
*/
private Object wrapLikeMe(final Object obj) {
return wrapLikeMe(obj, global);
}
/**
* Unwrap a script object mirror if needed.
*
* @param obj object to be unwrapped
* @param homeGlobal global to which this object belongs
* @return unwrapped object
*/
public static Object unwrap(final Object obj, final Object homeGlobal) {
if (obj instanceof ScriptObjectMirror) {
final ScriptObjectMirror mirror = (ScriptObjectMirror)obj;
return (mirror.global == homeGlobal)? mirror.sobj : obj;
} else if (obj instanceof JSONListAdapter) {
return ((JSONListAdapter)obj).unwrap(homeGlobal);
}
return obj;
}
/**
* Wrap an array of object to script object mirrors if needed.
*
* @param args array to be unwrapped
* @param homeGlobal global to which this object belongs
* @return wrapped array
*/
public static Object[] wrapArray(final Object[] args, final Object homeGlobal) {
return wrapArray(args, homeGlobal, false);
}
private static Object[] wrapArray(final Object[] args, final Object homeGlobal, final boolean jsonCompatible) {
if (args == null || args.length == 0) {
return args;
}
final Object[] newArgs = new Object[args.length];
int index = 0;
for (final Object obj : args) {
newArgs[index] = wrap(obj, homeGlobal, jsonCompatible);
index++;
}
return newArgs;
}
private Object[] wrapArrayLikeMe(final Object[] args, final Object homeGlobal) {
return wrapArray(args, homeGlobal, jsonCompatible);
}
/**
* Unwrap an array of script object mirrors if needed.
*
* @param args array to be unwrapped
* @param homeGlobal global to which this object belongs
* @return unwrapped array
*/
public static Object[] unwrapArray(final Object[] args, final Object homeGlobal) {
if (args == null || args.length == 0) {
return args;
}
final Object[] newArgs = new Object[args.length];
int index = 0;
for (final Object obj : args) {
newArgs[index] = unwrap(obj, homeGlobal);
index++;
}
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) {
this(sobj, global, false);
}
private ScriptObjectMirror(final ScriptObject sobj, final Global global, final boolean jsonCompatible) {
assert sobj != null : "ScriptObjectMirror on null!";
assert global != null : "home Global is null";
this.sobj = sobj;
this.global = global;
this.strict = global.isStrictContext();
this.jsonCompatible = jsonCompatible;
}
// accessors for script engine
ScriptObject getScriptObject() {
return sobj;
}
Global getHomeGlobal() {
return global;
}
static Object translateUndefined(final Object obj) {
return (obj == ScriptRuntime.UNDEFINED)? null : obj;
}
private int getCallSiteFlags() {
return strict ? NashornCallSiteDescriptor.CALLSITE_STRICT : 0;
}
// internals only below this.
private <V> V inGlobal(final Callable<V> callable) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
if (globalChanged) {
Context.setGlobal(global);
}
try {
return callable.call();
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new AssertionError("Cannot happen", e);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
/**
* Ensures the key is not null, empty string, or a non-String object. The contract of the {@link Bindings}
* interface requires that these are not accepted as keys.
* @param key the key to check
* @throws NullPointerException if key is null
* @throws ClassCastException if key is not a String
* @throws IllegalArgumentException if key is empty string
*/
private static void checkKey(final Object key) {
Objects.requireNonNull(key, "key can not be null");
if (!(key instanceof String)) {
throw new ClassCastException("key should be a String. It is " + key.getClass().getName() + " instead.");
} else if (((String)key).length() == 0) {
throw new IllegalArgumentException("key can not be empty");
}
}
@Override @Deprecated
public double toNumber() {
return inGlobal(new Callable<Double>() {
@Override public Double call() {
return JSType.toNumber(sobj);
}
});
}
@Override
public Object getDefaultValue(final Class<?> hint) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
try {
return sobj.getDefaultValue(hint);
} catch (final ECMAException e) {
// We're catching ECMAException (likely TypeError), and translating it to
// UnsupportedOperationException. This in turn will be translated into TypeError of the
// caller's Global by JSType#toPrimitive(JSObject,Class) therefore ensuring that it's
// recognized as "instanceof TypeError" in the caller.
throw new UnsupportedOperationException(e.getMessage(), e);
}
}
});
}
private ScriptObjectMirror asJSONCompatible() {
if (this.jsonCompatible) {
return this;
}
return new ScriptObjectMirror(sobj, global, true);
}
}

View file

@ -1,192 +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.api.scripting;
import java.lang.invoke.MethodHandle;
import jdk.dynalink.beans.StaticClass;
import jdk.dynalink.linker.LinkerServices;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
/**
* Utilities that are to be called from script code.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
public final class ScriptUtils {
private ScriptUtils() {}
/**
* Returns AST as JSON compatible string. This is used to
* implement "parse" function in resources/parse.js script.
*
* @param code code to be parsed
* @param name name of the code source (used for location)
* @param includeLoc tells whether to include location information for nodes or not
* @return JSON string representation of AST of the supplied code
*/
public static String parse(final String code, final String name, final boolean includeLoc) {
return ScriptRuntime.parse(code, name, includeLoc);
}
/**
* Method which converts javascript types to java types for the
* String.format method (jrunscript function sprintf).
*
* @param format a format string
* @param args arguments referenced by the format specifiers in format
* @return a formatted string
*/
public static String format(final String format, final Object[] args) {
return Formatter.format(format, args);
}
/**
* Create a wrapper function that calls {@code func} synchronized on {@code sync} or, if that is undefined,
* {@code self}. Used to implement "sync" function in resources/mozilla_compat.js.
*
* @param func the function to wrap
* @param sync the object to synchronize on
* @return a synchronizing wrapper function
* @throws IllegalArgumentException if func does not represent a script function
*/
public static Object makeSynchronizedFunction(final Object func, final Object sync) {
final Object unwrapped = unwrap(func);
if (unwrapped instanceof ScriptFunction) {
return ((ScriptFunction)unwrapped).createSynchronized(unwrap(sync));
}
throw new IllegalArgumentException();
}
/**
* Make a script object mirror on given object if needed.
*
* @param obj object to be wrapped
* @return wrapped object
* @throws IllegalArgumentException if obj cannot be wrapped
*/
public static ScriptObjectMirror wrap(final Object obj) {
if (obj instanceof ScriptObjectMirror) {
return (ScriptObjectMirror)obj;
}
if (obj instanceof ScriptObject) {
final ScriptObject sobj = (ScriptObject)obj;
return (ScriptObjectMirror) ScriptObjectMirror.wrap(sobj, Context.getGlobal());
}
throw new IllegalArgumentException();
}
/**
* Unwrap a script object mirror if needed.
*
* @param obj object to be unwrapped
* @return unwrapped object
*/
public static Object unwrap(final Object obj) {
if (obj instanceof ScriptObjectMirror) {
return ScriptObjectMirror.unwrap(obj, Context.getGlobal());
}
return obj;
}
/**
* Wrap an array of object to script object mirrors if needed.
*
* @param args array to be unwrapped
* @return wrapped array
*/
public static Object[] wrapArray(final Object[] args) {
if (args == null || args.length == 0) {
return args;
}
return ScriptObjectMirror.wrapArray(args, Context.getGlobal());
}
/**
* Unwrap an array of script object mirrors if needed.
*
* @param args array to be unwrapped
* @return unwrapped array
*/
public static Object[] unwrapArray(final Object[] args) {
if (args == null || args.length == 0) {
return args;
}
return ScriptObjectMirror.unwrapArray(args, Context.getGlobal());
}
/**
* Convert the given object to the given type.
*
* @param obj object to be converted
* @param type destination type to convert to. type is either a Class
* or nashorn representation of a Java type returned by Java.type() call in script.
* @return converted object
*/
public static Object convert(final Object obj, final Object type) {
if (obj == null) {
return null;
}
final Class<?> clazz;
if (type instanceof Class) {
clazz = (Class<?>)type;
} else if (type instanceof StaticClass) {
clazz = ((StaticClass)type).getRepresentedClass();
} else {
throw new IllegalArgumentException("type expected");
}
final LinkerServices linker = Bootstrap.getLinkerServices();
final Object objToConvert = unwrap(obj);
final MethodHandle converter = linker.getTypeConverter(objToConvert.getClass(), clazz);
if (converter == null) {
// no supported conversion!
throw new UnsupportedOperationException("conversion not supported");
}
try {
return converter.invoke(objToConvert);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
}
}
}

View file

@ -1,125 +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.api.scripting;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Objects;
import jdk.nashorn.internal.runtime.Source;
/**
* A Reader that reads from a URL. Used to make sure that the reader
* reads content from given URL and can be trusted to do so.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 1.8u40
*/
@Deprecated(since="11", forRemoval=true)
public final class URLReader extends Reader {
// underlying URL
private final URL url;
// Charset used to convert
private final Charset cs;
// lazily initialized underlying reader for URL
private Reader reader;
/**
* Constructor
*
* @param url URL for this URLReader
* @throws NullPointerException if url is null
*/
public URLReader(final URL url) {
this(url, (Charset)null);
}
/**
* Constructor
*
* @param url URL for this URLReader
* @param charsetName Name of the Charset used to convert bytes to chars
* @throws NullPointerException if url is null
*/
public URLReader(final URL url, final String charsetName) {
this(url, Charset.forName(charsetName));
}
/**
* Constructor
*
* @param url URL for this URLReader
* @param cs Charset used to convert bytes to chars
* @throws NullPointerException if url is null
*/
public URLReader(final URL url, final Charset cs) {
this.url = Objects.requireNonNull(url);
this.cs = cs;
}
@Override
public int read(final char cbuf[], final int off, final int len) throws IOException {
return getReader().read(cbuf, off, len);
}
@Override
public void close() throws IOException {
getReader().close();
}
/**
* URL of this reader
* @return the URL from which this reader reads.
*/
public URL getURL() {
return url;
}
/**
* Charset used by this reader
*
* @return the Charset used to convert bytes to chars
*/
public Charset getCharset() {
return cs;
}
// lazily initialize char array reader using URL content
private Reader getReader() throws IOException {
synchronized (lock) {
if (reader == null) {
reader = new CharArrayReader(Source.readFully(url, cs));
}
}
return reader;
}
}

View file

@ -1,41 +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.
*/
/**
* This package provides the {@code javax.script} integration, which is the preferred way to use Nashorn.
* You will ordinarily do this to obtain an instance of a Nashorn script engine:
* <pre>
* import javax.script.*;
* ...
* ScriptEngine nashornEngine = new ScriptEngineManager().getEngineByName("Nashorn");
* </pre>
* <p>Nashorn script engines implement the optional {@link javax.script.Invocable} and {@link javax.script.Compilable}
* interfaces, allowing for efficient pre-compilation and repeated execution of scripts. In addition,
* this package provides nashorn specific extension classes, interfaces and methods. See
* {@link jdk.nashorn.api.scripting.NashornScriptEngineFactory} for further details.
*
* @since 1.8u40
*/
package jdk.nashorn.api.scripting;

View file

@ -1,32 +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.
#
thiz.cannot.be.null=script object 'this' for getMethod, getInterface calls can not be null
interface.class.expected=interface Class expected in getInterface
interface.on.non.script.object=getInterface cannot be called on non-script object
no.current.nashorn.global=no current Global instance for nashorn
implementing.non.public.interface=Cannot implement non-public interface: {0}
script.object.from.another.engine=Script object belongs to another script engine

View file

@ -1,56 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
/**
* A tree node for an array access expression.
*
* For example:
* <pre>
* <em>expression</em> [ <em>index</em> ]
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface ArrayAccessTree extends ExpressionTree {
/**
* Returns the array that is accessed.
*
* @return the array that is accessed
*/
ExpressionTree getExpression();
/**
* Returns the index of the array element accessed.
*
* @return the index expression
*/
ExpressionTree getIndex();
}

View file

@ -1,59 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import jdk.nashorn.internal.ir.Expression;
final class ArrayAccessTreeImpl extends ExpressionTreeImpl implements ArrayAccessTree {
private final ExpressionTree base, index;
ArrayAccessTreeImpl(final Expression node, final ExpressionTree base, final ExpressionTree index) {
super(node);
this.base = base;
this.index = index;
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.ARRAY_ACCESS;
}
@Override
public ExpressionTree getExpression() {
return base;
}
@Override
public ExpressionTree getIndex() {
return index;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitArrayAccess(this, data);
}
}

View file

@ -1,46 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import java.util.List;
/**
* Represents ECMAScript array literal expression.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface ArrayLiteralTree extends ExpressionTree {
/**
* Returns the list of Array element expressions.
*
* @return array element expressions
*/
public List<? extends ExpressionTree> getElements();
}

View file

@ -1,53 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import java.util.List;
import jdk.nashorn.internal.ir.LiteralNode;
final class ArrayLiteralTreeImpl extends ExpressionTreeImpl
implements ArrayLiteralTree {
private final List<? extends ExpressionTree> elements;
ArrayLiteralTreeImpl(final LiteralNode<?> node, final List<? extends ExpressionTree> elements) {
super(node);
this.elements = elements;
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.ARRAY_LITERAL;
}
@Override
public List<? extends ExpressionTree> getElements() {
return elements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitArrayLiteral(this, data);
}
}

View file

@ -1,56 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
/**
* A tree node for an assignment expression.
*
* For example:
* <pre>
* <em>variable</em> = <em>expression</em>
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface AssignmentTree extends ExpressionTree {
/**
* Returns the left hand side (LHS) of this assignment.
*
* @return left hand side (LHS) expression
*/
ExpressionTree getVariable();
/**
* Returns the right hand side (RHS) of this assignment.
*
* @return right hand side (RHS) expression
*/
ExpressionTree getExpression();
}

View file

@ -1,61 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import jdk.nashorn.internal.ir.BinaryNode;
final class AssignmentTreeImpl extends ExpressionTreeImpl implements AssignmentTree {
private final Tree.Kind kind;
private final ExpressionTree var, expr;
AssignmentTreeImpl(final BinaryNode node, final ExpressionTree left, final ExpressionTree right) {
super(node);
assert node.isAssignment() : "assignment node expected";
this.var = left;
this.expr = right;
this.kind = getOperator(node.tokenType());
}
@Override
public Tree.Kind getKind() {
return kind;
}
@Override
public ExpressionTree getVariable() {
return var;
}
@Override
public ExpressionTree getExpression() {
return expr;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitAssignment(this, data);
}
}

View file

@ -1,57 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
/**
* A tree node for a binary expression.
* Use {@link #getKind getKind} to determine the kind of operator.
*
* For example:
* <pre>
* <em>leftOperand</em> <em>operator</em> <em>rightOperand</em>
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface BinaryTree extends ExpressionTree {
/**
* Returns left hand side (LHS) of this binary expression.
*
* @return left hand side (LHS) of this binary expression
*/
ExpressionTree getLeftOperand();
/**
* Returns right hand side (RHS) of this binary expression.
*
* @return right hand side (RHS) of this binary expression
*/
ExpressionTree getRightOperand();
}

View file

@ -1,61 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import jdk.nashorn.internal.ir.BinaryNode;
class BinaryTreeImpl extends ExpressionTreeImpl implements BinaryTree {
private final Tree.Kind kind;
private final ExpressionTree left, right;
BinaryTreeImpl(final BinaryNode node, final ExpressionTree left, final ExpressionTree right) {
super(node);
assert !node.isAssignment() : "assignment node";
this.left = left;
this.right = right;
this.kind = getOperator(node.tokenType());
}
@Override
public Tree.Kind getKind() {
return kind;
}
@Override
public ExpressionTree getLeftOperand() {
return left;
}
@Override
public ExpressionTree getRightOperand() {
return right;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitBinary(this, data);
}
}

View file

@ -1,53 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import java.util.List;
/**
* A tree node for a statement block.
*
* For example:
* <pre>
* { }
*
* { <em>statements</em> }
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface BlockTree extends StatementTree {
/**
* Returns the list of statements in this block.
*
* @return the list of statements in this block
*/
List<? extends StatementTree> getStatements();
}

View file

@ -1,59 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import java.util.List;
import jdk.nashorn.internal.ir.Block;
import jdk.nashorn.internal.ir.BlockStatement;
final class BlockTreeImpl extends StatementTreeImpl implements BlockTree {
private final List<? extends StatementTree> statements;
BlockTreeImpl(final BlockStatement node, final List<? extends StatementTree> statements) {
super(node);
this.statements = statements;
}
BlockTreeImpl(final Block node, final List<? extends StatementTree> statements) {
super(node);
this.statements = statements;
}
@Override
public Kind getKind() {
return Kind.BLOCK;
}
@Override
public List<? extends StatementTree> getStatements() {
return statements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitBlock(this, data);
}
}

View file

@ -1,53 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
/**
* A tree node for a 'break' statement.
*
* For example:
* <pre>
* break;
*
* break <em>label</em> ;
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface BreakTree extends GotoTree {
/**
* Label associated with this break statement. This is null
* if there is no label associated with this break statement.
*
* @return label associated with this break statement.
*/
@Override
String getLabel();
}

View file

@ -1,52 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import jdk.nashorn.internal.ir.BreakNode;
final class BreakTreeImpl extends StatementTreeImpl implements BreakTree {
private final String label;
BreakTreeImpl(final BreakNode node) {
super(node);
this.label = node.getLabelName();
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.BREAK;
}
@Override
public String getLabel() {
return label;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitBreak(this, data);
}
}

View file

@ -1,62 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import java.util.List;
/**
* A tree node for a 'case' in a 'switch' statement.
*
* For example:
* <pre>
* case <em>expression</em> :
* <em>statements</em>
*
* default :
* <em>statements</em>
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface CaseTree extends Tree {
/**
* Case expression of this 'case' statement.
*
* @return null if and only if this Case is {@code default:}
*/
ExpressionTree getExpression();
/**
* Return the list of statements for this 'case'.
*
* @return list of statements for this 'case'
*/
List<? extends StatementTree> getStatements();
}

View file

@ -1,62 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import java.util.List;
import jdk.nashorn.internal.ir.CaseNode;
final class CaseTreeImpl extends TreeImpl implements CaseTree {
private final ExpressionTree expression;
private final List<? extends StatementTree> statements;
public CaseTreeImpl(final CaseNode node,
final ExpressionTree expression,
final List<? extends StatementTree> statements) {
super(node);
this.expression = expression;
this.statements = statements;
}
@Override
public Kind getKind() {
return Kind.CASE;
}
@Override
public ExpressionTree getExpression() {
return expression;
}
@Override
public List<? extends StatementTree> getStatements() {
return statements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitCase(this, data);
}
}

View file

@ -1,65 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
/**
* A tree node for a 'catch' block in a 'try' statement.
*
* For example:
* <pre>
* catch ( <em>parameter</em> )
* <em>block</em>
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface CatchTree extends Tree {
/**
* Returns the catch parameter identifier or parameter binding pattern of the exception caught.
*
* @return the catch parameter identifier or parameter binding pattern
*/
ExpressionTree getParameter();
/**
* Returns the code block of this catch block.
*
* @return the code block
*/
BlockTree getBlock();
/**
* Returns the optional catch condition expression. This is null
* if this is an unconditional catch statement.
*
* @return the optional catch condition expression.
*/
ExpressionTree getCondition();
}

View file

@ -1,69 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import jdk.nashorn.internal.ir.CatchNode;
final class CatchTreeImpl extends TreeImpl implements CatchTree {
private final ExpressionTree param;
private final BlockTree block;
private final ExpressionTree condition;
CatchTreeImpl(final CatchNode node,
final ExpressionTree param,
final BlockTree block,
final ExpressionTree condition) {
super(node);
this.param = param;
this.block = block;
this.condition = condition;
}
@Override
public Kind getKind() {
return Kind.CATCH;
}
@Override
public ExpressionTree getParameter() {
return param;
}
@Override
public BlockTree getBlock() {
return block;
}
@Override
public ExpressionTree getCondition() {
return condition;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitCatch(this, data);
}
}

View file

@ -1,67 +0,0 @@
/*
* Copyright (c) 2016, 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.tree;
import java.util.List;
/**
* A tree node that represents a <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-class-definitions">class declaration</a>.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface ClassDeclarationTree extends StatementTree {
/**
* Class identifier.
*
* @return the class identifier
*/
IdentifierTree getName();
/**
* The expression of the {@code extends} clause. Optional.
*
* @return the class heritage
*/
ExpressionTree getClassHeritage();
/**
* Get the constructor method definition.
*
* @return the constructor
*/
PropertyTree getConstructor();
/**
* Get other property definitions except for the constructor.
*
* @return the class elements
*/
List<? extends PropertyTree> getClassElements();
}

View file

@ -1,77 +0,0 @@
/*
* Copyright (c) 2016, 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.tree;
import java.util.List;
import jdk.nashorn.internal.ir.VarNode;
final class ClassDeclarationTreeImpl extends StatementTreeImpl implements ClassDeclarationTree {
private final IdentifierTree name;
private final ExpressionTree classHeritage;
private final PropertyTree constructor;
private final List<? extends PropertyTree> classElements;
ClassDeclarationTreeImpl(final VarNode node, final IdentifierTree name,
final ExpressionTree classHeritage, final PropertyTree constructor,
final List<? extends PropertyTree> classElements) {
super(node);
this.name = name;
this.classHeritage = classHeritage;
this.constructor = constructor;
this.classElements = classElements;
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.CLASS;
}
@Override
public IdentifierTree getName() {
return name;
}
@Override
public ExpressionTree getClassHeritage() {
return classHeritage;
}
@Override
public PropertyTree getConstructor() {
return constructor;
}
@Override
public List<? extends PropertyTree> getClassElements() {
return classElements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitClassDeclaration(this, data);
}
}

View file

@ -1,67 +0,0 @@
/*
* Copyright (c) 2016, 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.tree;
import java.util.List;
/**
* A tree node that represents a <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-class-definitions">class expression</a>.
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface ClassExpressionTree extends ExpressionTree {
/**
* Class identifier. Optional.
*
* @return the class identifier
*/
IdentifierTree getName();
/**
* The expression of the {@code extends} clause. Optional.
*
* @return the class heritage
*/
ExpressionTree getClassHeritage();
/**
* Get the constructor method definition.
*
* @return the constructor
*/
PropertyTree getConstructor();
/**
* Get other property definitions except for the constructor.
*
* @return the class elements
*/
List<? extends PropertyTree> getClassElements();
}

View file

@ -1,76 +0,0 @@
/*
* Copyright (c) 2016, 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.tree;
import java.util.List;
import jdk.nashorn.internal.ir.ClassNode;
final class ClassExpressionTreeImpl extends ExpressionTreeImpl implements ClassExpressionTree {
private final IdentifierTree name;
private final ExpressionTree classHeritage;
private final PropertyTree constructor;
private final List<? extends PropertyTree> classElements;
ClassExpressionTreeImpl(final ClassNode cn, final IdentifierTree name,
final ExpressionTree classHeritage, final PropertyTree constructor,
final List<? extends PropertyTree> classElements) {
super(cn);
this.name = name;
this.classHeritage = classHeritage;
this.constructor = constructor;
this.classElements = classElements;
}
@Override
public Kind getKind() {
return Kind.CLASS_EXPRESSION;
}
@Override
public IdentifierTree getName() {
return name;
}
@Override
public ExpressionTree getClassHeritage() {
return classHeritage;
}
@Override
public PropertyTree getConstructor() {
return constructor;
}
@Override
public List<? extends PropertyTree> getClassElements() {
return classElements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitClassExpression(this, data);
}
}

View file

@ -1,77 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import java.util.List;
/**
* Represents the abstract syntax tree for compilation units (source
* files)
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface CompilationUnitTree extends Tree {
/**
* Return the list of source elements in this compilation unit.
*
* @return the list of source elements in this compilation unit
*/
List<? extends Tree> getSourceElements();
/**
* Return the source name of this script compilation unit.
*
* @return the source name of this script compilation unit
*/
String getSourceName();
/**
* Returns if this is a ECMAScript "strict" compilation unit or not.
*
* @return true if this compilation unit is declared "strict"
*/
boolean isStrict();
/**
* Returns the line map for this compilation unit, if available.
* Returns null if the line map is not available.
*
* @return the line map for this compilation unit
*/
LineMap getLineMap();
/**
* Return the {@link ModuleTree} associated with this compilation unit. This is null,
* if there is no module information from this compilation unit.
*
* @return the Module info or null
*/
ModuleTree getModule();
}

View file

@ -1,83 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import java.util.List;
import jdk.nashorn.internal.ir.FunctionNode;
final class CompilationUnitTreeImpl extends TreeImpl
implements CompilationUnitTree {
private final FunctionNode funcNode;
private final List<? extends Tree> elements;
private final ModuleTree module;
CompilationUnitTreeImpl(final FunctionNode node,
final List<? extends Tree> elements,
final ModuleTree module) {
super(node);
this.funcNode = node;
assert funcNode.getKind() == FunctionNode.Kind.SCRIPT ||
funcNode.getKind() == FunctionNode.Kind.MODULE :
"script or module function expected";
this.elements = elements;
this.module = module;
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.COMPILATION_UNIT;
}
@Override
public List<? extends Tree> getSourceElements() {
return elements;
}
@Override
public String getSourceName() {
return funcNode.getSourceName();
}
@Override
public boolean isStrict() {
return funcNode.isStrict();
}
@Override
public LineMap getLineMap() {
return new LineMapImpl(funcNode.getSource());
}
@Override
public ModuleTree getModule() {
return module;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitCompilationUnit(this, data);
}
}

View file

@ -1,57 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
/**
* A tree node for compound assignment operator.
* Use {@link #getKind getKind} to determine the kind of operator.
*
* For example:
* <pre>
* <em>variable</em> <em>operator</em> <em>expression</em>
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface CompoundAssignmentTree extends ExpressionTree {
/**
* Returns the left hand side (LHS) of this assignment.
*
* @return left hand side (LHS) expression
*/
ExpressionTree getVariable();
/**
* Returns the right hand side (RHS) of this assignment.
*
* @return right hand side (RHS) expression
*/
ExpressionTree getExpression();
}

View file

@ -1,63 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import jdk.nashorn.internal.ir.BinaryNode;
final class CompoundAssignmentTreeImpl extends ExpressionTreeImpl implements CompoundAssignmentTree {
private final ExpressionTree var, expr;
private final Kind kind;
CompoundAssignmentTreeImpl(final BinaryNode node, final ExpressionTree left, final ExpressionTree right) {
super(node);
assert node.isAssignment() : "not an assignment node";
this.var = left;
this.expr = right;
this.kind = getOperator(node.tokenType());
assert kind != Tree.Kind.ASSIGNMENT : "compound assignment expected";
}
@Override
public Kind getKind() {
return kind;
}
@Override
public ExpressionTree getVariable() {
return var;
}
@Override
public ExpressionTree getExpression() {
return expr;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitCompoundAssignment(this, data);
}
}

View file

@ -1,63 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
/**
* A tree node for the conditional operator ? :.
*
* For example:
* <pre>
* <em>condition</em> ? <em>trueExpression</em> : <em>falseExpression</em>
* </pre>
*
* @deprecated Nashorn JavaScript script engine and APIs, and the jjs tool
* are deprecated with the intent to remove them in a future release.
*
* @since 9
*/
@Deprecated(since="11", forRemoval=true)
public interface ConditionalExpressionTree extends ExpressionTree {
/**
* Returns the condition expression of this ternary expression.
*
* @return the condition expression
*/
ExpressionTree getCondition();
/**
* Returns the true part of this ternary expression.
*
* @return the 'true' part expression
*/
ExpressionTree getTrueExpression();
/**
* Returns the false part of this ternary expression.
*
* @return the 'false' part expression
*/
ExpressionTree getFalseExpression();
}

View file

@ -1,67 +0,0 @@
/*
* Copyright (c) 2015, 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.tree;
import jdk.nashorn.internal.ir.TernaryNode;
final class ConditionalExpressionTreeImpl extends ExpressionTreeImpl implements ConditionalExpressionTree {
private final ExpressionTree condExpr, trueExpr, falseExpr;
ConditionalExpressionTreeImpl(final TernaryNode node,
final ExpressionTree condExpr, final ExpressionTree trueExpr,
final ExpressionTree falseExpr) {
super(node);
this.condExpr = condExpr;
this.trueExpr = trueExpr;
this.falseExpr = falseExpr;
}
@Override
public Kind getKind() {
return Kind.CONDITIONAL_EXPRESSION;
}
@Override
public ExpressionTree getCondition() {
return condExpr;
}
@Override
public ExpressionTree getTrueExpression() {
return trueExpr;
}
@Override
public ExpressionTree getFalseExpression() {
return falseExpr;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitConditionalExpression(this, data);
}
}

Some files were not shown because too many files have changed in this diff Show more