Compare commits

..

2 Commits

Author SHA1 Message Date
igor%mir2.org
96154ba631 cosmetics: end-of-line whitespace removal again
git-svn-id: svn://10.0.0.236/branches/less_static@115249 18797224-902f-48f8-a5cc-f745e15eee43
2002-02-22 23:28:28 +00:00
(no author)
771cbc6bfd This commit was manufactured by cvs2svn to create branch 'less_static'.
git-svn-id: svn://10.0.0.236/branches/less_static@113702 18797224-902f-48f8-a5cc-f745e15eee43
2002-02-05 13:47:17 +00:00
189 changed files with 28203 additions and 35829 deletions

222
mozilla/js/rhino/Makefile Normal file
View File

@@ -0,0 +1,222 @@
#! gmake
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is Rhino code, released
# May 6, 1998.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1999 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU Public License (the "GPL"), in which case the
# provisions of the GPL are applicable instead of those above.
# If you wish to allow use of your version of this file only
# under the terms of the GPL and not to allow others to use your
# version of this file under the NPL, indicate your decision by
# deleting the provisions above and replace them with the notice
# and other provisions required by the GPL. If you do not delete
# the provisions above, a recipient may use your version of this
# file under either the NPL or the GPL.
#
# Makefile for javascript in java.
#
# This makefile is intended for packaging releases, and probably isn't
# suitable for production use - it doesn't attempt to do understand
# java dependencies beyond the package level.
#
# The makefiles for the subdirectories included in this package are
# intended to be called by this makefile with the proper CLASSDIR,
# PATH_PREFIX etc. variables. Makefiles in subdirectories are
# actually executed in the toplevel directory, with the PATH_PREFIX
# variable set to the subdirectory where the makefile is located.
#
# Initial version courtesy Mike Ang.
# Next version by Mike McCabe
# Don't include SHELL define (per GNU manual recommendation) because it
# breaks WinNT (with GNU make) builds.
# SHELL = /bin/sh
# Some things we might want to tweek.
CLASSDIR = classes
PACKAGE_NAME = org.mozilla.javascript
PACKAGE_PATH = org/mozilla/javascript
# jar filenames and the directories that build them.
JS_JAR = js.jar
JS_DIR = $(PACKAGE_PATH)
JSTOOLS_JAR = jstools.jar
JSTOOLS_DIR = $(PACKAGE_PATH)/tools
JARS = $(JS_JAR) $(JSTOOLS_JAR)
# It's not polite to store toplevel files in a tarball or zip files.
# What is the name of the toplevel directory to store files in?
# XXX we should probably add versioning to this.
DIST_DIR = jsjava
# XXX test this with sj
# JAVAC = mgcj
JAVAC=javac
# We don't define JFLAGS but we do export it to child
# builds in case it's defined by the environment.
# To build optimized (with javac) say 'make JFLAGS=-O'
GZIP = gzip
ZIP = zip
UNZIP = unzip
# JFLAGS="-O -g:none"
# Shouldn't need to change anything below here.
# For Windows NT builds (under GNU make).
ifeq ($(OS_TARGET), WINNT)
CLASSPATHSEP = '\\;'
else
CLASSPATHSEP = :
endif
# Make compatibility - use these instead of gmake 'export VARIABLE'
EXPORTS = CLASSDIR=$(CLASSDIR) JAVAC=$(JAVAC) JFLAGS=$(JFLAGS) SHELL=$(SHELL) \
PACKAGE_PATH=$(PACKAGE_PATH) PACKAGE_NAME=$(PACKAGE_NAME)
helpmessage : FORCE
@echo 'Targets include:'
@echo ' all - make jars, examples'
@echo ' jars - make js.jar, jstools.jar'
@echo ' fast - quick-and-dirty "make jars", for development'
@echo ' examples - build the .class files in the examples directory'
@echo ' check - perform checks on the source.'
@echo ' clean - remove intermediate files'
@echo ' clobber - make clean, and remove .jar files'
@echo ' zip - make a distribution .zip file'
@echo ' zip-source - make a distribution .zip file, with source'
@echo ' tar - make a distribution .tar.gz file'
@echo ' tar-source - make a distribution .tar.gz, with source'
@echo
@echo 'Define OS_TARGET to "WINNT" to build on Windows NT with GNU make.'
@echo
@echo 'The make-based build system does not include graphical'
@echo 'debugger or Bean Scripting Framework support. To build with'
@echo 'these, use the Ant build tool.'
@echo
@echo 'Ant is available at http://jakarta.apache.org/ant/'
all : jars examples
jars : $(JARS)
fast : fast_$(JS_JAR) $(JSTOOLS_JAR)
# Always call the sub-Makefile - which may decide that the jar is up to date.
$(JS_JAR) : FORCE
$(MAKE) -f $(JS_DIR)/Makefile JAR=$(@) $(EXPORTS) \
PATH_PREFIX=$(JS_DIR) \
CLASSPATH=.
fast_$(JS_JAR) :
$(MAKE) -f $(JS_DIR)/Makefile JAR=$(JS_JAR) $(EXPORTS) \
PATH_PREFIX=$(JS_DIR) \
CLASSPATH=. \
fast
$(JSTOOLS_JAR) : $(JS_JAR) FORCE
$(MAKE) -f $(JSTOOLS_DIR)/Makefile JAR=$(@) $(EXPORTS) \
PATH_PREFIX=$(JSTOOLS_DIR) \
CLASSPATH=./$(JS_JAR)$(CLASSPATHSEP).
examples : $(JS_JAR) FORCE
$(MAKE) -f examples/Makefile $(EXPORTS) \
PATH_PREFIX=examples \
CLASSPATH=./$(JS_JAR)
# We ask the subdirs to update their MANIFESTs
MANIFEST : FORCE
$(MAKE) -f $(JS_DIR)/Makefile JAR=$(JS_JAR) $(EXPORTS) \
PATH_PREFIX=$(JS_DIR) $(JS_DIR)/MANIFEST
$(MAKE) -f $(JSTOOLS_DIR)/Makefile JAR=$(JSTOOLS_JAR) $(EXPORTS) \
PATH_PREFIX=$(JSTOOLS_DIR) $(JSTOOLS_DIR)/MANIFEST
$(MAKE) -f examples/Makefile $(EXPORTS) \
PATH_PREFIX=examples examples/MANIFEST
# so ls below always has something to work on
touch MANIFEST
# examples/Makefile doesn't get included in the
# MANIFEST file, (which is used to create the non-source distribution) so
# we include it here.
cat examples/MANIFEST $(JS_DIR)/MANIFEST \
$(JSTOOLS_DIR)/MANIFEST \
| xargs ls MANIFEST README.html \
$(JARS) \
Makefile examples/Makefile \
> $(@)
# Make a MANIFEST file containing only the binaries and documentation.
# This could be abstracted further...
MANIFEST_binonly : MANIFEST
cat examples/MANIFEST \
| xargs ls $(JARS) README.html MANIFEST > MANIFEST
# A subroutine - not intended to be called from outside the makefile.
do_zip :
# Make sure we get a fresh one
- rm -r $(DIST_DIR)
- mkdir $(DIST_DIR)
- rm $(DIST_DIR).zip
cat MANIFEST | xargs $(ZIP) -0 -q $(DIST_DIR).zip
mv $(DIST_DIR).zip $(DIST_DIR)
cd $(DIST_DIR) ; \
$(UNZIP) -q $(DIST_DIR).zip ; \
rm $(DIST_DIR).zip
$(ZIP) -r -9 -q $(DIST_DIR).zip $(DIST_DIR)
- rm -r $(DIST_DIR)
zip : check jars examples MANIFEST_binonly do_zip
zip-source : check jars examples MANIFEST do_zip
# A subroutine - not intended to be called from outside the makefile.
do_tar :
- rm -r $(DIST_DIR)
- mkdir $(DIST_DIR)
- rm $(DIST_DIR).tar $(DIST_DIR).tar.gz
cat MANIFEST | xargs tar cf $(DIST_DIR).tar
mv $(DIST_DIR).tar $(DIST_DIR)
cd $(DIST_DIR) ; \
tar xf $(DIST_DIR).tar ; \
rm $(DIST_DIR).tar
tar cf $(DIST_DIR).tar $(DIST_DIR)
- rm -r $(DIST_DIR)
$(GZIP) -9 $(DIST_DIR).tar
tar: check jars examples MANIFEST_binonly do_tar
tar-source : check jars examples MANIFEST do_tar
# These commands just get passed to the respective sub-Makefiles.
clean clobber check:
$(MAKE) -f $(JS_DIR)/Makefile $(EXPORTS) JAR=$(JS_JAR) \
PATH_PREFIX=$(JS_DIR) $(@)
$(MAKE) -f $(JSTOOLS_DIR)/Makefile $(EXPORTS) JAR=$(JSTOOLS_JAR) \
PATH_PREFIX=$(JSTOOLS_DIR) $(@)
$(MAKE) -f examples/Makefile $(EXPORTS) PATH_PREFIX=examples $(@)
#emulate .PHONY
FORCE :

View File

@@ -40,7 +40,7 @@ Rhino: JavaScript in Java<p>
</h1>
<span CLASS=LXRLONGDESC>
Rhino is an implementation of JavaScript in Java. Documentation can be found
<a href="http://www.mozilla.org/rhino/index.html">here</a>.
<a href="http://www.mozilla.org/js/rhino/rhino.html">here</a>.
</span>
</body>
</html>

View File

@@ -1,7 +1,6 @@
apiClasses=\
src/org/mozilla/javascript/ClassCache.java,\
src/org/mozilla/javascript/ClassDefinitionException.java,\
src/org/mozilla/javascript/ClassShutter.java,\
src/org/mozilla/javascript/ClassOutput.java,\
src/org/mozilla/javascript/Context.java,\
src/org/mozilla/javascript/ContextListener.java,\
src/org/mozilla/javascript/EcmaError.java,\
@@ -10,12 +9,13 @@ apiClasses=\
src/org/mozilla/javascript/FunctionObject.java,\
src/org/mozilla/javascript/ImporterTopLevel.java,\
src/org/mozilla/javascript/JavaScriptException.java,\
src/org/mozilla/javascript/NotAFunctionException.java,\
src/org/mozilla/javascript/PropertyException.java,\
src/org/mozilla/javascript/Script.java,\
src/org/mozilla/javascript/Scriptable.java,\
src/org/mozilla/javascript/ScriptableObject.java,\
src/org/mozilla/javascript/SecurityController.java,\
src/org/mozilla/javascript/WrapFactory.java,\
src/org/mozilla/javascript/SecuritySupport.java,\
src/org/mozilla/javascript/WrapHandler.java,\
src/org/mozilla/javascript/Wrapper.java,\
src/org/mozilla/javascript/Synchronizer.java,\
src/org/mozilla/javascript/serialize/ScriptableInputStream.java,\

View File

@@ -1,25 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
<!--
Build file for Rhino using Ant (see http://jakarta.apache.org/ant/index.html)
Requires Ant version 1.2 or later
-->
<project name="Rhino" default="help" basedir=".">
<project name="Rhino" default="default" basedir=".">
<target name="properties">
<property name="name" value="rhino"/>
<property name="Name" value="Rhino"/>
<property name="version" value="1_5R5pre"/>
<property name="version" value="1_5R4pre"/>
<property name="rhino.jar" value="js.jar"/>
<property name="small-rhino.jar" value="smalljs.jar"/>
<property name="jar-compression" value="true"/>
<property name="debug" value="on"/>
<property name="debug" value="off"/>
<property name="src.dir" value="src"/>
<property name="toolsrc.dir" value="toolsrc"/>
<property name="src.examples" value="examples"/>
<property name="build.dir" value="./build"/>
<property name="classes" value="${build.dir}/classes"/>
<property name="build.dest" value="${build.dir}/classes"/>
<property name="dist.name" value="rhino${version}"/>
<property name="dist.dir" value="${build.dir}/${dist.name}"/>
<property name="dist.src" value="${dist.dir}/src"/>
@@ -28,16 +29,18 @@ Requires Ant version 1.2 or later
<property name="dist.docs" value="${dist.dir}/docs"/>
<property name="dist.apidocs" value="${dist.docs}/apidocs"/>
<property name="dist.file" value="rhino${version}.zip"/>
<property name="dist.source-only-zip" value="rhino${version}-sources.zip"/>
<property file="apiClasses.properties"/>
<property name="docsrc.dir" value="docs"/>
<property name="dist.docsrc.dir" value="src/docs"/>
<property name="dist.docsrc.dir" value="${src.dir}/docs"/>
</target>
<target name="init" depends="properties">
</target>
<target name="prepare" depends="init">
<mkdir dir="${build.dir}"/>
<mkdir dir="${classes}"/>
<mkdir dir="${build.dest}"/>
<mkdir dir="${dist.dir}"/>
<mkdir dir="${dist.src}"/>
<mkdir dir="${dist.toolsrc}"/>
@@ -46,78 +49,62 @@ Requires Ant version 1.2 or later
<mkdir dir="${dist.apidocs}"/>
</target>
<target name="compile" depends="init">
<ant dir="src" target="compile"/>
<ant dir="toolsrc" target="compile"/>
<target name="compile-src" depends="prepare">
<ant dir="${src.dir}"/>
</target>
<target name="copy-source" depends="init">
<ant dir="src" target="copy-source"/>
<ant dir="toolsrc" target="copy-source"/>
<copy todir="${dist.dir}" file="build.xml"/>
<copy todir="${dist.dir}" file="apiClasses.properties"/>
<target name="compile-toolsrc" depends="prepare">
<ant dir="${toolsrc.dir}"/>
</target>
<target name="compile" depends="compile-src,compile-toolsrc"/>
<target name="jar" depends="compile">
<jar jarfile="${dist.dir}/${rhino.jar}"
basedir="${classes}"
manifest="src/manifest"
compress="${jar-compression}"
/>
<jar jarfile="${dist.dir}/${rhino.jar}"
basedir="${build.dest}"
manifest="${src.dir}/manifest" />
</target>
<target name="smalljar" depends="compile">
<jar basedir="${classes}" destfile="${dist.dir}/${small-rhino.jar}"
compress="${jar-compression}">
<include name="org/mozilla/javascript/*.class"/>
<exclude name="org/mozilla/javascript/ClassNameHelper*.class"/>
<exclude name="org/mozilla/javascript/ClassRepository*.class"/>
<exclude name="org/mozilla/javascript/JavaAdapter*.class"/>
<exclude name="org/mozilla/javascript/NotAFunctionException*.class"/>
<exclude name="org/mozilla/javascript/Token.class"/>
<include name="org/mozilla/javascript/debug/*.class"/>
<include name="org/mozilla/javascript/resources/*.properties"/>
<include name="org/mozilla/javascript/regexp/*.class"
unless="no-regexp"/>
</jar>
<target name="jar-src" depends="compile-src">
<jar jarfile="${dist.dir}/${rhino.jar}"
basedir="${build.dest}"
manifest="${src.dir}/manifest" />
</target>
<target name="copy-examples" depends="init">
<target name="copy-examples" depends="prepare">
<copy todir="${dist.examples}">
<fileset dir="examples" includes="*.java,*.js,*.html" />
<fileset dir="${src.examples}" includes="*.java,*.js,*.html" />
</copy>
</target>
<target name="copy-misc" depends="init">
<target name="copy-misc" depends="prepare">
<tstamp/>
<filter token="datestamp" value="${TODAY}"/>
<copy todir="${dist.dir}" filtering="yes">
<fileset dir=".">
<patternset>
<include name="build.xml"/>
<include name="apiClasses.properties"/>
<include name="build-date"/>
</patternset>
</fileset>
</copy>
</target>
<target name="copy-all" depends="copy-source,copy-examples,copy-misc">
<target name="copy-all" depends="copy-examples,copy-misc">
</target>
<target name="copy-docs" depends="init">
<target name="copy-docs" depends="prepare">
<echo message="copy from ${docsrc.dir}"/>
<copy todir="${dist.docs}">
<fileset dir="${docsrc.dir}"
<fileset dir="${docsrc.dir}"
includes="**/*.html,**/*.jpg,**/*.gif" />
</copy>
</target>
<target name="javadoc" depends="compile,copy-docs">
<javadoc sourcefiles="${apiClasses}"
sourcepath="src"
sourcepath="${src.dir}"
destdir="${dist.apidocs}"
overview="${dist.docs}/api.html"
version="true"
@@ -126,58 +113,19 @@ Requires Ant version 1.2 or later
windowtitle="${Name}" />
</target>
<target name="dist" depends="deepclean,jar,copy-all,javadoc">
<target name="dist" depends="copy-all,javadoc,jar">
<delete file="${dist.file}" />
<zip zipfile="${dist.file}"
basedir="${build.dir}"
basedir="${build.dir}"
includes="**"
excludes="classes/**" />
</target>
<target name="source-zip" depends="copy-source">
<delete file="${dist.source-only-zip}" />
<zip zipfile="${dist.source-only-zip}" basedir="${build.dir}"
includes="${dist.name}/src/**,${dist.name}/toolsrc/**,${dist.name}/build.xml,${dist.name}/apiClasses.properties"/>
<target name="default">
<echo>
**** Building core only; for full distribution build, try "ant dist".
</echo>
<antcall target="jar-src"/>
</target>
<target name="clean" depends="properties">
<delete quiet="true" file="${dist.dir}/${rhino.jar}"/>
<delete quiet="true" file="${dist.dir}/${small-rhino.jar}"/>
<delete quiet="true" dir="${classes}"/>
</target>
<target name="deepclean" depends="properties">
<delete quiet="true" dir="${build.dir}"/>
<delete quiet="true" file="${dist.file}"/>
<delete quiet="true" file="${dist.source-only-zip}"/>
</target>
<target name="help" depends="properties">
<echo>The following targets are available with this build file:
clean remove all compiled classes and copied property files
compile compile all classes and copy all property files
into ${classes} directory
deepclean remove all generated files and directories
dist create ${dist.file} with full Rhino distribution
help print this help
jar create ${rhino.jar} in ${dist.dir}
smalljar create ${small-rhino.jar} in ${dist.dir} with
minimalist set of Rhino classes. See footprint.html
from the doc directory for details.
javadoc generate generate Rhino API documentation
in ${dist.apidocs}
source-zip create ${dist.source-only-zip} with all Rhino
source files necessary to recreate ${rhino.jar}
</echo>
</target>
</project>

File diff suppressed because it is too large Load Diff

View File

@@ -8,9 +8,9 @@
</head>
<body bgcolor="#FFFFFF">
<h1 align="center">
Rhino API Reference.</h1>
<center>
<h1>
Rhino API Reference.</h1></center>
<h4>
The Control API</h4>
@@ -38,15 +38,10 @@ This interface can be implemented to control the actions the JavaScript
engine takes when it encounters errors.</li>
<li>
<a href="org/mozilla/javascript/SecurityController.html">SecurityController</a>
<a href="org/mozilla/javascript/SecuritySupport.html">SecuritySupport</a>
- Optional support routines that must be provided by embeddings implementing
security controls on scripts.</li>
<li>
<a href="org/mozilla/javascript/ClassShutter.html">ClassShutter</a>
- Embeddings that wish to filter Java classes that are visible to scripts
through the LiveConnect, should implement this interface.</li>
<li>
<a href="org/mozilla/javascript/Wrapper.html">Wrapper</a> - Interface implemented
by objects wrapping other objects. Provides a method for recovering the

View File

@@ -27,8 +27,8 @@ Scripting Framework</a> (or BSF) was originally developed by IBM and now
published as open source. It provides a framework for using a number of
scripting languages with Java. Rhino is one of the supported languages.
<p>This framework has been embedded in a number of open source projects,
including the XSL processor <a href="http://xml.apache.org/xalan-j/index.html">Xalan</a>
and the XML/Java build tool <a href="http://ant.apache.org/">Ant</a>.
including the XSL processor <a href="http://xml.apache.org/xalan/index.html">Xalan</a>
and the XML/Java build tool <a href="http://jakarta.apache.org/ant/index.html">Ant</a>.
<p>You can download a version of <tt>bsf.jar</tt> from <a href="http://oss.software.ibm.com/developerworks/projects/bsf">http://oss.software.ibm.com/developerworks/projects/bsf</a>
that includes the <tt>com.ibm.bsf.engines.javascript.JavaScriptEngine</tt>
class. The current version is 2.2 release candidate at the time of this

View File

@@ -1,21 +1,24 @@
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="Author" content="Norris Boyd">
<meta name="KeyWords" content="Rhino, JavaScript, Java">
<title>Change Log</title>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="Norris Boyd">
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
<meta name="KeyWords" content="Rhino, JavaScript, Java">
<title>Change Log</title>
</head>
<body bgcolor="#FFFFFF">
<body bgcolor="#ffffff">
<center>
<h1>
Change Log for Significant Rhino Changes</h1></center>
This is a log of significant changes since the release of Rhino 1.5 Release
3.
<p><i>None yet!</i>
<h3>
<h1 align="center">
Change Log for Significant Rhino Changes</h1>
This is a log of significant changes since Rhino 1.5 Release 4.
<h3>Nothing significant yet!</h3>
<hr width="100%"><br>
<hr WIDTH="100%"><br>
<a href="index.html">back to top</a></h3>
</body></html>
</body>
</html>

View File

@@ -0,0 +1,98 @@
<html>
<head>
<title>Debugger API for Rhino</title>
</head>
<body bgcolor="#FFFFFF">
<h1><center>Debugger API for Rhino</center></h1>
<p>
<font color="red"><center>This release of the Debugger API should be considered to be of Beta quality.</center></font>
<p>
The Debugger API for Rhino consists of a set of Java interfaces
which describes a high level debugger API and a default implementation of that
API.
<p>
Most of the API is in the <code>com.netscape.javascript.debug</code> package. It is built
upon low-level support built into the core engine in <code>com.netscape.javascript</code>.
<p>
The <code>com.netscape.javascript.debug</code> package includes an implementation of the Debugger API
interfaces outlined below. The class <code>com.netscape.javascript.debug.DebugManager.java</code>
implements the <a href="com/netscape/javascript/debug/IDebugManager.html">IDebugManager</a>
interface and <code>com.netscape.javascript.debug.SourceTextManagerImpl.java</code> implements
the <a href="com/netscape/javascript/SourceTextManager.html">SourceTextManager</a> interface.
<p>
The class <code>com.netscape.javascript.tools.shell.Main.java</code> provides an
example which invokes the Debugger API.
<p>
<hr>
<p>
The core interface of the API is <a href="com/netscape/javascript/debug/IDebugManager.html">IDebugManager</a>.
This interface provide the central point for interacting with the debug system.
It supports the setting of the following hooks:
<ul>
<li><a href="com/netscape/javascript/debug/IInterruptHook.html">IInterruptHook</a> for immediate interrupt.
<li><a href="com/netscape/javascript/debug/IInstructionHook.html">IInstructionHook</a> for breakpoints.
<li><a href="com/netscape/javascript/debug/IDebugBreakHook.html">IDebugBreakHook</a> for breaking on errors.
<li><a href="com/netscape/javascript/debug/IErrorReporter.html">IErrorReporter</a> for hooking into the error reporter system.
<li><a href="com/netscape/javascript/debug/IScriptHook.html">IScriptHook</a> for notification of script and function load and unload.
</ul>
Customers of the Debugger API can provide implementations of these hook
interfaces which can be passed to the <i>IDebugManager</i> in order receive
notification of the various events within the core JavaScript engine.
<p>
When hooks are called they are passed appropriate objects which are implemented
by the Debugger API to describe such things as <i>stack frames</i>,
<i> program counter locations</i>, etc. The interfaces for these objects are:
<ul>
<li><a href="com/netscape/javascript/debug/IThreadState.html">IThreadState</a> representing the state of the stopped thread.
<li><a href="com/netscape/javascript/debug/IStackFrame.html">IStackFrame</a> representing a stack frame.
<li><a href="com/netscape/javascript/debug/IPC.html">IPC</a> representing a program counter location.
<li><a href="com/netscape/javascript/debug/IScript.html">IScript</a> representing a compiled JavaScript script or function.
<li><a href="com/netscape/javascript/debug/ISourceLocation.html">ISourceLocation</a> representing a location in the souce code.
</ul>
<p>
<hr>
<p>
<a href="com/netscape/javascript/SourceTextManager.html">SourceTextManager</a>
is an interface used to supply a centralized location from which a debugger
client can access JavaScript source. It supports capturing source as it is
parsed by <i>Rhino</i>. Alternately, source can be fed to it by the
embedding; e.g. in a browser embedding where the JavaScript code is just a
part of the html source the browser can feed the entire source to the
<i>SourceTextManager</i> so that a debugger can 'see' the whole source and
not just the part that is fed to the JavaScript compiler.
<p>
<a href="com/netscape/javascript/SourceTextItem.html">SourceTextItem</a> is an
interface representing a single 'block' of source code text (typically this
is an entire source file). This may be pure JavaScript source, or may include
JavaScript source embedded in html or whatever. The point is that this is the
text that a debugger should show to a user while debugging the JavaScript code.
This interface supports incrementally updated content. This is specifically
useful in browser embeddings where text is received in blocks. In fact, in a
browser it is possible that some of the source on a page may be compiled
and run even before the entire content of the page has been received from a
server.
<p>
<hr>
<p>
<a href="com/netscape/javascript/debug/ILaunchableDebugger.html">ILaunchableDebugger</a>
is an interface that abstractly represents a debugger user interface. It is
defined to allow an embedding to request that a debugger be launched without
requiring that the embedding be coupled at compile time to a particular debugger
implementation.
<p>
<hr>
<h3>Limitations and unimplemented features</h3>
<ul>
<li>Data Watchpoints are not implemented.
<li>Catching exceptions thrown in JavaScript code is not implemented.
<li>Per context hooking is not implemented.
<li>Setting the debug level to any non-zero value forces the optimization level to zero.
<li>Tracking of calls to plain Java methods from JavaScript is not implemented.
<li>Running at debug level >= 6 causes JIT errors with the Symantec JVM (but no other JVMs)
<li>The Debug API has not been rigorously tested.
</ul>
<p>
<hr WIDTH="100%">
<br><A HREF="overview-summary.html">back to top</A>
</body>
</html>

View File

@@ -156,7 +156,6 @@ bar</font></li>
<li>
<font size=-1>Press the Pause/Break key on the keyboard</font></li>
</ul>
<a NAME="_RunningScripts"></a><b><font face="Arial"><font color="#000080"><font size=-1>Break
on Exceptions</font></font></font></b>
<br><font size=-1>To give control to the debugger whenever a JavaScript
@@ -164,13 +163,6 @@ is exception is thrown select the <b><i>Debug->Break on Exceptions</i></b>
checkbox from the menu bar.&nbsp; Whenever a JavaScript exception is thrown
by a script a message dialog will be displayed and control will be given
to the debugger at the location the exception is raised.</font>
<p><a NAME="_BreakOnFunctionEnter"></a><b><font face="Arial"><font color="#000080"><font size=-1>Break on Function Enter</font></font></font></b>
<br><font size=-1>Selecting <b><i>Debug->Break on Function Enter</i></b> will give control to the debugger whenever the execution is entered into a function or script.</font>
<p><a NAME="_BreakOnFunctionExit"></a><b><font face="Arial"><font color="#000080"><font size=-1>Break on Function Exit</font></font></font></b>
<br><font size=-1>Selecting <b><i>Debug->Break on Function Return</i></b> will give control to the debugger whenever the execution is about to return from a function or script.</font>
<p><a NAME="_Toc502165112"></a><b><font face="Arial"><font color="#000080">Moving
Up and Down the Stack</font></font></b>
<br><font size=-1>The lower-left (dockable) pane in the debugger main window

View File

@@ -30,9 +30,9 @@
<td>What you must have to run Rhino; what Rhino cannot do.</td>
</tr>
<tr>
<td><a href="rhino15R4.html">What's new in 1.5R4</a>
<td><a href="rhino15R3.html">What's new in 1.5R3</a>
</td>
<td>Changes since 1.5R3.</td>
<td>Changes since 1.5R2.</td>
</tr>
<tr>
<td><a href="debugger.html">Rhino Debugger</a>
@@ -88,14 +88,9 @@ Scripting Languages for Java</a>
<table width="100%">
<tbody>
<tr>
<td><a href="ScriptingJava.html">Scripting Java</a>
</td>
<td>How to use Rhino to script Java classes.</td>
</tr>
<tr>
<td><a href="scriptjava.html">Scripting Java</a>
</td>
<td>How to use Rhino to script Java classes (an older treatment).</td>
<td>How to use Rhino to script Java classes.</td>
</tr>
<tr>
<td><a href="perf.html">Performance Hints</a>

View File

@@ -1,91 +1,88 @@
<!DOCTYPE html PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="Author" content="Igor Bukanov">
<meta name="KeyWords" content="Rhino, JavaScript, Java">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="Norris Boyd">
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
<title>Rhino Downloads</title>
</head>
<body>
<body>
<center><b><font size="+3">Rhino Downloads</font></b></center>
<p>Rhino is available for download both in source and compiled form. </p>
<h3> Binaries</h3>
You can download binaries (JAR files) from <a
href="ftp://ftp.mozilla.org/pub/mozilla.org/js/"> ftp://ftp.mozilla.org/pub/mozilla.org/js/</a>
. Rhino 1.5 Release 4.1 is the last qualified release. It is also possible
to download the latest rhino build that reflects newer features and bug
fixes, but has not been fully qualified. These zip files also include
the source.
<p>If you are looking for <tt>js.jar</tt> for XSLT or for IBM's Bean
Scripting Framework (BSF), download one of the zip files below and
unzip it. </p>
You can download binaries (JAR files) from <a href="ftp://ftp.mozilla.org/pub/js/">
ftp://ftp.mozilla.org/pub/js/</a>
. Rhino 1.5 Release 2 is the last qualified release. It is also possible to
download the latest rhino build that reflects newer features and bug fixes,
but has not been fully qualified. These zip files also include the source.
<p>If you are looking for <tt>js.jar</tt> for XSLT or for IBM's Bean Scripting
Framework (BSF), download one of the zip files below and unzip it. </p>
<ul>
<li> <a href="ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino15R41.zip">Rhino 1.5R4.1.</a>
<ul>
<li> <i><font size="-1"><a href="rhino15R41.html">Description of changes from 1.5R4.1</a> </font></i>.</li>
</ul>
</li>
<li> <a href="ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino15R4.zip">Rhino 1.5R4.</a>
<ul>
<li> <i><font size="-1"><a href="rhino15R4.html">Description of changes from 1.5R3</a> </font></i>.</li>
</ul>
</li>
<li><a href="ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino15R3.zip">Rhino 1.5R3.</a>
<ul>
<li> <i><font size="-1"><a href="rhino15R3.html">Description of
changes from 1.5R2</a> </font></i>.</li>
</ul>
<li> <a href="ftp://ftp.mozilla.org/pub/js/rhino15R3-rc2.zip">Rhino 1.5R3
(release candidate 2).</a>
</li>
<li> <a
href="ftp://ftp.mozilla.org/pub/mozilla.org/js/older-packages/rhino15R2.zip">Rhino
1.5R2.</a>
<ul>
<li> <i><font size="-1"><a href="rhino15R2.html">Description of
changes from 1.5R1</a> </font></i>.</li>
</ul>
</li>
<li><a
href="ftp://ftp.mozilla.org/pub/mozilla.org/js/older-packages/rhino15R1.zip">Rhino
1.5R1.</a>
<ul>
<li> <i><font size="-1"><a href="rhino15R1.html">Description of
changes from 1.4R3</a> </font></i>.</li>
<li> <i><font size="-1"><a href="rhino15R3.html">Description of changes
from 1.5R2</a>
</font></i>.</li>
</ul>
<li> <a href="ftp://ftp.mozilla.org/pub/js/rhino15R2.zip">Rhino 1.5R2.</a>
</li>
<li> <a
href="ftp://ftp.mozilla.org/pub/mozilla.org/js/older-packages/rhino14R3.zip"> Rhino
1.4 Release 3</a> .</li>
<li> <a href="ftp://ftp.mozilla.org/pub/mozilla.org/js/rhinoLatest.zip">Latest
Rhino builds</a> .
<ul>
<li> <i><font size="-1"><a href="changes.html">Description of
changes from 1.5R4</a> </font></i>.</li>
<li> <i><font size="-1"><a href="rhino15R2.html">Description of changes
from 1.5R1</a>
</font></i>.</li>
</ul>
<li> <a href="ftp://ftp.mozilla.org/pub/js/rhino15R1.zip">Rhino 1.5R1.</a>
</li>
<ul>
<li> <i><font size="-1"><a href="rhino15R1.html">Description of changes
from 1.4R3</a>
</font></i>.</li>
</ul>
<li> <a href="ftp://ftp.mozilla.org/pub/js/rhino14R3.zip">Rhino 1.4 Release
3</a>
.</li>
<li> <a href="ftp://ftp.mozilla.org/pub/js/rhinoLatest.zip">Latest Rhino
builds</a>
.</li>
<ul>
<li> <i><font size="-1"><a href="changes.html">Description of changes from
1.5R3</a>
</font></i>.</li>
</ul>
</ul>
<h3> Source</h3>
The source code for Rhino is available under <a
href="http://www.mozilla.org/NPL/"> NPL 1.1</a> . In addition to getting
the source from the zip files above, the source code for Rhino can be
found in the CVS tree at mozilla/js/rhino. See&nbsp; <a
href="http://www.mozilla.org/cvs.html">source code via cvs</a> for
details on how to set up CVS, define your CVSROOT, and login. Once
you've done that, just execute the command
The source code for Rhino is available under <a href="http://www.mozilla.org/NPL/">
NPL 1.1</a>
. In addition to getting the source from the zip files above, the source
code for Rhino can be found in the CVS tree at mozilla/js/rhino. See&nbsp;
<a href="http://www.mozilla.org/cvs.html">source code via cvs</a>
for details on how to set up CVS, define your CVSROOT, and login. Once you've
done that, just execute the command
<pre>&nbsp;&nbsp;&nbsp; cvs co mozilla/js/rhino</pre>
to get the tip source.
<p>The current tip can also be viewed using LXR at <a
href="http://lxr.mozilla.org/mozilla/source/js/rhino/">
http://lxr.mozilla.org/mozilla/source/js/rhino/</a> . </p>
to get the tip source.
<p>The current tip can also be viewed using LXR at <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/">
http://lxr.mozilla.org/mozilla/source/js/rhino/</a>
. </p>
<p> </p>
<hr width="100%"><a href="index.html">back to top</a> <br>
&nbsp; <br>
<hr width="100%"><a href="index.html">back to top</a>
<br>
&nbsp;
</body>
</html>

View File

@@ -164,7 +164,7 @@ jsbuff){</font></font>
<br><font face="Arial"><font size=-1><i>// Refer </i><u><font color="#0000FF">http://www.mozilla.org/js/rhino/tutorial.html</font></u></font></font>
<br><font face="Arial"><font size=-1>Context context = Context.enter();</font></font>
<br><i><font face="Arial"><font size=-1>// Get the execution scope</font></font></i>
<br><font face="Arial"><font size=-1>Scriptable scope = context.initStandardObjects();</font></font>
<br><font face="Arial"><font size=-1>Scriptable scope = context.initStandardObjects(null);</font></font>
<p><i><font face="Arial"><font size=-1>//----------- For Test 1 - Get System.out
in scope</font></font></i>
<br><font face="Arial"><font size=-1>//Scriptable jObj1 = Context.toObject(System.out,

View File

@@ -53,11 +53,6 @@ is a program that executes JavaScript programs; it is a simplified version
of the shell in the <tt>tools</tt> package. The programs may be specified
as files on the command line or by typing interactively while the shell
is running.
<h4>PrimitiveWrapFactory</h4>
<a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/PrimitiveWrap
Factory.java">PrimitiveWrapFactory.java</a> is an example of a WrapFactory that
can be used to control the wrapping behavior of the Rhino engine on calls to Jav
a methods.<br>
<h4>
<b>Multithreaded Script Execution</b></h4>
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/DynamicScopes.java">DynamicScopes.java</a></tt>

View File

@@ -12,47 +12,35 @@
<h1>
Small Footprint</h1></center>
A few changes can be made to reduce the footprint of Rhino for embeddings
where space is at a premium. On a recent build, the length of js.jar was 603,127 bytes corresponding to 1,171,708 bytes of all uncompressed Rhino classes with debug information included.
With various changes js.jar size can be reduced to 204,689 bytes corresponding to 424,774 bytes of uncompressed classes.
<h3>Tools</h3>
<p>
Most embeddings won't need any of the classes in <tt>org.mozilla.javascript.tools</tt> or any of its sub-packages.
where space is at a premium. On a recent build, Rhino consumed 355,883
bytes of space for uncompressed class files. With various changes that
number can be reduced to 281,455 bytes.
<br>&nbsp;
<h3>
Optimizer</h3>
<p>
It is possible to run Rhino with interpreter mode only, allowing you to remove
classes for classfile generation that include all the classes from
<tt>org.mozilla.javascript.optimizer</tt> package and <tt>ClassNameHelper</tt>, <tt>ClassRepository</tt> classes from <tt>org.mozilla.javascript</tt> package.
<h3>JavaAdapter</h3>
<p>
Implementing the JavaAdapter functionality requires the ability to generate
classes on the fly. Removing <tt>org.mozilla.javascript.JavaAdapter</tt> will disable this functionality, but Rhino will otherwise run correctly.
<h3>Class generation library</h3>
<p>
If you do not include Optimizer or JavaAdapter, then you do not need Rhino library for class file generation and you can remove all the classes from in <tt>org.mozilla.classfile</tt> package.
<h3>Regular Expressions</h3>
<p>
Tools</h3>
Most embeddings won't need any of the classes in <tt>org.mozilla.javascript.tools</tt>
or any of its subpackages.
<br>&nbsp;
<h3>
Regular Expressions</h3>
The package <tt>org.mozilla.javascript.regexp</tt> can be removed. Rhino
will continue to run, although it will not be able to execute any regular
expression matches. This change saves 47,984 bytes of class files.
<h3>Debug information</h3>
<p>
Debug information in Rhino classes consumes about 25% of code size and if you can live without that, you can recompile Rhino to remove it.
<h2>smalljs.jar</h2>
Ant build script in Rhino supports smalljar target that will generate smalljs.jar that does not include Tools, Optimizer, JavaAdapter and Class generation library, Regular Expressions and deprecated files. To build such minimalist jar without debug information, run the following command from the top directory of Rhino distribution:
<pre>
ant clean
ant -Ddebug=off -Dno-regexp=true smalljar
</pre>
If you omit <tt>-Dno-regexp=true</tt>, then the resulting smalljs.jar will include Regular Expression support.
expression matches. This change saves 37,792 bytes of class files.
<br>&nbsp;
<h3>
JavaAdapter</h3>
Implementing the JavaAdapter functionality requires the ability to generate
classes on the fly. Removing <tt>org.mozilla.javascript.JavaAdapter</tt> and all
the classes in package <tt>org.mozilla.classfile</tt> will disable this
functionality, but Rhino will otherwise run correctly. These changes save
36,636 bytes.
<br>&nbsp;
<h3>
Optimizer</h3>
It is possible to run Rhino with interpreter mode only, allowing you to remove
classes for classfile generation. Remove the classes in packages
<tt>org.mozilla.classfile</tt> and <tt>org.mozilla.javascript.optimizer</tt>.
<br>&nbsp;
<p>
<hr WIDTH="100%">
<br><a href="index.html">back to top</a>

View File

@@ -24,7 +24,8 @@ documents.
All the features of JavaScript 1.5</li>
<li>
Allows direct scripting of Java</li>
<a href="http://developer.netscape.com/library/documentation/communicator/jsguide4/livecon.htm">LiveConnect</a>
-- allows direct scripting of Java</li>
<li>
A JavaScript shell for executing JavaScript scripts</li>
@@ -39,7 +40,7 @@ Language</h3>
The JavaScript language itself is standardized by Standard ECMA-262 <i>ECMAScript:
A general purpose, cross-platform programming language</i>. Rhino 1.5 implements
JavaScript 1.5, which conforms to Edition 3 of the Standard. The Standard
may be <a href="http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM">downloaded</a> or
may be <a href="http://www.ecma.ch/stand/ecma-262.htm">downloaded</a> or
obtained by mail from ECMA, 114 Rue du Rh&ocirc;ne, CH1204 Geneva, Switzerland.
<p>In addition, Rhino has implemented JavaAdapters, which allows JavaScript
to implement any Java interface or extend any Java class with a JavaScript

View File

@@ -1,201 +0,0 @@
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="Igor Bukanov">
<meta name="KeyWords" content="Rhino, JavaScript, Java">
<title>Debug API changes</title>
</head>
<body bgcolor="#ffffff">
<h2 align="center">Debug API changes in Rhino 1.5 Release 4</h2>
<p>
The main difference between the old and new API is that the application needs to implement both org.mozilla.javascript.debugger.Debugger and
org.mozilla.javascript.debugger.DebugFrame interfaces to receive debug
information during script execution. See the API documentation for these
classes for details:
<br>
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/DebugFrame.java">http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/DebugFrame.java</a>
<br><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/Debugger.java">http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/Debugger.java</a>
</tt>
<p>
In addition the org.mozilla.javascript.debugger.DebuggableEngine interface and the getDebuggableEngine method in org.mozilla.javascript.Context are replaced by 3 Context methods: setDebugger, getDebugger and getDebuggerContextData to set/get debugger and its Context data in the current thread Context:<br>
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/Context.java">http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/Context.java</a></tt>
<p>The following gives few examples how to update your current application to the new API.
<p>
1. Setting and querying a Debugger implementation
<p>
Old API:
<pre>
cx.getDebuggableEngine.setDebugger(debugger);
cx.getDebuggableEngine.getDebugger();
</pre>
New API:
<pre>
cx.setDebugger(debugger);
cx.getDebugger();
</pre>
<p>
2. Monitoring execution of each line in the script
<p>
Old implementation:
<pre>
public MyDebugger implement Debugger {
public void handleCompilationDone(Context cx,
DebuggableScript fnOrScript,
StringBuffer source)
{
}
void handleBreakpointHit(Context cx)
{
DebugFrame frame = cx.getDebuggableEngine().getFrame(0);
System.out.println("New line:" + frame.getLineNumber());
}
void handleExceptionThrown(Context cx, Object exception)
{
}
}
...
cx.getDebuggableEngine.setDebugger(new MyDebugger());
cx.getDebuggableEngine.setBreakNextLine(true);
</pre>
New implementation:
<pre>
public MyDebugger implement Debugger
{
public void handleCompilationDone(Context cx,
DebuggableScript fnOrScript,
StringBuffer source)
{
}
public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript)
{
return new MyDebugFrame();
}
}
class MyDebugFrame implements DebugFrame
{
public void onEnter(Context cx, Scriptable activation,
Scriptable thisObj, Object[] args)
{
}
public void onExceptionThrown(Context cx, Throwable ex)
{
}
public void onExit(Context cx, boolean byThrow,
Object resultOrException)
{
}
public void onLineChange(Context cx, int lineNumber)
{
System.out.println("New line:" + frame.getLineNumber());
}
}
...
cx.setDebugger(new MyDebugger());
</pre>
Note the in the new implementation the application can monitor function enter/exit by customizing enterFrame and onExit in the above code.
<p>
3. Breakpoint handling
<p>
Old implementation:
<pre>
public MyDebugger implement Debugger {
public void handleCompilationDone(Context cx, DebuggableScript fnOrScript,
StringBuffer source)
{
int breakpointLine = ...;
fnOrScript.placeBreakpoint(breakpointLine);
}
void handleBreakpointHit(Context cx) {
DebugFrame frame = cx.getDebuggableEngine().getFrame(0);
System.out.println("Breakpoint hit: "+frame.getSourceName()+":"+frame.getLineNumber());
}
void handleExceptionThrown(Context cx, Object exception)
{
}
}
...
cx.getDebuggableEngine.setDebugger(new MyDebugger());
</pre>
New implementation:
<pre>
public MyDebugger implement Debugger
{
public void handleCompilationDone(Context cx,
DebuggableScript fnOrScript,
StringBuffer source)
{
}
public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript)
{
return new MyDebugFrame(fnOrScript);
}
}
class MyDebugFrame implements DebugFrame
{
DebuggableScript fnOrScript;
MyDebugFrame(DebuggableScript fnOrScript)
{
this.fnOrScript = fnOrScript;
}
public void onEnter(Context cx, Scriptable activation,
Scriptable thisObj, Object[] args)
{
System.out.println("Frame entered");
}
public void onLineChange(Context cx, int lineNumber)
{
if (isBreakpoint(lineNumber)) {
System.out.println("Breakpoint hit: "+fnOrScript.getSourceName()+":"+lineNumber);
}
}
public void onExceptionThrown(Context cx, Throwable ex)
{
}
public void onExit(Context cx, boolean byThrow,
Object resultOrException)
{
System.out.println("Frame exit, result="+resultOrException);
}
private boolean isBreakpoint(int lineNumber)
{
...
}
}
...
cx.setDebugger(new MyDebugger());
</pre>
Here debugger during execution needs to decide if a particular line has breakpoint on it set or not during script execution, not at the moment of script initialization.
<p>See also Rhino Debugger that fully explore the new API:<br><tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/debugger/Main.java">http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/debugger/Main.java</a></tt>. The debugger changes includes support for debugging eval and Function scripts and loading script sources from their URL if debugger was not installed during scripts initialization.
<hr width="100%"><br>
<a href="index.html">back to top</a></h3>
</body></html>

View File

@@ -1,217 +0,0 @@
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en"><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="Norris Boyd">
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
<meta name="KeyWords" content="Rhino, JavaScript, Java"><title>Change Log</title></head>
<body bgcolor="#ffffff">
<h1 align="center">
Rhino Change Log</h1>
This is a log of changes since the release of Rhino 1.5 Release 3.
<h3>Rhino debug API changes</h3>
A new, incompatible Rhino debug API gives an option to monitor
entering/leaving of script functions while decreasing the amount of code to
implement the API in the Rhino core. Details are available <a href="rhino15R4-debugger.html">here</a>. With the new API <a href="debugger.html">Rhino Debugger</a> provides options to break on function enter/exit, can debug scripts defined by eval and Function construction and scripts loaded prior the debugger were started.
<h3>WrapFactory introduced, WrapHandler deprecated</h3>
A design flaw in the WrapHandler interface (a call to a Java contructor from
JavaScript would result in a call to wrap the result, which would then be
cast to a Scriptable) inspired the deprecation of that interface and the
introduction of a new class, WrapFactory, that contains a new method called
on the result of a constructor call and can be customized by application if necessary.
<p>
In addition, WrapFactory has the new <tt>setJavaPrimitiveWrap</tt> method to control if instances of Java <tt>String</tt> and <tt>Number</tt> class should be wrapped to special script objects as any other Java objects so a script can access any method <tt>String</tt> and <tt>Number</tt>, or they should be converted to JavaScript primitive strings and numbers.
<h3>New security interfaces</h3>
<p>
Igor Bukanov contributed a new security implementation that allows integration with Java2 security model and prevents scripts to escape the security sandbox via eval/Function schemes.
<p>
Due to this changes SecuritySupport interface is replaced by ClassShutter and SecurityController, where ClassShutter controls which classes are visible to scripts via LiveConnect and SecurityController provides permission management. For compatibility SecuritySupport is still available as a deprecated interface but only its visibleToScripts method is used as an alias for ClassShutter.visibleToScripts. See API documentation for new classes for details.
<p>
An implementation of SecurityController that uses java policy settings to restrict script permissions based on its URL is available with Rhino shell. See the <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/JavaPolicySecurity.java">JavaPolicySecurity</a> source for details. To activate it, set the <tt>rhino.use_java_policy_security</tt> system property to true when invoking Rhino shell together with installing a security manager.
<h3>Serialization chages</h3>
Due to changes in Rhino implementation and bug fixes in serialization support runtime data serialized in Rhino 1.5 Release 3 can not be read back in the Release 4.
<h3>Regular expressions improvements</h3>
Roger Lawrence provided new regular expressions implementation which fully confirms to EcmaScript 262 standard and faster.
<h3>Scripting of classes from any class loader</h3>
Christopher Oliver contributed code to allow to use the <tt>Packages</tt> object as a constructor taking a class loader argument so a script can access classes defined by that class loader. For example, to access classes from foo.jar file in the current directory, the following can be used:
<pre>
// create class loader
var loader = new java.net.URLClassLoader([new java.net.URL("file:./foo.jar")]);
// create its LiveConnect wrapper
var fooJar = new Packages(loader);
// create an instance of the class For from foo.jar
var obj = new fooJar.Foo(1, 2, 3);
obj.someMethod();
</pre>
<h3>Shell function to run external processes.</h3>
A new <tt>runCommand</tt> function is added to <a href="shell.html">Rhino Shell</a> to run external priocesses. For details, see JavaDoc for <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/Global.java">org.mozilla.javascript.tools.shell.Global#runCommand</a>.
<h3>Resolved Bugzilla reports</h3>
The following Rhino reports in <a href="http://bugzilla.mozilla.org/">Bugzilla</a> where resolved for Rhino 1.5 Release 4.
<p>
<a href="http://bugzilla.mozilla.org/show_bug.cgi?id=61579">61579</a> -
context.decompileScript doesn't work.
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=72021">72021</a> -
The ScriptRuntime class tries to convert even the String values to JavaNativeObject
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=83051">83051</a> -
A function defined under a with block can't be invoked outside it
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=104089">104089</a> -
Cannot reattach context to its thread because of the bug in Context class
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=105438">105438</a> -
SourceName and lineNumbers of syntax errors in Javascript files not dispalyed.
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=106548">106548</a> -
/^.*?$/ will not match anything
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=114583">114583</a> -
script compile/decompile bug
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=114969">114969</a> -
[], [^] are valid RegExp conditions
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=115717">115717</a> -
java.lang.ArrayIndexOutOfBoundsException on with/try/finally
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=120194">120194</a> -
JS toInt32(x) conversion doesn't match ECMAScript definition
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=122167">122167</a> -
string.replace() placeholder '$1' not working
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=123439">123439</a> -
Backreferences /(a)? etc./ must hold |undefined| if not used
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=124508">124508</a> -
regexp.lastIndex should be integer-valued double, not uint32
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=124900">124900</a> -
arguments object storing duplicate parameter values
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=125562">125562</a> -
Regexp performance improvement
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=126317">126317</a> -
Crash on re.exec(str) if re.lastIndex set to certain values
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=126722">126722</a> -
(undefined === null) evaluating to true in Rhino compiled mode
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=128468">128468</a> -
java.io.NotSerializableException: org.mozilla.javascript.NativeError
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=129365">129365</a> -
Incorrect licensing in dtoa.java
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=132217">132217</a> -
delete on global function should not delete the function
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=136893">136893</a> -
Rhino treatment of |for(i in undefined)|, |for(i in null)|
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=137181">137181</a> -
delete on an arguments[i] not working correctly
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=145791">145791</a> -
ECMA conformance: Function.prototype.apply(), Function.prototype.call()
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=149285">149285</a> -
Complier does not report the correct line number on SyntaxError:Invalid assignment left-hand side.
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=151337">151337</a> -
EcmaError.getLineSource() returns 0x0 characters.
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=153223">153223</a> -
New RegExp engine in Rhino
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=154693">154693</a> -
Interpreted mode doesn't grok different functions on different objects
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=156510">156510</a> -
for (i in undefined) {} should not throw TypeError
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=157196">157196</a> -
ScriptableObject needs custom serialization implementation
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=157509">157509</a> -
No error on invalid usage of \ in identifiers
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=158159">158159</a> -
Should Rhino support octal escape sequences in regexps?
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=159334">159334</a> -
The javascript functions size is limited by a bug
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=164947">164947</a> -
Debugging unique.js produce a stack trace and erratic results
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=166530">166530</a> -
ClassCostException in FunctionObject static initializer
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=169830">169830</a> -
Array.concat(function) doesn't add function to the array
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=173180">173180</a> -
Rhino UTF-8 decoder accepts overlong sequences
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=173906">173906</a> -
Dynamic scope not working correctly with optimzation level >= 1
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=175383">175383</a> -
ArrayIndexOutOfBoundsException in string.replace()
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=177314">177314</a> -
Rhino should allow '\400' to mean ' 0'
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=179068">179068</a> -
String literals in Rhino are limited to 64K
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=179366">179366</a> -
--&gt; after whitespace after line start should mean comments to line end
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=181654">181654</a> -
Calling toString for an object derived from the Error class throws TypeError
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=181834">181834</a> -
wrong scope used for inner functions when compiling functions with dynamic scopes (interpreted only)
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=181909">181909</a> -
some regression tests for Error invalid
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=182028">182028</a> -
Calling has() in get() of a ScriptableObject causes getter function to not be called
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=184107">184107</a> -
with(...) { function f ...} should set f in the global scope
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=184111">184111</a> -
ArrayOutOfBounds Exception thrown when using Rhino Javascript Debugger
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=185165">185165</a> -
Decompilation of "\\" gives broken "\"
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=189183">189183</a> -
Debugger source frame window layering fix
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=189898">189898</a> -
Broken String.replace: "XaXY".replace("XY", "--") gives --aXY
<hr width="100%"><br>
<a href="index.html">back to top</a></h3>
</body></html>

View File

@@ -1,41 +0,0 @@
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="Igor Bukanov">
<meta name="KeyWords" content="Rhino, JavaScript, Java">
<title>Rhino 1.5 Release 4.1 Change Log</title>
</head>
<body bgcolor="#ffffff">
<h1 align="center">Rhino 1.5 Release 4.1 Change Log</h1>
1.5R4.1 is a bug fix release to address mostly regressions from 1.5R3 found in 1.5R4. The only visible API change compared with 1.5R4 is two new methods in <tt>org.mozilla.javascript.Context</tt>, <tt>getApplicationClassLoader()</tt> and <tt>setApplicationClassLoader(ClasssLoader)</tt>. They allow to control the class loader Rhino uses when accessing application classes.
<p>
For differences between 1.5R4 and 1.5R3, see <a href="rhino15R4.html">1.5R4 change log</a>.
<h3>Resolved Bugzilla reports</h3>
The following Rhino reports in <a href="http://bugzilla.mozilla.org/">Bugzilla</a> where resolved for Rhino 1.5 Release 4.
<p>
<a href="http://bugzilla.mozilla.org/show_bug.cgi?id=96270">96270</a> -
Unable to create java objects from within a javascript.
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=193168">193168</a> -
Rhino debugger in v1.5R4 fails to update script source when a script is reloaded.
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=193555">193555</a> -
1.5R4 regression: function expression has no access to its name.
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=196017">196017</a> -
1.5R4 regression: script can not find classes on some versions of JDK.
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=200551">200551</a> -
JavaAdapter not loading a class if js.jar installed in jre/lib/ext directory.
<hr width="100%"><br>
<a href="index.html">back to top</a></h3>
</body></html>

View File

@@ -39,13 +39,9 @@ the execution environment. There should be one and only one Context associated
with each thread that will be executing JavaScript.
<p>To associate the current thread with a Context, simply call the <tt>enter</tt>
method of Context: </p>
<pre>
Context cx = Context.enter();
</pre>
<pre>&nbsp;&nbsp;&nbsp; Context cx = Context.enter();</pre>
Once you are done with execution, simply exit the Context:
<pre>
Context.exit();
</pre>
<pre>&nbsp;&nbsp;&nbsp; Context.exit();</pre>
These calls will work properly even if there is already a Context associated
with the current thread. That context will be returned and an internal counter
incremented. Only when the counter reaches zero will it be disassociated from
@@ -69,9 +65,7 @@ the scripts are responsible for coordinating any accesses to shared variables.
</p>
<p>A top-level scope is created by calling <tt>Context.initStandardObjects</tt>
to create all the standard objects: </p>
<pre>
ScriptableObject scope = cx.initStandardObjects();
</pre>
<pre>&nbsp;&nbsp;&nbsp; Scriptable scope = cx.initStandardObjects(null);</pre>
The easiest way to embed Rhino is just to create a new scope this way whenever
you need one. However, <tt>initStandardObjects</tt> is an expensive method
to call and it allocates a fair amount of memory. We'll see below that there
@@ -114,8 +108,9 @@ for the variable <tt>g</tt> and the function <tt>f</tt>.
traversed looking for a 'x' property. When none is found, a new property 'x'
is created in the top-level scope. </p>
<h2> Sharing Scopes</h2>
JavaScript is a language that uses delegation rather than traditional class-based inheritance. This is a large topic in itself, but for our purposes it gives us an easy way to share a set of read-only variables across multiple scopes.
JavaScript is a language that uses delegation rather than traditional class-based
inheritance. This is a large topic in itself, but for our purposes it gives
us an easy way to share a set of read-only variables across multiple scopes.
To do this we set an object's prototype. When accessing a property of an object
in JavaScript, the object is first searched for a property with the given
name. If none is found, the object's prototype is searched. This continues
@@ -125,12 +120,9 @@ we wish to share. Typically this object will have been created with <tt>initStan
and may also have additional objects specific to the embedding. Then all
we need to do is create a new object and call its <tt>setPrototype</tt> method
to set the prototype to the shared object, and the parent of the new scope
to null:
<pre> Scriptable newScope = cx.newObject(sharedScope);
newScope.setPrototype(sharedScope);
newScope.setParentScope(null);
</pre>
The call to <tt>newObject</tt> simply creates a new JavaScript object with
to null: </p>
<pre>&nbsp;&nbsp;&nbsp; Scriptable newScope = cx.newObject(sharedScope);<br>&nbsp;&nbsp;&nbsp; newScope.setPrototype(sharedScope);<br>&nbsp;&nbsp;&nbsp; newScope.setParentScope(null);<br></pre>
The call to <tt>newObject</tt> simply creates a new JavaScript object with
no properties. It uses the <tt>sharedScope</tt> passed in to initialize the
prototype with the standard <tt>Object.prototype</tt> value.
<p>We can now use <tt>newScope</tt> as a scope for calls to evaluate scripts.
@@ -142,16 +134,6 @@ instance scopes can be defined and have their own variables for scripts yet
share the definitions in the shared scope. These multiple instance scopes
can be used concurrently. <br>
&nbsp; </p>
<h2>Sealed shared scopes</h2>
<p>The ECMAScript standard defines that scripts can add properties to all standard library objects and in many cases it is also possible to change or delete their properties as well. Such behavior may not be suitable with shared scopes since if a script by mistake adds a property to a library object from the shared scope, that object would not be garbage collected until there re active references to the shared scope potentially leading to memory leaks. In addition if a script alters some of the standard objects, the library may not work properly for other scripts. Such bugs are hard to debug and to remove a possibility for them to occur one can use seal the shared scope and all its objects.
<p>
A notion of a sealed object is a JavaScript extension supported by Rhino and it means that properties can not be added/deleted to the object and the existing object properties can not be changed. Any attempt to modify sealed object throws an exception. To seal all objects in the standard library pass <tt>true</tt> for the sealed argument when calling <tt>Context.initStandardObjects(ScriptableObject, boolean)</tt>:
<pre> ScriptableObject sealedSharedScope = cx.initStandardObjects(null, true);</pre>
This seals only all standard library objects, it does not seal the shared scope itself thus after calling <tt>initStandardObjects</tt>, <tt>sealedSharedScope</tt> cab be farther populated with application-specific objects and functions. Then after a custom initialization is done, one can seal the shared scope by calling <tt>ScriptableObject.sealObject()</tt>:
<pre> sealedSharedScope.sealObject();</pre>
Note that currently one needs to explicitly seal any additional properties he adds to the sealed shared scope since although after calling <tt>sealedSharedScope.sealObject();</tt> it would no be possible to set the additional properties to different values, one still would be able to alter the objects themselves.
<h2> Dynamic Scopes</h2>
There's one problem with the setup outlined above. Calls to functions in
JavaScript use <i>static scope</i>, which means that variables are first looked

View File

@@ -36,7 +36,7 @@ a command line.
file, <tt>js.jar</tt>. If you add the JAR file to your class path, you
can start the Rhino shell using the command
<pre>&nbsp;&nbsp;&nbsp; java org.mozilla.javascript.tools.shell.Main</pre>
or if you have Java 2 (JDK 1.2 or greater), you can avoid changing your classpath
or if you have Java 2 (JDK 1.2), you can avoid changing your classpath
and simply use the command
<pre>&nbsp;&nbsp;&nbsp; java -jar js.jar</pre>
Unfortunately the <tt>-jar</tt> option to <tt>java</tt> will overwrite
@@ -167,27 +167,7 @@ When we type <tt>buttonListener = java.awt.event.ActionListener(o)</tt>,
Rhino actually creates a new Java class that implements <tt>ActionListener</tt>
and forwards calls from that class to the JavaScript object. So when you
click on the button, the <tt>printDate</tt> method is called.
<p>
Starting from the release 1.5R5 Rhino allows to pass JavaScript functions directly to Java methods if the corresponding argument is Java interface with single method. It allows to pass <tt>printDate</tt> directly to <tt>addActionListener</tt> and simplifies example:
<pre>$ java org.mozilla.javascript.tools.shell.Main
js> importPackage(java.awt);
js> frame = new Frame("JavaScript")
java.awt.Frame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=JavaScript,resizable,normal]
js> button = new Button("OK")
java.awt.Button[button0,0,0,0x0,invalid,label=OK]
js> frame.setSize(new Dimension(200,100))
js> frame.add(button)
java.awt.Button[button0,0,0,0x0,invalid,label=OK]
js> frame.show()
js> function printDate() { print(new Date()) }
js> printDate()
Mon Oct 27 2003 10:35:44 GMT+0100 (CET)
js> button.addActionListener(printDate)
js> Mon Oct 27 2003 10:36:09 GMT+0100 (CET)
Mon Oct 27 2003 10:36:10 GMT+0100 (CET)
quit()
$</pre>
<br>&nbsp;
<h2>
JavaAdapter constructor</h2>
Another way to create a JavaAdapter is to call the JavaAdapter constructor

View File

@@ -15,24 +15,25 @@ The JavaScript shell provides a simple way to run scripts in batch mode
or an interactive environment for exploratory programming.
<h2>
Invoking the Shell</h2>
<tt>java org.mozilla.javascript.tools.shell.Main [<i>options</i>]
<i>script-filename-or-url</i> [<i>script-arguments</i>]</tt>
<p>where <tt><i>options</i></tt> are:
<p><tt>-e <i>script-source</i></tt>
<tt>java org.mozilla.javascript.tools.shell.Main</tt> [<i>options</i>]
<i>file</i><tt>.js
[<i>script-arguments</i>]</tt>
<p>where <i>options</i> are:
<p><tt>-e </tt><i>script-source</i>
<blockquote>Executes <i>script-source</i> as a JavaScript script.</blockquote>
<tt>-f <i>script-filename-or-url</i></tt>
<blockquote>Reads <i>script-filename-or-url</i> content and execute it as a JavaScript script.</blockquote>
<tt>-opt <i>optLevel</i></tt>
<br><tt>-O <i>optLevel</i></tt>
<tt>-f </tt><i>script-filename</i>
<blockquote>Reads filename specified by <i>script-filename</i> and executes
it as a JavaScript script.</blockquote>
<tt>-opt </tt><i>optLevel</i>
<br><tt>-O</tt> <i>optLevel</i>
<ul>Optimizes at level <i>optLevel</i>, which must be an integer between
0 and 9. See <a href="opt.html">Optimization</a> for more details.</ul>
<tt>-version <i>versionNumber</i></tt>
<tt>-version </tt><i>versionNumber</i>
<ul>Specifies the language version to compile with. The string <i>versionNumber</i>
must be one of <tt>100</tt>, <tt>110</tt>, <tt>120</tt>, <tt>130</tt>,
or <tt>140</tt>. See <a href="overview.html#versions">JavaScript Language
Versions</a> for more information on language versions.</ul>
If the shell is invoked with the system property rhino.use_java_policy_security set to true and with a security manager installed, the shell restricts scripts permissions based on their URLs according to Java policy settings. This is available only if JVM implements Java2 security model.
<h2>
Predefined Properties</h2>
Scripts executing in the shell have access to some additional properties
@@ -56,11 +57,6 @@ defineClass(<i>className</i>)</h4>
argument <i>className</i>. Uses ScriptableObject.defineClass() to define
the extension.</blockquote>
<h4>
deserialize(<i>filename</i>)</h4>
<blockquote>Restore from the specified file an object previously written by a call to <tt>serialize</tt>.</blockquote>
<h4>
load([<i>filename</i>, ...])</h4>
@@ -80,40 +76,6 @@ print([<i>expr</i> ...])</h4>
<blockquote>Evaluate and print expressions. Evaluates each expression,
converts the result to a string, and prints it.</blockquote>
<h4>
readFile(<i>path</i> [, <i>characterCoding</i>)</h4>
<blockquote>Read given file and convert its bytes to a string using the
specified character coding or default character coding if explicit coding
argument is not given.</blockquote>
<h4>
readUrl(<i>url</i> [, <i>characterCoding</i>)</h4>
<blockquote>Open an input connection to the given string url, read all its
bytes and convert them to a string using the specified character coding or
default character coding if explicit coding argument is not given.</blockquote>
<h4>
runCommand(<i>commandName</i>, [<i>arg</i>, ...] [<i>options</i>])</h4>
<blockquote>Execute the specified command with the given argument and options
as a separate process and return the exit status of the process. For details, see JavaDoc for <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/Global.java">org.mozilla.javascript.tools.shell.Global#runCommand</a>.</blockquote>
<h4>
serialize(<i>object</i>, <i>filename</i>)</h4>
<blockquote>Serialize the given object to the specified file.</blockquote>
<h4>
spawn(<i>functionOrScript</i>)</h4>
<blockquote>Run the given function or script in a different thread.</blockquote>
<h4>
sync(<i>function</i>)</h4>
<blockquote>creates a synchronized function (in the sense of a Java synchronized method) from an existing function. The new function synchronizes on the <code>this</code> object of its invocation.</blockquote>
<h4>
quit()</h4>
@@ -131,103 +93,35 @@ respectively.</blockquote>
<h2>
Example</h2>
<h4>Invocation</h4>
Here the shell is invoked three times from the command line. (The system
command prompt is shown as <tt>$</tt>.) The first invocation executes a
script specified on the command line itself. The next invocation has no
arguments, so the shell goes into interactive mode, reading and evaluating
each line as it is typed in. Finally, the last invocation executes a script
from a file and accesses arguments to the script itself.
<pre>
$ java org.mozilla.javascript.tools.shell.Main -e print('hi')
hi
$ java org.mozilla.javascript.tools.shell.Main
js> print('hi')
hi
js> 6*7
42
js> function f() {
return a;
}
js> var a = 34;
js> f()
34
js> quit()
$ cat echo.js
for (i in arguments) {
print(arguments[i])
}
$ java org.mozilla.javascript.tools.shell.Main echo.js foo bar
foo
bar
$
</pre>
<h4>spawn and sync</h4>
The following example creates 2 threads via <tt>spawn</tt> and uses <tt>sync</tt> to create a synchronized version of the function <tt>test</tt>.
<pre>
js> function test(x) {
print("entry");
java.lang.Thread.sleep(x*1000);
print("exit");
}
js> var o = { f : sync(test) };
js> spawn(function() {o.f(5);});
Thread[Thread-0,5,main]
entry
js> spawn(function() {o.f(5);});
Thread[Thread-1,5,main]
js>
exit
entry
exit
</pre>
<h4>runCommand</h4>
Here is few examples of invoking <tt>runCommand</tt> under Linux.
<pre>
js> runCommand('date')
Thu Jan 23 16:49:36 CET 2003
0
// Using input option to provide process input
js> runCommand("sort", {input: "c\na\nb"})
a
b
c
0
js> // Demo of output and err options
js> var opt={input: "c\na\nb", output: 'Sort Output:\n'}
js> runCommand("sort", opt)
0
js> print(opt.output)
Sort Output:
a
b
c
js> var opt={input: "c\na\nb", output: 'Sort Output:\n', err: ''}
js> runCommand("sort", "--bad-arg", opt)
2
js> print(opt.err)
/bin/sort: unrecognized option `--bad-arg'
Try `/bin/sort --help' for more information.
js> runCommand("bad_command", "--bad-arg", opt)
js: "<stdin>", line 18: uncaught JavaScript exception: java.io.IOException: bad_command: not found
js> // Passing explicit environment to the system shell
js> runCommand("sh", "-c", "echo $env1 $env2", { env: {env1: 100, env2: 200}})
100 200
0
js> // Use args option to provide additional command arguments
js> var arg_array = [1, 2, 3, 4];
js> runCommand("echo", { args: arg_array})
1 2 3 4
0
</pre>
<p><tt>$ java org.mozilla.javascript.tools.shell.Main -e print('hi')</tt>
<p><tt>hi</tt>
<p><tt>$ java org.mozilla.javascript.tools.shell.Main</tt>
<p><tt>js> print('hi')</tt>
<br><tt>hi</tt>
<br><tt>js> 6*7</tt>
<br><tt>42</tt>
<br><tt>js> function f() {</tt>
<br><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return a;</tt>
<br><tt>}</tt>
<br><tt>js> var a = 34;</tt>
<br><tt>js> f()</tt>
<br><tt>34</tt>
<br><tt>js> quit()</tt>
<p><tt>$ cat echo.js</tt>
<br><tt>for (i in arguments) {</tt>
<br><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(arguments[i])</tt>
<br><tt>}</tt>
<br><tt>$ java org.mozilla.javascript.tools.shell.Main echo.js foo bar</tt>
<p><tt>foo</tt>
<br><tt>bar</tt>
<p><tt>$</tt>
<p>
<hr WIDTH="100%">
<br><a href="index.html">back to top</a>
</body>

View File

@@ -110,7 +110,7 @@ example</a>. All it does it read a script from the command line, execute
it, and print a result.
<p>Here's an example use of RunScript from a shell command line:
<blockquote>
<pre><font color="#663366">$ java RunScript "Math.cos(Math.PI)"
<pre><font color="#663366">$ java RunScript 'Math.cos(Math.PI)'
-1
$ java RunScript 'function f(x){return x+1} f(7)'
8</font></pre>
@@ -129,7 +129,7 @@ about the execution environment of a script.
<p><a NAME="initializing"></a><font size=+2>Initializing standard objects</font>
<p>The code
<blockquote>
<pre><font color="#006600">Scriptable scope = cx.initStandardObjects();</font></pre>
<pre><font color="#006600">Scriptable scope = cx.initStandardObjects(null);</font></pre>
</blockquote>
Initializes the standard objects (<tt>Object</tt>,
<tt>Function</tt>, etc.)
@@ -139,14 +139,10 @@ that we use in later calls.
<p><a NAME="Collecting"></a><font size=+2>Collecting the arguments</font>
<p>This code is standard Java and not specific to Rhino. It just collects
all the arguments and concatenates them together.
<blockquote>
<pre style="color: #006600">
String s = "";
for (int i=0; i &lt; args.length; i++) {
s += args[i];
}
</pre>
</blockquote>
<blockquote><tt><font color="#006600">String s = "";</font></tt>
<br><tt><font color="#006600">for (int i=0; i &lt; args.length; i++)</font></tt>
<br><tt><font color="#006600">&nbsp;&nbsp;&nbsp; s += args[i];</font></tt></blockquote>
<p><br><a NAME="Evaluating"></a><font size=+2>Evaluating a script</font>
<p>The code
<blockquote>
@@ -170,15 +166,11 @@ method converts any JavaScript value to a string.
<p><a NAME="Exit"></a><font size=+2>Exit the Context</font>
<p>The code
<blockquote>
<pre style="color: #006600">
} finally {
Context.exit();
}
</pre>
<pre><font color="#006600">Context.exit();</font></pre>
</blockquote>
exits the Context. This removes the association between the Context and
the current thread and is an essential cleanup action. There should be
a call to <tt>exit</tt> for every call to <tt>enter</tt>. To make sure that it is called even if an exception is thrown, it is put into the finally block corresponding to the try block starting after <tt>Context.enter()</tt>.
a call to <tt>exit</tt> for every call to <tt>enter</tt>.
<br>&nbsp;
<dir>&nbsp;</dir>
<a NAME="Expose"></a><font size=+3>Expose Java APIs</font>
@@ -227,45 +219,40 @@ is illustrated in the <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/ex
example. This example adds the ability to print the value of variable <tt>x</tt>
and the result of calling function <tt>f</tt>. Both <tt>x</tt> and <tt>f</tt>
are expected to be defined by the evaluated script. For example,
<blockquote>
<pre style="color: #663366">
$ java RunScript3 'x = 7'
x = 7
f is undefined or not a function.
$ java RunScript3 'function f(a) { return a; }'
x is not defined.
f('my args') = my arg
</pre>
</blockquote>
<blockquote><tt><font color="#663366">$ java RunScript3 'x = 7'</font></tt>
<br><tt><font color="#663366">x = 7</font></tt>
<br><tt><font color="#663366">f is undefined or not a function.</font></tt>
<br><tt><font color="#663366">$ java RunScript3 'function f(a) { return
a; }'</font></tt>
<br><tt><font color="#663366">x is not defined.</font></tt>
<br><tt><font color="#663366">f('my args') = my arg</font></tt>
<br><tt><font color="#663366"></font></tt>&nbsp;</blockquote>
<a NAME="UsingJSvars"></a><font size=+2>Using JavaScript variables</font>
<p>To print out the value of <tt>x</tt>, we add the following code.
<blockquote>
<pre style="color: #006600">
Object x = scope.get("x", scope);
if (x == Scriptable.NOT_FOUND) {
System.out.println("x is not defined.");
} else {
System.out.println("x = " + Context.toString(x));
}
</pre>
</blockquote>
<dir><tt><font color="#006600">Object x = scope.get("x", scope);</font></tt>
<br><tt><font color="#006600">if (x == Scriptable.NOT_FOUND)</font></tt>
<br><tt><font color="#006600">&nbsp;&nbsp;&nbsp; System.out.println("x
is not defined.");</font></tt>
<br><tt><font color="#006600">else</font></tt>
<br><tt><font color="#006600">&nbsp;&nbsp;&nbsp; System.out.println("x
= " + Context.toString(x));</font></tt>
<br><tt><font color="#006600"></font></tt>&nbsp;</dir>
<a NAME="CallingJSfuns"></a><font size=+2>Calling JavaScript functions</font>
<p>To get the function <tt>f</tt>, call it, and print the result, we add
this code:
<blockquote>
<pre style="color: #006600">
Object fObj = scope.get("f", scope);
if (!(fObj instanceof Function)) {
System.out.println("f is undefined or not a function.");
} else {
Object functionArgs[] = { "my arg" };
Function f = (Function)fObj;
Object result = f.call(cx, scope, scope, functionArgs);
String report = "f('my args') = " + Context.toString(result);
System.out.println(report);
}
</pre>
</blockquote>
<dir><tt><font color="#006600">Object f = scope.get("f", scope);</font></tt>
<br><tt><font color="#006600">if (!(f instanceof Function))</font></tt>
<br><tt><font color="#006600">&nbsp;&nbsp;&nbsp; System.out.println("f
is undefined or not a function.");</font></tt>
<br><tt><font color="#006600">else {</font></tt>
<br><tt><font color="#006600">&nbsp;&nbsp;&nbsp; Object functionArgs[]
= { "my arg" };</font></tt>
<br><tt><font color="#006600">&nbsp;&nbsp;&nbsp; Object result = ((Function)
f).call(cx, scope, scope, functionArgs);</font></tt>
<br><tt><font color="#006600">&nbsp;&nbsp;&nbsp; System.out.println("f('my
args') = " + Context.toString(result));</font></tt>
<br><tt><font color="#006600">}</font></tt></dir>
<p><br><a NAME="JavaScriptHostObjects"></a><font size=+3>JavaScript host
objects</font>
<p><a NAME="DefiningHostObjects"></a><font size=+2>Defining Host Objects</font>
@@ -280,8 +267,7 @@ built-in <tt>defineClass</tt> function. We'll see how to add it to RunScript
later. (Note that because the <tt>java -jar</tt> option preempts the rest
of the classpath, we can't use that and access the <tt>Counter</tt> class.)
<blockquote>
<pre style="color: #663366">
$ java -cp 'js.jar;examples' org.mozilla.javascript.tools.shell.Main
<pre><font color="#663366">$ java -cp 'js.jar;examples' org.mozilla.javascript.tools.shell.Main
js> defineClass("Counter")
js> c = new Counter(7)
[object Counter]
@@ -293,8 +279,7 @@ js> c.count
9
js> c.resetCount()
js> c.count
0
</pre>
0</font></pre>
</blockquote>
<a NAME="CounterCtors"></a><font size=+2>Counter's constructors</font>
<p>The zero-argument constructor is used by Rhino runtime to create instances.
@@ -338,20 +323,14 @@ c.count;'</font></tt>
It also creates a new instance of the <tt>Counter</tt> object from within
our Java code, constructing it with the value 7, and assigning it to the
top-level variable <tt>myCounter</tt>:
<blockquote>
<pre style="color: #006600">
Object[] arg = { new Integer(7) };
Scriptable myCounter = cx.newObject(scope, "Counter", arg);
scope.put("myCounter", scope, myCounter);
</pre>
</blockquote>
<dir><tt><font color="#006600">Object[] arg = { new Integer(7) };</font></tt>
<br><tt><font color="#006600">Scriptable myCounter = cx.newObject(scope,
"Counter", arg);</font></tt>
<br><tt><font color="#006600">scope.put("myCounter", scope, myCounter);</font></tt></dir>
Now we can reference the <tt>myCounter</tt> object from our script:
<blockquote>
<pre style="color: #663366">
$ java RunScript3 'RunScript4 'myCounter.count; myCounter.count'
8
</pre>
</blockquote>
<dir><tt><font color="#663366">$ java RunScript3 'RunScript4 'myCounter.count;
myCounter.count'</font></tt>
<br><tt><font color="#663366">8</font></tt></dir>
</body>
</html>

View File

@@ -39,9 +39,10 @@ and compile it down to Java classes which could be used directly for greater
speed in production. Netscape's JavaScript engine is rock solid and standards
compliant, and my only regret is that we didn't start using it sooner,"
said Don Anderson, President of Bristow Hill Software.
<p><a href="http://www.icesoft.com/">ICEsoft Technologies</a>
<br>ICEsoft Technologies adds JavaScript support to their <a href="http://www.icesoft.com/ps_browser_overview.html">ICEbrowser</a> using Rhino.
<p><a href="http://homepage.mac.com/pcbeard/JShell/">JShell</a>
<p><a href="http://www.icesoft.no/">ICEsoft</a>
<br>ICEsoft adds JavaScript support to their <a href="http://www.icesoft.no/ICEBrowser/">ICE
Browser</a> using Rhino.
<p><a href="http://www.vmeng.com/beard/JShell/Release_Notes.html">JShell</a>
<br>Rhino is used as the scripting language for the open source command
shell JShell written by Patrick Beard.
<p><a href="http://www.softcom.com">Softcom</a>

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -38,7 +38,7 @@ import org.mozilla.javascript.*;
* Example of controlling the JavaScript execution engine.
*
* We evaluate a script and then manipulate the result.
*
*
*/
public class Control {
@@ -59,7 +59,7 @@ public class Control {
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed.
Scriptable scope = cx.initStandardObjects();
Scriptable scope = cx.initStandardObjects(null);
// Now we can evaluate a script. Let's create a new object
// using the object literal notation.
@@ -96,7 +96,7 @@ public class Control {
System.out.println(fn.call(cx, scope, obj, new Object[0]));
} catch (JavaScriptException e) {
// ignore
}
}
cx.exit();
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -39,17 +39,17 @@ public class Counter extends ScriptableObject {
// The zero-argument constructor used by Rhino runtime to create instances
public Counter() { }
// Method jsConstructor defines the JavaScript constructor
// Method jsConstructor defines the JavaScript constructor
public void jsConstructor(int a) { count = a; }
// The class name is defined by the getClassName method
public String getClassName() { return "Counter"; }
// The method jsGet_count defines the count property.
// The method jsGet_count defines the count property.
public int jsGet_count() { return count++; }
// Methods can be defined using the jsFunction_ prefix. Here we define
// resetCount for JavaScript.
// Methods can be defined using the jsFunction_ prefix. Here we define
// resetCount for JavaScript.
public void jsFunction_resetCount() { count = 0; }
private int count;

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -49,31 +49,27 @@ import org.mozilla.javascript.*;
*/
public class CounterTest {
public static void main(String[] args) throws Exception
{
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
ScriptableObject.defineClass(scope, Counter.class);
public static void main(String[] args) throws Exception
{
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects(null);
ScriptableObject.defineClass(scope, Counter.class);
Scriptable testCounter = cx.newObject(scope, "Counter");
Scriptable testCounter = cx.newObject(scope, "Counter");
Object count = ScriptableObject.getProperty(testCounter, "count");
System.out.println("count = " + count);
Object count = ScriptableObject.getProperty(testCounter, "count");
System.out.println("count = " + count);
count = ScriptableObject.getProperty(testCounter, "count");
System.out.println("count = " + count);
count = ScriptableObject.getProperty(testCounter, "count");
System.out.println("count = " + count);
ScriptableObject.callMethod(testCounter, "resetCount", new Object[0]);
System.out.println("resetCount");
ScriptableObject.callMethod(testCounter,
"resetCount",
new Object[0]);
System.out.println("resetCount");
count = ScriptableObject.getProperty(testCounter, "count");
System.out.println("count = " + count);
count = ScriptableObject.getProperty(testCounter, "count");
System.out.println("count = " + count);
} finally {
Context.exit();
}
}
Context.exit();
}
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -44,9 +44,9 @@ public class DynamicScopes {
* Main entry point.
*
* Set up the shared scope and then spawn new threads that execute
* relative to that shared scope. Try compiling functions with and
* relative to that shared scope. Try compiling functions with and
* without dynamic scope to see the effect.
*
*
* The expected output is
* <pre>
* sharedScope
@@ -59,7 +59,7 @@ public class DynamicScopes {
* The final three lines may be permuted in any order depending on
* thread scheduling.
*/
public static void main(String[] args)
public static void main(String[] args)
throws JavaScriptException
{
Context cx = Context.enter();
@@ -72,14 +72,14 @@ public class DynamicScopes {
cx.exit();
}
}
static void runScripts(Context cx)
static void runScripts(Context cx)
throws JavaScriptException
{
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed. The call
// returns a new scope that we will share.
ScriptableObject scope = cx.initStandardObjects(null, true);
Scriptable scope = cx.initStandardObjects(null);
// Now we can evaluate a script and functions will be compiled to
// use dynamic scope if the Context is so initialized.
@@ -87,7 +87,7 @@ public class DynamicScopes {
"function f() { return x; }";
cx.evaluateString(scope, source, "MySource", 1, null);
// Now we spawn some threads that execute a script that calls the
// Now we spawn some threads that execute a script that calls the
// function 'f'. The scope chain looks like this:
// <pre>
// ------------------
@@ -105,7 +105,7 @@ public class DynamicScopes {
// ------------------
// </pre>
// Both the shared scope and the per-thread scope have variables 'x'
// defined in them. If 'f' is compiled with dynamic scope enabled,
// defined in them. If 'f' is compiled with dynamic scope enabled,
// the 'x' from the per-thread scope will be used. Otherwise, the 'x'
// from the shared scope will be used. The 'x' defined in 'g' (which
// calls 'f') should not be seen by 'f'.
@@ -114,12 +114,12 @@ public class DynamicScopes {
for (int i=0; i < threadCount; i++) {
String script = "function g() { var x = 'local'; return f(); }" +
"java.lang.System.out.println(g());";
t[i] = new Thread(new PerThread(scope, script,
t[i] = new Thread(new PerThread(scope, script,
"thread" + i));
}
for (int i=0; i < threadCount; i++)
t[i].start();
// Don't return in this thread until all the spawned threads have
// Don't return in this thread until all the spawned threads have
// completed.
for (int i=0; i < threadCount; i++) {
try {
@@ -128,15 +128,15 @@ public class DynamicScopes {
}
}
}
static class PerThread implements Runnable {
PerThread(Scriptable scope, String script, String x) {
this.scope = scope;
this.script = script;
this.x = x;
}
}
public void run() {
// We need a new Context for this thread.
Context cx = Context.enter();
@@ -144,18 +144,24 @@ public class DynamicScopes {
// We can share the scope.
Scriptable threadScope = cx.newObject(scope);
threadScope.setPrototype(scope);
// We want "threadScope" to be a new top-level
// scope, so set its parent scope to null. This
// We want "threadScope" to be a new top-level
// scope, so set its parent scope to null. This
// means that any variables created by assignments
// will be properties of "threadScope".
threadScope.setParentScope(null);
// Create a JavaScript property of the thread scope named
// 'x' and save a value for it.
threadScope.put("x", threadScope, x);
cx.evaluateString(threadScope, script, "threadScript", 1, null);
}
catch (NotAFunctionException jse) {
// ignore
}
catch (PropertyException jse) {
// ignore
}
catch (JavaScriptException jse) {
// ignore
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -64,7 +64,7 @@ import java.util.Vector;
* be wrapped as JavaScript exceptions when called from JavaScript,
* and may be caught within JavaScript.
*
* @author Norris Boyd
* @author Norris Boyd
*/
public class File extends ScriptableObject {
@@ -88,7 +88,7 @@ public class File extends ScriptableObject {
* to the use.
*/
public static Scriptable jsConstructor(Context cx, Object[] args,
Function ctorObj,
Function ctorObj,
boolean inNewExpr)
{
File result = new File();
@@ -143,8 +143,17 @@ public class File extends ScriptableObject {
v.copyInto(lines);
Scriptable scope = ScriptableObject.getTopLevelScope(this);
Context cx = Context.getCurrentContext();
return cx.newObject(scope, "Array", lines);
Scriptable result;
try {
Context cx = Context.getCurrentContext();
result = cx.newObject(scope, "Array", lines);
} catch (PropertyException e) {
throw Context.reportRuntimeError(e.getMessage());
} catch (NotAFunctionException e) {
throw Context.reportRuntimeError(e.getMessage());
}
return result;
}
/**

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the

View File

@@ -0,0 +1,59 @@
#! gmake
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is Rhino code, released
# May 6, 1998.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1999 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU Public License (the "GPL"), in which case the
# provisions of the GPL are applicable instead of those above.
# If you wish to allow use of your version of this file only
# under the terms of the GPL and not to allow others to use your
# version of this file under the NPL, indicate your decision by
# deleting the provisions above and replace them with the notice
# and other provisions required by the GPL. If you do not delete
# the provisions above, a recipient may use your version of this
# file under either the NPL or the GPL.
#
# Makefile for the examples directory.
#
# This Makefile just calls $(JAVAC) on all the .java files. This
# Makefile is intended to be called from the toplevel Makefile.
#
JSFILES = $(PATH_PREFIX)/*.js
SOURCES = $(PATH_PREFIX)/*.java
CLASSES = $(PATH_PREFIX)/*.class
$(CLASSES) : $(SOURCES)
$(JAVAC) $(JFLAGS) $(SOURCES)
clean :
- rm $(CLASSES) $(PATH_PREFIX)/MANIFEST
clobber : clean
check :
$(PATH_PREFIX)/MANIFEST : $(SOURCES) $(CLASSES) $(JSFILES)
ls $(SOURCES) $(CLASSES) $(JSFILES) \
> $(@)
# Emulate .PHONY
FORCE :

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -259,7 +259,7 @@ public class Matrix implements Scriptable {
public boolean hasInstance(Scriptable value) {
Scriptable proto = value.getPrototype();
while (proto != null) {
if (proto.equals(this))
if (proto.equals(this))
return true;
proto = proto.getPrototype();
}

View File

@@ -1,19 +1,7 @@
<html>
<body>
This is the NervousText applet in javascript:
<applet archive="js.jar" code=NervousText width=200 height=50 >
<applet code=NervousText.class width=200 height=50 >
</applet>
<hr>
The test assumes that applet code is generated with:
<pre>
java -classpath js.jar org.mozilla.javascript.tools.jsc.Main \
-extends java.applet.Applet \
-implements java.lang.Runnable \
NervousText.js
</pre>
and the resulting 2 classes, NervousText.class extending java.applet.Applet and implementing java.lang.Runnable and NervousText1.class which represents compiled JavaScript code, are placed in the same directory as NervousText.html.
<p>
The test also assumes that js.jar from Rhino distribution is available in the same directory.
</body>
</html>

View File

@@ -1,10 +1,10 @@
// The Java "NervousText" example ported to JavaScript.
// Compile using java org.mozilla.javascript.tools.jsc.Main -extends java.applet.Applet -implements java.lang.Runnable NervousText.js
/*
/*
Adapted from Java code by
Daniel Wyszynski
Center for Applied Large-Scale Computing (CALC)
04-12-95
Daniel Wyszynski
Center for Applied Large-Scale Computing (CALC)
04-12-95
Test of text animation.
@@ -23,7 +23,7 @@ var counter =0;
var threadSuspended = false; //added by kwalrath
function init() {
this.resize(150,50);
this.resize(150,50);
this.setFont(new Font("TimesRoman",Font.BOLD,36));
s = this.getParameter("text");
if (s == null) {
@@ -33,7 +33,7 @@ function init() {
}
function start() {
if(killme == null)
if(killme == null)
{
killme = new java.lang.Thread(java.lang.Runnable(this));
killme.start();
@@ -60,7 +60,7 @@ function paint(g) {
g.drawChars(separated, i,1,x_coord,y_coord);
}
}
/* Added by kwalrath. */
function mouseDown(evt, x, y) {
if (threadSuspended) {

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -36,41 +36,38 @@ import org.mozilla.javascript.*;
/**
* RunScript: simplest example of controlling execution of Rhino.
*
* Collects its arguments from the command line, executes the
*
* Collects its arguments from the command line, executes the
* script, and prints the result.
*
*
* @author Norris Boyd
*/
public class RunScript {
public static void main(String args[])
throws JavaScriptException
public static void main(String args[])
throws JavaScriptException
{
// Creates and enters a Context. The Context stores information
// about the execution environment of a script.
Context cx = Context.enter();
try {
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed. Returns
// a scope object that we use in later calls.
Scriptable scope = cx.initStandardObjects();
// Collect the arguments into a single string.
String s = "";
for (int i=0; i < args.length; i++) {
s += args[i];
}
// Now evaluate the string we've colected.
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
// Convert the result to a string and print it.
System.err.println(cx.toString(result));
} finally {
// Exit from the context.
Context.exit();
}
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed. Returns
// a scope object that we use in later calls.
Scriptable scope = cx.initStandardObjects(null);
// Collect the arguments into a single string.
String s = "";
for (int i=0; i < args.length; i++)
s += args[i];
// Now evaluate the string we've colected.
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
// Convert the result to a string and print it.
System.err.println(cx.toString(result));
// Exit from the context.
Context.exit();
}
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -36,31 +36,27 @@ import org.mozilla.javascript.*;
/**
* RunScript2: Like RunScript, but reflects the System.out into JavaScript.
*
*
* @author Norris Boyd
*/
public class RunScript2 {
public static void main(String args[])
throws JavaScriptException
public static void main(String args[])
throws JavaScriptException
{
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
Scriptable scope = cx.initStandardObjects(null);
// Add a global variable "out" that is a JavaScript reflection
// of System.out
Scriptable jsArgs = Context.toObject(System.out, scope);
scope.put("out", scope, jsArgs);
String s = "";
for (int i=0; i < args.length; i++) {
s += args[i];
}
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
System.err.println(cx.toString(result));
} finally {
Context.exit();
}
// Add a global variable "out" that is a JavaScript reflection
// of System.out
Scriptable jsArgs = Context.toObject(System.out, scope);
scope.put("out", scope, jsArgs);
String s = "";
for (int i=0; i < args.length; i++)
s += args[i];
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
System.err.println(cx.toString(result));
Context.exit();
}
}

View File

@@ -18,7 +18,7 @@
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -36,51 +36,45 @@ import org.mozilla.javascript.*;
/**
* RunScript3: Example of using JavaScript objects
*
* Collects its arguments from the command line, executes the
*
* Collects its arguments from the command line, executes the
* script, and then ...
*
*
* @author Norris Boyd
*/
public class RunScript3 {
public static void main(String args[])
throws JavaScriptException
public static void main(String args[])
throws JavaScriptException
{
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
Scriptable scope = cx.initStandardObjects(null);
// Collect the arguments into a single string.
String s = "";
for (int i=0; i < args.length; i++)
s += args[i];
// Now evaluate the string we've colected. We'll ignore the result.
cx.evaluateString(scope, s, "<cmd>", 1, null);
// Collect the arguments into a single string.
String s = "";
for (int i=0; i < args.length; i++) {
s += args[i];
}
// Print the value of variable "x"
Object x = scope.get("x", scope);
if (x == Scriptable.NOT_FOUND)
System.out.println("x is not defined.");
else
System.out.println("x = " + Context.toString(x));
// Now evaluate the string we've colected. We'll ignore the result.
cx.evaluateString(scope, s, "<cmd>", 1, null);
// Print the value of variable "x"
Object x = scope.get("x", scope);
if (x == Scriptable.NOT_FOUND) {
System.out.println("x is not defined.");
} else {
System.out.println("x = " + Context.toString(x));
}
// Call function "f('my arg')" and print its result.
Object fObj = scope.get("f", scope);
if (!(fObj instanceof Function)) {
System.out.println("f is undefined or not a function.");
} else {
Object functionArgs[] = { "my arg" };
Function f = (Function)fObj;
Object result = f.call(cx, scope, scope, functionArgs);
String report = "f('my args') = " + Context.toString(result);
System.out.println(report);
}
} finally {
Context.exit();
// Call function "f('my arg')" and print its result.
Object f = scope.get("f", scope);
if (!(f instanceof Function))
System.out.println("f is undefined or not a function.");
else {
Object functionArgs[] = { "my arg" };
Object result = ((Function) f).call(cx, scope, scope, functionArgs);
System.out.println("f('my args') = " + Context.toString(result));
}
Context.exit();
}
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -37,38 +37,34 @@ import org.mozilla.javascript.*;
/**
* RunScript4: Execute scripts in an environment that includes the
* example Counter class.
*
*
* @author Norris Boyd
*/
public class RunScript4 {
public static void main(String args[])
throws Exception
public static void main(String args[])
throws Exception
{
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
Scriptable scope = cx.initStandardObjects(null);
// Use the Counter class to define a Counter constructor
// and prototype in JavaScript.
ScriptableObject.defineClass(scope, Counter.class);
// Use the Counter class to define a Counter constructor
// and prototype in JavaScript.
ScriptableObject.defineClass(scope, Counter.class);
// Create an instance of Counter and assign it to
// the top-level variable "myCounter". This is
// equivalent to the JavaScript code
// myCounter = new Counter(7);
Object[] arg = { new Integer(7) };
Scriptable myCounter = cx.newObject(scope, "Counter", arg);
scope.put("myCounter", scope, myCounter);
String s = "";
for (int i=0; i < args.length; i++) {
s += args[i];
}
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
System.err.println(cx.toString(result));
} finally {
Context.exit();
}
// Create an instance of Counter and assign it to
// the top-level variable "myCounter". This is
// equivalent to the JavaScript code
// myCounter = new Counter(7);
Object[] arg = { new Integer(7) };
Scriptable myCounter = cx.newObject(scope, "Counter", arg);
scope.put("myCounter", scope, myCounter);
String s = "";
for (int i=0; i < args.length; i++)
s += args[i];
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
System.err.println(cx.toString(result));
Context.exit();
}
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -43,12 +43,7 @@ import java.io.*;
*
* @author Norris Boyd
*/
public class Shell extends ScriptableObject
{
public String getClassName()
{
return "global";
}
public class Shell extends ScriptableObject {
/**
* Main entry point.
@@ -61,40 +56,42 @@ public class Shell extends ScriptableObject
public static void main(String args[]) {
// Associate a new Context with this thread
Context cx = Context.enter();
// A bit of shorthand: since Shell extends ScriptableObject,
// we can make it the global object.
global = new Shell();
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed.
cx.initStandardObjects(global);
// Define some global functions particular to the shell. Note
// that these functions are not part of ECMA.
String[] names = { "print", "quit", "version", "load", "help" };
try {
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed.
Shell shell = new Shell();
cx.initStandardObjects(shell);
// Define some global functions particular to the shell. Note
// that these functions are not part of ECMA.
String[] names = { "print", "quit", "version", "load", "help" };
try {
shell.defineFunctionProperties(names, Shell.class,
ScriptableObject.DONTENUM);
} catch (PropertyException e) {
throw new Error(e.getMessage());
}
args = processOptions(cx, args);
// Set up "arguments" in the global scope to contain the command
// line arguments after the name of the script to execute
Object[] array = args;
if (args.length > 0) {
int length = args.length - 1;
array = new Object[length];
System.arraycopy(args, 1, array, 0, length);
}
Scriptable argsObj = cx.newArray(shell, array);
shell.defineProperty("arguments", argsObj,
ScriptableObject.DONTENUM);
shell.processSource(cx, args.length == 0 ? null : args[0]);
} finally {
Context.exit();
global.defineFunctionProperties(names, Shell.class,
ScriptableObject.DONTENUM);
} catch (PropertyException e) {
throw new Error(e.getMessage());
}
args = processOptions(cx, args);
// Set up "arguments" in the global scope to contain the command
// line arguments after the name of the script to execute
Object[] array = args;
if (args.length > 0) {
int length = args.length - 1;
array = new Object[length];
System.arraycopy(args, 1, array, 0, length);
}
Scriptable argsObj = cx.newArray(global, array);
global.defineProperty("arguments", argsObj,
ScriptableObject.DONTENUM);
processSource(cx, args.length == 0 ? null : args[0]);
cx.exit();
}
/**
@@ -123,13 +120,25 @@ public class Shell extends ScriptableObject
return new String[0];
}
/**
* Return name of this class, the global object.
*
* This method must be implemented in all concrete classes
* extending ScriptableObject.
*
* @see org.mozilla.javascript.Scriptable#getClassName
*/
public String getClassName() {
return "global";
}
/**
* Print a usage message.
*/
private static void usage(String s) {
public static void usage(String s) {
p("Didn't understand \"" + s + "\".");
p("Valid arguments are:");
p("-version 100|110|120|130|140|150");
p("-version 100|110|120|130");
System.exit(1);
}
@@ -138,7 +147,7 @@ public class Shell extends ScriptableObject
*
* This method is defined as a JavaScript function.
*/
public void help() {
public static void help(String s) {
p("");
p("Command Description");
p("======= ===========");
@@ -188,8 +197,7 @@ public class Shell extends ScriptableObject
*
* This method is defined as a JavaScript function.
*/
public void quit()
{
public static void quit() {
quitting = true;
}
@@ -218,9 +226,8 @@ public class Shell extends ScriptableObject
public static void load(Context cx, Scriptable thisObj,
Object[] args, Function funObj)
{
Shell shell = (Shell)getTopLevelScope(thisObj);
for (int i = 0; i < args.length; i++) {
shell.processSource(cx, cx.toString(args[i]));
for (int i=0; i < args.length; i++) {
processSource(cx, cx.toString(args[i]));
}
}
@@ -232,8 +239,7 @@ public class Shell extends ScriptableObject
* @param filename the name of the file to compile, or null
* for interactive mode.
*/
private void processSource(Context cx, String filename)
{
public static void processSource(Context cx, String filename) {
if (filename == null) {
BufferedReader in = new BufferedReader
(new InputStreamReader(System.in));
@@ -265,7 +271,7 @@ public class Shell extends ScriptableObject
if (cx.stringIsCompilableUnit(source))
break;
}
Object result = cx.evaluateString(this, source,
Object result = cx.evaluateString(global, source,
sourceName, startline,
null);
if (result != cx.getUndefinedValue()) {
@@ -309,7 +315,7 @@ public class Shell extends ScriptableObject
// Here we evalute the entire contents of the file as
// a script. Text is printed only if the print() function
// is called.
cx.evaluateReader(this, in, filename, 1, null);
cx.evaluateReader(global, in, filename, 1, null);
}
catch (WrappedException we) {
System.err.println(we.getWrappedException().toString());
@@ -340,6 +346,7 @@ public class Shell extends ScriptableObject
System.out.println(s);
}
private boolean quitting;
static Shell global;
static boolean quitting;
}

View File

@@ -1,7 +1,7 @@
/*
* SwingApplication.js - a translation into JavaScript of
* SwingApplication.java, a java.sun.com Swing example.
*
*
* @author Roger E Critchlow, Jr.
*/
@@ -14,13 +14,13 @@ function createComponents() {
var numClicks = 0;
var label = new JLabel(labelPrefix + numClicks);
var button = new JButton("I'm a Swing button!");
button.mnemonic = KeyEvent.VK_I;
// Since Rhino 1.5R5 JS functions can be passed to Java method if
// corresponding argument type is Java interface with single method.
button.addActionListener(function() {
numClicks += 1;
label.setText(labelPrefix + numClicks);
});
button.setMnemonic(KeyEvent.VK_I);
button.addActionListener(new ActionListener({
actionPerformed : function() {
numClicks += 1;
label.setText(labelPrefix + numClicks);
}
}));
label.setLabelFor(button);
/*
@@ -29,10 +29,12 @@ function createComponents() {
* that has an "empty" border.
*/
var pane = new JPanel();
pane.border = BorderFactory.createEmptyBorder(30, //top
30, //left
10, //bottom
30); //right
pane.setBorder(BorderFactory.createEmptyBorder(
30, //top
30, //left
10, //bottom
30) //right
);
pane.setLayout(new GridLayout(0, 1));
pane.add(button);
pane.add(label);

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -38,7 +38,7 @@
*
* The files given as arguments on the command line are assumed to be
* Java source code files. This program checks to see that the @param
* tags in the documentation comments match with the parameters for
* tags in the documentation comments match with the parameters for
* the associated Java methods.
* <p>
* Any errors found are reported.
@@ -54,12 +54,12 @@ function stringEndsWith(str, suffix) {
/**
* Perform processing once the end of a documentation comment is seen.
*
* Look for a parameter list following the end of the comment and
* Look for a parameter list following the end of the comment and
* collect the parameters and compare to the @param entries.
* Report any discrepancies.
* @param f the current file
* @param a an array of parameters from @param comments
* @param line the string containing the comment end (in case the
* @param line the string containing the comment end (in case the
* parameters are on the same line)
*/
function processCommentEnd(f, a, line) {
@@ -72,14 +72,14 @@ function processCommentEnd(f, a, line) {
var m = line.match(/\(([^\)]+)\)/);
var args = m ? m[1].split(",") : [];
if (a.length != args.length) {
print('"' + f.name +
print('"' + f.name +
'"; line ' + f.lineNumber +
' mismatch: had a different number' +
' of @param entries and parameters.');
} else {
for (var i=0; i < a.length; i++) {
if (!stringEndsWith(args[i], a[i])) {
print('"' + f.name +
print('"' + f.name +
'"; line ' + f.lineNumber +
' mismatch: had "' + a[i] +
'" and "' + args[i] + '".');
@@ -88,9 +88,9 @@ function processCommentEnd(f, a, line) {
}
}
}
/**
* Process the given file, looking for mismatched @param lists and
* Process the given file, looking for mismatched @param lists and
* parameter lists.
* @param f the file to process
*/
@@ -104,11 +104,11 @@ function processFile(f) {
if (line.match(/@param/)) {
while (m = line.match(/@param[ ]+([^ ]+)/)) {
a[i++] = m[1];
line = f.readLine();
line = f.readLine();
if (line == null)
break outer;
}
}
}
if (i != 0 && line.match(/\*\//)) {
processCommentEnd(f, a, line);
i = 0;
@@ -116,7 +116,7 @@ function processFile(f) {
}
}
if (i != 0) {
print('"' + f.name +
print('"' + f.name +
'"; line ' + f.lineNumber +
' missing parameters at end of file.');
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -35,10 +35,10 @@
/*
enum.js
Implementing the interface java.util.Enumeration using the new syntax.
Note that this syntax is experimental only, and hasn't been approved
by ECMA.
by ECMA.
The same functionality can be had without the new syntax using the
uglier syntax:
@@ -47,7 +47,7 @@
hasMoreElements: function ...
nextElement: function ...
});
by Patrick C. Beard.
*/

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -40,7 +40,7 @@
* @author Norris Boyd
* @see rhinotip.jar
* @lastmodified xx
* @version 1.2 Roland Pennings: Allow multiple files for a function.
* @version 1.2 Roland Pennings: Allow multiple files for a function.
* @version 1.3 Roland Pennings: Removes ../.. from the input directory name
*/
defineClass("File")
@@ -61,7 +61,7 @@ var debug = 0;
/**
* Process JavaScript source file <code>f</code>, writing jsdoc to
* Process JavaScript source file <code>f</code>, writing jsdoc to
* file <code>out</code>.
* @param f input file
* @param fname name of the input file (without the path)
@@ -72,11 +72,11 @@ function processFile(f, fname, inputdir, out) {
var s;
var firstLine = true;
indexFileArray[fname] = "";
// write the header of the output file
out.writeLine('<HTML><HEADER><TITLE>' + fname + '</TITLE><BODY>');
if (inputdir != null) {
outstr = '<a name=\"_top_\"></a><pre><a href=\"' + indexFile + '\">Index Files</a> ';
outstr = '<a name=\"_top_\"></a><pre><a href=\"' + indexFile + '\">Index Files</a> ';
outstr += '<a href=\"' + indexFunction + '\">Index Functions</a></pre><hr>';
out.writeLine(outstr);
}
@@ -98,7 +98,7 @@ function processFile(f, fname, inputdir, out) {
// Strip leading whitespace and "*".
comment += s.replace(/^\s*\*/, "");
s = f.readLine();
} while (s != null);
} while (s != null);
if (debug)
print("Found comment " + comment);
@@ -116,7 +116,7 @@ function processFile(f, fname, inputdir, out) {
// match the beginning of the function
// NB we also match functions without a comment!
// if we have two comments one after another only the last one will be taken
m = s.match(/^\s*function\s+((\w+)|(\w+)(\s+))\(([^)]*)\)/);
m = s.match(/^\s*function\s+((\w+)|(\w+)(\s+))\(([^)]*)\)/);
if (m != null)
{
// Found a function start
@@ -126,7 +126,7 @@ function processFile(f, fname, inputdir, out) {
// can write out a table of contents first.
functionDocArray[functionDocArray.length] = {name:m[1], text:htmlText};
// Store the function also in the indexFunctionArray
// Store the function also in the indexFunctionArray
// so we can have a seperate file with the function table of contents
if (indexFunctionArray[m[1]]) {
// print("ERROR: function: " + m[1] + " is defined more than once!");
@@ -135,25 +135,25 @@ function processFile(f, fname, inputdir, out) {
filename = filename + "|" + fname;
// print("filename = " + filename);
}
}
}
else {
indexFunctionArray[m[1]] = {filename:fname};
}
//reset comment
//reset comment
comment = "";
}
}
// match a method being bound to a prototype
m = s.match(/^\s*(\w*)\.prototype\.(\w*)\s*=\s*function\s*\(([^)]*)\)/);
if (m != null)
{
// Found a method being bound to a prototype.
// Found a method being bound to a prototype.
var htmlText = processPrototypeMethod(m[1], m[2], m[3], comment);
// Save the text in a global variable, so we
// can write out a table of contents first.
functionDocArray[functionDocArray.length] = {name:m[1]+".prototype."+m[2], text:htmlText};
// Store the function also in the indexFunctionArray
// Store the function also in the indexFunctionArray
// so we can have a seperate file with the function table of contents
if (indexFunctionArray[m[1]]) {
// print("ERROR: function: " + m[1] + " is defined more than once!");
@@ -162,15 +162,15 @@ function processFile(f, fname, inputdir, out) {
filename = filename + "|" + fname;
// print("filename = " + filename);
}
}
}
else {
indexFunctionArray[m[1]] = {filename:fname};
}
//reset comment
//reset comment
comment = "";
}
}
firstLine = false;
}
@@ -193,7 +193,7 @@ function processFile(f, fname, inputdir, out) {
out.writeLine('</BODY></HTML>');
// Now clean up the doc array
functionDocArray = [];
functionDocArray = [];
}
/**
@@ -215,7 +215,7 @@ function processFunction(name, args, comment) {
}
/**
* Process a method being bound to a prototype.
* Process a method being bound to a prototype.
* @param proto the name of the prototype
* @param name the name of the function
* @param args the args of the function as a single string
@@ -244,11 +244,11 @@ function processPrototypeMethod(proto, name, args, comment) {
function processComment(comment,firstLine,fname) {
var tags = {};
// Use the "lambda" form of regular expression replace,
// where the replacement object is a function rather
// than a string. The function is called with the
// where the replacement object is a function rather
// than a string. The function is called with the
// matched text and any parenthetical matches as
// arguments, and the result of the function used as the
// replacement text.
// replacement text.
// Here we use the function to build up the "tags" object,
// which has a property for each "@" tag that is the name
// of the tag, and whose value is an array of the
@@ -260,9 +260,9 @@ function processComment(comment,firstLine,fname) {
tags[name] = a;
return "";
});
// if we have a comment at the beginning of a file
// store the comment for the index file
// store the comment for the index file
if (firstLine) {
indexFileArray[fname] = comment;
}
@@ -274,7 +274,7 @@ function processComment(comment,firstLine,fname) {
var params = "";
for (var i=0; i < array.length; i++) {
var m = array[i].match(/(\w+)\s+(.*)/);
params += '<TR><TD><I>'+m[1]+'</I></TD>' +
params += '<TR><TD><I>'+m[1]+'</I></TD>' +
'<TD>'+m[2]+'</TD></TR>';
}
out += '<TABLE WIDTH="90%" BORDER=1>';
@@ -326,7 +326,7 @@ function processComment(comment,firstLine,fname) {
out += '<DT><B>Last modified:</B><DD>';
out += '<script><!--\n';
out += 'document.writeln(document.lastModified);\n';
out += '// ---></script>\n';
out += '// ---></script>\n';
out += '</DL><P>';
}
@@ -338,9 +338,9 @@ function processComment(comment,firstLine,fname) {
* Create an html output file
* @param outputdir directory to put the file
* @param htmlfile name of the file
*/
*/
function CreateOutputFile(outputdir,htmlfile)
{
{
if (outputdir==null)
{
var outname = htmlfile;
@@ -355,18 +355,18 @@ function CreateOutputFile(outputdir,htmlfile)
}
/**
* Process a javascript file. Puts the generated HTML file in the outdir
* Process a javascript file. Puts the generated HTML file in the outdir
* @param filename name of the javascript file
* @inputdir input directory of the file (default null)
*/
function processJSFile(filename,inputdir)
function processJSFile(filename,inputdir)
{
if (debug) print("filename = " + filename + " inputdir = " + inputdir);
if (!filename.match(/\.js$/)) {
print("Expected filename to end in '.js'; had instead " +
if (!filename.match(/\.js$/)) {
print("Expected filename to end in '.js'; had instead " +
filename + ". I don't treat the file.");
} else {
} else {
if (inputdir==null)
{
var inname = filename;
@@ -379,12 +379,12 @@ function processJSFile(filename,inputdir)
print("Processing file " + inname);
var f = new File(inname);
// create the output file
var htmlfile = filename.replace(/\.js$/, ".html");
var out = CreateOutputFile(outputdir,htmlfile);
processFile(f, filename, inputdir, out);
out.close();
}
@@ -398,7 +398,7 @@ function GenerateIndex(dirname)
{
// construct the files index file
var out = CreateOutputFile(outputdir,indexFile);
// write the beginning of the file
out.writeLine('<HTML><HEADER><TITLE>File Index - directory: ' + dirname + '</TITLE><BODY>');
out.writeLine('<H1>File Index - directory: ' + dirname + '</H1>\n');
@@ -412,7 +412,7 @@ function GenerateIndex(dirname)
// sort the index file array
var SortedFileArray = [];
for (var fname in indexFileArray)
SortedFileArray.push(fname);
SortedFileArray.push(fname);
SortedFileArray.sort();
for (var i=0; i < SortedFileArray.length; i++) {
@@ -427,10 +427,10 @@ function GenerateIndex(dirname)
}
out.writeLine('</TABLE></BODY></HTML>');
out.close();
// construct the functions index file
var out = CreateOutputFile(outputdir,indexFunction);
// write the beginning of the file
out.writeLine('<HTML><HEADER><TITLE>Function Index - directory: ' + dirname + '</TITLE><BODY>');
out.writeLine('<H1>Function Index - directory: ' + dirname + '</H1>\n');
@@ -438,11 +438,11 @@ function GenerateIndex(dirname)
out.writeLine('<TR BGCOLOR=0xdddddddd>');
out.writeLine('<TD><B>Function</B></TD>');
out.writeLine('<TD><B>Files</B></TD></TR>');
// sort the function array
var SortedFunctionArray = [];
for (var functionname in indexFunctionArray)
SortedFunctionArray.push(functionname);
SortedFunctionArray.push(functionname);
SortedFunctionArray.sort();
for (var j=0; j < SortedFunctionArray.length; j++) {
@@ -476,10 +476,10 @@ function PrintOptions()
// Main Script
// first read the arguments
// first read the arguments
if (! arguments)
PrintOptions();
for (var i=0; i < arguments.length; i++) {
if (debug) print("argument: + \'" + arguments[i] + "\'");
if (arguments[i].match(/^\-/)) {
@@ -489,7 +489,7 @@ for (var i=0; i < arguments.length; i++) {
outputdir = String(arguments[i+1]);
if (debug) print("outputdir: + \'" + outputdir + "\'");
i++;
i++;
}
else if (String(arguments[i])=="-i"){
// process all files in an input directory
@@ -510,16 +510,16 @@ if (debug) print("inputdir: + \'" + arguments[i+1] + "\'");
FileList.push(String(arguments[i]));
}
}
}
// first handle the single files
for (var i in FileList)
for (var i in FileList)
processJSFile(FileList[i],null);
// then handle the input directories
for (var j in DirList) {
var inputdir = String(DirList[j]);
print("Process input directory: " + inputdir);
// clean up index arrays
@@ -528,13 +528,13 @@ for (var j in DirList) {
// for the directory name get rid of ../../ or ..\..\
inputDirName = inputdir.replace(/\.\.\/|\.\.\\/g,"");
indexFile = indexFileName + "_" + inputDirName + ".html";
indexFunction = indexFunctionName + "_" + inputDirName + ".html";
print("indexFile = " + indexFile);
print("indexFunction = " + indexFunction);
// read the files in the directory
var DirFile = new java.io.File(inputdir);
var lst = DirFile.list();
@@ -543,7 +543,7 @@ print("indexFunction = " + indexFunction);
for (var i=0; i < lst.length; i++)
{
processJSFile(String(lst[i]),inputdir);
}
}
// generate the index files for the input directory
GenerateIndex(inputDirName);

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -38,7 +38,7 @@
*/
// Create a new StringBuffer. Note that the class name must be fully qualified
// by its package. Packages other than "java" must start with "Packages", i.e.,
// by its package. Packages other than "java" must start with "Packages", i.e.,
// "Packages.javax.servlet...".
var sb = new java.lang.StringBuffer();
@@ -51,4 +51,4 @@ sb.append(true);
// Now print it out. (The toString() method of sb is automatically called
// to convert the buffer to a string.)
// Should print "hi, mom3.0true".
print(sb);
print(sb);

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -37,7 +37,7 @@
defineClass("File")
// "arguments[0]" refers to the first argument at the command line to the
// "arguments[0]" refers to the first argument at the command line to the
// script, if present. If not present, "arguments[0]" will be undefined,
// which will cause f to read from System.in.
var f = new File(arguments[0]);
@@ -50,4 +50,4 @@ while ((line = f.readLine()) != null) {
}
for (i in o) {
print(i);
}
}

View File

@@ -1,41 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
<!--
Build file for Rhino using Ant (see http://jakarta.apache.org/ant/index.html)
Requires Ant version 1.2
-->
<project name="src" default="compile" basedir=".">
<project name="src" default="build" basedir=".">
<target name="properties">
<property name="nest" value=".."/>
<property name="build.dir" value="./build"/>
<property name="classes" value="${build.dir}/classes"/>
<property name="nest" value=".."/>
</target>
<target name="compile" depends="properties">
<javac srcdir="."
destdir="${nest}/${classes}"
destdir="${nest}/${build.dest}"
includes="org/**/*.java"
deprecation="on"
debug="${debug}">
</javac>
<copy todir="${nest}/${classes}">
</target>
<target name="copy-properties">
<copy todir="${nest}/${build.dest}">
<fileset dir="." includes="org/**/*.properties" />
</copy>
</target>
<target name="copy-source" depends="properties">
<target name="copy-source">
<copy todir="${nest}/${dist.src}">
<fileset dir="."
includes="org/**/*.java,org/**/*.properties,build.xml,manifest"/>
</copy>
</target>
<target name="clean" depends="properties">
<delete includeEmptyDirs="true">
<fileset dir="${nest}/${classes}"
excludes="org/mozilla/javascript/tools/**"/>
</delete>
</target>
<target name="build" depends="compile,copy-properties,copy-source"/>
</project>

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
@@ -37,9 +37,9 @@ package org.mozilla.classfile;
/**
* This class provides opcode values expected by the JVM in Java class files.
*
*
* It also provides tables for internal use by the ClassFileWriter.
*
*
* @author Roger Lawrence
*/
public class ByteCode {
@@ -234,6 +234,7 @@ public class ByteCode {
INVOKESPECIAL = (byte)0xB7,
INVOKESTATIC = (byte)0xB8,
INVOKEINTERFACE = (byte)0xB9,
XXXUNUSEDXXX = (byte)0xBA,
NEW = (byte)0xBB,
NEWARRAY = (byte)0xBC,
ANEWARRAY = (byte)0xBD,
@@ -250,11 +251,37 @@ public class ByteCode {
GOTO_W = (byte)0xC8,
JSR_W = (byte)0xC9,
BREAKPOINT = (byte)0xCA,
LDC_QUICK = (byte)0xCB,
LDC_W_QUICK = (byte)0xCC,
LDC2_W_QUICK = (byte)0xCD,
GETFIELD_QUICK = (byte)0xCE,
PUTFIELD_QUICK = (byte)0xCF,
GETFIELD2_QUICK = (byte)0xD0,
PUTFIELD2_QUICK = (byte)0xD1,
GETSTATIC_QUICK = (byte)0xD2,
PUTSTATIC_QUICK = (byte)0xD3,
GETSTATIC2_QUICK = (byte)0xD4,
PUTSTATIC2_QUICK = (byte)0xD5,
INVOKEVIRTUAL_QUICK = (byte)0xD6,
INVOKENONVIRTUAL_QUICK = (byte)0xD7,
INVOKESUPER_QUICK = (byte)0xD8,
INVOKESTATIC_QUICK = (byte)0xD9,
INVOKEINTERFACE_QUICK = (byte)0xDA,
INVOKEVIRTUALOBJECT_QUICK = (byte)0xDB,
NEW_QUICK = (byte)0xDD,
ANEWARRAY_QUICK = (byte)0xDE,
MULTIANEWARRAY_QUICK = (byte)0xDF,
CHECKCAST_QUICK = (byte)0xE0,
INSTANCEOF_QUICK = (byte)0xE1,
INVOKEVIRTUAL_QUICK_W = (byte)0xE2,
GETFIELD_QUICK_W = (byte)0xE3,
PUTFIELD_QUICK_W = (byte)0xE4,
IMPDEP1 = (byte)0xFE,
IMPDEP2 = (byte)0xFF;
/**
/**
* Types for the NEWARRAY opcode.
*/
public static final byte
@@ -267,5 +294,789 @@ public class ByteCode {
T_INT = 10,
T_LONG = 11;
/**
* Number of bytes of operands generated after the opcode.
*/
static final byte[] extra = {
/* NOP */ 0,
/* ACONST_NULL */ 0,
/* ICONST_M1 */ 0,
/* ICONST_0 */ 0,
/* ICONST_1 */ 0,
/* ICONST_2 */ 0,
/* ICONST_3 */ 0,
/* ICONST_4 */ 0,
/* ICONST_5 */ 0,
/* LCONST_0 */ 0,
/* LCONST_1 */ 0,
/* FCONST_0 */ 0,
/* FCONST_1 */ 0,
/* FCONST_2 */ 0,
/* DCONST_0 */ 0,
/* DCONST_1 */ 0,
/* BIPUSH */ 1,
/* SIPUSH */ 2,
/* LDC */ 1,
/* LDC_W */ 2,
/* LDC2_W */ 2,
/* ILOAD */ 1,
/* LLOAD */ 1,
/* FLOAD */ 1,
/* DLOAD */ 1,
/* ALOAD */ 1,
/* ILOAD_0 */ 0,
/* ILOAD_1 */ 0,
/* ILOAD_2 */ 0,
/* ILOAD_3 */ 0,
/* LLOAD_0 */ 0,
/* LLOAD_1 */ 0,
/* LLOAD_2 */ 0,
/* LLOAD_3 */ 0,
/* FLOAD_0 */ 0,
/* FLOAD_1 */ 0,
/* FLOAD_2 */ 0,
/* FLOAD_3 */ 0,
/* DLOAD_0 */ 0,
/* DLOAD_1 */ 0,
/* DLOAD_2 */ 0,
/* DLOAD_3 */ 0,
/* ALOAD_0 */ 0,
/* ALOAD_1 */ 0,
/* ALOAD_2 */ 0,
/* ALOAD_3 */ 0,
/* IALOAD */ 0,
/* LALOAD */ 0,
/* FALOAD */ 0,
/* DALOAD */ 0,
/* AALOAD */ 0,
/* BALOAD */ 0,
/* CALOAD */ 0,
/* SALOAD */ 0,
/* ISTORE */ 1,
/* LSTORE */ 1,
/* FSTORE */ 1,
/* DSTORE */ 1,
/* ASTORE */ 1,
/* ISTORE_0 */ 0,
/* ISTORE_1 */ 0,
/* ISTORE_2 */ 0,
/* ISTORE_3 */ 0,
/* LSTORE_0 */ 0,
/* LSTORE_1 */ 0,
/* LSTORE_2 */ 0,
/* LSTORE_3 */ 0,
/* FSTORE_0 */ 0,
/* FSTORE_1 */ 0,
/* FSTORE_2 */ 0,
/* FSTORE_3 */ 0,
/* DSTORE_0 */ 0,
/* DSTORE_1 */ 0,
/* DSTORE_2 */ 0,
/* DSTORE_3 */ 0,
/* ASTORE_0 */ 0,
/* ASTORE_1 */ 0,
/* ASTORE_2 */ 0,
/* ASTORE_3 */ 0,
/* IASTORE */ 0,
/* LASTORE */ 0,
/* FASTORE */ 0,
/* DASTORE */ 0,
/* AASTORE */ 0,
/* BASTORE */ 0,
/* CASTORE */ 0,
/* SASTORE */ 0,
/* POP */ 0,
/* POP2 */ 0,
/* DUP */ 0,
/* DUP_X1 */ 0,
/* DUP_X2 */ 0,
/* DUP2 */ 0,
/* DUP2_X1 */ 0,
/* DUP2_X2 */ 0,
/* SWAP */ 0,
/* IADD */ 0,
/* LADD */ 0,
/* FADD */ 0,
/* DADD */ 0,
/* ISUB */ 0,
/* LSUB */ 0,
/* FSUB */ 0,
/* DSUB */ 0,
/* IMUL */ 0,
/* LMUL */ 0,
/* FMUL */ 0,
/* DMUL */ 0,
/* IDIV */ 0,
/* LDIV */ 0,
/* FDIV */ 0,
/* DDIV */ 0,
/* IREM */ 0,
/* LREM */ 0,
/* FREM */ 0,
/* DREM */ 0,
/* INEG */ 0,
/* LNEG */ 0,
/* FNEG */ 0,
/* DNEG */ 0,
/* ISHL */ 0,
/* LSHL */ 0,
/* ISHR */ 0,
/* LSHR */ 0,
/* IUSHR */ 0,
/* LUSHR */ 0,
/* IAND */ 0,
/* LAND */ 0,
/* IOR */ 0,
/* LOR */ 0,
/* IXOR */ 0,
/* LXOR */ 0,
/* IINC */ 2,
/* I2L */ 0,
/* I2F */ 0,
/* I2D */ 0,
/* L2I */ 0,
/* L2F */ 0,
/* L2D */ 0,
/* F2I */ 0,
/* F2L */ 0,
/* F2D */ 0,
/* D2I */ 0,
/* D2L */ 0,
/* D2F */ 0,
/* I2B */ 0,
/* I2C */ 0,
/* I2S */ 0,
/* LCMP */ 0,
/* FCMPL */ 0,
/* FCMPG */ 0,
/* DCMPL */ 0,
/* DCMPG */ 0,
/* IFEQ */ 2,
/* IFNE */ 2,
/* IFLT */ 2,
/* IFGE */ 2,
/* IFGT */ 2,
/* IFLE */ 2,
/* IF_ICMPEQ */ 2,
/* IF_ICMPNE */ 2,
/* IF_ICMPLT */ 2,
/* IF_ICMPGE */ 2,
/* IF_ICMPGT */ 2,
/* IF_ICMPLE */ 2,
/* IF_ACMPEQ */ 2,
/* IF_ACMPNE */ 2,
/* GOTO */ 2,
/* JSR */ 2,
/* RET */ 1,
/* TABLESWITCH */ -1, // depends on alignment
/* LOOKUPSWITCH */ -1, // depends on alignment
/* IRETURN */ 0,
/* LRETURN */ 0,
/* FRETURN */ 0,
/* DRETURN */ 0,
/* ARETURN */ 0,
/* RETURN */ 0,
/* GETSTATIC */ 2,
/* PUTSTATIC */ 2,
/* GETFIELD */ 2,
/* PUTFIELD */ 2,
/* INVOKEVIRTUAL */ 2,
/* INVOKESPECIAL */ 2,
/* INVOKESTATIC */ 2,
/* INVOKEINTERFACE */ 2,
/* XXXUNUSEDXXX */ 0,
/* NEW */ 2,
/* NEWARRAY */ 1,
/* ANEWARRAY */ 2,
/* ARRAYLENGTH */ 0,
/* ATHROW */ 0,
/* CHECKCAST */ 2,
/* INSTANCEOF */ 2,
/* MONITORENTER */ 0,
/* MONITOREXIT */ 0,
/* WIDE */ 0,
/* MULTIANEWARRAY */ 3,
/* IFNULL */ 2,
/* IFNONNULL */ 2,
/* GOTO_W */ 4,
/* JSR_W */ 4,
/* BREAKPOINT */ 0,
/* LDC_QUICK */ 1,
/* LDC_W_QUICK */ 2,
/* LDC2_W_QUICK */ 2,
/* GETFIELD_QUICK */ 2,
/* PUTFIELD_QUICK */ 2,
/* GETFIELD2_QUICK */ 2,
/* PUTFIELD2_QUICK */ 2,
/* GETSTATIC_QUICK */ 2,
/* PUTSTATIC_QUICK */ 2,
/* GETSTATIC2_QUICK */ 2,
/* PUTSTATIC2_QUICK */ 2,
/* INVOKEVIRTUAL_QUICK */ 2,
/* INVOKENONVIRTUAL_QUICK */ 2,
/* INVOKESUPER_QUICK */ 2,
/* INVOKESTATIC_QUICK */ 2,
/* INVOKEINTERFACE_QUICK */ 2,
/* INVOKEVIRTUALOBJECT_QUICK */ 2,
/* XXXUNUSEDXXX */ 0,
/* NEW_QUICK */ 2,
/* ANEWARRAY_QUICK */ 2,
/* MULTIANEWARRAY_QUICK */ 3,
/* CHECKCAST_QUICK */ 2,
/* INSTANCEOF_QUICK */ 2,
/* INVOKEVIRTUAL_QUICK_W */ 0,
/* GETFIELD_QUICK_W */ 2,
/* PUTFIELD_QUICK_W */ 2,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* IMPDEP1 */ 0,
/* IMPDEP2 */ 0
};
/**
* Number of operands accompanying the opcode.
*/
static final byte[] opcodeCount = {
/* NOP */ 0,
/* ACONST_NULL */ 0,
/* ICONST_M1 */ 0,
/* ICONST_0 */ 0,
/* ICONST_1 */ 0,
/* ICONST_2 */ 0,
/* ICONST_3 */ 0,
/* ICONST_4 */ 0,
/* ICONST_5 */ 0,
/* LCONST_0 */ 0,
/* LCONST_1 */ 0,
/* FCONST_0 */ 0,
/* FCONST_1 */ 0,
/* FCONST_2 */ 0,
/* DCONST_0 */ 0,
/* DCONST_1 */ 0,
/* BIPUSH */ 1,
/* SIPUSH */ 1,
/* LDC */ 1,
/* LDC_W */ 1,
/* LDC2_W */ 1,
/* ILOAD */ 1,
/* LLOAD */ 1,
/* FLOAD */ 1,
/* DLOAD */ 1,
/* ALOAD */ 1,
/* ILOAD_0 */ 0,
/* ILOAD_1 */ 0,
/* ILOAD_2 */ 0,
/* ILOAD_3 */ 0,
/* LLOAD_0 */ 0,
/* LLOAD_1 */ 0,
/* LLOAD_2 */ 0,
/* LLOAD_3 */ 0,
/* FLOAD_0 */ 0,
/* FLOAD_1 */ 0,
/* FLOAD_2 */ 0,
/* FLOAD_3 */ 0,
/* DLOAD_0 */ 0,
/* DLOAD_1 */ 0,
/* DLOAD_2 */ 0,
/* DLOAD_3 */ 0,
/* ALOAD_0 */ 0,
/* ALOAD_1 */ 0,
/* ALOAD_2 */ 0,
/* ALOAD_3 */ 0,
/* IALOAD */ 0,
/* LALOAD */ 0,
/* FALOAD */ 0,
/* DALOAD */ 0,
/* AALOAD */ 0,
/* BALOAD */ 0,
/* CALOAD */ 0,
/* SALOAD */ 0,
/* ISTORE */ 1,
/* LSTORE */ 1,
/* FSTORE */ 1,
/* DSTORE */ 1,
/* ASTORE */ 1,
/* ISTORE_0 */ 0,
/* ISTORE_1 */ 0,
/* ISTORE_2 */ 0,
/* ISTORE_3 */ 0,
/* LSTORE_0 */ 0,
/* LSTORE_1 */ 0,
/* LSTORE_2 */ 0,
/* LSTORE_3 */ 0,
/* FSTORE_0 */ 0,
/* FSTORE_1 */ 0,
/* FSTORE_2 */ 0,
/* FSTORE_3 */ 0,
/* DSTORE_0 */ 0,
/* DSTORE_1 */ 0,
/* DSTORE_2 */ 0,
/* DSTORE_3 */ 0,
/* ASTORE_0 */ 0,
/* ASTORE_1 */ 0,
/* ASTORE_2 */ 0,
/* ASTORE_3 */ 0,
/* IASTORE */ 0,
/* LASTORE */ 0,
/* FASTORE */ 0,
/* DASTORE */ 0,
/* AASTORE */ 0,
/* BASTORE */ 0,
/* CASTORE */ 0,
/* SASTORE */ 0,
/* POP */ 0,
/* POP2 */ 0,
/* DUP */ 0,
/* DUP_X1 */ 0,
/* DUP_X2 */ 0,
/* DUP2 */ 0,
/* DUP2_X1 */ 0,
/* DUP2_X2 */ 0,
/* SWAP */ 0,
/* IADD */ 0,
/* LADD */ 0,
/* FADD */ 0,
/* DADD */ 0,
/* ISUB */ 0,
/* LSUB */ 0,
/* FSUB */ 0,
/* DSUB */ 0,
/* IMUL */ 0,
/* LMUL */ 0,
/* FMUL */ 0,
/* DMUL */ 0,
/* IDIV */ 0,
/* LDIV */ 0,
/* FDIV */ 0,
/* DDIV */ 0,
/* IREM */ 0,
/* LREM */ 0,
/* FREM */ 0,
/* DREM */ 0,
/* INEG */ 0,
/* LNEG */ 0,
/* FNEG */ 0,
/* DNEG */ 0,
/* ISHL */ 0,
/* LSHL */ 0,
/* ISHR */ 0,
/* LSHR */ 0,
/* IUSHR */ 0,
/* LUSHR */ 0,
/* IAND */ 0,
/* LAND */ 0,
/* IOR */ 0,
/* LOR */ 0,
/* IXOR */ 0,
/* LXOR */ 0,
/* IINC */ 2,
/* I2L */ 0,
/* I2F */ 0,
/* I2D */ 0,
/* L2I */ 0,
/* L2F */ 0,
/* L2D */ 0,
/* F2I */ 0,
/* F2L */ 0,
/* F2D */ 0,
/* D2I */ 0,
/* D2L */ 0,
/* D2F */ 0,
/* I2B */ 0,
/* I2C */ 0,
/* I2S */ 0,
/* LCMP */ 0,
/* FCMPL */ 0,
/* FCMPG */ 0,
/* DCMPL */ 0,
/* DCMPG */ 0,
/* IFEQ */ 1,
/* IFNE */ 1,
/* IFLT */ 1,
/* IFGE */ 1,
/* IFGT */ 1,
/* IFLE */ 1,
/* IF_ICMPEQ */ 1,
/* IF_ICMPNE */ 1,
/* IF_ICMPLT */ 1,
/* IF_ICMPGE */ 1,
/* IF_ICMPGT */ 1,
/* IF_ICMPLE */ 1,
/* IF_ACMPEQ */ 1,
/* IF_ACMPNE */ 1,
/* GOTO */ 1,
/* JSR */ 1,
/* RET */ 1,
/* TABLESWITCH */ -1,
/* LOOKUPSWITCH */ -1,
/* IRETURN */ 0,
/* LRETURN */ 0,
/* FRETURN */ 0,
/* DRETURN */ 0,
/* ARETURN */ 0,
/* RETURN */ 0,
/* GETSTATIC */ 1,
/* PUTSTATIC */ 1,
/* GETFIELD */ 1,
/* PUTFIELD */ 1,
/* INVOKEVIRTUAL */ 1,
/* INVOKESPECIAL */ 1,
/* INVOKESTATIC */ 1,
/* INVOKEINTERFACE */ 1,
/* XXXUNUSEDXXX */ 0,
/* NEW */ 1,
/* NEWARRAY */ 1,
/* ANEWARRAY */ 1,
/* ARRAYLENGTH */ 0,
/* ATHROW */ 0,
/* CHECKCAST */ 1,
/* INSTANCEOF */ 1,
/* MONITORENTER */ 0,
/* MONITOREXIT */ 0,
/* WIDE */ 0,
/* MULTIANEWARRAY */ 2,
/* IFNULL */ 1,
/* IFNONNULL */ 1,
/* GOTO_W */ 1,
/* JSR_W */ 1,
/* BREAKPOINT */ 0,
/* LDC_QUICK */ -1,
/* LDC_W_QUICK */ -1,
/* LDC2_W_QUICK */ -1,
/* GETFIELD_QUICK */ -1,
/* PUTFIELD_QUICK */ -1,
/* GETFIELD2_QUICK */ -1,
/* PUTFIELD2_QUICK */ -1,
/* GETSTATIC_QUICK */ -1,
/* PUTSTATIC_QUICK */ -1,
/* GETSTATIC2_QUICK */ -1,
/* PUTSTATIC2_QUICK */ -1,
/* INVOKEVIRTUAL_QUICK */ -1,
/* INVOKENONVIRTUAL_QUICK */ -1,
/* INVOKESUPER_QUICK */ -1,
/* INVOKESTATIC_QUICK */ -1,
/* INVOKEINTERFACE_QUICK */ -1,
/* INVOKEVIRTUALOBJECT_QUICK */ -1,
/* XXXUNUSEDXXX */ -1,
/* NEW_QUICK */ -1,
/* ANEWARRAY_QUICK */ -1,
/* MULTIANEWARRAY_QUICK */ -1,
/* CHECKCAST_QUICK */ -1,
/* INSTANCEOF_QUICK */ -1,
/* INVOKEVIRTUAL_QUICK_W */ -1,
/* GETFIELD_QUICK_W */ -1,
/* PUTFIELD_QUICK_W */ -1,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* IMPDEP1 */ 0,
/* IMPDEP2 */ 0
};
/**
* The effect on the operand stack of a given opcode.
*/
static final byte[] stackChange = {
/* NOP */ 0,
/* ACONST_NULL */ 1,
/* ICONST_M1 */ 1,
/* ICONST_0 */ 1,
/* ICONST_1 */ 1,
/* ICONST_2 */ 1,
/* ICONST_3 */ 1,
/* ICONST_4 */ 1,
/* ICONST_5 */ 1,
/* LCONST_0 */ 2,
/* LCONST_1 */ 2,
/* FCONST_0 */ 1,
/* FCONST_1 */ 1,
/* FCONST_2 */ 1,
/* DCONST_0 */ 2,
/* DCONST_1 */ 2,
/* BIPUSH */ 1,
/* SIPUSH */ 1,
/* LDC */ 1,
/* LDC_W */ 1,
/* LDC2_W */ 2,
/* ILOAD */ 1,
/* LLOAD */ 2,
/* FLOAD */ 1,
/* DLOAD */ 2,
/* ALOAD */ 1,
/* ILOAD_0 */ 1,
/* ILOAD_1 */ 1,
/* ILOAD_2 */ 1,
/* ILOAD_3 */ 1,
/* LLOAD_0 */ 2,
/* LLOAD_1 */ 2,
/* LLOAD_2 */ 2,
/* LLOAD_3 */ 2,
/* FLOAD_0 */ 1,
/* FLOAD_1 */ 1,
/* FLOAD_2 */ 1,
/* FLOAD_3 */ 1,
/* DLOAD_0 */ 2,
/* DLOAD_1 */ 2,
/* DLOAD_2 */ 2,
/* DLOAD_3 */ 2,
/* ALOAD_0 */ 1,
/* ALOAD_1 */ 1,
/* ALOAD_2 */ 1,
/* ALOAD_3 */ 1,
/* IALOAD */ -1,
/* LALOAD */ 0,
/* FALOAD */ -1,
/* DALOAD */ 0,
/* AALOAD */ -1,
/* BALOAD */ -1,
/* CALOAD */ -1,
/* SALOAD */ -1,
/* ISTORE */ -1,
/* LSTORE */ -2,
/* FSTORE */ -1,
/* DSTORE */ -2,
/* ASTORE */ -1,
/* ISTORE_0 */ -1,
/* ISTORE_1 */ -1,
/* ISTORE_2 */ -1,
/* ISTORE_3 */ -1,
/* LSTORE_0 */ -2,
/* LSTORE_1 */ -2,
/* LSTORE_2 */ -2,
/* LSTORE_3 */ -2,
/* FSTORE_0 */ -1,
/* FSTORE_1 */ -1,
/* FSTORE_2 */ -1,
/* FSTORE_3 */ -1,
/* DSTORE_0 */ -2,
/* DSTORE_1 */ -2,
/* DSTORE_2 */ -2,
/* DSTORE_3 */ -2,
/* ASTORE_0 */ -1,
/* ASTORE_1 */ -1,
/* ASTORE_2 */ -1,
/* ASTORE_3 */ -1,
/* IASTORE */ -3,
/* LASTORE */ -4,
/* FASTORE */ -3,
/* DASTORE */ -4,
/* AASTORE */ -3,
/* BASTORE */ -3,
/* CASTORE */ -3,
/* SASTORE */ -3,
/* POP */ -1,
/* POP2 */ -2,
/* DUP */ 1,
/* DUP_X1 */ 1,
/* DUP_X2 */ 1,
/* DUP2 */ 2,
/* DUP2_X1 */ 2,
/* DUP2_X2 */ 2,
/* SWAP */ 0,
/* IADD */ -1,
/* LADD */ -2,
/* FADD */ -1,
/* DADD */ -2,
/* ISUB */ -1,
/* LSUB */ -2,
/* FSUB */ -1,
/* DSUB */ -2,
/* IMUL */ -1,
/* LMUL */ -2,
/* FMUL */ -1,
/* DMUL */ -2,
/* IDIV */ -1,
/* LDIV */ -2,
/* FDIV */ -1,
/* DDIV */ -2,
/* IREM */ -1,
/* LREM */ -2,
/* FREM */ -1,
/* DREM */ -2,
/* INEG */ 0,
/* LNEG */ 0,
/* FNEG */ 0,
/* DNEG */ 0,
/* ISHL */ -1,
/* LSHL */ -1,
/* ISHR */ -1,
/* LSHR */ -1,
/* IUSHR */ -1,
/* LUSHR */ -1,
/* IAND */ -1,
/* LAND */ -2,
/* IOR */ -1,
/* LOR */ -2,
/* IXOR */ -1,
/* LXOR */ -2,
/* IINC */ 0,
/* I2L */ 1,
/* I2F */ 0,
/* I2D */ 1,
/* L2I */ -1,
/* L2F */ -1,
/* L2D */ 0,
/* F2I */ 0,
/* F2L */ 1,
/* F2D */ 1,
/* D2I */ -1,
/* D2L */ 0,
/* D2F */ -1,
/* I2B */ 0,
/* I2C */ 0,
/* I2S */ 0,
/* LCMP */ -3,
/* FCMPL */ -1,
/* FCMPG */ -1,
/* DCMPL */ -3,
/* DCMPG */ -3,
/* IFEQ */ -1,
/* IFNE */ -1,
/* IFLT */ -1,
/* IFGE */ -1,
/* IFGT */ -1,
/* IFLE */ -1,
/* IF_ICMPEQ */ -2,
/* IF_ICMPNE */ -2,
/* IF_ICMPLT */ -2,
/* IF_ICMPGE */ -2,
/* IF_ICMPGT */ -2,
/* IF_ICMPLE */ -2,
/* IF_ACMPEQ */ -2,
/* IF_ACMPNE */ -2,
/* GOTO */ 0,
/* JSR */ 1,
/* RET */ 0,
/* TABLESWITCH */ -1,
/* LOOKUPSWITCH */ -1,
/* IRETURN */ -1,
/* LRETURN */ -2,
/* FRETURN */ -1,
/* DRETURN */ -2,
/* ARETURN */ -1,
/* RETURN */ 0,
/* GETSTATIC */ 0,
/* PUTSTATIC */ 0,
/* GETFIELD */ -1,
/* PUTFIELD */ -1,
/* INVOKEVIRTUAL */ -1, // pops 'this' (unless static)
/* INVOKESPECIAL */ -1, // but needs to account for
/* INVOKESTATIC */ 0, // parameters and return type
/* INVOKEINTERFACE */ -1, //
/* XXXUNUSEDXXX */ 0,
/* NEW */ 1,
/* NEWARRAY */ 0,
/* ANEWARRAY */ 0,
/* ARRAYLENGTH */ 0,
/* ATHROW */ -1,
/* CHECKCAST */ 0,
/* INSTANCEOF */ 0,
/* MONITORENTER */ -1,
/* MONITOREXIT */ -1,
/* WIDE */ 0,
/* MULTIANEWARRAY */ 1,
/* IFNULL */ -1,
/* IFNONNULL */ -1,
/* GOTO_W */ 0,
/* JSR_W */ 1,
/* BREAKPOINT */ 0,
/* LDC_QUICK */ 1,
/* LDC_W_QUICK */ 1,
/* LDC2_W_QUICK */ 2,
/* GETFIELD_QUICK */ 0,
/* PUTFIELD_QUICK */ 0,
/* GETFIELD2_QUICK */ 0,
/* PUTFIELD2_QUICK */ 0,
/* GETSTATIC_QUICK */ 0,
/* PUTSTATIC_QUICK */ 0,
/* GETSTATIC2_QUICK */ 0,
/* PUTSTATIC2_QUICK */ 0,
/* INVOKEVIRTUAL_QUICK */ 0,
/* INVOKENONVIRTUAL_QUICK */ 0,
/* INVOKESUPER_QUICK */ 0,
/* INVOKESTATIC_QUICK */ 0,
/* INVOKEINTERFACE_QUICK */ 0,
/* INVOKEVIRTUALOBJECT_QUICK */ 0,
/* XXXUNUSEDXXX */ 0,
/* NEW_QUICK */ 1,
/* ANEWARRAY_QUICK */ 1,
/* MULTIANEWARRAY_QUICK */ 1,
/* CHECKCAST_QUICK */ -1,
/* INSTANCEOF_QUICK */ 0,
/* INVOKEVIRTUAL_QUICK_W */ 0,
/* GETFIELD_QUICK_W */ 0,
/* PUTFIELD_QUICK_W */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* XXXUNUSEDXXX */ 0,
/* IMPDEP1 */ 0,
/* IMPDEP2 */ 0
};
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,107 @@
/*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Roger Lawrence
* Patrick Beard
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.classfile;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/**
* Load generated classes.
*
* @author Norris Boyd
*/
public class DefiningClassLoader extends ClassLoader {
public static ClassLoader getContextClassLoader() {
try {
if (getContextClassLoaderMethod != null) {
return (ClassLoader) getContextClassLoaderMethod.invoke(
Thread.currentThread(),
new Object[0]);
}
} catch (IllegalAccessException e) {
// fall through...
} catch (InvocationTargetException e) {
// fall through...
}
return DefiningClassLoader.class.getClassLoader();
}
public Class defineClass(String name, byte data[]) {
return super.defineClass(name, data, 0, data.length);
}
public Class loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
Class clazz = findLoadedClass(name);
if (clazz == null) {
ClassLoader loader = getContextClassLoader();
if (loader != null) {
clazz = loader.loadClass(name);
} else {
clazz = findSystemClass(name);
}
}
if (resolve)
resolveClass(clazz);
return clazz;
}
private static Method getContextClassLoaderMethod;
static {
try {
// Don't use "Thread.class": that performs the lookup
// in the class initializer, which doesn't allow us to
// catch possible security exceptions.
Class threadClass = Class.forName("java.lang.Thread");
// We'd like to use "getContextClassLoader", but
// that's only available on Java2.
getContextClassLoaderMethod =
threadClass.getDeclaredMethod("getContextClassLoader",
new Class[0]);
} catch (ClassNotFoundException e) {
// ignore exceptions; we'll use Class.forName instead.
} catch (NoSuchMethodException e) {
// ignore exceptions; we'll use Class.forName instead.
} catch (SecurityException e) {
// ignore exceptions; we'll use Class.forName instead.
}
}
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,9 +18,8 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -44,7 +43,7 @@ package org.mozilla.javascript;
* @see org.mozilla.javascript.NativeCall
* @author Norris Boyd
*/
class Arguments extends IdScriptable {
class Arguments extends ScriptableObject {
public Arguments(NativeCall activation) {
this.activation = activation;
@@ -54,223 +53,88 @@ class Arguments extends IdScriptable {
setPrototype(ScriptableObject.getObjectPrototype(parent));
args = activation.getOriginalArguments();
lengthObj = new Integer(args.length);
int length = args.length;
Object callee = activation.funObj;
NativeFunction funObj = activation.funObj;
calleeObj = funObj;
defineProperty("length", new Integer(length),
ScriptableObject.DONTENUM);
defineProperty("callee", callee, ScriptableObject.DONTENUM);
if (funObj.version <= Context.VERSION_1_3
&& funObj.version != Context.VERSION_DEFAULT)
{
callerObj = null;
}else {
callerObj = NOT_FOUND;
}
hasCaller = (activation.funObj.version <= Context.VERSION_1_3 &&
activation.funObj.version != Context.VERSION_DEFAULT);
}
public String getClassName() {
return "Arguments";
}
public boolean has(String name, Scriptable start) {
return (hasCaller && name.equals("caller")) || super.has(name, start);
}
public boolean has(int index, Scriptable start) {
if (0 <= index && index < args.length) {
if (args[index] != NOT_FOUND) {
return true;
}
Object[] args = activation.getOriginalArguments();
return (0 <= index && index < args.length) || super.has(index, start);
}
public Object get(String name, Scriptable start) {
if (hasCaller && name.equals("caller")) {
NativeCall caller = activation.caller;
if (caller == null || caller.originalArgs == null)
return null;
return caller.get("arguments", caller);
}
return super.has(index, start);
return super.get(name, start);
}
public Object get(int index, Scriptable start) {
if (0 <= index && index < args.length) {
Object value = args[index];
if (value != NOT_FOUND) {
if (sharedWithActivation(index)) {
String argName = activation.funObj.argNames[index];
value = activation.get(argName, activation);
if (value == NOT_FOUND) Kit.codeBug();
}
return value;
}
NativeFunction f = activation.funObj;
if (index < f.argCount)
return activation.get(f.argNames[index], activation);
return args[index];
}
return super.get(index, start);
}
private boolean sharedWithActivation(int index) {
NativeFunction f = activation.funObj;
int definedCount = f.argCount;
if (index < definedCount) {
// Check if argument is not hidden by later argument with the same
// name as hidden arguments are not shared with activation
if (index < definedCount - 1) {
String argName = f.argNames[index];
for (int i = index + 1; i < definedCount; i++) {
if (argName.equals(f.argNames[i])) {
return false;
}
}
}
return true;
public void put(String name, Scriptable start, Object value) {
if (name.equals("caller")) {
// Set "hasCaller" to false so that we won't look up a
// computed value.
hasCaller = false;
}
return false;
super.put(name, start, value);
}
public void put(int index, Scriptable start, Object value) {
if (0 <= index && index < args.length) {
if (args[index] != NOT_FOUND) {
if (sharedWithActivation(index)) {
String argName = activation.funObj.argNames[index];
activation.put(argName, activation, value);
return;
}
synchronized (this) {
if (args[index] != NOT_FOUND) {
if (args == activation.getOriginalArguments()) {
args = (Object[])args.clone();
}
args[index] = value;
return;
}
}
}
NativeFunction f = activation.funObj;
if (index < f.argCount)
activation.put(f.argNames[index], activation, value);
else
args[index] = value;
return;
}
super.put(index, start, value);
}
public void delete(String name) {
if (name.equals("caller"))
hasCaller = false;
super.delete(name);
}
public void delete(int index) {
if (0 <= index && index < args.length) {
synchronized (this) {
if (args[index] != NOT_FOUND) {
if (args == activation.getOriginalArguments()) {
args = (Object[])args.clone();
}
args[index] = NOT_FOUND;
return;
}
}
NativeFunction f = activation.funObj;
if (index < f.argCount)
activation.delete(f.argNames[index]);
else
args[index] = Undefined.instance;
}
super.delete(index);
}
protected int getIdAttributes(int id)
{
switch (id) {
case Id_callee:
case Id_caller:
case Id_length:
return DONTENUM;
}
return super.getIdAttributes(id);
}
protected boolean hasIdValue(int id)
{
switch (id) {
case Id_callee: return calleeObj != NOT_FOUND;
case Id_length: return lengthObj != NOT_FOUND;
case Id_caller: return callerObj != NOT_FOUND;
}
return super.hasIdValue(id);
}
protected Object getIdValue(int id)
{
switch (id) {
case Id_callee: return calleeObj;
case Id_length: return lengthObj;
case Id_caller: {
Object value = callerObj;
if (value == UniqueTag.NULL_VALUE) { value = null; }
else if (value == null) {
NativeCall caller = activation.caller;
if (caller == null) {
value = null;
}else {
value = caller.get("arguments", caller);
}
}
return value;
}
}
return super.getIdValue(id);
}
protected void setIdValue(int id, Object value)
{
switch (id) {
case Id_callee: calleeObj = value; return;
case Id_length: lengthObj = value; return;
case Id_caller:
callerObj = (value != null) ? value : UniqueTag.NULL_VALUE;
return;
}
super.setIdValue(id, value);
}
protected void deleteIdValue(int id)
{
switch (id) {
case Id_callee: calleeObj = NOT_FOUND; return;
case Id_length: lengthObj = NOT_FOUND; return;
case Id_caller: callerObj = NOT_FOUND; return;
}
super.deleteIdValue(id);
}
protected String getIdName(int id)
{
switch (id) {
case Id_callee: return "callee";
case Id_length: return "length";
case Id_caller: return "caller";
}
return null;
}
// #string_id_map#
private static final int
Id_callee = 1,
Id_length = 2,
Id_caller = 3,
MAX_INSTANCE_ID = 3;
{ setMaxId(MAX_INSTANCE_ID); }
protected int mapNameToId(String s)
{
int id;
// #generated# Last update: 2002-04-09 20:46:33 CEST
L0: { id = 0; String X = null; int c;
if (s.length()==6) {
c=s.charAt(5);
if (c=='e') { X="callee";id=Id_callee; }
else if (c=='h') { X="length";id=Id_length; }
else if (c=='r') { X="caller";id=Id_caller; }
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
return id;
}
// #/string_id_map#
// Fields to hold caller, callee and length properties,
// where NOT_FOUND value tags deleted properties.
// In addition if callerObj == NULL_VALUE, it tags null for scripts, as
// initial callerObj == null means access to caller arguments available
// only in JS <= 1.3 scripts
private Object callerObj;
private Object calleeObj;
private Object lengthObj;
private NativeCall activation;
// Initially args holds activation.getOriginalArgs(), but any modification
// of its elements triggers creation of a copy. If its element holds NOT_FOUND,
// it indicates deleted index, in which case super class is queried.
private Object[] args;
private boolean hasCaller;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
* Igor Bukanov
* Roger Lawrence
@@ -49,14 +49,14 @@ public class BaseFunction extends IdScriptable implements Function {
BaseFunction obj = new BaseFunction();
obj.prototypeFlag = true;
obj.functionName = "";
obj.isPrototypePropertyImmune = true;
obj.prototypePropertyAttrs = DONTENUM | READONLY | PERMANENT;
obj.addAsPrototype(MAX_PROTOTYPE_ID, cx, scope, sealed);
}
protected void fillConstructorProperties
(Context cx, IdFunction ctor, boolean sealed)
{
// Fix up bootstrapping problem: getPrototype of the IdFunction
// Fix up bootstrapping problem: getPrototype of the IdFunction
// can not return Function.prototype because Function object is not
// yet defined.
ctor.setPrototype(this);
@@ -80,68 +80,47 @@ public class BaseFunction extends IdScriptable implements Function {
* value's prototype chain
*
*/
public boolean hasInstance(Scriptable instance)
{
public boolean hasInstance(Scriptable instance) {
Object protoProp = ScriptableObject.getProperty(this, "prototype");
if (protoProp instanceof Scriptable && protoProp != Undefined.instance)
{
return ScriptRuntime.jsDelegatesTo(instance, (Scriptable)protoProp);
}
throw ScriptRuntime.typeError1("msg.instanceof.bad.prototype",
functionName);
throw NativeGlobal.typeError1
("msg.instanceof.bad.prototype", functionName, instance);
}
protected String toSource(Context cx, Scriptable scope, Object[] args)
{
int indent = 0;
int flags = Decompiler.TO_SOURCE_FLAG;
if (args.length != 0) {
indent = ScriptRuntime.toInt32(args[0]);
if (indent >= 0) {
flags = 0;
} else {
indent = 0;
}
}
return decompile(cx, indent, flags);
}
protected int getIdAttributes(int id)
{
protected int getIdDefaultAttributes(int id) {
switch (id) {
case Id_length:
case Id_arity:
case Id_name:
return DONTENUM | READONLY | PERMANENT;
case Id_prototype:
return isPrototypePropertyImmune
? DONTENUM | READONLY | PERMANENT
: DONTENUM;
return prototypePropertyAttrs;
case Id_arguments:
return EMPTY;
}
return super.getIdAttributes(id);
return super.getIdDefaultAttributes(id);
}
protected boolean hasIdValue(int id)
{
protected boolean hasIdValue(int id) {
if (id == Id_prototype) {
return prototypeProperty != NOT_FOUND;
}
else if (id == Id_arguments) {
// Should after delete Function.arguments its activation still
// be available during Function call?
// be available during Function call?
// This code assumes it should not: after default set/deleteIdValue
// hasIdValue/getIdValue would not be called again
// To handle the opposite case, set/deleteIdValue should be
// To handle the opposite case, set/deleteIdValue should be
// overwritten as well
return null != getActivation(Context.getContext());
}
return super.hasIdValue(id);
}
protected Object getIdValue(int id)
{
protected Object getIdValue(int id) {
switch (id) {
case Id_length: return wrap_int(getLength());
case Id_arity: return wrap_int(getArity());
@@ -151,18 +130,16 @@ public class BaseFunction extends IdScriptable implements Function {
}
return super.getIdValue(id);
}
protected void setIdValue(int id, Object value)
{
protected void setIdValue(int id, Object value) {
if (id == Id_prototype) {
prototypeProperty = (value != null) ? value : UniqueTag.NULL_VALUE;
prototypeProperty = (value != null) ? value : NULL_TAG;
return;
}
super.setIdValue(id, value);
}
protected void deleteIdValue(int id)
{
protected void deleteIdValue(int id) {
if (id == Id_prototype) {
prototypeProperty = NOT_FOUND;
return;
@@ -170,42 +147,37 @@ public class BaseFunction extends IdScriptable implements Function {
super.deleteIdValue(id);
}
public int methodArity(int methodId)
{
public int methodArity(int methodId) {
if (prototypeFlag) {
switch (methodId) {
case Id_constructor: return 1;
case Id_toString: return 1;
case Id_apply: return 2;
case Id_call: return 1;
case Id_constructor:
case Id_toString:
case Id_apply:
case Id_call:
return 1;
}
}
return super.methodArity(methodId);
}
public Object execMethod(int methodId, IdFunction f, Context cx,
Scriptable scope, Scriptable thisObj,
Scriptable scope, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
if (prototypeFlag) {
switch (methodId) {
case Id_constructor:
return jsConstructor(cx, scope, args);
case Id_constructor:
return jsConstructor(cx, scope, args);
case Id_toString: {
int indent = ScriptRuntime.toInt32(args, 0);
Object x = thisObj.getDefaultValue(ScriptRuntime.FunctionClass);
if (x instanceof BaseFunction) {
return ((BaseFunction)x).decompile(cx, indent, 0);
}
throw ScriptRuntime.typeError1("msg.incompat.call", "toString");
}
case Id_toString:
return jsFunction_toString(cx, thisObj, args);
case Id_apply:
case Id_call:
return applyOrCall(methodId == Id_apply, cx, scope,
thisObj, args);
case Id_apply:
return jsFunction_apply(cx, scope, thisObj, args);
case Id_call:
return jsFunction_call(cx, scope, thisObj, args);
}
}
return super.execMethod(methodId, f, cx, scope, thisObj, args);
@@ -213,21 +185,20 @@ public class BaseFunction extends IdScriptable implements Function {
/**
* Make value as DontEnum, DontDelete, ReadOnly
* prototype property of this Function object
* prototype property of this Function object
*/
public void setImmunePrototypeProperty(Object value)
{
prototypeProperty = (value != null) ? value : UniqueTag.NULL_VALUE;
isPrototypePropertyImmune = true;
public void setImmunePrototypeProperty(Object value) {
prototypeProperty = (value != null) ? value : NULL_TAG;
prototypePropertyAttrs = DONTENUM | READONLY | PERMANENT;
}
protected Scriptable getClassPrototype()
{
protected Scriptable getClassPrototype() {
Object protoVal = getPrototypeProperty();
if (protoVal instanceof Scriptable && protoVal != Undefined.instance) {
return (Scriptable) protoVal;
}
return getClassPrototype(this, "Object");
if (protoVal == null
|| !(protoVal instanceof Scriptable)
|| (protoVal == Undefined.instance))
protoVal = getClassPrototype(this, "Object");
return (Scriptable) protoVal;
}
/**
@@ -242,51 +213,16 @@ public class BaseFunction extends IdScriptable implements Function {
public Scriptable construct(Context cx, Scriptable scope, Object[] args)
throws JavaScriptException
{
Scriptable result = createObject(cx, scope);
if (result != null) {
Object val = call(cx, scope, result, args);
if (val instanceof Scriptable && val != Undefined.instance) {
result = (Scriptable)val;
}
} else {
Object val = call(cx, scope, null, args);
if (!(val instanceof Scriptable && val != Undefined.instance)) {
// It is program error not to return Scriptable from
// the call method if createObject returns null.
throw new IllegalStateException(
"Bad implementaion of call as constructor, name="
+functionName+" in "+getClass().getName());
}
result = (Scriptable)val;
if (result.getPrototype() == null) {
result.setPrototype(getClassPrototype());
}
if (result.getParentScope() == null) {
Scriptable parent = getParentScope();
if (result != parent) {
result.setParentScope(parent);
}
}
}
return result;
}
/**
* Creates new script object.
* The default implementation of {@link #construct} uses the method to
* to get the value for <tt>thisObj</tt> argument when invoking
* {@link #call}.
* The methos is allowed to return <tt>null</tt> to indicate that
* {@link #call} will create a new object itself. In this case
* {@link #construct} will set scope and prototype on the result
* {@link #call} unless they are already set.
*/
public Scriptable createObject(Context cx, Scriptable scope)
{
Scriptable newInstance = new NativeObject();
newInstance.setPrototype(getClassPrototype());
newInstance.setParentScope(getParentScope());
Object val = call(cx, scope, newInstance, args);
if (val instanceof Scriptable && val != Undefined.instance) {
return (Scriptable) val;
}
return newInstance;
}
@@ -294,16 +230,16 @@ public class BaseFunction extends IdScriptable implements Function {
* Decompile the source information associated with this js
* function/script back into a string.
*
* @param cx Current context.
* @param cx Current context
*
* @param indent How much to indent the decompiled result.
* @param indent How much to indent the decompiled result
*
* @param flags Flags specifying format of decompilation output.
* @param justbody Whether the decompilation should omit the
* function header and trailing brace.
*/
public String decompile(Context cx, int indent, int flags)
{
public String decompile(Context cx, int indent, boolean justbody) {
StringBuffer sb = new StringBuffer();
boolean justbody = (0 != (flags & Decompiler.ONLY_BODY_FLAG));
if (!justbody) {
sb.append("function ");
sb.append(getFunctionName());
@@ -325,12 +261,17 @@ public class BaseFunction extends IdScriptable implements Function {
public String getFunctionName() {
if (functionName == null)
return "";
if (functionName.equals("anonymous")) {
Context cx = Context.getCurrentContext();
if (cx != null && cx.getLanguageVersion() == Context.VERSION_1_2)
return "";
}
return functionName;
}
private Object getPrototypeProperty() {
Object result = prototypeProperty;
if (result == null) {
if (result == null) {
synchronized (this) {
result = prototypeProperty;
if (result == null) {
@@ -339,12 +280,11 @@ public class BaseFunction extends IdScriptable implements Function {
}
}
}
else if (result == UniqueTag.NULL_VALUE) { result = null; }
else if (result == NULL_TAG) { result = null; }
return result;
}
private void setupDefaultPrototype()
{
private void setupDefaultPrototype() {
NativeObject obj = new NativeObject();
final int attr = ScriptableObject.DONTENUM |
ScriptableObject.READONLY |
@@ -354,81 +294,60 @@ public class BaseFunction extends IdScriptable implements Function {
// wacky case of a user defining a function Object(), we don't
// get an infinite loop trying to find the prototype.
prototypeProperty = obj;
Scriptable proto = getObjectPrototype(this);
Scriptable proto = getObjectPrototype(this);
if (proto != obj) {
// not the one we just made, it must remain grounded
obj.setPrototype(proto);
}
}
private Object getArguments()
{
private Object getArguments() {
// <Function name>.arguments is deprecated, so we use a slow
// way of getting it that doesn't add to the invocation cost.
// TODO: add warning, error based on version
NativeCall activation = getActivation(Context.getContext());
return activation == null
? null
return activation == null
? null
: activation.get("arguments", activation);
}
NativeCall getActivation(Context cx)
{
NativeCall getActivation(Context cx) {
NativeCall activation = cx.currentActivation;
while (activation != null) {
if (activation.getFunctionObject() == this)
if (activation.getFunctionObject() == this)
return activation;
activation = activation.caller;
}
return null;
}
private static Object jsConstructor(Context cx, Scriptable scope,
private static Object jsConstructor(Context cx, Scriptable scope,
Object[] args)
{
int arglen = args.length;
StringBuffer sourceBuf = new StringBuffer();
StringBuffer funArgs = new StringBuffer();
sourceBuf.append("function ");
/* version != 1.2 Function constructor behavior -
* print 'anonymous' as the function name if the
* version (under which the function was compiled) is
* less than 1.2... or if it's greater than 1.2, because
* we need to be closer to ECMA.
*/
if (cx.getLanguageVersion() != Context.VERSION_1_2) {
sourceBuf.append("anonymous");
}
sourceBuf.append('(');
/* Collect the arguments into a string. */
// Append arguments as coma separated strings
for (int i = 0; i < arglen - 1; i++) {
if (i > 0) {
sourceBuf.append(',');
}
sourceBuf.append(ScriptRuntime.toString(args[i]));
int i;
for (i = 0; i < arglen - 1; i++) {
if (i > 0)
funArgs.append(',');
funArgs.append(ScriptRuntime.toString(args[i]));
}
sourceBuf.append(") {");
if (arglen != 0) {
// append function body
String funBody = ScriptRuntime.toString(args[arglen - 1]);
sourceBuf.append(funBody);
}
sourceBuf.append('}');
String source = sourceBuf.toString();
String funBody = arglen == 0 ? "" : ScriptRuntime.toString(args[i]);
int[] linep = new int[1];
String source = "function (" + funArgs.toString() + ") {" +
funBody + "}";
int[] linep = { 0 };
String filename = Context.getSourcePositionFromStack(linep);
if (filename == null) {
filename = "<eval'ed string>";
linep[0] = 1;
}
String sourceName = ScriptRuntime.
makeUrlForGeneratedScript(false, filename, linep[0]);
Object securityDomain = cx.getSecurityDomainForStackDepth(4);
Scriptable global = ScriptableObject.getTopLevelScope(scope);
// Compile the function with opt level of -1 to force interpreter
// mode.
int oldOptLevel = cx.getOptimizationLevel();
@@ -436,68 +355,87 @@ public class BaseFunction extends IdScriptable implements Function {
NativeFunction fn;
try {
fn = (NativeFunction) cx.compileFunction(global, source,
sourceName, 1,
null);
filename, linep[0],
securityDomain);
}
finally { cx.setOptimizationLevel(oldOptLevel); }
ScriptRuntime.setFunctionProtoAndParent(global, fn);
fn.functionName = "anonymous";
fn.setPrototype(getFunctionPrototype(global));
fn.setParentScope(global);
return fn;
}
/**
* Function.prototype.apply and Function.prototype.call
*
* See Ecma 15.3.4.[34]
*/
private static Object applyOrCall(boolean isApply,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
private static Object jsFunction_toString(Context cx, Scriptable thisObj,
Object[] args)
{
int L = args.length;
Object function = thisObj.getDefaultValue(ScriptRuntime.FunctionClass);
Object callThis;
if (L == 0 || args[0] == null || args[0] == Undefined.instance) {
callThis = ScriptableObject.getTopLevelScope(scope);
} else {
callThis = ScriptRuntime.toObject(cx, scope, args[0]);
int indent = ScriptRuntime.toInt32(args, 0);
Object val = thisObj.getDefaultValue(ScriptRuntime.FunctionClass);
if (val instanceof BaseFunction) {
return ((BaseFunction)val).decompile(cx, indent, false);
}
Object[] callArgs;
if (isApply) {
// Follow Ecma 15.3.4.3
if (L <= 1) {
callArgs = ScriptRuntime.emptyArgs;
} else {
Object arg1 = args[1];
if (arg1 == null || arg1 == Undefined.instance) {
callArgs = ScriptRuntime.emptyArgs;
} else if (arg1 instanceof NativeArray
|| arg1 instanceof Arguments)
{
callArgs = cx.getElements((Scriptable) arg1);
} else {
throw ScriptRuntime.typeError0("msg.arg.isnt.array");
}
}
} else {
// Follow Ecma 15.3.4.4
if (L <= 1) {
callArgs = ScriptRuntime.emptyArgs;
} else {
callArgs = new Object[L - 1];
System.arraycopy(args, 1, callArgs, 0, L - 1);
}
}
return ScriptRuntime.call(cx, function, callThis, callArgs, scope);
throw NativeGlobal.typeError1("msg.incompat.call", "toString", thisObj);
}
protected String getIdName(int id)
/**
* Function.prototype.apply
*
* A proposed ECMA extension for round 2.
*/
private static Object jsFunction_apply(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
if (args.length != 2)
return jsFunction_call(cx, scope, thisObj, args);
Object val = thisObj.getDefaultValue(ScriptRuntime.FunctionClass);
Scriptable newThis = args[0] == null
? ScriptableObject.getTopLevelScope(thisObj)
: ScriptRuntime.toObject(scope, args[0]);
Object[] newArgs;
if (args.length > 1) {
if ((args[1] instanceof NativeArray)
|| (args[1] instanceof Arguments))
newArgs = cx.getElements((Scriptable) args[1]);
else
throw NativeGlobal.typeError0("msg.arg.isnt.array", thisObj);
}
else
newArgs = ScriptRuntime.emptyArgs;
return ScriptRuntime.call(cx, val, newThis, newArgs, newThis);
}
/**
* Function.prototype.call
*
* A proposed ECMA extension for round 2.
*/
private static Object jsFunction_call(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
Object val = thisObj.getDefaultValue(ScriptRuntime.FunctionClass);
if (args.length == 0) {
Scriptable s = ScriptRuntime.toObject(scope, val);
Scriptable topScope = s.getParentScope();
return ScriptRuntime.call(cx, val,
topScope, ScriptRuntime.emptyArgs,
topScope);
} else {
Scriptable newThis = args[0] == null
? ScriptableObject.getTopLevelScope(thisObj)
: ScriptRuntime.toObject(scope, args[0]);
Object[] newArgs = new Object[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
return ScriptRuntime.call(cx, val, newThis, newArgs, newThis);
}
}
protected int maxInstanceId() { return MAX_INSTANCE_ID; }
protected String getIdName(int id) {
switch (id) {
case Id_length: return "length";
case Id_arity: return "arity";
@@ -505,7 +443,7 @@ public class BaseFunction extends IdScriptable implements Function {
case Id_prototype: return "prototype";
case Id_arguments: return "arguments";
}
if (prototypeFlag) {
switch (id) {
case Id_constructor: return "constructor";
@@ -525,13 +463,10 @@ public class BaseFunction extends IdScriptable implements Function {
Id_name = 3,
Id_prototype = 4,
Id_arguments = 5,
MAX_INSTANCE_ID = 5;
{ setMaxId(MAX_INSTANCE_ID); }
protected int mapNameToId(String s)
{
protected int mapNameToId(String s) {
int id;
// #generated# Last update: 2001-05-20 00:12:12 GMT+02:00
L0: { id = 0; String X = null; int c;
@@ -571,15 +506,16 @@ public class BaseFunction extends IdScriptable implements Function {
Id_toString = MAX_INSTANCE_ID + 2,
Id_apply = MAX_INSTANCE_ID + 3,
Id_call = MAX_INSTANCE_ID + 4,
MAX_PROTOTYPE_ID = MAX_INSTANCE_ID + 4;
// #/string_id_map#
protected String functionName;
private Object prototypeProperty;
private boolean isPrototypePropertyImmune;
private Object prototypeProperty;
private int prototypePropertyAttrs = DONTENUM;
private boolean prototypeFlag;
}

View File

@@ -1,3 +1,4 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
@@ -6,20 +7,20 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1998.
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Contributor(s):
* Waldemar Horwat
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -32,38 +33,43 @@
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import org.mozilla.javascript.*;
final class BinaryDigitReader {
int lgBase; // Logarithm of base of number
int digit; // Current digit value in radix given by base
int digitPos; // Bit position of last bit extracted from digit
String digits; // String containing the digits
int start; // Index of the first remaining digit
int end; // Index past the last remaining digit
/**
* An example WrapFactory that can be used to avoid wrapping of Java types
* that can be converted to ECMA primitive values.
* So java.lang.String is mapped to ECMA string, all java.lang.Numbers are
* mapped to ECMA numbers, and java.lang.Booleans are mapped to ECMA booleans
* instead of being wrapped as objects. Additionally java.lang.Character is
* converted to ECMA string with length 1.
* Other types have the default behavior.
* <p>
* Note that calling "new java.lang.String('foo')" in JavaScript with this
* wrap factory enabled will still produce a wrapped Java object since the
* WrapFactory.wrapNewObject method is not overridden.
* <p>
* The PrimitiveWrapFactory is enabled on a Context by calling setWrapFactory
* on that context.
*/
public class PrimitiveWrapFactory extends WrapFactory {
public Object wrap(Context cx, Scriptable scope, Object obj,
Class staticType)
{
if (obj instanceof String || obj instanceof Number ||
obj instanceof Boolean)
{
return obj;
} else if (obj instanceof Character) {
char[] a = { ((Character)obj).charValue() };
return new String(a);
BinaryDigitReader(int base, String digits, int start, int end) {
lgBase = 0;
while (base != 1) {
lgBase++;
base >>= 1;
}
digitPos = 0;
this.digits = digits;
this.start = start;
this.end = end;
}
/* Return the next binary digit from the number or -1 if done */
int getNextBinaryDigit()
{
if (digitPos == 0) {
if (start == end)
return -1;
char c = digits.charAt(start++);
if ('0' <= c && c <= '9')
digit = c - '0';
else if ('a' <= c && c <= 'z')
digit = c - 'a' + 10;
else digit = c - 'A' + 10;
digitPos = lgBase;
}
return digit >> --digitPos & 1;
}
return super.wrap(cx, scope, obj, staticType);
}
}

View File

@@ -1,63 +0,0 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is interface specifiing callable object to execute script
* related code on demand.
*
* The Initial Developer of the Original Code is
* RUnit Software AS.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Igor Bukanov, igor@fastmail.fm
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
/**
* Generic notion of callable object that can execute some script-related code
* upon request with specified values for script scope and this objects.
*/
public interface Callable
{
/**
* Perform the call.
*
* @param cx the current Context for this thread
* @param scope the scope to use to resolve properties.
* @param thisObj the JavaScript <code>this</code> object
* @param args the array of arguments
* @return the result of the call
* @exception JavaScriptException if an uncaught exception
* occurred while executing the function
*/
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
throws JavaScriptException;
}

View File

@@ -1,199 +0,0 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cache holder of generated code for Java reflection
*
* The Initial Developer of the Original Code is
* RUnit Software AS.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Igor Bukanov, igor@fastmail.fm
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import java.io.*;
import java.util.Hashtable;
/**
* Cache of generated classes and data structures to access Java runtime
* from JavaScript.
*
* @author Igor Bukanov
*
* @since Rhino 1.5 Release 5
*/
public class ClassCache
{
private static final Object AKEY = new Object();
private volatile boolean cachingIsEnabled = true;
Hashtable classTable = new Hashtable();
boolean invokerOptimization = true;
Invoker invokerMaster;
Hashtable javaAdapterGeneratedClasses = new Hashtable();
Hashtable javaAdapterIFGlueMasters = new Hashtable();
private int generatedClassSerial;
/**
* Search for ClassCache object in the given scope.
* The method first calls
* {@link ScriptableObject#getTopLevelScope(Scriptable scope)}
* to get the top most scope and then tries to locate associated
* ClassCache object in the prototype chain of the top scope.
*
* @param scope scope to search for ClassCache object.
* @return previously associated ClassCache object or a new instance of
* ClassCache if no ClassCache object was found.
*
* @see #associate(ScriptableObject topScope)
*/
public static ClassCache get(Scriptable scope)
{
scope = ScriptableObject.getTopLevelScope(scope);
Scriptable obj = scope;
do {
if (obj instanceof ScriptableObject) {
ScriptableObject so = (ScriptableObject)obj;
ClassCache lc = (ClassCache)so.getAssociatedValue(AKEY);
if (lc != null) {
return lc;
}
}
obj = obj.getPrototype();
} while (obj != null);
// ALERT: warn somehow about wrong cache usage ?
return new ClassCache();
}
/**
* Associate ClassCache object with the given top-level scope.
* The ClassCache object can only be associated with the given scope once.
*
* @param topScope scope to associate this ClassCache object with.
* @return true if no prevous ClassCache objects were embedded into
* the scope and this ClassCache were successfully associated
* or false otherwise.
*
* @see #get(Scriptable scope)
*/
public boolean associate(ScriptableObject topScope)
{
if (topScope.getParentScope() != null) {
// Can only associate cache with top level scope
throw new IllegalArgumentException();
}
return this != topScope.associateValue(AKEY, this);
}
/**
* Empty caches of generated Java classes and Java reflection information.
*/
public synchronized void clearCaches()
{
classTable = new Hashtable();
javaAdapterGeneratedClasses = new Hashtable();
javaAdapterIFGlueMasters = new Hashtable();
Invoker im = invokerMaster;
if (im != null) {
im.clearMasterCaches();
}
}
/**
* Check if generated Java classes and Java reflection information
* is cached.
*/
public final boolean isCachingEnabled()
{
return cachingIsEnabled;
}
/**
* Set whether to cache some values.
* <p>
* By default, the engine will cache generated classes and
* results of <tt>Class.getMethods()</tt> and similar calls.
* This can speed execution dramatically, but increases the memory
* footprint. Also, with caching enabled, references may be held to
* objects past the lifetime of any real usage.
* <p>
* If caching is enabled and this method is called with a
* <code>false</code> argument, the caches will be emptied.
* <p>
* Caching is enabled by default.
*
* @param cachingEnabled if true, caching is enabled
*
* @see #clearCaches()
*/
public synchronized void setCachingEnabled(boolean enabled)
{
if (enabled == cachingIsEnabled)
return;
if (!enabled)
clearCaches();
cachingIsEnabled = enabled;
}
/**
* To optimize invocation of reflected Java methods, the engine generates
* special glue classes that will call the methods directly. By default
* the optimization is enabled since it allows to speedup method invocation
* compared with calling <tt>Method.invoke</tt> by factor 2-2.5 under JDK
* 1.4.2 and by factor 10-15 under JDK 1.3.1. If increase memory
* consumption is too high or the optimization brings no benefits in a
* particular VM, then the optimization can be disabled.
*
* @param enabled if true, invoke optimization is enabled.
*/
public synchronized void setInvokerOptimizationEnabled(boolean enabled)
{
if (invokerOptimization == enabled)
return;
if (!enabled)
invokerMaster = null;
invokerOptimization = enabled;
}
/**
* Internal engine method to return serial number for generated classes
* to ensure name uniqueness.
*/
public final synchronized int newClassSerialNumber()
{
return ++generatedClassSerial;
}
}

View File

@@ -7,7 +7,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -19,7 +19,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -38,105 +38,23 @@
package org.mozilla.javascript;
import java.io.*;
public interface ClassNameHelper {
public abstract class ClassNameHelper {
public String getTargetPackage();
public static ClassNameHelper get(Context cx) {
ClassNameHelper helper = savedNameHelper;
if (helper == null && !helperNotAvailable) {
Class nameHelperClass = Kit.classOrNull(
"org.mozilla.javascript.optimizer.OptClassNameHelper");
// nameHelperClass == null if running lite
if (nameHelperClass != null) {
helper = (ClassNameHelper)Kit.newInstanceOrNull(
nameHelperClass);
}
if (helper != null) {
savedNameHelper = helper;
} else {
helperNotAvailable = true;
}
}
return helper;
}
public void setTargetPackage(String targetPackage);
/**
* Get the current target class file name.
* <p>
* If nonnull, requests to compile source will result in one or
* more class files being generated.
*
* @since 1.5 Release 4
*/
public abstract String getTargetClassFileName();
public void setTargetExtends(Class extendsClass);
public void setTargetImplements(Class[] implementsClasses);
/**
* Set the current target class file name.
* <p>
* If nonnull, requests to compile source will result in one or
* more class files being generated. If null, classes will only
* be generated in memory.
*
* @since 1.5 Release 4
*/
public abstract void setTargetClassFileName(String classFileName);
public ClassRepository getClassRepository();
/**
* Get the current package to generate classes into.
*/
public abstract String getTargetPackage();
public void setClassRepository(ClassRepository repository);
public String getClassName();
/**
* Set the package to generate classes into.
*/
public abstract void setTargetPackage(String targetPackage);
/**
* Set the class that the generated target will extend.
*
* @param extendsClass the class it extends
*/
public abstract void setTargetExtends(Class extendsClass);
/**
* Set the interfaces that the generated target will implement.
*
* @param implementsClasses an array of Class objects, one for each
* interface the target will extend
*/
public abstract void setTargetImplements(Class[] implementsClasses);
/**
* Get the current class repository.
*
* @see ClassRepository
* @since 30/10/01 tip + patch (Kemal Bayram)
*/
public abstract ClassRepository getClassRepository();
/**
* Set the current class repository.
*
* @see ClassRepository
* @since 30/10/01 tip + patch (Kemal Bayram)
*/
public abstract void setClassRepository(ClassRepository repository);
/**
* Get the current class name.
*
* @since 30/10/01 tip + patch (Kemal Bayram)
*/
public abstract String getClassName();
/**
* Set the current class name.
*
* @since 30/10/01 tip + patch (Kemal Bayram)
*/
public abstract void setClassName(String initialName);
private static ClassNameHelper savedNameHelper;
private static boolean helperNotAvailable;
public void setClassName(String initialName);
public void reset();
}

View File

@@ -15,11 +15,11 @@
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Igor Bukanov
* Contributor(s):
* Andi Vajda
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -32,14 +32,26 @@
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
package org.mozilla.javascript.tools.shell;
// API class
import org.mozilla.javascript.*;
public abstract class SecurityProxy extends SecurityController
{
protected abstract void callProcessFileSecure(Context cx, Scriptable scope,
String filename);
import java.io.*;
/**
* This interface is implemented by classes interested in the bytecode
* generated by the rhino compiler for script objects.
*
* @see Context
* @author Andi Vajda
*/
public interface ClassOutput {
/**
* @param className the name of the class for which bytecode is ready.
* @param isTopLevel if true, represents the top-level script being compiled
* @return a stream into which to write bytecode.
* @since 1.5 Release 2
*/
public OutputStream getOutputStream(String className, boolean isTopLevel)
throws IOException;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Kemal Bayram
*
* Alternatively, the contents of this file may be used under the
@@ -40,16 +40,16 @@ import java.io.*;
* This interface provides a means to store generated class and to
* allow selective class loading.
*
* @see ClassNameHelper
* @see Context
* @author Kemal Bayram
*/
public interface ClassRepository {
public interface ClassRepository {
/**
* @param className the name of the class.
* @param classBytes a byte array of the generated class.
* @param isTopLevel if true, represents the top-level script being compiled.
* @return true if the class should be loaded, false otherwise.
* @return true if the class should be loaded, false otherwise.
*/
public boolean storeClass(String className, byte[] classBytes,
boolean isTopLevel) throws IOException;
public boolean storeClass(String className, byte[] classBytes,
boolean isTopLevel) throws IOException;
}

View File

@@ -1,86 +0,0 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
// API class
package org.mozilla.javascript;
/**
Embeddings that wish to filter Java classes that are visible to scripts
through the LiveConnect, should implement this interface.
@see Context#setClassShutter(ClassShutter)
@since 1.5 Release 4
@author Norris Boyd
*/
public interface ClassShutter {
/**
* Return true iff the Java class with the given name should be exposed
* to scripts.
* <p>
* An embedding may filter which Java classes are exposed through
* LiveConnect to JavaScript scripts.
* <p>
* Due to the fact that there is no package reflection in Java,
* this method will also be called with package names. There
* is no way for Rhino to tell if "Packages.a.b" is a package name
* or a class that doesn't exist. What Rhino does is attempt
* to load each segment of "Packages.a.b.c": It first attempts to
* load class "a", then attempts to load class "a.b", then
* finally attempts to load class "a.b.c". On a Rhino installation
* without any ClassShutter set, and without any of the
* above classes, the expression "Packages.a.b.c" will result in
* a [JavaPackage a.b.c] and not an error.
* <p>
* With ClassShutter supplied, Rhino will first call
* visibleToScripts before attempting to look up the class name. If
* visibleToScripts returns false, the class name lookup is not
* performed and subsequent Rhino execution assumes the class is
* not present. So for "java.lang.System.out.println" the lookup
* of "java.lang.System" is skipped and thus Rhino assumes that
* "java.lang.System" doesn't exist. So then for "java.lang.System.out",
* Rhino attempts to load the class "java.lang.System.out" because
* it assumes that "java.lang.System" is a package name.
* <p>
* @param fullClassName the full name of the class (including the package
* name, with '.' as a delimiter). For example the
* standard string class is "java.lang.String"
* @return whether or not to reveal this class to scripts
*/
public boolean visibleToScripts(String fullClassName);
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -38,16 +38,16 @@
package org.mozilla.javascript;
/**
* Embeddings that wish to
* Embeddings that wish to
* @see org.mozilla.javascript.Context#addContextListener
*/
public interface ContextListener {
public void contextCreated(Context cx);
public void contextEntered(Context cx);
public void contextExited(Context cx);
public void contextReleased(Context cx);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,111 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
// API class
package org.mozilla.javascript;
import org.mozilla.javascript.debug.*;
public class DebuggableEngineImpl implements DebuggableEngine {
public DebuggableEngineImpl(Context cx) {
this.cx = cx;
}
/**
* Set whether the engine should break when it encounters
* the next line.
* <p>
* The engine will call the attached debugger's handleBreakpointHit
* method on the next line it executes if isLineStep is true.
* May be used from another thread to interrupt execution.
*
* @param isLineStep if true, break next line
*/
public void setBreakNextLine(boolean isLineStep) {
cx.inLineStepMode = isLineStep;
}
/**
* Return the value of the breakNextLine flag.
* @return true if the engine will break on execution of the
* next line.
*/
public boolean getBreakNextLine() {
return cx.inLineStepMode;
}
/**
* Set the associated debugger.
* @param debugger the debugger to be used on callbacks from
* the engine.
*/
public void setDebugger(Debugger debugger) {
cx.debugger = debugger;
}
/**
* Return the current debugger.
* @return the debugger, or null if none is attached.
*/
public Debugger getDebugger() {
return cx.debugger;
}
/**
* Return the number of frames in current execution.
* @return the count of current frames
*/
public int getFrameCount() {
return cx.frameStack == null ? 0 : cx.frameStack.size();
}
/**
* Return a frame from the current execution.
* Frames are numbered starting from 0 for the innermost
* frame.
* @param frameNumber the number of the frame in the range
* [0,frameCount-1]
* @return the relevant DebugFrame, or null if frameNumber is out
* of range or the engine isn't currently saving
* frames
*/
public DebugFrame getFrame(int frameNumber) {
return (DebugFrame) cx.frameStack.elementAt(cx.frameStack.size() - frameNumber - 1);
}
private Context cx;
}

View File

@@ -1,892 +0,0 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Mike Ang
* Igor Bukanov
* Mike McCabe
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
/**
* The following class save decompilation information about the source.
* Source information is returned from the parser as a String
* associated with function nodes and with the toplevel script. When
* saved in the constant pool of a class, this string will be UTF-8
* encoded, and token values will occupy a single byte.
* Source is saved (mostly) as token numbers. The tokens saved pretty
* much correspond to the token stream of a 'canonical' representation
* of the input program, as directed by the parser. (There were a few
* cases where tokens could have been left out where decompiler could
* easily reconstruct them, but I left them in for clarity). (I also
* looked adding source collection to TokenStream instead, where I
* could have limited the changes to a few lines in getToken... but
* this wouldn't have saved any space in the resulting source
* representation, and would have meant that I'd have to duplicate
* parser logic in the decompiler to disambiguate situations where
* newlines are important.) The function decompile expands the
* tokens back into their string representations, using simple
* lookahead to correct spacing and indentation.
*
* Assignments are saved as two-token pairs (Token.ASSIGN, op). Number tokens
* are stored inline, as a NUMBER token, a character representing the type, and
* either 1 or 4 characters representing the bit-encoding of the number. String
* types NAME, STRING and OBJECT are currently stored as a token type,
* followed by a character giving the length of the string (assumed to
* be less than 2^16), followed by the characters of the string
* inlined into the source string. Changing this to some reference to
* to the string in the compiled class' constant pool would probably
* save a lot of space... but would require some method of deriving
* the final constant pool entry from information available at parse
* time.
*/
public class Decompiler
{
/**
* Flag to indicate that the decompilation should omit the
* function header and trailing brace.
*/
public static final int ONLY_BODY_FLAG = 1 << 0;
/**
* Flag to indicate that the decompilation generates toSource result.
*/
public static final int TO_SOURCE_FLAG = 1 << 1;
/**
* Decompilation property to specify initial ident value.
*/
public static final int INITIAL_INDENT_PROP = 1;
/**
* Decompilation property to specify default identation offset.
*/
public static final int INDENT_GAP_PROP = 2;
/**
* Decompilation property to specify identation offset for case labels.
*/
public static final int CASE_GAP_PROP = 3;
// Marker to denote the last RC of function so it can be distinguished from
// the last RC of object literals in case of function expressions
private static final int FUNCTION_END = Token.LAST_TOKEN + 1;
String getEncodedSource()
{
return sourceToString(0);
}
int getCurrentOffset()
{
return sourceTop;
}
int markFunctionStart(int functionType, String name)
{
int savedOffset = getCurrentOffset();
addToken(Token.FUNCTION);
append((char)functionType);
if (name.length() != 0) {
addName(name);
}
return savedOffset;
}
int markFunctionEnd(int functionStart)
{
int offset = getCurrentOffset();
append((char)FUNCTION_END);
return offset;
}
void addToken(int token)
{
if (!(0 <= token && token <= Token.LAST_TOKEN))
throw new IllegalArgumentException();
append((char)token);
}
void addEOL(int token)
{
if (!(0 <= token && token <= Token.LAST_TOKEN))
throw new IllegalArgumentException();
append((char)token);
append((char)Token.EOL);
}
void addAssignOp(int op)
{
if (!(0 <= op && op <= Token.LAST_TOKEN))
throw new IllegalArgumentException();
append((char)Token.ASSIGNOP);
append((char)op);
}
void addName(String str)
{
addToken(Token.NAME);
appendString(str);
}
void addString(String str)
{
addToken(Token.STRING);
appendString(str);
}
void addRegexp(String regexp, String flags)
{
addToken(Token.REGEXP);
appendString('/' + regexp + '/' + flags);
}
void addNumber(double n)
{
addToken(Token.NUMBER);
/* encode the number in the source stream.
* Save as NUMBER type (char | char char char char)
* where type is
* 'D' - double, 'S' - short, 'J' - long.
* We need to retain float vs. integer type info to keep the
* behavior of liveconnect type-guessing the same after
* decompilation. (Liveconnect tries to present 1.0 to Java
* as a float/double)
* OPT: This is no longer true. We could compress the format.
* This may not be the most space-efficient encoding;
* the chars created below may take up to 3 bytes in
* constant pool UTF-8 encoding, so a Double could take
* up to 12 bytes.
*/
long lbits = (long)n;
if (lbits != n) {
// if it's floating point, save as a Double bit pattern.
// (12/15/97 our scanner only returns Double for f.p.)
lbits = Double.doubleToLongBits(n);
append('D');
append((char)(lbits >> 48));
append((char)(lbits >> 32));
append((char)(lbits >> 16));
append((char)lbits);
}
else {
// we can ignore negative values, bc they're already prefixed
// by NEG
if (lbits < 0) Kit.codeBug();
// will it fit in a char?
// this gives a short encoding for integer values up to 2^16.
if (lbits <= Character.MAX_VALUE) {
append('S');
append((char)lbits);
}
else { // Integral, but won't fit in a char. Store as a long.
append('J');
append((char)(lbits >> 48));
append((char)(lbits >> 32));
append((char)(lbits >> 16));
append((char)lbits);
}
}
}
private void appendString(String str)
{
int L = str.length();
int lengthEncodingSize = 1;
if (L >= 0x8000) {
lengthEncodingSize = 2;
}
int nextTop = sourceTop + lengthEncodingSize + L;
if (nextTop > sourceBuffer.length) {
increaseSourceCapacity(nextTop);
}
if (L >= 0x8000) {
// Use 2 chars to encode strings exceeding 32K, were the highest
// bit in the first char indicates presence of the next byte
sourceBuffer[sourceTop] = (char)(0x8000 | (L >>> 16));
++sourceTop;
}
sourceBuffer[sourceTop] = (char)L;
++sourceTop;
str.getChars(0, L, sourceBuffer, sourceTop);
sourceTop = nextTop;
}
private void append(char c)
{
if (sourceTop == sourceBuffer.length) {
increaseSourceCapacity(sourceTop + 1);
}
sourceBuffer[sourceTop] = c;
++sourceTop;
}
private void increaseSourceCapacity(int minimalCapacity)
{
// Call this only when capacity increase is must
if (minimalCapacity <= sourceBuffer.length) Kit.codeBug();
int newCapacity = sourceBuffer.length * 2;
if (newCapacity < minimalCapacity) {
newCapacity = minimalCapacity;
}
char[] tmp = new char[newCapacity];
System.arraycopy(sourceBuffer, 0, tmp, 0, sourceTop);
sourceBuffer = tmp;
}
private String sourceToString(int offset)
{
if (offset < 0 || sourceTop < offset) Kit.codeBug();
return new String(sourceBuffer, offset, sourceTop - offset);
}
/**
* Decompile the source information associated with this js
* function/script back into a string. For the most part, this
* just means translating tokens back to their string
* representations; there's a little bit of lookahead logic to
* decide the proper spacing/indentation. Most of the work in
* mapping the original source to the prettyprinted decompiled
* version is done by the parser.
*
* @param source encoded source tree presentation
*
* @param flags flags to select output format
*
* @param properties indentation properties
*
*/
public static String decompile(String source, int flags,
UintMap properties)
{
int length = source.length();
if (length == 0) { return ""; }
int indent = properties.getInt(INITIAL_INDENT_PROP, 0);
if (indent < 0) Kit.badArg();
int indentGap = properties.getInt(INDENT_GAP_PROP, 4);
if (indentGap < 0) Kit.badArg();
int caseGap = properties.getInt(CASE_GAP_PROP, 2);
if (caseGap < 0) Kit.badArg();
StringBuffer result = new StringBuffer();
boolean justFunctionBody = (0 != (flags & Decompiler.ONLY_BODY_FLAG));
boolean toSource = (0 != (flags & Decompiler.TO_SOURCE_FLAG));
// Spew tokens in source, for debugging.
// as TYPE number char
if (printSource) {
System.err.println("length:" + length);
for (int i = 0; i < length; ++i) {
// Note that tokenToName will fail unless Context.printTrees
// is true.
String tokenname = null;
if (Token.printNames) {
tokenname = Token.name(source.charAt(i));
}
if (tokenname == null) {
tokenname = "---";
}
String pad = tokenname.length() > 7
? "\t"
: "\t\t";
System.err.println
(tokenname
+ pad + (int)source.charAt(i)
+ "\t'" + ScriptRuntime.escapeString
(source.substring(i, i+1))
+ "'");
}
System.err.println();
}
int braceNesting = 0;
boolean afterFirstEOL = false;
int i = 0;
int topFunctionType;
if (source.charAt(i) == Token.SCRIPT) {
++i;
topFunctionType = -1;
} else {
topFunctionType = source.charAt(i + 1);
}
if (!toSource) {
// add an initial newline to exactly match js.
result.append('\n');
for (int j = 0; j < indent; j++)
result.append(' ');
} else {
if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) {
result.append('(');
}
}
while (i < length) {
switch(source.charAt(i)) {
case Token.NAME:
case Token.REGEXP: // re-wrapped in '/'s in parser...
i = printSourceString(source, i + 1, false, result);
continue;
case Token.STRING:
i = printSourceString(source, i + 1, true, result);
continue;
case Token.NUMBER:
i = printSourceNumber(source, i + 1, result);
continue;
case Token.TRUE:
result.append("true");
break;
case Token.FALSE:
result.append("false");
break;
case Token.NULL:
result.append("null");
break;
case Token.THIS:
result.append("this");
break;
case Token.FUNCTION:
++i; // skip function type
result.append("function ");
break;
case FUNCTION_END:
// Do nothing
break;
case Token.COMMA:
result.append(", ");
break;
case Token.LC:
++braceNesting;
if (Token.EOL == getNext(source, length, i))
indent += indentGap;
result.append('{');
break;
case Token.RC: {
--braceNesting;
/* don't print the closing RC if it closes the
* toplevel function and we're called from
* decompileFunctionBody.
*/
if (justFunctionBody && braceNesting == 0)
break;
result.append('}');
switch (getNext(source, length, i)) {
case Token.EOL:
case FUNCTION_END:
indent -= indentGap;
break;
case Token.WHILE:
case Token.ELSE:
indent -= indentGap;
result.append(' ');
break;
}
break;
}
case Token.LP:
result.append('(');
break;
case Token.RP:
result.append(')');
if (Token.LC == getNext(source, length, i))
result.append(' ');
break;
case Token.LB:
result.append('[');
break;
case Token.RB:
result.append(']');
break;
case Token.EOL: {
if (toSource) break;
boolean newLine = true;
if (!afterFirstEOL) {
afterFirstEOL = true;
if (justFunctionBody) {
/* throw away just added 'function name(...) {'
* and restore the original indent
*/
result.setLength(0);
indent -= indentGap;
newLine = false;
}
}
if (newLine) {
result.append('\n');
}
/* add indent if any tokens remain,
* less setback if next token is
* a label, case or default.
*/
if (i + 1 < length) {
int less = 0;
int nextToken = source.charAt(i + 1);
if (nextToken == Token.CASE
|| nextToken == Token.DEFAULT)
{
less = indentGap - caseGap;
} else if (nextToken == Token.RC) {
less = indentGap;
}
/* elaborate check against label... skip past a
* following inlined NAME and look for a COLON.
*/
else if (nextToken == Token.NAME) {
int afterName = getSourceStringEnd(source, i + 2);
if (source.charAt(afterName) == Token.COLON)
less = indentGap;
}
for (; less < indent; less++)
result.append(' ');
}
break;
}
case Token.DOT:
result.append('.');
break;
case Token.NEW:
result.append("new ");
break;
case Token.DELPROP:
result.append("delete ");
break;
case Token.IF:
result.append("if ");
break;
case Token.ELSE:
result.append("else ");
break;
case Token.FOR:
result.append("for ");
break;
case Token.IN:
result.append(" in ");
break;
case Token.WITH:
result.append("with ");
break;
case Token.WHILE:
result.append("while ");
break;
case Token.DO:
result.append("do ");
break;
case Token.TRY:
result.append("try ");
break;
case Token.CATCH:
result.append("catch ");
break;
case Token.FINALLY:
result.append("finally ");
break;
case Token.THROW:
result.append("throw ");
break;
case Token.SWITCH:
result.append("switch ");
break;
case Token.BREAK:
result.append("break");
if (Token.NAME == getNext(source, length, i))
result.append(' ');
break;
case Token.CONTINUE:
result.append("continue");
if (Token.NAME == getNext(source, length, i))
result.append(' ');
break;
case Token.CASE:
result.append("case ");
break;
case Token.DEFAULT:
result.append("default");
break;
case Token.RETURN:
result.append("return");
if (Token.SEMI != getNext(source, length, i))
result.append(' ');
break;
case Token.VAR:
result.append("var ");
break;
case Token.SEMI:
result.append(';');
if (Token.EOL != getNext(source, length, i)) {
// separators in FOR
result.append(' ');
}
break;
case Token.ASSIGN:
result.append(" = ");
break;
case Token.ASSIGNOP:
++i;
switch (source.charAt(i)) {
case Token.ADD:
result.append(" += ");
break;
case Token.SUB:
result.append(" -= ");
break;
case Token.MUL:
result.append(" *= ");
break;
case Token.DIV:
result.append(" /= ");
break;
case Token.MOD:
result.append(" %= ");
break;
case Token.BITOR:
result.append(" |= ");
break;
case Token.BITXOR:
result.append(" ^= ");
break;
case Token.BITAND:
result.append(" &= ");
break;
case Token.LSH:
result.append(" <<= ");
break;
case Token.RSH:
result.append(" >>= ");
break;
case Token.URSH:
result.append(" >>>= ");
break;
}
break;
case Token.HOOK:
result.append(" ? ");
break;
case Token.OBJLIT:
// pun OBJLIT to mean colon in objlit property initialization.
// this needs to be distinct from COLON in the general case
// to distinguish from the colon in a ternary... which needs
// different spacing.
result.append(':');
break;
case Token.COLON:
if (Token.EOL == getNext(source, length, i))
// it's the end of a label
result.append(':');
else
// it's the middle part of a ternary
result.append(" : ");
break;
case Token.OR:
result.append(" || ");
break;
case Token.AND:
result.append(" && ");
break;
case Token.BITOR:
result.append(" | ");
break;
case Token.BITXOR:
result.append(" ^ ");
break;
case Token.BITAND:
result.append(" & ");
break;
case Token.SHEQ:
result.append(" === ");
break;
case Token.SHNE:
result.append(" !== ");
break;
case Token.EQ:
result.append(" == ");
break;
case Token.NE:
result.append(" != ");
break;
case Token.LE:
result.append(" <= ");
break;
case Token.LT:
result.append(" < ");
break;
case Token.GE:
result.append(" >= ");
break;
case Token.GT:
result.append(" > ");
break;
case Token.INSTANCEOF:
result.append(" instanceof ");
break;
case Token.LSH:
result.append(" << ");
break;
case Token.RSH:
result.append(" >> ");
break;
case Token.URSH:
result.append(" >>> ");
break;
case Token.TYPEOF:
result.append("typeof ");
break;
case Token.VOID:
result.append("void ");
break;
case Token.NOT:
result.append('!');
break;
case Token.BITNOT:
result.append('~');
break;
case Token.POS:
result.append('+');
break;
case Token.NEG:
result.append('-');
break;
case Token.INC:
result.append("++");
break;
case Token.DEC:
result.append("--");
break;
case Token.ADD:
result.append(" + ");
break;
case Token.SUB:
result.append(" - ");
break;
case Token.MUL:
result.append(" * ");
break;
case Token.DIV:
result.append(" / ");
break;
case Token.MOD:
result.append(" % ");
break;
default:
// If we don't know how to decompile it, raise an exception.
throw new RuntimeException();
}
++i;
}
if (!toSource) {
// add that trailing newline if it's an outermost function.
if (!justFunctionBody)
result.append('\n');
} else {
if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) {
result.append(')');
}
}
return result.toString();
}
private static int getNext(String source, int length, int i)
{
return (i + 1 < length) ? source.charAt(i + 1) : Token.EOF;
}
private static int getSourceStringEnd(String source, int offset)
{
return printSourceString(source, offset, false, null);
}
private static int printSourceString(String source, int offset,
boolean asQuotedString,
StringBuffer sb)
{
int length = source.charAt(offset);
++offset;
if ((0x8000 & length) != 0) {
length = ((0x7FFF & length) << 16) | source.charAt(offset);
++offset;
}
if (sb != null) {
String str = source.substring(offset, offset + length);
if (!asQuotedString) {
sb.append(str);
} else {
sb.append('"');
sb.append(ScriptRuntime.escapeString(str));
sb.append('"');
}
}
return offset + length;
}
private static int printSourceNumber(String source, int offset,
StringBuffer sb)
{
double number = 0.0;
char type = source.charAt(offset);
++offset;
if (type == 'S') {
if (sb != null) {
int ival = source.charAt(offset);
number = ival;
}
++offset;
} else if (type == 'J' || type == 'D') {
if (sb != null) {
long lbits;
lbits = (long)source.charAt(offset) << 48;
lbits |= (long)source.charAt(offset + 1) << 32;
lbits |= (long)source.charAt(offset + 2) << 16;
lbits |= (long)source.charAt(offset + 3);
if (type == 'J') {
number = lbits;
} else {
number = Double.longBitsToDouble(lbits);
}
}
offset += 4;
} else {
// Bad source
throw new RuntimeException();
}
if (sb != null) {
sb.append(ScriptRuntime.numberToString(number, 10));
}
return offset;
}
private char[] sourceBuffer = new char[128];
// Per script/function source buffer top: parent source does not include a
// nested functions source and uses function index as a reference instead.
private int sourceTop;
// whether to do a debug print of the source information, when decompiling.
private static final boolean printSource = false;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -51,15 +51,13 @@ class DefaultErrorReporter implements ErrorReporter {
public void error(String message, String sourceName, int line,
String lineSource, int lineOffset)
{
throw new EvaluatorException(message, sourceName, line,
lineSource, lineOffset);
throw new EvaluatorException(message);
}
public EvaluatorException runtimeError(String message, String sourceName,
int line, String lineSource,
int line, String lineSource,
int lineOffset)
{
throw new EvaluatorException(message, sourceName, line,
lineSource, lineOffset);
return new EvaluatorException(message);
}
}

View File

@@ -76,21 +76,6 @@ public class Delegator implements Function {
this.obj = obj;
}
/**
* Crete new Delegator instance.
* The default implementation calls this.getClass().newInstance().
*
* @see #construct(Context cx, Scriptable scope, Object[] args)
*/
protected Delegator newInstance()
{
try {
return (Delegator)this.getClass().newInstance();
} catch (Exception ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
}
/**
* Retrieve the delegee.
*
@@ -247,15 +232,16 @@ public class Delegator implements Function {
if (obj == null) {
//this little trick allows us to declare prototype objects for
//Delegators
Delegator n = newInstance();
Scriptable delegee;
if (args.length == 0) {
delegee = Undefined.instance;
} else {
delegee = ScriptRuntime.toObject(cx, scope, args[0]);
try {
Delegator n = (Delegator)this.getClass().newInstance();
n.setDelegee((Scriptable)args[0]);
return n;
}
n.setDelegee(delegee);
return n;
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
return null;
}
else {
return ((Function)obj).construct(cx,scope,args);

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,9 +18,9 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Roger Lawrence
*
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
@@ -38,100 +38,85 @@
package org.mozilla.javascript;
/**
* The class of exceptions raised by the engine as described in
* The class of exceptions raised by the engine as described in
* ECMA edition 3. See section 15.11.6 in particular.
*/
public class EcmaError extends RuntimeException
{
public class EcmaError extends RuntimeException {
/**
* Create an exception with the specified detail message.
*
* Errors internal to the JavaScript engine will simply throw a
* RuntimeException.
*
* @param nativeError the NativeError object constructed for this error
* @param sourceName the name of the source reponsible for the error
* @param lineNumber the line number of the source
* @param columnNumber the columnNumber of the source (may be zero if
* unknown)
* @param lineSource the source of the line containing the error (may be
* @param lineSource the source of the line containing the error (may be
* null if unknown)
*/
EcmaError(String errorName, String errorMessage,
String sourceName, int lineNumber,
String lineSource, int columnNumber)
public EcmaError(NativeError nativeError, String sourceName,
int lineNumber, int columnNumber, String lineSource)
{
super("EcmaError: "+errorName+": "+errorMessage);
this.errorName = errorName;
this.errorMessage = errorMessage;
super("EcmaError");
errorObject = nativeError;
this.sourceName = sourceName;
this.lineNumber = lineNumber;
this.lineSource = lineSource;
this.columnNumber = columnNumber;
this.lineSource = lineSource;
}
/**
* @deprecated EcmaError error instances should not be constructed
* explicitly since they are generated by the engine.
*/
public EcmaError(Scriptable nativeError, String sourceName,
int lineNumber, int columnNumber, String lineSource)
{
this("InternalError", ScriptRuntime.toString(nativeError),
sourceName, lineNumber, lineSource, columnNumber);
}
/**
* Return a string representation of the error, which currently consists
* Return a string representation of the error, which currently consists
* of the name of the error together with the message.
*/
public String toString()
{
public String toString() {
if (sourceName == null && lineNumber <= 0)
return errorObject.toString();
StringBuffer buf = new StringBuffer();
buf.append(errorName);
buf.append(": ");
buf.append(errorMessage);
if (sourceName != null || lineNumber > 0) {
buf.append(" (");
if (sourceName != null) {
buf.append(sourceName);
buf.append("; ");
}
if (lineNumber > 0) {
buf.append("line ");
buf.append(lineNumber);
}
buf.append(')');
buf.append(errorObject.toString());
buf.append(" (");
if (sourceName != null) {
buf.append(sourceName);
buf.append("; ");
}
if (lineNumber > 0) {
buf.append("line ");
buf.append(lineNumber);
}
buf.append(')');
return buf.toString();
}
/**
* Gets the name of the error.
*
*
* ECMA edition 3 defines the following
* errors: EvalError, RangeError, ReferenceError,
* errors: EvalError, RangeError, ReferenceError,
* SyntaxError, TypeError, and URIError. Additional error names
* may be added in the future.
*
*
* See ECMA edition 3, 15.11.7.9.
*
* @return the name of the error.
*
* @return the name of the error.
*/
public String getName() {
return errorName;
return errorObject.getName();
}
/**
* Gets the message corresponding to the error.
*
*
* See ECMA edition 3, 15.11.7.10.
*
*
* @return an implemenation-defined string describing the error.
*/
public String getMessage() {
return errorMessage;
return errorObject.getMessage();
}
/**
* Get the name of the source containing the error, or null
* if that information is not available.
@@ -139,7 +124,7 @@ public class EcmaError extends RuntimeException
public String getSourceName() {
return sourceName;
}
/**
* Returns the line number of the statement causing the error,
* or zero if not available.
@@ -147,32 +132,29 @@ public class EcmaError extends RuntimeException
public int getLineNumber() {
return lineNumber;
}
/**
* Get the error object corresponding to this exception.
*/
public Scriptable getErrorObject() {
return errorObject;
}
/**
* The column number of the location of the error, or zero if unknown.
*/
public int getColumnNumber() {
return columnNumber;
}
/**
* The source of the line causing the error, or zero if unknown.
*/
public String getLineSource() {
return lineSource;
}
/**
* @deprecated Always returns result of {@link Context#getUndefinedValue()}.
*
*/
public Scriptable getErrorObject()
{
return Undefined.instance;
}
private String errorName;
private String errorMessage;
private NativeError errorObject;
private String sourceName;
private int lineNumber;
private int columnNumber;

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -97,7 +97,7 @@ public interface ErrorReporter {
* @param lineOffset the offset into lineSource where problem was detected
* @return an EvaluatorException that will be thrown.
*/
EvaluatorException runtimeError(String message, String sourceName,
int line, String lineSource,
EvaluatorException runtimeError(String message, String sourceName,
int line, String lineSource,
int lineOffset);
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -39,8 +39,7 @@ package org.mozilla.javascript;
/**
* The class of exceptions thrown by the JavaScript engine.
*/
public class EvaluatorException extends RuntimeException
{
public class EvaluatorException extends RuntimeException {
/**
* Create an exception with the specified detail message.
@@ -50,98 +49,8 @@ public class EvaluatorException extends RuntimeException
*
* @param detail a message with detail about the exception
*/
public EvaluatorException(String detail)
{
public EvaluatorException(String detail) {
super(detail);
Context cx = Context.getCurrentContext();
if (cx!= null) {
int[] linep = { 0 };
this.sourceName = cx.getSourcePositionFromStack(linep);
this.lineNumber = linep[0];
}
}
/**
* Create an exception with the specified detail message.
*
* Errors internal to the JavaScript engine will simply throw a
* RuntimeException.
*
* @param nativeError the Scriptable object constructed for this error.
Scripts will get it as an argument to catch statement.
* @param sourceName the name of the source reponsible for the error
* @param lineNumber the line number of the source
* @param columnNumber the columnNumber of the source (may be zero if
* unknown)
* @param lineSource the source of the line containing the error (may be
* null if unknown)
*/
public EvaluatorException(String detail, String sourceName, int lineNumber,
String lineSource, int columnNumber)
{
super(generateErrorMessage(detail, sourceName, lineNumber));
this.sourceName = sourceName;
this.lineNumber = lineNumber;
this.lineSource = lineSource;
this.columnNumber = columnNumber;
}
/**
* Get the name of the source containing the error, or null
* if that information is not available.
*/
public String getSourceName()
{
return sourceName;
}
/**
* Returns the line number of the statement causing the error,
* or zero if not available.
*/
public int getLineNumber()
{
return lineNumber;
}
/**
* The column number of the location of the error, or zero if unknown.
*/
public int getColumnNumber()
{
return columnNumber;
}
/**
* The source of the line causing the error, or zero if unknown.
*/
public String getLineSource()
{
return lineSource;
}
static String generateErrorMessage(String message,
String sourceName,
int line)
{
if (sourceName == null || line <= 0) {
return message;
}
StringBuffer buf = new StringBuffer(message);
buf.append(" (");
if (sourceName != null) {
buf.append(sourceName);
}
if (line > 0) {
buf.append('#');
buf.append(line);
}
buf.append(')');
return buf.toString();
}
private String sourceName;
private int lineNumber;
private String lineSource;
private int columnNumber;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -45,7 +45,7 @@ package org.mozilla.javascript;
* @author Norris Boyd
*/
public interface Function extends Scriptable, Callable {
public interface Function extends Scriptable {
/**
* Call the function.
*

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
* Roger Lawrence
*
@@ -38,15 +38,19 @@ package org.mozilla.javascript;
import java.util.*;
public class FunctionNode extends ScriptOrFnNode {
public class FunctionNode extends Node {
public FunctionNode(String name) {
super(Token.FUNCTION);
functionName = name;
public FunctionNode(String name, Node left, Node right) {
super(TokenStream.FUNCTION, left, right, name);
itsVariableTable = new VariableTable();
}
public String getFunctionName() {
return functionName;
return getString();
}
public VariableTable getVariableTable() {
return itsVariableTable;
}
public boolean requiresActivation() {
@@ -56,98 +60,44 @@ public class FunctionNode extends ScriptOrFnNode {
public boolean setRequiresActivation(boolean b) {
return itsNeedsActivation = b;
}
public boolean getCheckThis() {
return itsCheckThis;
}
public void setCheckThis() {
itsCheckThis = true;
public void setCheckThis(boolean b) {
itsCheckThis = b;
}
public boolean getIgnoreDynamicScope() {
return itsIgnoreDynamicScope;
}
public void setIgnoreDynamicScope() {
itsIgnoreDynamicScope = true;
}
/**
* There are three types of functions that can be defined. The first
* is a function statement. This is a function appearing as a top-level
* statement (i.e., not nested inside some other statement) in either a
* script or a function.
*
*
* The second is a function expression, which is a function appearing in
* an expression except for the third type, which is...
*
* The third type is a function expression where the expression is the
*
* The third type is a function expression where the expression is the
* top-level expression in an expression statement.
*
* The three types of functions have different treatment and must be
*
* The three types of functions have different treatment and must be
* distinquished.
*/
public static final int FUNCTION_STATEMENT = 1;
public static final int FUNCTION_EXPRESSION = 2;
public static final int FUNCTION_EXPRESSION_STATEMENT = 3;
public int getFunctionType() {
public static final byte FUNCTION_STATEMENT = 1;
public static final byte FUNCTION_EXPRESSION = 2;
public static final byte FUNCTION_EXPRESSION_STATEMENT = 3;
public byte getFunctionType() {
return itsFunctionType;
}
public void setFunctionType(int functionType) {
public void setFunctionType(byte functionType) {
itsFunctionType = functionType;
}
protected void finishParsing(IRFactory irFactory) {
super.finishParsing(irFactory);
int functionCount = getFunctionCount();
if (functionCount != 0) {
for (int i = 0; i != functionCount; ++i) {
FunctionNode fn = getFunctionNode(i);
// nested function expression statements overrides var
if (fn.getFunctionType() == FUNCTION_EXPRESSION_STATEMENT) {
String name = fn.getFunctionName();
if (name != null && name.length() != 0) {
removeParamOrVar(name);
}
}
}
// Functions containing other functions require activation objects
setRequiresActivation(true);
}
Node stmts = getLastChild();
if (getFunctionType() == FUNCTION_EXPRESSION) {
String name = getFunctionName();
if (name != null && name.length() != 0 && !hasParamOrVar(name))
{
// A function expression needs to have its name as a
// variable (if it isn't already allocated as a variable).
// See ECMA Ch. 13. We add code to the beginning of the
// function to initialize a local variable of the
// function's name to the function value.
addVar(name);
Node setFn = new Node(Token.POP,
new Node(Token.SETVAR, Node.newString(name),
new Node(Token.THISFN)));
stmts.addChildrenToFront(setFn);
}
}
// Add return to end if needed.
Node lastStmt = stmts.getLastChild();
if (lastStmt == null || lastStmt.getType() != Token.RETURN) {
stmts.addChildToBack(new Node(Token.RETURN));
}
}
private String functionName;
private boolean itsNeedsActivation;
private boolean itsCheckThis;
private int itsFunctionType;
private boolean itsIgnoreDynamicScope;
protected VariableTable itsVariableTable;
protected boolean itsNeedsActivation;
protected boolean itsCheckThis;
protected byte itsFunctionType;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
* Igor Bukanov
* David C. Navas
@@ -40,11 +40,14 @@
package org.mozilla.javascript;
import java.lang.reflect.*;
import java.io.*;
import java.util.Vector;
import java.lang.reflect.Constructor;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.InvocationTargetException;
public class FunctionObject extends BaseFunction
{
public class FunctionObject extends NativeFunction {
static final long serialVersionUID = -4074285335521944312L;
@@ -56,10 +59,10 @@ public class FunctionObject extends BaseFunction
*
* The first form is a member with zero or more parameters
* of the following types: Object, String, boolean, Scriptable,
* int, or double. The Long type is not supported
* because the double representation of a long (which is the
* byte, short, int, float, or double. The Long type is not supported
* because the double representation of a long (which is the
* EMCA-mandated storage type for Numbers) may lose precision.
* If the member is a Method, the return value must be void or one
* If the member is a Method, the return value must be void or one
* of the types allowed for parameters.<p>
*
* The runtime will perform appropriate conversions based
@@ -115,23 +118,25 @@ public class FunctionObject extends BaseFunction
public FunctionObject(String name, Member methodOrConstructor,
Scriptable scope)
{
ClassCache cache = ClassCache.get(scope);
String methodName;
if (methodOrConstructor instanceof Constructor) {
member = new MemberBox((Constructor) methodOrConstructor, cache);
ctor = (Constructor) methodOrConstructor;
isStatic = true; // well, doesn't take a 'this'
types = ctor.getParameterTypes();
methodName = ctor.getName();
} else {
member = new MemberBox((Method) methodOrConstructor, cache);
isStatic = member.isStatic();
method = (Method) methodOrConstructor;
isStatic = Modifier.isStatic(method.getModifiers());
types = method.getParameterTypes();
methodName = method.getName();
}
String methodName = member.getName();
this.functionName = name;
Class[] types = member.argTypes;
int arity = types.length;
if (arity == 4 && (types[1].isArray() || types[2].isArray())) {
int length;
if (types.length == 4 && (types[1].isArray() || types[2].isArray())) {
// Either variable args or an error.
if (types[1].isArray()) {
if (!isStatic ||
types[0] != ScriptRuntime.ContextClass ||
types[0] != Context.class ||
types[1].getComponentType() != ScriptRuntime.ObjectClass ||
types[2] != ScriptRuntime.FunctionClass ||
types[3] != Boolean.TYPE)
@@ -142,7 +147,7 @@ public class FunctionObject extends BaseFunction
parmsLength = VARARGS_CTOR;
} else {
if (!isStatic ||
types[0] != ScriptRuntime.ContextClass ||
types[0] != Context.class ||
types[1] != ScriptRuntime.ScriptableClass ||
types[2].getComponentType() != ScriptRuntime.ObjectClass ||
types[3] != ScriptRuntime.FunctionClass)
@@ -152,157 +157,134 @@ public class FunctionObject extends BaseFunction
}
parmsLength = VARARGS_METHOD;
}
// XXX check return type
length = 1;
} else {
parmsLength = arity;
if (arity > 0) {
typeTags = new byte[arity];
for (int i = 0; i != arity; ++i) {
int tag = getTypeTag(types[i]);
if (tag == JAVA_UNSUPPORTED_TYPE) {
throw Context.reportRuntimeError2(
"msg.bad.parms", types[i].getName(), methodName);
}
typeTags[i] = (byte)tag;
parmsLength = (short) types.length;
for (int i=0; i < parmsLength; i++) {
Class type = types[i];
if (type != ScriptRuntime.ObjectClass &&
type != ScriptRuntime.StringClass &&
type != ScriptRuntime.BooleanClass &&
!ScriptRuntime.NumberClass.isAssignableFrom(type) &&
!Scriptable.class.isAssignableFrom(type) &&
type != Boolean.TYPE &&
type != Byte.TYPE &&
type != Short.TYPE &&
type != Integer.TYPE &&
type != Float.TYPE &&
type != Double.TYPE)
{
// Note that long is not supported.
throw Context.reportRuntimeError1("msg.bad.parms",
methodName);
}
}
length = parmsLength;
}
if (member.isMethod()) {
Method method = member.method();
Class returnType = method.getReturnType();
if (returnType == Void.TYPE) {
hasVoidReturn = true;
} else {
int returnTypeTag = getTypeTag(returnType);
if (returnTypeTag == JAVA_UNSUPPORTED_TYPE) {
throw Context.reportRuntimeError2(
"msg.bad.method.return",
returnType.getName(), methodName);
}
}
member.prepareInvokerOptimization();
} else {
Class ctorType = member.getDeclaringClass();
if (!ScriptRuntime.ScriptableClass.isAssignableFrom(ctorType)) {
throw Context.reportRuntimeError1(
"msg.bad.ctor.return", ctorType.getName());
}
}
// Initialize length property
lengthPropertyValue = (short) length;
ScriptRuntime.setFunctionProtoAndParent(scope, this);
}
hasVoidReturn = method != null && method.getReturnType() == Void.TYPE;
this.argCount = (short) length;
/**
* @return One of <tt>JAVA_*_TYPE</tt> constants to indicate desired type
* or {@link #JAVA_UNSUPPORTED_TYPE} if the convertion is not
* possible
*/
public static int getTypeTag(Class type)
{
if (type == ScriptRuntime.StringClass)
return JAVA_STRING_TYPE;
if (type == ScriptRuntime.IntegerClass || type == Integer.TYPE)
return JAVA_INT_TYPE;
if (type == ScriptRuntime.BooleanClass || type == Boolean.TYPE)
return JAVA_BOOLEAN_TYPE;
if (type == ScriptRuntime.DoubleClass || type == Double.TYPE)
return JAVA_DOUBLE_TYPE;
if (ScriptRuntime.ScriptableClass.isAssignableFrom(type))
return JAVA_SCRIPTABLE_TYPE;
if (type == ScriptRuntime.ObjectClass)
return JAVA_OBJECT_TYPE;
// Note that the long type is not supported; see the javadoc for
// the constructor for this class
return JAVA_UNSUPPORTED_TYPE;
}
public static Object convertArg(Context cx, Scriptable scope,
Object arg, int typeTag)
{
switch (typeTag) {
case JAVA_STRING_TYPE:
if (arg instanceof String)
return arg;
return ScriptRuntime.toString(arg);
case JAVA_INT_TYPE:
if (arg instanceof Integer)
return arg;
return new Integer(ScriptRuntime.toInt32(arg));
case JAVA_BOOLEAN_TYPE:
if (arg instanceof Boolean)
return arg;
return ScriptRuntime.toBoolean(arg) ? Boolean.TRUE
: Boolean.FALSE;
case JAVA_DOUBLE_TYPE:
if (arg instanceof Double)
return arg;
if (arg instanceof Number)
return new Double(((Number)arg).doubleValue());
return new Double(ScriptRuntime.toNumber(arg));
case JAVA_SCRIPTABLE_TYPE:
if (arg instanceof Scriptable)
return arg;
return ScriptRuntime.toObject(cx, scope, arg);
case JAVA_OBJECT_TYPE:
return arg;
default:
throw new IllegalArgumentException();
}
setParentScope(scope);
setPrototype(getFunctionPrototype(scope));
Context cx = Context.getCurrentContext();
useDynamicScope = cx != null &&
cx.hasCompileFunctionsWithDynamicScope();
}
/**
* Return the value defined by the method used to construct the object
* (number of parameters of the method, or 1 if the method is a "varargs"
* form).
*/
public int getArity() {
return parmsLength < 0 ? 1 : parmsLength;
}
/**
* Return the same value as {@link #getArity()}.
* form), unless setLength has been called with a new value.
* Overrides getLength in BaseFunction.
*
* @see org.mozilla.javascript.FunctionObject#setLength
* @see org.mozilla.javascript.BaseFunction#getLength
*/
public int getLength() {
return getArity();
return lengthPropertyValue;
}
/**
* Get Java method or constructor this function represent.
* Set the value of the "length" property.
*
* <p>Changing the value of the "length" property of a FunctionObject only
* affects the value retrieved from get() and does not affect the way
* the method itself is called. <p>
*
* The "length" property will be defined by default as the number
* of parameters of the method used to construct the FunctionObject,
* unless the method is a "varargs" form, in which case the "length"
* property will be defined to 1.
*
* @param length the new length
*/
public Member getMethodOrConstructor()
{
if (member.isMethod()) {
return member.method();
} else {
return member.ctor();
}
public void setLength(short length) {
lengthPropertyValue = length;
}
static Method findSingleMethod(Method[] methods, String name)
{
Method found = null;
for (int i = 0, N = methods.length; i != N; ++i) {
Method method = methods[i];
if (method != null && name.equals(method.getName())) {
if (found != null) {
throw Context.reportRuntimeError2(
"msg.no.overload", name,
method.getDeclaringClass().getName());
// TODO: Make not public
/**
* Finds methods of a given name in a given class.
*
* <p>Searches <code>clazz</code> for methods with name
* <code>name</code>. Maintains a cache so that multiple
* lookups on the same class are cheap.
*
* @param clazz the class to search
* @param name the name of the methods to find
* @return an array of the found methods, or null if no methods
* by that name were found.
* @see java.lang.Class#getMethods
*/
public static Method[] findMethods(Class clazz, String name) {
return findMethods(getMethodList(clazz), name);
}
static Method[] findMethods(Method[] methods, String name) {
// Usually we're just looking for a single method, so optimize
// for that case.
Vector v = null;
Method first = null;
for (int i=0; i < methods.length; i++) {
if (methods[i] == null)
continue;
if (methods[i].getName().equals(name)) {
if (first == null) {
first = methods[i];
} else {
if (v == null) {
v = new Vector(5);
v.addElement(first);
}
v.addElement(methods[i]);
}
found = method;
}
}
return found;
if (v == null) {
if (first == null)
return null;
Method[] single = { first };
return single;
}
Method[] result = new Method[v.size()];
v.copyInto(result);
return result;
}
static Method[] getMethodList(Class clazz) {
Method[] cached = methodsCache; // get once to avoid synchronization
if (cached != null && cached[0].getDeclaringClass() == clazz)
return cached;
Method[] methods = null;
try {
// getDeclaredMethods may be rejected by the security manager
// but getMethods is more expensive
if (!sawSecurityException)
if (!sawSecurityException)
methods = clazz.getDeclaredMethods();
} catch (SecurityException e) {
// If we get an exception once, give up on getDeclaredMethods
@@ -313,7 +295,7 @@ public class FunctionObject extends BaseFunction
}
int count = 0;
for (int i=0; i < methods.length; i++) {
if (sawSecurityException
if (sawSecurityException
? methods[i].getDeclaringClass() != clazz
: !Modifier.isPublic(methods[i].getModifiers()))
{
@@ -328,6 +310,8 @@ public class FunctionObject extends BaseFunction
if (methods[i] != null)
result[j++] = methods[i];
}
if (result.length > 0 && Context.isCachingEnabled)
methodsCache = result;
return result;
}
@@ -348,11 +332,12 @@ public class FunctionObject extends BaseFunction
* @see org.mozilla.javascript.Scriptable#getClassName
*/
public void addAsConstructor(Scriptable scope, Scriptable prototype) {
ScriptRuntime.setFunctionProtoAndParent(scope, this);
setParentScope(scope);
setPrototype(getFunctionPrototype(scope));
setImmunePrototypeProperty(prototype);
prototype.setParentScope(this);
final int attr = ScriptableObject.DONTENUM |
ScriptableObject.PERMANENT |
ScriptableObject.READONLY;
@@ -364,20 +349,36 @@ public class FunctionObject extends BaseFunction
setParentScope(scope);
}
/**
* @deprecated Use {@link #getTypeTag(Class)}
* and {@link #convertArg(Context, Scriptable, Object, int)}
* for type convertion.
*/
public static Object convertArg(Context cx, Scriptable scope,
static public Object convertArg(Scriptable scope,
Object arg, Class desired)
{
int tag = getTypeTag(desired);
if (tag == JAVA_UNSUPPORTED_TYPE) {
throw Context.reportRuntimeError1
("msg.cant.convert", desired.getName());
if (desired == ScriptRuntime.StringClass)
return ScriptRuntime.toString(arg);
if (desired == ScriptRuntime.IntegerClass ||
desired == Integer.TYPE)
{
return new Integer(ScriptRuntime.toInt32(arg));
}
return convertArg(cx, scope, arg, tag);
if (desired == ScriptRuntime.BooleanClass ||
desired == Boolean.TYPE)
{
return ScriptRuntime.toBoolean(arg) ? Boolean.TRUE
: Boolean.FALSE;
}
if (desired == ScriptRuntime.DoubleClass ||
desired == Double.TYPE)
{
return new Double(ScriptRuntime.toNumber(arg));
}
if (desired == ScriptRuntime.ScriptableClass)
return ScriptRuntime.toObject(scope, arg);
if (desired == ScriptRuntime.ObjectClass)
return arg;
// Note that the long type is not supported; see the javadoc for
// the constructor for this class
throw Context.reportRuntimeError1
("msg.cant.convert", desired.getName());
}
/**
@@ -387,7 +388,7 @@ public class FunctionObject extends BaseFunction
* Implements Function.call.
*
* @see org.mozilla.javascript.Function#call
* @exception JavaScriptException if the underlying Java method or
* @exception JavaScriptException if the underlying Java method or
* constructor threw an exception
*/
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
@@ -395,143 +396,217 @@ public class FunctionObject extends BaseFunction
throws JavaScriptException
{
if (parmsLength < 0) {
return callVarargs(cx, thisObj, args);
return callVarargs(cx, thisObj, args, false);
}
if (!isStatic) {
Class clazz = member.getDeclaringClass();
if (!clazz.isInstance(thisObj)) {
boolean compatible = false;
if (thisObj == scope) {
Scriptable parentScope = getParentScope();
if (scope != parentScope) {
// Call with dynamic scope for standalone function,
// use parentScope as thisObj
compatible = clazz.isInstance(parentScope);
if (compatible) {
thisObj = parentScope;
}
}
}
if (!compatible) {
// OPT: cache "clazz"?
Class clazz = method != null ? method.getDeclaringClass()
: ctor.getDeclaringClass();
while (!clazz.isInstance(thisObj)) {
thisObj = thisObj.getPrototype();
if (thisObj == null || !useDynamicScope) {
// Couldn't find an object to call this on.
throw ScriptRuntime.typeError1("msg.incompat.call",
functionName);
throw NativeGlobal.typeError1
("msg.incompat.call", functionName, scope);
}
}
}
Object[] invokeArgs;
int i;
if (parmsLength == args.length) {
// Do not allocate new argument array if java arguments are
// the same as the original js ones.
invokeArgs = args;
for (int i = 0; i != parmsLength; ++i) {
Object arg = args[i];
Object converted = convertArg(cx, scope, arg, typeTags[i]);
if (arg != converted) {
if (invokeArgs == args) {
invokeArgs = (Object[])args.clone();
}
invokeArgs[i] = converted;
}
}
} else if (parmsLength == 0) {
invokeArgs = ScriptRuntime.emptyArgs;
// avoid copy loop if no conversions needed
i = (types == null) ? parmsLength : 0;
} else {
invokeArgs = new Object[parmsLength];
for (int i = 0; i != parmsLength; ++i) {
Object arg = (i < args.length)
? args[i]
: Undefined.instance;
invokeArgs[i] = convertArg(cx, scope, arg, typeTags[i]);
i = 0;
}
for (; i < parmsLength; i++) {
Object arg = (i < args.length)
? args[i]
: Undefined.instance;
if (types != null) {
arg = convertArg(this, arg, types[i]);
}
invokeArgs[i] = arg;
}
Object result;
if (member.isMethod()) {
result = member.invoke(thisObj, invokeArgs);
} else {
result = member.newInstance(invokeArgs);
try {
Object result = method == null ? ctor.newInstance(invokeArgs)
: doInvoke(thisObj, invokeArgs);
return hasVoidReturn ? Undefined.instance : result;
}
catch (InvocationTargetException e) {
throw JavaScriptException.wrapException(scope, e);
}
catch (IllegalAccessException e) {
throw WrappedException.wrapException(e);
}
catch (InstantiationException e) {
throw WrappedException.wrapException(e);
}
return hasVoidReturn ? Undefined.instance : result;
}
/**
* Return new {@link Scriptable} instance using the default
* constructor for the class of the underlying Java method.
* Return null to indicate that the call method should be used to create
* new objects.
* Performs conversions on argument types if needed and
* invokes the underlying Java method or constructor
* to create a new Scriptable object.
* <p>
* Implements Function.construct.
*
* @param cx the current Context for this thread
* @param scope the scope to execute the function relative to. This
* set to the value returned by getParentScope() except
* when the function is called from a closure.
* @param args arguments to the constructor
* @see org.mozilla.javascript.Function#construct
* @exception JavaScriptException if the underlying Java method or constructor
* threw an exception
*/
public Scriptable createObject(Context cx, Scriptable scope) {
if (member.isCtor() || parmsLength == VARARGS_CTOR) {
return null;
}
Scriptable result;
try {
result = (Scriptable) member.getDeclaringClass().newInstance();
} catch (Exception ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
result.setPrototype(getClassPrototype());
result.setParentScope(getParentScope());
return result;
}
private Object callVarargs(Context cx, Scriptable thisObj, Object[] args)
public Scriptable construct(Context cx, Scriptable scope, Object[] args)
throws JavaScriptException
{
if (parmsLength == VARARGS_METHOD) {
Object[] invokeArgs = { cx, thisObj, args, this };
Object result = member.invoke(null, invokeArgs);
return hasVoidReturn ? Undefined.instance : result;
} else {
boolean inNewExpr = (thisObj == null);
Boolean b = inNewExpr ? Boolean.TRUE : Boolean.FALSE;
Object[] invokeArgs = { cx, args, this, b };
return (member.isCtor())
? member.newInstance(invokeArgs)
: member.invoke(null, invokeArgs);
if (method == null || parmsLength == VARARGS_CTOR) {
Scriptable result;
if (method != null) {
result = (Scriptable) callVarargs(cx, null, args, true);
} else {
result = (Scriptable) call(cx, scope, null, args);
}
if (result.getPrototype() == null)
result.setPrototype(getClassPrototype());
if (result.getParentScope() == null) {
Scriptable parent = getParentScope();
if (result != parent)
result.setParentScope(parent);
}
return result;
} else if (method != null && !isStatic) {
Scriptable result;
try {
result = (Scriptable) method.getDeclaringClass().newInstance();
} catch (IllegalAccessException e) {
throw WrappedException.wrapException(e);
} catch (InstantiationException e) {
throw WrappedException.wrapException(e);
}
result.setPrototype(getClassPrototype());
result.setParentScope(getParentScope());
Object val = call(cx, scope, result, args);
if (val != null && val != Undefined.instance &&
val instanceof Scriptable)
{
return (Scriptable) val;
}
return result;
}
return super.construct(cx, scope, args);
}
private final Object doInvoke(Object thisObj, Object[] args)
throws IllegalAccessException, InvocationTargetException
{
Invoker master = invokerMaster;
if (master != null) {
if (invoker == null) {
invoker = master.createInvoker(method, types);
}
try {
return invoker.invoke(thisObj, args);
} catch (Exception e) {
throw new InvocationTargetException(e);
}
}
return method.invoke(thisObj, args);
}
boolean isVarArgsMethod() {
private Object callVarargs(Context cx, Scriptable thisObj, Object[] args,
boolean inNewExpr)
throws JavaScriptException
{
try {
if (parmsLength == VARARGS_METHOD) {
Object[] invokeArgs = { cx, thisObj, args, this };
Object result = doInvoke(null, invokeArgs);
return hasVoidReturn ? Undefined.instance : result;
} else {
Boolean b = inNewExpr ? Boolean.TRUE : Boolean.FALSE;
Object[] invokeArgs = { cx, args, this, b };
return (method == null)
? ctor.newInstance(invokeArgs)
: doInvoke(null, invokeArgs);
}
}
catch (InvocationTargetException e) {
Throwable target = e.getTargetException();
if (target instanceof EvaluatorException)
throw (EvaluatorException) target;
if (target instanceof EcmaError)
throw (EcmaError) target;
Scriptable scope = thisObj == null ? this : thisObj;
throw JavaScriptException.wrapException(scope, target);
}
catch (IllegalAccessException e) {
throw WrappedException.wrapException(e);
}
catch (InstantiationException e) {
throw WrappedException.wrapException(e);
}
}
boolean isVarArgsMethod() {
return parmsLength == VARARGS_METHOD;
}
boolean isVarArgsConstructor() {
boolean isVarArgsConstructor() {
return parmsLength == VARARGS_CTOR;
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (parmsLength > 0) {
Class[] types = member.argTypes;
typeTags = new byte[parmsLength];
for (int i = 0; i != parmsLength; ++i) {
typeTags[i] = (byte)getTypeTag(types[i]);
}
static void setCachingEnabled(boolean enabled) {
if (!enabled) {
methodsCache = null;
invokerMaster = null;
} else if (invokerMaster == null) {
invokerMaster = newInvokerMaster();
}
}
/** Get default master implementation or null if not available */
private static Invoker newInvokerMaster() {
try {
Class cl = ScriptRuntime.loadClassName(INVOKER_MASTER_CLASS);
return (Invoker)cl.newInstance();
}
catch (ClassNotFoundException ex) {}
catch (IllegalAccessException ex) {}
catch (InstantiationException ex) {}
catch (SecurityException ex) {}
return null;
}
private static final String
INVOKER_MASTER_CLASS = "org.mozilla.javascript.optimizer.InvokerImpl";
static Invoker invokerMaster = newInvokerMaster();
private static final short VARARGS_METHOD = -1;
private static final short VARARGS_CTOR = -2;
private static boolean sawSecurityException;
public static final int JAVA_UNSUPPORTED_TYPE = 0;
public static final int JAVA_STRING_TYPE = 1;
public static final int JAVA_INT_TYPE = 2;
public static final int JAVA_BOOLEAN_TYPE = 3;
public static final int JAVA_DOUBLE_TYPE = 4;
public static final int JAVA_SCRIPTABLE_TYPE = 5;
public static final int JAVA_OBJECT_TYPE = 6;
static Method[] methodsCache;
MemberBox member;
transient private byte[] typeTags;
private int parmsLength;
Method method;
Constructor ctor;
private Class[] types;
Invoker invoker;
private short parmsLength;
private short lengthPropertyValue;
private boolean hasVoidReturn;
private boolean isStatic;
private boolean useDynamicScope;
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the
@@ -39,46 +39,30 @@ package org.mozilla.javascript;
public class IdFunction extends BaseFunction
{
public IdFunction(IdFunctionMaster master, String name, int id)
{
public static final int FUNCTION_ONLY = 0;
public static final int CONSTRUCTOR_ONLY = 1;
public static final int FUNCTION_AND_CONSTRUCTOR = 2;
public IdFunction(IdFunctionMaster master, String name, int id) {
this.functionName = name;
this.master = master;
this.methodId = id;
}
public static void define(Scriptable scope, String name,
IdFunctionMaster master, int id)
{
define(scope, name, master, id, ScriptableObject.DONTENUM, false);
public final int functionType() {
return functionType;
}
public static void define(Scriptable scope, String name,
IdFunctionMaster master, int id,
int attributes)
{
define(scope, name, master, id, attributes, false);
public void setFunctionType(int type) {
functionType = type;
}
public static void define(Scriptable scope, String name,
IdFunctionMaster master, int id,
int attributes, boolean sealed)
{
IdFunction f = new IdFunction(master, name, id);
f.setParentScope(scope);
if (sealed) { f.sealObject(); }
ScriptableObject.defineProperty(scope, name, f, attributes);
}
public final int getMethodId()
{
return methodId;
}
public Scriptable getPrototype()
{
public Scriptable getPrototype() {
// Lazy initialization of prototype: for native functions this
// may not be called at all
Scriptable proto = super.getPrototype();
Scriptable proto = super.getPrototype();
if (proto == null) {
proto = getFunctionPrototype(getParentScope());
setPrototype(proto);
@@ -86,29 +70,36 @@ public class IdFunction extends BaseFunction
return proto;
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
return master.execMethod(methodId, this, cx, scope, thisObj, args);
}
public Scriptable createObject(Context cx, Scriptable scope)
{
if (useCallAsConstructor) {
return null;
if (functionType != CONSTRUCTOR_ONLY) {
return master.execMethod(methodId, this, cx, scope, thisObj, args);
}
else {
return Undefined.instance;
}
// Throw error if not explicitly coded to be used as constructor,
// to satisfy ECMAScript standard (see bugzilla 202019).
// To follow current (2003-05-01) SpiderMonkey behavior, change it to:
// return super.createObject(cx, scope);
throw ScriptRuntime.typeError1("msg.not.ctor", functionName);
}
public String decompile(Context cx, int indent, int flags)
public Scriptable construct(Context cx, Scriptable scope, Object[] args)
throws JavaScriptException
{
if (functionType != FUNCTION_ONLY) {
// It is program error not to return Scriptable from constructor
Scriptable result = (Scriptable)master.execMethod(methodId, this,
cx, scope,
null, args);
postConstruction(result);
return result;
}
else {
return Undefined.instance;
}
}
public String decompile(Context cx, int indent, boolean justbody) {
StringBuffer sb = new StringBuffer();
boolean justbody = (0 != (flags & Decompiler.ONLY_BODY_FLAG));
if (!justbody) {
sb.append("function ");
sb.append(getFunctionName());
@@ -126,37 +117,48 @@ public class IdFunction extends BaseFunction
sb.append(justbody ? "]\n" : "] }\n");
return sb.toString();
}
public int getArity()
{
public int getArity() {
int arity = master.methodArity(methodId);
if (arity < 0) {
if (arity < 0) {
throw onBadMethodId(master, methodId);
}
return arity;
}
public int getLength() { return getArity(); }
/** Prepare to be used as constructor .
** @param scope constructor scope
** @param prototype DontEnum, DontDelete, ReadOnly prototype property
** @param prototype DontEnum, DontDelete, ReadOnly prototype property
** of the constructor */
public void initAsConstructor(Scriptable scope, Scriptable prototype)
{
useCallAsConstructor = true;
public void initAsConstructor(Scriptable scope, Scriptable prototype) {
setFunctionType(FUNCTION_AND_CONSTRUCTOR);
setParentScope(scope);
setImmunePrototypeProperty(prototype);
}
static RuntimeException onBadMethodId(IdFunctionMaster master, int id)
{
// It is program error to call id-like methods for unknown or
static RuntimeException onBadMethodId(IdFunctionMaster master, int id) {
// It is program error to call id-like methods for unknown or
// non-function id
return new RuntimeException("BAD FUNCTION ID="+id+" MASTER="+master);
}
IdFunctionMaster master;
private int methodId;
private boolean useCallAsConstructor;
// Copied from NativeFunction.construct
private void postConstruction(Scriptable newObj) {
if (newObj.getPrototype() == null) {
newObj.setPrototype(getClassPrototype());
}
if (newObj.getParentScope() == null) {
Scriptable parent = getParentScope();
if (newObj != parent) {
newObj.setParentScope(parent);
}
}
}
protected IdFunctionMaster master;
protected int methodId;
protected int functionType = FUNCTION_ONLY;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -44,14 +44,13 @@ Any descendant should implement at least the following methods:
execMethod
methodArity
To define non-function properties, the descendant should override
To define non-function properties, the descendant should customize
getIdValue
setIdValue
getIdAttributes
getIdDefaultAttributes
maxInstanceId
to get/set property value and provide its default attributes.
During initialization descendant should call setMaxId directly or via calling addAsPrototype.
To customize initializition of constructor and protype objects, descendant
may override scopeInit or fillConstructorProperties methods.
@@ -59,10 +58,18 @@ may override scopeInit or fillConstructorProperties methods.
public abstract class IdScriptable extends ScriptableObject
implements IdFunctionMaster
{
public boolean has(String name, Scriptable start)
{
/** NULL_TAG can be used to distinguish between uninitialized and null
** values
*/
protected static final Object NULL_TAG = new Object();
public IdScriptable() {
activateIdMap(maxInstanceId());
}
public boolean has(String name, Scriptable start) {
if (maxId != 0) {
int id = mapNameToId_writeCached(name);
int id = mapNameToId(name);
if (id != 0) {
return hasValue(id);
}
@@ -70,40 +77,65 @@ public abstract class IdScriptable extends ScriptableObject
return super.has(name, start);
}
public Object get(String name, Scriptable start)
{
if (maxId != 0) {
int id = mapNameToId_writeCached(name);
if (id != 0) {
public Object get(String name, Scriptable start) {
if (CACHE_NAMES) {
int maxId = this.maxId;
L:if (maxId != 0) {
Object[] data = idMapData;
if (data == null) {
return getIdValue(id);
if (data == null) {
int id = mapNameToId(name);
if (id != 0) {
return getIdValue(id);
}
}
else {
int id = lastIdCache;
if (data[id - 1 + maxId] != name) {
id = mapNameToId(name);
if (id == 0) { break L; }
data[id - 1 + maxId] = name;
lastIdCache = id;
}
Object value = data[id - 1];
if (value == null) {
value = getIdValue(id);
}
else if (value == UniqueTag.NULL_VALUE) {
else if (value == NULL_TAG) {
value = null;
}
return value;
}
}
}
else {
if (maxId != 0) {
int id = mapNameToId(name);
if (id != 0) {
Object[] data = idMapData;
if (data == null) {
return getIdValue(id);
}
else {
Object value = data[id - 1];
if (value == null) {
value = getIdValue(id);
}
else if (value == NULL_TAG) {
value = null;
}
return value;
}
}
}
}
return super.get(name, start);
}
public void put(String name, Scriptable start, Object value)
{
public void put(String name, Scriptable start, Object value) {
if (maxId != 0) {
int id = mapNameToId_cached(name);
int id = mapNameToId(name);
if (id != 0) {
if (start == this && isSealed()) {
throw Context.reportRuntimeError1("msg.modify.sealed",
name);
}
int attr = getIdAttributes(id);
int attr = getAttributes(id);
if ((attr & READONLY) == 0) {
if (start == this) {
setIdValue(id, value);
@@ -118,14 +150,13 @@ public abstract class IdScriptable extends ScriptableObject
super.put(name, start, value);
}
public void delete(String name)
{
public void delete(String name) {
if (maxId != 0) {
int id = mapNameToId(name);
if (id != 0) {
// Let the super class to throw exceptions for sealed objects
if (!isSealed()) {
int attr = getIdAttributes(id);
int attr = getAttributes(id);
if ((attr & PERMANENT) == 0) {
deleteIdValue(id);
}
@@ -136,42 +167,50 @@ public abstract class IdScriptable extends ScriptableObject
super.delete(name);
}
public int getAttributes(String name)
public int getAttributes(String name, Scriptable start)
throws PropertyException
{
if (maxId != 0) {
int id = mapNameToId(name);
if (id != 0) {
if (hasValue(id)) {
return getIdAttributes(id);
return getAttributes(id);
}
// For ids with deleted values super will throw exceptions
}
}
return super.getAttributes(name);
return super.getAttributes(name, start);
}
public void setAttributes(String name, int attributes)
public void setAttributes(String name, Scriptable start,
int attributes)
throws PropertyException
{
if (maxId != 0) {
int id = mapNameToId(name);
if (id != 0) {
synchronized (this) {
if (hasValue(id)) {
setIdAttributes(id, attributes);
return;
if (hasValue(id)) {
synchronized (this) {
setAttributes(id, attributes);
}
return;
}
// For ids with deleted values super will throw exceptions
}
}
super.setAttributes(name, attributes);
super.setAttributes(name, start, attributes);
}
synchronized void addPropertyAttribute(int attribute) {
extraIdAttributes |= (byte)attribute;
super.addPropertyAttribute(attribute);
}
/**
* Redefine ScriptableObject.defineProperty to allow changing
* values/attributes of id-based properties unless
* getIdAttributes contains the READONLY attribute.
* @see #getIdAttributes
* values/attributes of id-based properties unless
* getIdDefaultAttributes contains the READONLY attribute.
* @see #getIdDefaultAttributes
* @see org.mozilla.javascript.ScriptableObject#defineProperty
*/
public void defineProperty(String propertyName, Object value,
@@ -180,13 +219,13 @@ public abstract class IdScriptable extends ScriptableObject
if (maxId != 0) {
int id = mapNameToId(propertyName);
if (id != 0) {
int current_attributes = getIdAttributes(id);
if ((current_attributes & READONLY) != 0) {
int default_attributes = getIdDefaultAttributes(id);
if ((default_attributes & READONLY) != 0) {
// It is a bug to redefine id with readonly attributes
throw new RuntimeException
("Attempt to redefine read-only id " + propertyName);
}
setIdAttributes(id, attributes);
setAttributes(id, attributes);
setIdValue(id, value);
return;
}
@@ -194,17 +233,16 @@ public abstract class IdScriptable extends ScriptableObject
super.defineProperty(propertyName, value, attributes);
}
Object[] getIds(boolean getAll)
{
Object[] getIds(boolean getAll) {
Object[] result = super.getIds(getAll);
if (maxId != 0) {
Object[] ids = null;
int count = 0;
for (int id = maxId; id != 0; --id) {
if (hasValue(id)) {
if (getAll || (getIdAttributes(id) & DONTENUM) == 0) {
if (getAll || (getAttributes(id) & DONTENUM) == 0) {
if (count == 0) {
// Need extra room for nor more then [1..id] names
ids = new Object[id];
@@ -228,40 +266,8 @@ public abstract class IdScriptable extends ScriptableObject
return result;
}
// Try to avoid calls to mapNameToId by quering name cache
private int mapNameToId_cached(String name)
{
if (CACHE_NAMES) {
Object[] data = idMapData;
if (data != null) {
int id = lastIdCache;
if (data[id - 1 + maxId] == name) {
return id;
}
}
}
return mapNameToId(name);
}
// Same as mapNameToId_cached but put to cache id found by mapNameToId
private int mapNameToId_writeCached(String name) {
if (CACHE_NAMES) {
Object[] data = idMapData;
if (data != null) {
int id = lastIdCache;
if (data[id - 1 + maxId] == name) {
return id;
}
id = mapNameToId(name);
if (id != 0) {
data[id - 1 + maxId] = name;
lastIdCache = id;
}
return id;
}
}
return mapNameToId(name);
}
/** Return maximum id number that should be present in each instance. */
protected int maxInstanceId() { return 0; }
/**
* Map name to id of prototype or instance property.
@@ -273,80 +279,58 @@ public abstract class IdScriptable extends ScriptableObject
*/
protected abstract String getIdName(int id);
/** Get attributes for id.
** Default implementation return DONTENUM that is the standard attribute
/** Get default attributes for id.
** Default implementation return DONTENUM that is the standard attribute
** for core EcmaScript function. Typically descendants need to overwrite
** this for non-function attributes like length to return
** DONTENUM | READONLY | PERMANENT or DONTENUM | PERMANENT
*/
protected int getIdAttributes(int id)
{
protected int getIdDefaultAttributes(int id) {
return DONTENUM;
}
/**
* Set attributes for id.
* Descendants should override the default implementation if they want to
* allow to change id attributes since the default implementation throw an
* exception unless new attributes eqaul the result of
* <tt>getIdAttributes(id)</tt>.
*/
protected void setIdAttributes(int id, int attributes)
{
int current = getIdAttributes(id);
if (attributes != current) {
throw new RuntimeException(
"Change of attributes for this id is not supported");
}
}
/** Check if id value exists.
** Default implementation always returns true */
protected boolean hasIdValue(int id)
{
protected boolean hasIdValue(int id) {
return true;
}
/** Get id value.
/** Get id value.
** If id value is constant, descendant can call cacheIdValue to store
** value in the permanent cache.
** Default implementation creates IdFunction instance for given id
** and cache its value
*/
protected Object getIdValue(int id)
{
protected Object getIdValue(int id) {
IdFunction f = newIdFunction(id);
f.setParentScope(getParentScope());
return cacheIdValue(id, f);
}
/**
* Set id value.
* Set id value.
* IdScriptable never calls this method if result of
* <code>getIdAttributes(id)</code> contains READONLY attribute.
* <code>getIdDefaultAttributes(id)</code> contains READONLY attribute.
* Descendants can overwrite this method to provide custom handler for
* property assignments.
*/
protected void setIdValue(int id, Object value)
{
protected void setIdValue(int id, Object value) {
synchronized (this) {
Object[] data = ensureIdData();
data[id - 1] = (value != null) ? value : UniqueTag.NULL_VALUE;
ensureIdData()[id - 1] = (value != null) ? value : NULL_TAG;
}
}
/**
* Store value in permanent cache unless value was already assigned to id.
* After this call IdScriptable never calls hasIdValue and getIdValue
* After this call IdScriptable never calls hasIdValue and getIdValue
* for the given id.
*/
protected Object cacheIdValue(int id, Object value)
{
protected Object cacheIdValue(int id, Object value) {
synchronized (this) {
Object[] data = ensureIdData();
Object curValue = data[id - 1];
if (curValue == null) {
data[id - 1] = (value != null) ? value : UniqueTag.NULL_VALUE;
data[id - 1] = (value != null) ? value : NULL_TAG;
}
else {
value = curValue;
@@ -354,21 +338,20 @@ public abstract class IdScriptable extends ScriptableObject
}
return value;
}
/**
* Delete value represented by id so hasIdValue return false.
* Delete value represented by id so hasIdValue return false.
* IdScriptable never calls this method if result of
* <code>getIdAttributes(id)</code> contains PERMANENT attribute.
* <code>getIdDefaultAttributes(id)</code> contains PERMANENT attribute.
* Descendants can overwrite this method to provide custom handler for
* property delete.
*/
protected void deleteIdValue(int id)
{
protected void deleteIdValue(int id) {
synchronized (this) {
ensureIdData()[id - 1] = NOT_FOUND;
}
}
/** 'thisObj' will be null if invoked as constructor, in which case
** instance of Scriptable should be returned. */
public Object execMethod(int methodId, IdFunction function,
@@ -379,46 +362,60 @@ public abstract class IdScriptable extends ScriptableObject
throw IdFunction.onBadMethodId(this, methodId);
}
/** Get arity or defined argument count for method with given id.
/** Get arity or defined argument count for method with given id.
** Should return -1 if methodId is not known or can not be used
** with execMethod call. */
public int methodArity(int methodId)
{
public int methodArity(int methodId) {
return -1;
}
/** Get maximum id mapNameToId can generate */
protected final int getMaxId()
{
return maxId;
}
/** Set maximum id mapNameToId can generate */
protected final void setMaxId(int maxId)
{
// maxId can only go up
if (maxId < this.maxId) Kit.codeBug();
/** Activate id support with the given maximum id */
protected void activateIdMap(int maxId) {
this.maxId = maxId;
}
/** Sets whether newly constructed function objects should be sealed */
protected void setSealFunctionsFlag(boolean sealed) {
setSetupFlag(SEAL_FUNCTIONS_FLAG, sealed);
}
/**
* Set parameters of function properties.
* Currently only determines whether functions should use dynamic scope.
* @param cx context to read function parameters.
*
* @see org.mozilla.javascript.Context#hasCompileFunctionsWithDynamicScope
*/
protected void setFunctionParametrs(Context cx) {
setSetupFlag(USE_DYNAMIC_SCOPE_FLAG,
cx.hasCompileFunctionsWithDynamicScope());
}
private void setSetupFlag(int flag, boolean value) {
setupFlags = (byte)(value ? setupFlags | flag : setupFlags & ~flag);
}
/**
* Prepare this object to serve as the prototype property of constructor
/**
* Prepare this object to serve as the prototype property of constructor
* object with name <code>getClassName()<code> defined in
* <code>scope</code>.
* @param maxId maximum id available in prototype object
* @param cx current context
* @param scope object to define constructor in.
* @param sealed indicates whether object and all its properties should
* be sealed
*/
public void addAsPrototype(int maxId, Context cx, Scriptable scope,
boolean sealed)
* @param sealed indicates whether object and all its properties should
* be sealed
*/
public void addAsPrototype(int maxId, Context cx, Scriptable scope,
boolean sealed)
{
setMaxId(maxId);
activateIdMap(maxId);
setSealFunctionsFlag(sealed);
setFunctionParametrs(cx);
int constructorId = mapNameToId("constructor");
if (constructorId == 0) {
// It is a bug to call this function without id for constructor
// It is a bug to call this function without id for constructor
throw new RuntimeException("No id for constructor property");
}
@@ -427,6 +424,7 @@ public abstract class IdScriptable extends ScriptableObject
fillConstructorProperties(cx, ctor, sealed);
if (sealed) {
ctor.sealObject();
ctor.addPropertyAttribute(READONLY);
}
setParentScope(ctor);
@@ -453,17 +451,17 @@ public abstract class IdScriptable extends ScriptableObject
defineProperty(obj, getIdName(id), f, DONTENUM);
}
/**
* Utility method to construct type error to indicate incompatible call
* when converting script thisObj to a particular type is not possible.
/**
* Utility method for converting target object into native this.
* Possible usage would be to have a private function like realThis:
* <pre>
private static NativeSomething realThis(Scriptable thisObj,
IdFunction f)
{
if (!(thisObj instanceof NativeSomething))
throw incompatibleCallError(f);
return (NativeSomething)thisObj;
private NativeSomething realThis(Scriptable thisObj,
IdFunction f, boolean readOnly)
{
while (!(thisObj instanceof NativeSomething)) {
thisObj = nextInstanceCheck(thisObj, f, readOnly);
}
return (NativeSomething)thisObj;
}
* </pre>
* Note that although such function can be implemented universally via
@@ -472,50 +470,50 @@ public abstract class IdScriptable extends ScriptableObject
* @return Scriptable object suitable for a check by the instanceof operator.
* @throws RuntimeException if no more instanceof target can be found
*/
protected static EcmaError incompatibleCallError(IdFunction f)
protected Scriptable nextInstanceCheck(Scriptable thisObj,
IdFunction f,
boolean readOnly)
{
throw ScriptRuntime.typeError1("msg.incompat.call",
f.getFunctionName());
if (readOnly && 0 != (setupFlags & USE_DYNAMIC_SCOPE_FLAG)) {
// for read only functions under dynamic scope look prototype chain
thisObj = thisObj.getPrototype();
if (thisObj != null) { return thisObj; }
}
throw NativeGlobal.typeError1("msg.incompat.call",
f.getFunctionName(), f);
}
protected IdFunction newIdFunction(int id)
{
protected IdFunction newIdFunction(int id) {
return newIdFunction(getIdName(id), id);
}
protected IdFunction newIdFunction(String name, int id)
{
protected IdFunction newIdFunction(String name, int id) {
IdFunction f = new IdFunction(this, name, id);
if (isSealed()) { f.sealObject(); }
if (0 != (setupFlags & SEAL_FUNCTIONS_FLAG)) { f.sealObject(); }
return f;
}
protected final Object wrap_double(double x)
{
protected final Object wrap_double(double x) {
return (x == x) ? new Double(x) : ScriptRuntime.NaNobj;
}
protected final Object wrap_int(int x)
{
protected final Object wrap_int(int x) {
byte b = (byte)x;
if (b == x) { return new Byte(b); }
return new Integer(x);
}
protected final Object wrap_long(long x)
{
protected final Object wrap_long(long x) {
int i = (int)x;
if (i == x) { return wrap_int(i); }
return new Long(x);
}
protected final Object wrap_boolean(boolean x)
{
protected final Object wrap_boolean(boolean x) {
return x ? Boolean.TRUE : Boolean.FALSE;
}
private boolean hasValue(int id)
{
private boolean hasValue(int id) {
Object value;
Object[] data = idMapData;
if (data == null || (value = data[id - 1]) == null) {
@@ -527,19 +525,57 @@ public abstract class IdScriptable extends ScriptableObject
}
// Must be called only from synchronized (this)
private Object[] ensureIdData()
{
private Object[] ensureIdData() {
Object[] data = idMapData;
if (data == null) {
if (data == null) {
idMapData = data = new Object[CACHE_NAMES ? maxId * 2 : maxId];
}
return data;
}
private int getAttributes(int id) {
int attributes = getIdDefaultAttributes(id) | extraIdAttributes;
byte[] array = attributesArray;
if (array != null) {
attributes |= 0xFF & array[id - 1];
}
return attributes;
}
private void setAttributes(int id, int attributes) {
int defaultAttrs = getIdDefaultAttributes(id);
if ((attributes & defaultAttrs) != defaultAttrs) {
// It is a bug to set attributes to less restrictive values
// then given by defaultAttrs
throw new RuntimeException("Attempt to unset default attributes");
}
// Store only additional bits
attributes &= ~defaultAttrs;
byte[] array = attributesArray;
if (array == null && attributes != 0) {
synchronized (this) {
array = attributesArray;
if (array == null) {
attributesArray = array = new byte[maxId];
}
}
}
if (array != null) {
array[id - 1] = (byte)attributes;
}
}
private int maxId;
private Object[] idMapData;
private byte[] attributesArray;
private static final boolean CACHE_NAMES = true;
private int lastIdCache;
private static final int USE_DYNAMIC_SCOPE_FLAG = 1 << 0;
private static final int SEAL_FUNCTIONS_FLAG = 1 << 1;
private byte setupFlags;
private byte extraIdAttributes;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
* Matthias Radestock
*
@@ -38,24 +38,24 @@
package org.mozilla.javascript;
import java.io.Serializable;
import java.util.Vector;
/**
* Class ImporterTopLevel
*
* This class defines a ScriptableObject that can be instantiated
*
* This class defines a ScriptableObject that can be instantiated
* as a top-level ("global") object to provide functionality similar
* to Java's "import" statement.
* <p>
* This class can be used to create a top-level scope using the following code:
* This class can be used to create a top-level scope using the following code:
* <pre>
* Scriptable scope = new ImporterTopLevel(cx);
* </pre>
* Then JavaScript code will have access to the following methods:
* <ul>
* <li>importClass - will "import" a class by making its unqualified name
* <li>importClass - will "import" a class by making its unqualified name
* available as a property of the top-level scope
* <li>importPackage - will "import" all the classes of the package by
* <li>importPackage - will "import" all the classes of the package by
* searching for unqualified names as classes qualified
* by the given package.
* </ul>
@@ -67,52 +67,50 @@ import java.io.Serializable;
* js> importPackage(java.util)
* js> v = new Vector()
* []
*
*
* @author Norris Boyd
*/
public class ImporterTopLevel extends ScriptableObject
{
public ImporterTopLevel() { }
public class ImporterTopLevel extends ScriptableObject {
/**
* @deprecated
*/
public ImporterTopLevel() {
init();
}
public ImporterTopLevel(Context cx) {
this(cx, false);
cx.initStandardObjects(this);
init();
}
private void init() {
String[] names = { "importClass", "importPackage" };
try {
this.defineFunctionProperties(names, ImporterTopLevel.class,
ScriptableObject.DONTENUM);
} catch (PropertyException e) {
throw new Error(); // should never happen
}
}
public ImporterTopLevel(Context cx, boolean sealed)
{
initStandardObjects(cx, sealed);
}
public String getClassName()
{
public String getClassName() {
return "global";
}
public void initStandardObjects(Context cx, boolean sealed)
{
cx.initStandardObjects(this, sealed);
ImporterFunctions.setup(this);
}
public boolean has(String name, Scriptable start) {
return super.has(name, start)
|| getPackageProperty(name, start) != NOT_FOUND;
}
public Object get(String name, Scriptable start) {
Object result = super.get(name, start);
if (result != NOT_FOUND)
if (result != NOT_FOUND)
return result;
result = getPackageProperty(name, start);
return result;
}
private Object getPackageProperty(String name, Scriptable start) {
Object result = NOT_FOUND;
Object[] elements;
synchronized (importedPackages) {
elements = importedPackages.toArray();
}
if (name.equals("_packages_"))
return result;
Object plist = ScriptableObject.getProperty(start,"_packages_");
if (plist == NOT_FOUND)
return result;
Context cx = Context.enter();
Object[] elements = cx.getElements((Scriptable)plist);
Context.exit();
for (int i=0; i < elements.length; i++) {
NativeJavaPackage p = (NativeJavaPackage) elements[i];
Object v = p.getPkgProperty(name, start, false);
@@ -127,9 +125,9 @@ public class ImporterTopLevel extends ScriptableObject
}
return result;
}
void importClass(Context cx, Scriptable thisObj, Object[] args)
{
public static void importClass(Context cx, Scriptable thisObj,
Object[] args, Function funObj) {
for (int i=0; i<args.length; i++) {
Object cl = args[i];
if (!(cl instanceof NativeJavaClass)) {
@@ -146,77 +144,33 @@ public class ImporterTopLevel extends ScriptableObject
thisObj.put(n,thisObj,cl);
}
}
public void importPackage(Context cx, Scriptable thisObj, Object[] args,
Function funObj)
{
importPackage(cx, thisObj, args);
}
void importPackage(Context cx, Scriptable thisObj, Object[] args)
{
for (int i = 0; i != args.length; i++) {
public static void importPackage(Context cx, Scriptable thisObj,
Object[] args, Function funObj) {
Scriptable importedPackages;
Object plist = thisObj.get("_packages_", thisObj);
if (plist == NOT_FOUND) {
importedPackages = cx.newArray(thisObj,0);
thisObj.put("_packages_", thisObj, importedPackages);
}
else {
importedPackages = (Scriptable)plist;
}
for (int i=0; i<args.length; i++) {
Object pkg = args[i];
if (!(pkg instanceof NativeJavaPackage)) {
throw Context.reportRuntimeError1(
"msg.not.pkg", Context.toString(pkg));
}
synchronized (importedPackages) {
for (int j = 0; j != importedPackages.size(); j++) {
if (pkg == importedPackages.get(j)) {
pkg = null;
break;
}
}
if (pkg != null) {
importedPackages.add(pkg);
Object[] elements = cx.getElements(importedPackages);
for (int j=0; j < elements.length; j++) {
if (pkg == elements[j]) {
pkg = null;
break;
}
}
if (pkg != null)
importedPackages.put(elements.length,importedPackages,pkg);
}
}
private ObjArray importedPackages = new ObjArray();
}
final class ImporterFunctions extends JIFunction
{
private ImporterFunctions(ImporterTopLevel importer, int id)
{
this.importer = importer;
this.id = id;
if (id == Id_importClass) {
initNameArity("importClass", 1);
} else {
if (id != Id_importPackage) Kit.codeBug();
initNameArity("importPackage", 1);
}
defineAsProperty(importer);
}
static void setup(ImporterTopLevel importer)
{
new ImporterFunctions(importer, Id_importClass);
new ImporterFunctions(importer, Id_importPackage);
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
if (id == Id_importClass) {
importer.importClass(cx, thisObj, args);
} else {
if (id != Id_importPackage) Kit.codeBug();
importer.importPackage(cx, thisObj, args);
}
return Undefined.instance;
}
private static final int
Id_importClass = 1,
Id_importPackage = 2;
private ImporterTopLevel importer;
private int id;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
@@ -36,36 +36,94 @@
package org.mozilla.javascript;
import java.io.Serializable;
import org.mozilla.javascript.debug.DebuggableScript;
final class InterpretedFunction extends NativeFunction
implements Serializable
class InterpretedFunction extends NativeFunction
implements DebuggableScript, Serializable
{
static final long serialVersionUID = -6235150451107527319L;
InterpretedFunction(InterpreterData theData)
InterpretedFunction(Context cx,
InterpreterData theData,
String[] argNames, short argCount)
{
itsData = theData;
initScriptFunction(itsData.languageVersion, itsData.itsName,
itsData.argNames, itsData.argCount);
this.argNames = argNames;
this.argCount = argCount;
init(cx);
}
void init(Context cx)
{
functionName = itsData.itsName;
source = itsData.itsSource;
nestedFunctions = itsData.itsNestedFunctions;
if (cx != null)
version = (short)cx.getLanguageVersion();
}
InterpretedFunction(InterpretedFunction theOther,
Scriptable theScope, Context cx)
{
itsData = theOther.itsData;
this.argNames = theOther.argNames;
this.argCount = theOther.argCount;
itsClosure = theScope;
init(cx);
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
throws JavaScriptException
{
return Interpreter.interpret(cx, scope, thisObj,
args, null, 0, args.length,
this, itsData);
}
{
if (itsClosure != null)
scope = itsClosure;
else if (!itsData.itsUseDynamicScope)
scope = getParentScope();
public String getEncodedSource()
{
return Interpreter.getEncodedSource(itsData);
if (itsData.itsCheckThis)
thisObj = ScriptRuntime.getThis(thisObj);
if (itsData.itsNeedsActivation) {
scope = ScriptRuntime.initVarObj(cx, scope, this, thisObj, args);
}
try {
return Interpreter.interpret(cx, scope, thisObj, args, this,
itsData);
}
finally {
if (itsData.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
}
}
public boolean isFunction() {
return true;
}
public Scriptable getScriptable() {
return this;
}
public String getSourceName() {
return itsData.itsSourceFile;
}
public int[] getLineNumbers() {
return itsData.itsLineNumberTable.getKeys();
}
public boolean placeBreakpoint(int line) { // XXX throw exn?
return itsData.placeBreakpoint(line);
}
public boolean removeBreakpoint(int line) {
return itsData.removeBreakpoint(line);
}
InterpreterData itsData;
boolean itsUseDynamicScope;
Scriptable[] itsRegExps;
Scriptable itsClosure;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
@@ -35,38 +35,63 @@
package org.mozilla.javascript;
import org.mozilla.javascript.debug.*;
import java.util.*;
final class InterpretedScript extends NativeFunction implements Script
{
public class InterpretedScript extends NativeScript implements DebuggableScript {
InterpretedScript(InterpreterData theData)
InterpretedScript(Context cx,
InterpreterData theData,
String[] argNames, short argCount)
{
itsData = theData;
initScriptFunction(itsData.languageVersion, "",
itsData.argNames, itsData.argCount);
this.argNames = argNames;
this.argCount = argCount;
functionName = "";
nestedFunctions = itsData.itsNestedFunctions;
version = (short)cx.getLanguageVersion();
}
public Object exec(Context cx, Scriptable scope)
throws JavaScriptException
{
return call(cx, scope, scope, ScriptRuntime.emptyArgs);
return call(cx, scope, scope, null);
}
public Object call(Context cx, Scriptable scope,
public Object call(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
return Interpreter.interpret(cx, scope, thisObj,
args, null, 0, args.length,
this, itsData);
scope = ScriptRuntime.initScript(cx, scope, this, thisObj,
itsData.itsFromEvalCode);
return Interpreter.interpret(cx, scope, thisObj, args, this, itsData);
}
public String getEncodedSource()
{
return Interpreter.getEncodedSource(itsData);
public boolean isFunction() {
return false;
}
public Scriptable getScriptable() {
return this;
}
public String getSourceName() {
return itsData.itsSourceFile;
}
public int[] getLineNumbers() {
return itsData.itsLineNumberTable.getKeys();
}
public boolean placeBreakpoint(int line) { // XXX throw exn?
return itsData.placeBreakpoint(line);
}
public boolean removeBreakpoint(int line) {
return itsData.removeBreakpoint(line);
}
InterpreterData itsData;
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
* Roger Lawrence
*
@@ -38,113 +38,91 @@ package org.mozilla.javascript;
import java.io.Serializable;
import org.mozilla.javascript.debug.DebuggableScript;
final class InterpreterData implements Serializable, DebuggableScript
{
class InterpreterData implements Serializable {
static final long serialVersionUID = 4815333329084415557L;
static final int INITIAL_MAX_ICODE_LENGTH = 1024;
static final int INITIAL_STRINGTABLE_SIZE = 64;
static final int INITIAL_NUMBERTABLE_SIZE = 64;
InterpreterData(Object securityDomain, int languageVersion)
InterpreterData(int lastICodeTop, int lastStringTableIndex,
Object securityDomain,
boolean useDynamicScope, boolean checkThis)
{
itsICodeTop = INITIAL_MAX_ICODE_LENGTH;
itsICodeTop = lastICodeTop == 0
? INITIAL_MAX_ICODE_LENGTH
: lastICodeTop * 2;
itsICode = new byte[itsICodeTop];
itsStringTable = new String[INITIAL_STRINGTABLE_SIZE];
itsStringTable = new String[lastStringTableIndex == 0
? INITIAL_STRINGTABLE_SIZE
: lastStringTableIndex * 2];
itsUseDynamicScope = useDynamicScope;
itsCheckThis = checkThis;
if (securityDomain == null)
Context.checkSecurityDomainRequired();
this.securityDomain = securityDomain;
this.languageVersion = languageVersion;
}
public boolean placeBreakpoint(int line) { // XXX throw exn?
int offset = getOffset(line);
if (offset != -1 && (itsICode[offset] == (byte)TokenStream.LINE ||
itsICode[offset] == (byte)TokenStream.BREAKPOINT))
{
itsICode[offset] = (byte) TokenStream.BREAKPOINT;
return true;
}
return false;
}
public boolean removeBreakpoint(int line) {
int offset = getOffset(line);
if (offset != -1 && itsICode[offset] == (byte) TokenStream.BREAKPOINT)
{
itsICode[offset] = (byte) TokenStream.LINE;
return true;
}
return false;
}
private int getOffset(int line) {
int offset = itsLineNumberTable.getInt(line, -1);
if (0 <= offset && offset <= itsICode.length) {
return offset;
}
return -1;
}
String itsName;
String itsSource;
String itsSourceFile;
boolean itsNeedsActivation;
boolean itsFromEvalCode;
boolean itsUseDynamicScope;
boolean itsCheckThis;
int itsFunctionType;
byte itsFunctionType;
String[] itsStringTable;
int itsStringTableIndex;
double[] itsDoubleTable;
InterpreterData[] itsNestedFunctions;
int itsDoubleTableIndex;
InterpretedFunction[] itsNestedFunctions;
Object[] itsRegExpLiterals;
byte[] itsICode;
int itsICodeTop;
int[] itsExceptionTable;
int itsMaxVars;
int itsMaxLocals;
int itsMaxArgs;
int itsMaxStack;
int itsMaxFrameArray;
// see comments in NativeFuncion for definition of argNames and argCount
String[] argNames;
int argCount;
int itsMaxCalleeArgs;
int itsMaxTryDepth;
UintMap itsLineNumberTable;
Object securityDomain;
String encodedSource;
int encodedSourceStart;
int encodedSourceEnd;
int languageVersion;
boolean useDynamicScope;
boolean topLevel;
InterpreterData parentData;
public boolean isTopLevel()
{
return topLevel;
}
public boolean isFunction()
{
return itsFunctionType != 0;
}
public String getFunctionName()
{
return itsName;
}
public String getSourceName()
{
return itsSourceFile;
}
public boolean isGeneratedScript()
{
return ScriptRuntime.isGeneratedScript(itsSourceFile);
}
public int[] getLineNumbers()
{
return Interpreter.getLineNumbers(this);
}
public int getFunctionCount()
{
return (itsNestedFunctions == null) ? 0 : itsNestedFunctions.length;
}
public DebuggableScript getFunction(int index)
{
return itsNestedFunctions[index];
}
public DebuggableScript getParent()
{
return parentData;
}
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -33,28 +33,45 @@
* file under either the NPL or the GPL.
*/
// API class
package org.mozilla.javascript;
package org.mozilla.javascript.debug;
import java.util.Vector;
import org.mozilla.javascript.*;
import org.mozilla.javascript.debug.*;
/**
* This interface exposes debugging information from objects.
*/
public interface DebuggableObject {
class InterpreterFrame implements DebugFrame {
InterpreterFrame(Scriptable scope, InterpreterData data, Scriptable obj) {
this.scope = scope;
this.data = data;
this.lineNumber = -1;
this.obj = obj;
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>All properties, even those with attribute {DontEnum}, are listed.
* This allows the debugger to display all properties of the object.<p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
public Object[] getAllIds();
public Scriptable getVariableObject() {
return scope;
}
public String getSourceName() {
return data.itsSourceFile;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public int getLineNumber() {
return lineNumber;
}
public DebuggableScript getScript() {
if (obj instanceof DebuggableScript)
return (DebuggableScript) obj;
return null;
}
private Scriptable scope;
private InterpreterData data;
private Scriptable obj;
private int lineNumber;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -20,7 +20,6 @@
*
* Contributor(s):
* Norris Boyd
* Igor Bukanov
* David C. Navas
*
* Alternatively, the contents of this file may be used under the
@@ -48,33 +47,8 @@ public abstract class Invoker {
public abstract Object invoke(Object that, Object [] args);
/** Factory method to get invoker for given method */
public Invoker createInvoker(ClassCache cache,
Method method, Class[] types)
{
// should not be called unless master
throw new IllegalStateException();
public Invoker createInvoker(Method method, Class[] types) {
return null;
}
/** Factory method to clear internal cache if any */
public void clearMasterCaches()
{
// should not be called unless master
throw new IllegalStateException();
}
public static Invoker makeMaster()
{
if (implClass == null)
return null;
Invoker master = (Invoker)Kit.newInstanceOrNull(implClass);
if (master == null)
implClass = null;
return master;
}
private static Class implClass = Kit.classOrNull(
"org.mozilla.javascript.optimizer.InvokerImpl");
}

View File

@@ -1,105 +0,0 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
// API class
package org.mozilla.javascript;
/**
* JIFunction or Java Implemented unction is a class to simplify implementation
* of JS functions in native code.
*/
public abstract class JIFunction extends BaseFunction
{
public JIFunction() { }
public JIFunction(String name, int arity)
{
initNameArity(name, arity);
}
protected final void initNameArity(String name, int arity)
{
this.functionName = name;
this.arity = arity;
}
public final void defineAsProperty(Scriptable scope)
{
defineAsProperty(scope, ScriptableObject.DONTENUM, false);
}
public final void defineAsProperty(Scriptable scope, int attributes)
{
defineAsProperty(scope, attributes, false);
}
public final void defineAsProperty(Scriptable scope, int attributes,
boolean sealed)
{
setParentScope(scope);
if (sealed) { sealObject(); }
ScriptableObject.defineProperty(scope, functionName, this, attributes);
}
public Scriptable getPrototype()
{
// Lazy initialization of prototype: for native functions this
// may not be called at all
Scriptable proto = super.getPrototype();
if (proto == null) {
proto = getFunctionPrototype(getParentScope());
setPrototype(proto);
}
return proto;
}
public abstract Object call(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException;
public int getArity()
{
return arity;
}
public int getLength()
{
return getArity();
}
private int arity;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,9 +18,8 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
* Bojan Cekrlic
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
@@ -38,65 +37,64 @@
package org.mozilla.javascript;
import java.lang.reflect.InvocationTargetException;
/**
* Java reflection of JavaScript exceptions.
* Instances of this class are thrown by the JavaScript 'throw' keyword.
* Java reflection of JavaScript exceptions. (Possibly wrapping a Java exception.)
*
* @author Mike McCabe
*/
public class JavaScriptException extends Exception
{
/**
* @deprecated
* Use {@link EvaluatorException#EvaluatorException(String)} to report
* exceptions in Java code.
*/
public JavaScriptException(Object value)
{
this(value, "", 0);
}
public class JavaScriptException extends Exception {
/**
* Create a JavaScript exception wrapping the given JavaScript value
* Create a JavaScript exception wrapping the given JavaScript value.
*
* Instances of this class are thrown by the JavaScript 'throw' keyword.
*
* @param value the JavaScript value thrown.
*/
public JavaScriptException(Object value, String sourceName, int lineNumber)
{
super(EvaluatorException.generateErrorMessage(
ScriptRuntime.toString(value), sourceName, lineNumber));
this.lineNumber = lineNumber;
this.sourceName = sourceName;
public JavaScriptException(Object value) {
super(ScriptRuntime.toString(value));
this.value = value;
}
static JavaScriptException wrapException(Scriptable scope,
Throwable exn)
{
if (exn instanceof InvocationTargetException)
exn = ((InvocationTargetException)exn).getTargetException();
if (exn instanceof JavaScriptException)
return (JavaScriptException)exn;
Object wrapper = NativeJavaObject.wrap(scope, exn, Throwable.class);
return new JavaScriptException(wrapper);
}
/**
* Get the exception value originally thrown. This may be a
* JavaScript value (null, undefined, Boolean, Number, String,
* Scriptable or Function) or a Java exception value thrown from a
* host object or from Java called through LiveConnect.
*
* @return the value wrapped by this exception
*/
public Object getValue()
{
return value;
public Object getValue() {
if (value != null && value instanceof Wrapper)
// this will also catch NativeStrings...
return ((Wrapper)value).unwrap();
else
return value;
}
/**
* Get the name of the source containing the error, or null
* if that information is not available.
* The JavaScript exception value. This value is not
* intended for general use; if the JavaScriptException wraps a
* Java exception, getScriptableValue may return a Scriptable
* wrapping the original Java exception object.
*
* We would prefer to go through a getter to encapsulate the value,
* however that causes the bizarre error "nanosecond timeout value
* out of range" on the MS JVM.
* @serial
*/
public String getSourceName()
{
return sourceName;
}
/**
* Returns the line number of the statement causing the error,
* or zero if not available.
*/
public int getLineNumber()
{
return lineNumber;
}
private Object value;
private String sourceName;
private int lineNumber;
Object value;
}

View File

@@ -1,377 +0,0 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is collection of utilities useful for Rhino code.
*
* The Initial Developer of the Original Code is
* RUnit Software AS.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Igor Bukanov, igor@fastmail.fm
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import java.util.Hashtable;
import java.io.IOException;
import java.io.Reader;
/**
* Collection of utilities
*/
public class Kit
{
static Class classOrNull(String className)
{
try {
return Class.forName(className);
} catch (ClassNotFoundException ex) {
} catch (SecurityException ex) {
} catch (LinkageError ex) {
} catch (IllegalArgumentException e) {
// Can be thrown if name has characters that a class name
// can not contain
}
return null;
}
static Class classOrNull(ClassLoader loader, String className)
{
try {
return loader.loadClass(className);
} catch (ClassNotFoundException ex) {
} catch (SecurityException ex) {
} catch (LinkageError ex) {
} catch (IllegalArgumentException e) {
// Can be thrown if name has characters that a class name
// can not contain
}
return null;
}
static Object newInstanceOrNull(Class cl)
{
try {
return cl.newInstance();
} catch (SecurityException x) {
} catch (LinkageError ex) {
} catch (InstantiationException x) {
} catch (IllegalAccessException x) {
}
return null;
}
/**
* Split string into array of strings using semicolon as string terminator
* (; after the last string is required).
*/
public static String[] semicolonSplit(String s)
{
int count = 0;
for (int cursor = 0; ;) {
int next = s.indexOf(';', cursor) + 1;
if (next <= 0) {
// check for missing ;
if (cursor + 1 < s.length())
throw new IllegalArgumentException();
break;
}
++count;
cursor = next + 1;
}
String[] array = new String[count];
count = 0;
for (int cursor = 0; ;) {
int next = s.indexOf(';', cursor);
if (next < 0) { break; }
array[count] = s.substring(cursor, next);
++count;
cursor = next + 1;
}
return array;
}
/**
* Add <i>listener</i> to <i>bag</i> of listeners.
* The function does not modify <i>bag</i> and return a new collection
* containing <i>listener</i> and all listeners from <i>bag</i>.
* Bag without listeners always represented as the null value.
* <p>
* Usage example:
* <pre>
* private volatile Object changeListeners;
*
* public void addMyListener(PropertyChangeListener l)
* {
* synchronized (this) {
* changeListeners = Kit.addListener(changeListeners, l);
* }
* }
*
* public void removeTextListener(PropertyChangeListener l)
* {
* synchronized (this) {
* changeListeners = Kit.removeListener(changeListeners, l);
* }
* }
*
* public void fireChangeEvent(Object oldValue, Object newValue)
* {
* // Get immune local copy
* Object listeners = changeListeners;
* if (listeners != null) {
* PropertyChangeEvent e = new PropertyChangeEvent(
* this, "someProperty" oldValue, newValue);
* for (int i = 0; ; ++i) {
* Object l = Kit.getListener(listeners, i);
* if (l == null)
* break;
* ((PropertyChangeListener)l).propertyChange(e);
* }
* }
* }
* </pre>
*
* @param listener Listener to add to <i>bag</i>
* @param bag Current collection of listeners.
* @return A new bag containing all listeners from <i>bag</i> and
* <i>listener</i>.
* @see #removeListener(Object bag, Object listener)
* @see #getListener(Object bag, int index)
*/
public static Object addListener(Object bag, Object listener)
{
if (listener == null) throw new IllegalArgumentException();
if (listener instanceof Object[]) throw new IllegalArgumentException();
if (bag == null) {
bag = listener;
} else if (!(bag instanceof Object[])) {
bag = new Object[] { bag, listener };
} else {
Object[] array = (Object[])bag;
int L = array.length;
// bag has at least 2 elements if it is array
if (L < 2) throw new IllegalArgumentException();
Object[] tmp = new Object[L + 1];
System.arraycopy(array, 0, tmp, 0, L);
tmp[L] = listener;
bag = tmp;
}
return bag;
}
/**
* Remove <i>listener</i> from <i>bag</i> of listeners.
* The function does not modify <i>bag</i> and return a new collection
* containing all listeners from <i>bag</i> except <i>listener</i>.
* If <i>bag</i> does not contain <i>listener</i>, the function returns
* <i>bag</i>.
* <p>
* For usage example, see {@link addListener(Object bag, Object listener)}.
*
* @param listener Listener to remove from <i>bag</i>
* @param bag Current collection of listeners.
* @return A new bag containing all listeners from <i>bag</i> except
* <i>listener</i>.
* @see #addListener(Object bag, Object listener)
* @see #getListener(Object bag, int index)
*/
public static Object removeListener(Object bag, Object listener)
{
if (listener == null) throw new IllegalArgumentException();
if (listener instanceof Object[]) throw new IllegalArgumentException();
if (bag == listener) {
bag = null;
} else if (bag instanceof Object[]) {
Object[] array = (Object[])bag;
int L = array.length;
// bag has at least 2 elements if it is array
if (L < 2) throw new IllegalArgumentException();
if (L == 2) {
if (array[1] == listener) {
bag = array[0];
} else if (array[0] == listener) {
bag = array[1];
}
} else {
int i = L;
do {
--i;
if (array[i] == listener) {
Object[] tmp = new Object[L - 1];
System.arraycopy(array, 0, tmp, 0, i);
System.arraycopy(array, i + 1, tmp, i, L - (i + 1));
bag = tmp;
break;
}
} while (i != 0);
}
}
return bag;
}
/**
* Get listener at <i>index</i> position in <i>bag</i> or null if
* <i>index</i> equals to number of listeners in <i>bag</i>.
* <p>
* For usage example, see {@link addListener(Object bag, Object listener)}.
*
* @param bag Current collection of listeners.
* @param index Index of the listener to access.
* @return Listener at the given index or null.
* @see #addListener(Object bag, Object listener)
* @see #removeListener(Object bag, Object listener)
*/
public static Object getListener(Object bag, int index)
{
if (index == 0) {
if (bag == null)
return null;
if (!(bag instanceof Object[]))
return bag;
Object[] array = (Object[])bag;
// bag has at least 2 elements if it is array
if (array.length < 2) throw new IllegalArgumentException();
return array[0];
} else if (index == 1) {
if (!(bag instanceof Object[])) {
if (bag == null) throw new IllegalArgumentException();
return null;
}
Object[] array = (Object[])bag;
// the array access will check for index on its own
return array[1];
} else {
// bag has to array
Object[] array = (Object[])bag;
int L = array.length;
if (L < 2) throw new IllegalArgumentException();
if (index == L)
return null;
return array[index];
}
}
static Object initHash(Hashtable h, Object key, Object initialValue)
{
synchronized (h) {
Object current = h.get(key);
if (current == null) {
h.put(key, initialValue);
} else {
initialValue = current;
}
}
return initialValue;
}
private final static class ComplexKey
{
private Object key1;
private Object key2;
private int hash;
ComplexKey(Object key1, Object key2)
{
this.key1 = key1;
this.key2 = key2;
}
public boolean equals(Object anotherObj)
{
if (!(anotherObj instanceof ComplexKey))
return false;
ComplexKey another = (ComplexKey)anotherObj;
return key1.equals(another.key1) && key2.equals(another.key2);
}
public int hashCode()
{
if (hash == 0) {
hash = key1.hashCode() ^ key2.hashCode();
}
return hash;
}
}
public static Object makeHashKeyFromPair(Object key1, Object key2)
{
if (key1 == null) throw new IllegalArgumentException();
if (key2 == null) throw new IllegalArgumentException();
return new ComplexKey(key1, key2);
}
public static String readReader(Reader r)
throws IOException
{
char[] buffer = new char[512];
int cursor = 0;
for (;;) {
int n = r.read(buffer, cursor, buffer.length - cursor);
if (n < 0) { break; }
cursor += n;
if (cursor == buffer.length) {
char[] tmp = new char[buffer.length * 2];
System.arraycopy(buffer, 0, tmp, 0, cursor);
buffer = tmp;
}
}
return new String(buffer, 0, cursor);
}
/**
* Throws RuntimeException to indicate failed assertion.
* The function never returns and its return type is RuntimeException
* only to be able to write <tt>throw Kit.codeBug()</tt> if plain
* <tt>Kit.codeBug()</tt> triggers unreachable code error.
*/
public static RuntimeException codeBug()
throws RuntimeException
{
throw new IllegalStateException("FAILED ASSERTION");
}
/**
* Convinient way to throw IllegalArgumentException to indicate bad
* argument.
*/
public static void badArg()
throws IllegalArgumentException
{
throw new IllegalArgumentException();
}
}

View File

@@ -0,0 +1,104 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
public class Label {
private static final int FIXUPTABLE_SIZE = 8;
private static final boolean DEBUG = true;
public Label()
{
itsPC = -1;
}
public short getPC()
{
return itsPC;
}
public void fixGotos(byte theCodeBuffer[])
{
if (DEBUG) {
if ((itsPC == -1) && (itsFixupTable != null))
throw new RuntimeException("Unlocated label");
}
if (itsFixupTable != null) {
for (int i = 0; i < itsFixupTableTop; i++) {
int fixupSite = itsFixupTable[i];
// -1 to get delta from instruction start
short offset = (short)(itsPC - (fixupSite - 1));
theCodeBuffer[fixupSite++] = (byte)(offset >> 8);
theCodeBuffer[fixupSite] = (byte)offset;
}
}
itsFixupTable = null;
}
public void setPC(short thePC)
{
if (DEBUG) {
if ((itsPC != -1) && (itsPC != thePC))
throw new RuntimeException("Duplicate label");
}
itsPC = thePC;
}
public void addFixup(int fixupSite)
{
if (itsFixupTable == null) {
itsFixupTableTop = 1;
itsFixupTable = new int[FIXUPTABLE_SIZE];
itsFixupTable[0] = fixupSite;
}
else {
if (itsFixupTableTop == itsFixupTable.length) {
int oldLength = itsFixupTable.length;
int newTable[] = new int[oldLength + FIXUPTABLE_SIZE];
System.arraycopy(itsFixupTable, 0, newTable, 0, oldLength);
itsFixupTable = newTable;
}
itsFixupTable[itsFixupTableTop++] = fixupSite;
}
}
private short itsPC;
private int itsFixupTable[];
private int itsFixupTableTop;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
@@ -37,89 +37,44 @@ package org.mozilla.javascript;
public class LabelTable {
private static final boolean DEBUGLABELS = false;
private static final int LabelTableSize = 32;
protected Label itsLabelTable[];
protected int itsLabelTableTop;
public int acquireLabel()
{
int top = itsLabelTableTop;
if (itsLabelTable == null || top == itsLabelTable.length) {
if (itsLabelTable == null) {
itsLabelTable = new int[MIN_LABEL_TABLE_SIZE];
}else {
int[] tmp = new int[itsLabelTable.length * 2];
System.arraycopy(itsLabelTable, 0, tmp, 0, top);
itsLabelTable = tmp;
if (itsLabelTable == null) {
itsLabelTable = new Label[LabelTableSize];
itsLabelTable[0] = new Label();
itsLabelTableTop = 1;
return 0x80000000;
}
else {
if (itsLabelTableTop == itsLabelTable.length) {
Label oldTable[] = itsLabelTable;
itsLabelTable = new Label[itsLabelTableTop * 2];
System.arraycopy(oldTable, 0, itsLabelTable, 0, itsLabelTableTop);
}
itsLabelTable[itsLabelTableTop] = new Label();
int result = itsLabelTableTop++;
return result | 0x80000000;
}
itsLabelTableTop = top + 1;
itsLabelTable[top] = -1;
return top;
}
public int getLabelPC(int label) {
if (label > itsLabelTableTop) throw new RuntimeException();
return itsLabelTable[label];
}
public void markLabel(int label, int pc) {
if (label > itsLabelTableTop || pc < 0) throw new RuntimeException();
if (itsLabelTable[label] != -1) {
// Can mark label only once
throw new RuntimeException();
public int markLabel(int theLabel, int pc)
{
if (DEBUGLABELS) {
if ((theLabel & 0x80000000) != 0x80000000)
throw new RuntimeException("Bad label, no biscuit");
}
itsLabelTable[label] = pc;
}
public void addLabelFixup(int label, int fixupSite) {
if (label > itsLabelTableTop || fixupSite < 0) {
throw new RuntimeException();
theLabel &= 0x7FFFFFFF;
if (DEBUGLABELS) {
System.out.println("Marking label " + theLabel + " at " + pc);
}
int top = itsFixupTableTop;
if (itsFixupTable == null || top == itsFixupTable.length) {
if (itsFixupTable == null) {
itsFixupTable = new long[MIN_FIXUP_TABLE_SIZE];
}else {
long[] tmp = new long[itsFixupTable.length * 2];
System.arraycopy(itsFixupTable, 0, tmp, 0, top);
itsFixupTable = tmp;
}
}
itsFixupTableTop = top + 1;
itsFixupTable[top] = ((long)label << 32) | fixupSite;
itsLabelTable[theLabel].setPC((short)pc);
return theLabel | 0x80000000;
}
public void fixLabelGotos(byte[] codeBuffer) {
for (int i = 0; i < itsFixupTableTop; i++) {
long fixup = itsFixupTable[i];
int label = (int)(fixup >> 32);
int fixupSite = (int)fixup;
int pc = itsLabelTable[label];
if (pc == -1) {
// Unlocated label
throw new RuntimeException();
}
// -1 to get delta from instruction start
int offset = pc - (fixupSite - 1);
if ((short)offset != offset) {
throw new RuntimeException
("Program too complex: too big jump offset");
}
codeBuffer[fixupSite] = (byte)(offset >> 8);
codeBuffer[fixupSite + 1] = (byte)offset;
}
itsFixupTableTop = 0;
}
public void clearLabels() {
itsLabelTableTop = 0;
itsFixupTableTop = 0;
}
private static final int MIN_LABEL_TABLE_SIZE = 32;
private int[] itsLabelTable;
private int itsLabelTableTop;
// itsFixupTable[i] = (label_index << 32) | fixup_site
private static final int MIN_FIXUP_TABLE_SIZE = 40;
private long[] itsFixupTable;
private int itsFixupTableTop;
}

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -53,9 +53,9 @@ public final class LazilyLoadedCtor {
this.sealed = sealed;
if (getter == null) {
Method[] methods = FunctionObject.getMethodList(getClass());
getter = FunctionObject.findSingleMethod(methods, "getProperty");
setter = FunctionObject.findSingleMethod(methods, "setProperty");
Method[] all = FunctionObject.getMethodList(getClass());
getter = FunctionObject.findMethods(all, "getProperty")[0];
setter = FunctionObject.findMethods(all, "setProperty")[0];
}
try {
@@ -63,7 +63,7 @@ public final class LazilyLoadedCtor {
ScriptableObject.DONTENUM);
}
catch (PropertyException e) {
throw ScriptRuntime.throwAsUncheckedException(e);
throw WrappedException.wrapException(e);
}
}
@@ -78,17 +78,33 @@ public final class LazilyLoadedCtor {
// java.util.PropertyPermission
// org.mozilla.javascript.JavaAdapter read
Class cl = Kit.classOrNull(className);
if (cl == null) {
removeOnError = true;
} else {
Class cl = null;
try { cl = Class.forName(className); }
catch (ClassNotFoundException ex) { removeOnError = true; }
catch (SecurityException ex) { removeOnError = true; }
if (cl != null) {
try {
ScriptableObject.defineClass(obj, cl, sealed);
isReplaced = true;
} catch (SecurityException ex) {
}
catch (InstantiationException e) {
throw WrappedException.wrapException(e);
}
catch (IllegalAccessException e) {
throw WrappedException.wrapException(e);
}
catch (InvocationTargetException e) {
throw WrappedException.wrapException(e);
}
catch (ClassDefinitionException e) {
throw WrappedException.wrapException(e);
}
catch (PropertyException e) {
throw WrappedException.wrapException(e);
}
catch (SecurityException ex) {
removeOnError = true;
} catch (Exception e) {
throw ScriptRuntime.throwAsUncheckedException(e);
}
}
if (removeOnError) {

View File

@@ -0,0 +1,456 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Mike McCabe
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.io.Reader;
import java.io.IOException;
/**
* An input buffer that combines fast character-based access with
* (slower) support for retrieving the text of the current line. It
* also supports building strings directly out of the internal buffer
* to support fast scanning with minimal object creation.
*
* Note that it is customized in several ways to support the
* TokenStream class, and should not be considered general.
*
* Credits to Kipp Hickman and John Bandhauer.
*
* @author Mike McCabe
*/
final class LineBuffer {
/*
* for smooth operation of getLine(), this should be greater than
* the length of any expected line. Currently, 256 is 3% slower
* than 4096 for large compiles, but seems safer given evaluateString.
* Strings for the scanner are are built with StringBuffers
* instead of directly out of the buffer whenever a string crosses
* a buffer boundary, so small buffer sizes will mean that more
* objects are created.
*/
static final int BUFLEN = 256;
LineBuffer(Reader in, int lineno) {
this.in = in;
this.lineno = lineno;
}
int read() throws IOException {
for(;;) {
if (end == offset && !fill())
return -1;
int c = buffer[offset];
++offset;
if ((c & EOL_HINT_MASK) == 0) {
switch (c) {
case '\r':
// if the next character is a newline, skip past it.
if (offset != end) {
if (buffer[offset] == '\n')
++offset;
} else {
// set a flag for fill(), in case the first char
// of the next fill is a newline.
lastWasCR = true;
}
// NO break here!
case '\n': case '\u2028': case '\u2029':
prevStart = lineStart;
lineStart = offset;
lineno++;
return '\n';
}
}
if (c < 128 || !formatChar(c)) {
return c;
}
hadCFSinceStringStart = true;
}
}
void unread() {
// offset can only be 0 when we're asked to unread() an implicit
// EOF_CHAR.
// This would be wrong behavior in the general case,
// because a peek() could map a buffer.length offset to 0
// in the process of a fill(), and leave it there. But
// the scanner never calls peek() or a failed match()
// followed by unread()... this would violate 1-character
// lookahead.
if (Context.check && offset == 0 && !hitEOF) Context.codeBug();
if (offset == 0) // Same as if (hitEOF)
return;
offset--;
int c = buffer[offset];
if ((c & EOL_HINT_MASK) == 0 && eolChar(c)) {
lineStart = prevStart;
lineno--;
}
}
private void skipFormatChar() {
if (checkSelf && !formatChar(buffer[offset])) Context.codeBug();
if (stringStart >= 0 || stringSoFar != null) {
hadCFSinceStringStart = true;
}
else {
// swap prev character with format one so possible call to
// startString can assume that previous non-format char is at
// offset - 1. Note it causes getLine to return not exactly the
// source LineBuffer read, but it is used only in error reporting
// and should not be a problem.
if (offset != 0) {
char tmp = buffer[offset];
buffer[offset] = buffer[offset - 1];
buffer[offset - 1] = tmp;
}
else if (otherEnd != 0) {
char tmp = buffer[offset];
buffer[offset] = otherBuffer[otherEnd - 1];
otherBuffer[otherEnd - 1] = tmp;
}
}
++offset;
}
int peek() throws IOException {
for (;;) {
if (end == offset && !fill()) {
return -1;
}
int c = buffer[offset];
if ((c & EOL_HINT_MASK) == 0 && eolChar(c)) {
return '\n';
}
if (c < 128 || !formatChar(c)) {
return c;
}
skipFormatChar();
}
}
boolean match(int test) throws IOException {
if (Context.check) {
// TokenStream never looks ahead for '\n', which allows simple code
if ((test & EOL_HINT_MASK) == 0 && eolChar(test))
Context.codeBug();
// Format chars are not allowed either
if (test >= 128 && formatChar(test))
Context.codeBug();
}
for (;;) {
if (end == offset && !fill())
return false;
int c = buffer[offset];
if (test == c) {
++offset;
return true;
}
if (c < 128 || !formatChar(c)) {
return false;
}
skipFormatChar();
}
}
// Reconstruct a source line from the buffers. This can be slow...
String getLine() {
StringBuffer result = new StringBuffer();
int start = lineStart;
if (start >= offset) {
// the line begins somewhere in the other buffer; get that first.
if (otherStart < otherEnd)
// if a line ending was seen in the other buffer... otherwise
// just ignore this strange case.
result.append(otherBuffer, otherStart,
otherEnd - otherStart);
start = 0;
}
// get the part of the line in the current buffer.
result.append(buffer, start, offset - start);
// Get the remainder of the line.
int i = offset;
while(true) {
if (i == buffer.length) {
// we're out of buffer, let's just expand it. We do
// this instead of reading into a StringBuffer to
// preserve the stream for later reads.
char[] newBuffer = new char[buffer.length * 2];
System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
buffer = newBuffer;
int charsRead = 0;
try {
charsRead = in.read(buffer, end, buffer.length - end);
} catch (IOException ioe) {
// ignore it, we're already displaying an error...
}
if (charsRead < 0)
break;
end += charsRead;
}
int c = buffer[i];
if ((c & EOL_HINT_MASK) == 0 && eolChar(c))
break;
i++;
}
result.append(buffer, offset, i - offset);
return result.toString();
}
// Get the offset of the current character, relative to
// the line that getLine() returns.
int getOffset() {
if (lineStart >= offset)
// The line begins somewhere in the other buffer.
return offset + (otherEnd - otherStart);
else
return offset - lineStart;
}
// Set a mark to indicate that the reader should begin
// accumulating characters for getString(). The string begins
// with the last character read.
void startString() {
char c;
if (offset == 0) {
// We can get here if startString is called after a peek()
// or failed match() with offset past the end of the
// buffer.
// We're at the beginning of the buffer, and the previous character
// (which we want to include) is at the end of the last one, so
// we just go to StringBuffer mode.
stringSoFar = new StringBuffer();
stringStart = -1; // Set sentinel value.
c = otherBuffer[otherEnd - 1];
stringSoFar.append(c);
} else {
// Support restarting strings
stringSoFar = null;
stringStart = offset - 1;
c = buffer[stringStart];
}
hadCFSinceStringStart = (c >= 128 && formatChar(c));
}
// Get a string consisting of the characters seen since the last
// startString.
String getString() {
// No calls to getString without previous startString
if (Context.check && !(stringStart >= 0 || stringSoFar != null))
Context.codeBug();
String result;
/*
* There's one strange case here: If the character offset currently
* points to (which we never want to include in the string) is
* a newline, then if the previous character is a carriage return,
* we probably want to exclude that as well. If the offset is 0,
* then we hope that fill() handled excluding it from stringSoFar.
*/
int loseCR = (offset > 0 &&
buffer[offset] == '\n' && buffer[offset - 1] == '\r') ?
1 : 0;
if (stringStart >= 0) {
// String mark is valid, and in this buffer.
result = new String(buffer, stringStart,
offset - stringStart - loseCR);
} else {
// Exclude cr as well as nl of newline. If offset is 0, then
// hopefully fill() did the right thing.
result = (stringSoFar.append(buffer, 0, offset - loseCR)).toString();
}
stringStart = -1;
stringSoFar = null;
if (hadCFSinceStringStart) {
char c[] = result.toCharArray();
StringBuffer x = null;
for (int i = 0; i < c.length; i++) {
if (formatChar(c[i])) {
if (x == null) {
x = new StringBuffer();
x.append(c, 0, i);
}
}
else
if (x != null) x.append(c[i]);
}
if (x != null) result = x.toString();
}
return result;
}
private boolean fill() throws IOException {
// fill should be caled only for emty buffer
if (checkSelf && !(end == offset)) Context.codeBug();
// If there's a string currently being accumulated, save
// off the progress.
/*
* Exclude an end-of-buffer carriage return. NOTE this is not
* fully correct in the general case, because we really only
* want to exclude the carriage return if it's followed by a
* linefeed at the beginning of the next buffer. But we fudge
* because the scanner doesn't do this.
*/
int loseCR = (offset > 0 && lastWasCR) ? 1 : 0;
if (stringStart != -1) {
// The mark is in the current buffer, save off from the mark to the
// end.
stringSoFar = new StringBuffer();
stringSoFar.append(buffer, stringStart, end - stringStart - loseCR);
stringStart = -1;
} else if (stringSoFar != null) {
// the string began prior to the current buffer, so save the
// whole current buffer.
stringSoFar.append(buffer, 0, end - loseCR);
}
// swap buffers
char[] tempBuffer = buffer;
buffer = otherBuffer;
otherBuffer = tempBuffer;
// allocate the buffers lazily, in case we're handed a short string.
if (buffer == null) {
buffer = new char[BUFLEN];
}
// buffers have switched, so move the newline marker.
otherStart = lineStart;
otherEnd = end;
// set lineStart to a sentinel value, unless this is the first
// time around.
prevStart = lineStart = (otherBuffer == null) ? 0 : buffer.length + 1;
offset = 0;
end = in.read(buffer, 0, buffer.length);
if (end < 0) {
end = 0;
// can't null buffers here, because a string might be retrieved
// out of the other buffer, and a 0-length string might be
// retrieved out of this one.
hitEOF = true;
return false;
}
// If the last character of the previous fill was a carriage return,
// then ignore a newline.
// There's another bizzare special case here. If lastWasCR is
// true, and we see a newline, and the buffer length is
// 1... then we probably just read the last character of the
// file, and returning after advancing offset is not the right
// thing to do. Instead, we try to ignore the newline (and
// likely get to EOF for real) by doing yet another fill().
if (lastWasCR) {
if (buffer[0] == '\n') {
offset++;
if (end == 1)
return fill();
}
lineStart = offset;
lastWasCR = false;
}
return true;
}
int getLineno() { return lineno; }
boolean eof() { return hitEOF; }
private static boolean formatChar(int c) {
return Character.getType((char)c) == Character.FORMAT;
}
private static boolean eolChar(int c) {
return c == '\r' || c == '\n' || c == '\u2028' || c == '\u2029';
}
// Optimization for faster check for eol character: eolChar(c) returns
// true only when (c & EOL_HINT_MASK) == 0
private static final int EOL_HINT_MASK = 0xdfd0;
private Reader in;
private char[] otherBuffer = null;
private char[] buffer = null;
// Yes, there are too too many of these.
private int offset = 0;
private int end = 0;
private int otherEnd;
private int lineno;
private int lineStart = 0;
private int otherStart = 0;
private int prevStart = 0;
private boolean lastWasCR = false;
private boolean hitEOF = false;
private int stringStart = -1;
private StringBuffer stringSoFar = null;
private boolean hadCFSinceStringStart = false;
// Rudimentary support for Design-by-Contract
private static final boolean checkSelf = Context.check && true;
}

View File

@@ -0,0 +1,131 @@
/* -*- Mode: java; tab-width: 4; indent-tabs-mode: 1; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
/* Helper class to add/remove listeners from Object array */
package org.mozilla.javascript;
/**
* Utility class to manage listeners array.
* A possible usage would be:
<pre>
private Object[] listeners;
...
void addListener(ListenerType listener) {
synchronized (this) {
listeners = ListenerArray.add(listeners, listener);
}
}
void removeListener(ListenerType listener) {
synchronized (this) {
listeners = ListenerArray.remove(listeners, listener);
}
}
</pre>
* Here is a thread safe while synchronization free example of event firing
<pre>
void fireEvent(EventType event) {
Object[] array = listeners;
if (array != null) {
for (int i = array.length; i-- != 0;) {
((ListenerType)array[i]).onEvent(event);
}
}
}
</pre>
* or if listeners of different types can present in listeners array:
<pre>
void fireEvent(EventType event) {
Object[] array = listeners;
if (array != null) {
for (int i = array.length; i-- != 0;) {
Object obj = array[i];
if (obj instanceof ListenerType) {
((ListenerType)obj).onEvent(event);
}
}
}
}
</pre>
*/
public class ListenerArray {
/** Return newly allocated array that contains listener and all elements
** from data array.
** Note: listener is added to resulting array even if it is already
** present in data */
public static Object[] add(Object[] data, Object listener) {
if (data == null) {
data = new Object[1];
}
else {
int N = data.length;
Object[] tmp = new Object[N + 1];
System.arraycopy(data, 0, tmp, 1, N);
data = tmp;
}
data[0] = listener;
return data;
}
/** Return a copy of data array with the first occurrence of listener
** removed.
** If listener is not present in data, simply return data.
** Note: return <code>null</code> if listener is the single element
** of data. */
public static Object[] remove(Object[] data, Object listener) {
if (data != null) {
int N = data.length;
for (int i = 0; i != N; ++i) {
if (data[i] == listener) {
if (N == 1) { data = null; }
else {
Object[] tmp = new Object[N - 1];
System.arraycopy(data, 0, tmp, 0, i);
System.arraycopy(data, i + 1, tmp, i, N - 1 - i);
data = tmp;
}
break;
}
}
}
return data;
}
}

View File

@@ -0,0 +1,79 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
public class LocalVariable {
public LocalVariable(String name, boolean isParameter) {
itsName = name;
itsIsParameter = isParameter;
}
public void setIndex(int index){ itsIndex = index; }
public int getIndex() { return itsIndex; }
public void setIsParameter() { itsIsParameter = true; }
public boolean isParameter() { return itsIsParameter; }
public String getName() { return itsName; }
/**
* Return the starting PC where this variable is live, or -1
* if it is not a Java register.
*/
public int getStartPC() {
return -1;
}
/**
* Return the Java register number or -1 if it is not a Java register.
*/
public short getJRegister() {
return -1;
}
/**
* Return true if the local variable is a Java register with double type.
*/
public boolean isNumber() {
return false;
}
private String itsName;
private int itsIndex = -1;
private boolean itsIsParameter;
}

View File

@@ -1,418 +0,0 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Igor Bukanov
* Felix Meschberger
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.lang.reflect.*;
import java.io.*;
/**
* Wrappper class for Method and Constructor instances to cache
* getParameterTypes() results, recover from IllegalAccessException
* in some cases and provide serialization support.
*
* @author Igor Bukanov
*/
final class MemberBox implements Serializable
{
MemberBox(Method method, ClassCache cache)
{
this.cache = cache;
init(method);
}
MemberBox(Constructor constructor, ClassCache cache)
{
this.cache = cache;
init(constructor);
}
private void init(Method method)
{
this.memberObject = method;
this.argTypes = method.getParameterTypes();
}
void prepareInvokerOptimization()
{
if (cache.invokerOptimization) {
Invoker master = (Invoker)cache.invokerMaster;
if (master == null) {
master = Invoker.makeMaster();
if (master == null) {
cache.invokerOptimization = false;
} else {
cache.invokerMaster = master;
}
}
if (master != null) {
try {
invoker = master.createInvoker(cache, method(), argTypes);
} catch (RuntimeException ex) {
cache.invokerOptimization = false;
}
}
}
}
private void init(Constructor constructor)
{
this.memberObject = constructor;
this.argTypes = constructor.getParameterTypes();
}
Method method()
{
return (Method)memberObject;
}
Constructor ctor()
{
return (Constructor)memberObject;
}
boolean isMethod()
{
return memberObject instanceof Method;
}
boolean isCtor()
{
return memberObject instanceof Constructor;
}
boolean isStatic()
{
return Modifier.isStatic(memberObject.getModifiers());
}
String getName()
{
return memberObject.getName();
}
Class getDeclaringClass()
{
return memberObject.getDeclaringClass();
}
String toJavaDeclaration()
{
StringBuffer sb = new StringBuffer();
if (isMethod()) {
Method method = method();
sb.append(method.getReturnType());
sb.append(' ');
sb.append(method.getName());
} else {
Constructor ctor = ctor();
String name = ctor.getDeclaringClass().getName();
int lastDot = name.lastIndexOf('.');
if (lastDot >= 0) {
name = name.substring(lastDot + 1);
}
sb.append(name);
}
sb.append(JavaMembers.liveConnectSignature(argTypes));
return sb.toString();
}
public String toString()
{
return memberObject.toString();
}
Object invoke(Object target, Object[] args)
{
if (invoker != null) {
try {
return invoker.invoke(target, args);
} catch (Exception ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
} catch (LinkageError ex) {
invoker = null;
}
}
Method method = method();
try {
try {
return method.invoke(target, args);
} catch (IllegalAccessException ex) {
Method accessible = searchAccessibleMethod(method, argTypes);
if (accessible != null) {
memberObject = accessible;
method = accessible;
} else {
if (!tryToMakeAccessible(method)) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
}
// Retry after recovery
return method.invoke(target, args);
}
} catch (IllegalAccessException ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
} catch (InvocationTargetException ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
}
Object newInstance(Object[] args)
{
Constructor ctor = ctor();
try {
try {
return ctor.newInstance(args);
} catch (IllegalAccessException ex) {
if (!tryToMakeAccessible(ctor)) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
}
return ctor.newInstance(args);
} catch (IllegalAccessException ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
} catch (InvocationTargetException ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
} catch (InstantiationException ex) {
throw ScriptRuntime.throwAsUncheckedException(ex);
}
}
private static Method searchAccessibleMethod(Method method, Class[] params)
{
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)) {
Class c = method.getDeclaringClass();
if (!Modifier.isPublic(c.getModifiers())) {
String name = method.getName();
Class[] intfs = c.getInterfaces();
for (int i = 0, N = intfs.length; i != N; ++i) {
Class intf = intfs[i];
if (Modifier.isPublic(intf.getModifiers())) {
try {
return intf.getMethod(name, params);
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) { }
}
}
for (;;) {
c = c.getSuperclass();
if (c == null) { break; }
if (Modifier.isPublic(c.getModifiers())) {
try {
Method m = c.getMethod(name, params);
int mModifiers = m.getModifiers();
if (Modifier.isPublic(mModifiers)
&& !Modifier.isStatic(mModifiers))
{
return m;
}
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) { }
}
}
}
}
return null;
}
private static boolean tryToMakeAccessible(Member member)
{
/**
* Due to a bug in Sun's VM, public methods in private
* classes are not accessible by default (Sun Bug #4071593).
* We have to explicitly set the method accessible
* via method.setAccessible(true) but we have to use
* reflection because the setAccessible() in Method is
* not available under jdk 1.1.
*/
if (method_setAccessible != null) {
try {
Object[] args_wrapper = { Boolean.TRUE };
method_setAccessible.invoke(member, args_wrapper);
return true;
} catch (Exception ex) { }
}
return false;
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
Member member = readMember(in);
if (member instanceof Method) {
init((Method)member);
} else {
init((Constructor)member);
}
}
private void writeObject(ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
writeMember(out, memberObject);
}
/**
* Writes a Constructor or Method object.
*
* Methods and Constructors are not serializable, so we must serialize
* information about the class, the name, and the parameters and
* recreate upon deserialization.
*/
private static void writeMember(ObjectOutputStream out, Member member)
throws IOException
{
if (member == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
if (!(member instanceof Method || member instanceof Constructor))
throw new IllegalArgumentException("not Method or Constructor");
out.writeBoolean(member instanceof Method);
out.writeObject(member.getName());
out.writeObject(member.getDeclaringClass());
if (member instanceof Method) {
writeParameters(out, ((Method) member).getParameterTypes());
} else {
writeParameters(out, ((Constructor) member).getParameterTypes());
}
}
/**
* Reads a Method or a Constructor from the stream.
*/
private static Member readMember(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
if (!in.readBoolean())
return null;
boolean isMethod = in.readBoolean();
String name = (String) in.readObject();
Class declaring = (Class) in.readObject();
Class[] parms = readParameters(in);
try {
if (isMethod) {
return declaring.getMethod(name, parms);
} else {
return declaring.getConstructor(parms);
}
} catch (NoSuchMethodException e) {
throw new IOException("Cannot find member: " + e);
}
}
private static final Class[] primitives = {
Boolean.TYPE,
Byte.TYPE,
Character.TYPE,
Double.TYPE,
Float.TYPE,
Integer.TYPE,
Long.TYPE,
Short.TYPE,
Void.TYPE
};
/**
* Writes an array of parameter types to the stream.
*
* Requires special handling because primitive types cannot be
* found upon deserialization by the default Java implementation.
*/
private static void writeParameters(ObjectOutputStream out, Class[] parms)
throws IOException
{
out.writeShort(parms.length);
outer:
for (int i=0; i < parms.length; i++) {
Class parm = parms[i];
out.writeBoolean(parm.isPrimitive());
if (!parm.isPrimitive()) {
out.writeObject(parm);
continue;
}
for (int j=0; j < primitives.length; j++) {
if (parm.equals(primitives[j])) {
out.writeByte(j);
continue outer;
}
}
throw new IllegalArgumentException("Primitive " + parm +
" not found");
}
}
/**
* Reads an array of parameter types from the stream.
*/
private static Class[] readParameters(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
Class[] result = new Class[in.readShort()];
for (int i=0; i < result.length; i++) {
if (!in.readBoolean()) {
result[i] = (Class) in.readObject();
continue;
}
result[i] = primitives[in.readByte()];
}
return result;
}
private ClassCache cache;
private transient Member memberObject;
transient Class[] argTypes;
transient Invoker invoker;
private static Method method_setAccessible;
static {
try {
Class MethodClass = Class.forName("java.lang.reflect.Method");
method_setAccessible = MethodClass.getMethod(
"setAccessible", new Class[] { Boolean.TYPE });
} catch (Exception ex) {
// Assume any exceptions means the method does not exist.
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
* Igor Bukanov
* Mike McCabe
@@ -66,14 +66,6 @@ final class NativeBoolean extends IdScriptable {
return super.getDefaultValue(typeHint);
}
protected String toSource(Context cx, Scriptable scope, Object[] args)
{
if (booleanValue)
return "(new Boolean(true))";
else
return "(new Boolean(false))";
}
public int methodArity(int methodId) {
if (prototypeFlag) {
if (methodId == Id_constructor) return 1;
@@ -90,28 +82,44 @@ final class NativeBoolean extends IdScriptable {
{
if (prototypeFlag) {
if (methodId == Id_constructor) {
boolean b = ScriptRuntime.toBoolean(args, 0);
if (thisObj == null) {
// new Boolean(val) creates a new boolean object.
return new NativeBoolean(b);
}
// Boolean(val) converts val to a boolean.
return wrap_boolean(b);
} else if (methodId == Id_toString) {
return realThisBoolean(thisObj, f) ? "true" : "false";
} else if (methodId == Id_valueOf) {
return wrap_boolean(realThisBoolean(thisObj, f));
return jsConstructor(args, thisObj == null);
}
else if (methodId == Id_toString) {
return realThis(thisObj, f).jsFunction_toString();
}
else if (methodId == Id_valueOf) {
return wrap_boolean(realThis(thisObj, f).jsFunction_valueOf());
}
}
return super.execMethod(methodId, f, cx, scope, thisObj, args);
}
private static boolean realThisBoolean(Scriptable thisObj, IdFunction f)
{
if (!(thisObj instanceof NativeBoolean))
throw incompatibleCallError(f);
return ((NativeBoolean)thisObj).booleanValue;
private NativeBoolean realThis(Scriptable thisObj, IdFunction f) {
while (!(thisObj instanceof NativeBoolean)) {
thisObj = nextInstanceCheck(thisObj, f, true);
}
return (NativeBoolean)thisObj;
}
private Object jsConstructor(Object[] args, boolean inNewExpr) {
boolean b = ScriptRuntime.toBoolean(args, 0);
if (inNewExpr) {
// new Boolean(val) creates a new boolean object.
return new NativeBoolean(b);
}
// Boolean(val) converts val to a boolean.
return wrap_boolean(b);
}
private String jsFunction_toString() {
return booleanValue ? "true" : "false";
}
private boolean jsFunction_valueOf() {
return booleanValue;
}
protected String getIdName(int id) {
@@ -120,7 +128,7 @@ final class NativeBoolean extends IdScriptable {
if (id == Id_toString) return "toString";
if (id == Id_valueOf) return "valueOf";
}
return null;
return null;
}
// #string_id_map#

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,7 +18,7 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Norris Boyd
*
* Alternatively, the contents of this file may be used under the
@@ -43,63 +43,63 @@ package org.mozilla.javascript;
* @see org.mozilla.javascript.Arguments
* @author Norris Boyd
*/
public final class NativeCall extends ScriptableObject
{
static void init(Context cx, Scriptable scope, boolean sealed)
{
new NativeCallPrototype(cx, scope, sealed);
public final class NativeCall extends IdScriptable {
static void init(Context cx, Scriptable scope, boolean sealed) {
NativeCall obj = new NativeCall();
obj.prototypeFlag = true;
obj.addAsPrototype(MAX_PROTOTYPE_ID, cx, scope, sealed);
}
NativeCall() { }
NativeCall(Context cx, Scriptable scope, NativeFunction funObj,
NativeCall(Context cx, Scriptable scope, NativeFunction funObj,
Scriptable thisObj, Object[] args)
{
this.funObj = funObj;
this.thisObj = thisObj;
setParentScope(scope);
// leave prototype null
// save current activation
this.caller = cx.currentActivation;
cx.currentActivation = this;
this.originalArgs = (args == null) ? ScriptRuntime.emptyArgs : args;
// initialize values of arguments
String[] argNames = funObj.argNames;
if (argNames != null) {
for (int i=0; i < funObj.argCount; i++) {
Object val = i < args.length ? args[i]
Object val = i < args.length ? args[i]
: Undefined.instance;
super.put(argNames[i], this, val);
}
}
// initialize "arguments" property but only if it was not overriden by
// the parameter with the same name
if (!super.has("arguments", this)) {
super.put("arguments", this, new Arguments(this));
}
if (argNames != null) {
for (int i = funObj.argCount; i != argNames.length; i++) {
String name = argNames[i];
if (!super.has(name, this)) {
super.put(name, this, Undefined.instance);
}
}
}
// initialize "arguments" property
super.put("arguments", this, new Arguments(this));
}
private NativeCall() {
}
public String getClassName()
{
public String getClassName() {
return "Call";
}
NativeCall getActivation(Function f)
private static Object jsConstructor(Context cx, Object[] args,
Function ctorObj, boolean inNewExpr)
{
if (!inNewExpr) {
throw Context.reportRuntimeError1("msg.only.from.new", "Call");
}
ScriptRuntime.checkDeprecated(cx, "Call");
NativeCall result = new NativeCall();
result.setPrototype(getObjectPrototype(ctorObj));
return result;
}
NativeCall getActivation(Function f) {
NativeCall x = this;
do {
if (x.funObj == f)
@@ -108,80 +108,64 @@ public final class NativeCall extends ScriptableObject
} while (x != null);
return null;
}
public Function getFunctionObject()
{
public Function getFunctionObject() {
return funObj;
}
public Object[] getOriginalArguments()
{
public Object[] getOriginalArguments() {
return originalArgs;
}
public NativeCall getCaller()
{
public NativeCall getCaller() {
return caller;
}
public Scriptable getThisObj()
{
public Scriptable getThisObj() {
return thisObj;
}
NativeCall caller;
NativeFunction funObj;
Scriptable thisObj;
private Object[] originalArgs;
}
final class NativeCallPrototype extends IdScriptable
{
NativeCallPrototype(Context cx, Scriptable scope, boolean sealed)
{
addAsPrototype(MAX_PROTOTYPE_ID, cx, scope, sealed);
}
public String getClassName()
{
return "Call";
}
public int methodArity(int methodId)
{
if (methodId == Id_constructor) return 1;
public int methodArity(int methodId) {
if (prototypeFlag) {
if (methodId == Id_constructor) return 1;
}
return super.methodArity(methodId);
}
public Object execMethod(int methodId, IdFunction f,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
public Object execMethod
(int methodId, IdFunction f,
Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
throws JavaScriptException
{
if (methodId == Id_constructor) {
if (thisObj != null) {
throw Context.reportRuntimeError1("msg.only.from.new", "Call");
if (prototypeFlag) {
if (methodId == Id_constructor) {
return jsConstructor(cx, args, f, thisObj == null);
}
ScriptRuntime.checkDeprecated(cx, "Call");
NativeCall result = new NativeCall();
result.setPrototype(getObjectPrototype(scope));
return result;
}
return super.execMethod(methodId, f, cx, scope, thisObj, args);
}
protected String getIdName(int id)
{
if (id == Id_constructor) return "constructor";
return null;
protected String getIdName(int id) {
if (prototypeFlag) {
if (id == Id_constructor) return "constructor";
}
return null;
}
protected int mapNameToId(String s)
{
protected int mapNameToId(String s) {
if (!prototypeFlag) { return 0; }
return s.equals("constructor") ? Id_constructor : 0;
}
private static final int
Id_constructor = 1,
MAX_PROTOTYPE_ID = 1;
NativeCall caller;
NativeFunction funObj;
Scriptable thisObj;
Object[] originalArgs;
public int debugPC;
private boolean prototypeFlag;
}

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,7 @@
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
@@ -18,10 +18,10 @@
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Contributor(s):
* Igor Bukanov
* Roger Lawrence
*
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
@@ -43,89 +43,46 @@ package org.mozilla.javascript;
*
* ECMA 15.11
*/
final class NativeError extends IdScriptable
{
final class NativeError extends IdScriptable {
static void init(Context cx, Scriptable scope, boolean sealed)
{
static void init(Context cx, Scriptable scope, boolean sealed) {
NativeError obj = new NativeError();
obj.prototypeFlag = true;
ScriptableObject.putProperty(obj, "name", "Error");
ScriptableObject.putProperty(obj, "message", "");
ScriptableObject.putProperty(obj, "fileName", "");
ScriptableObject.putProperty(obj, "lineNumber", new Integer(0));
obj.messageValue = "";
obj.nameValue = "Error";
obj.addAsPrototype(MAX_PROTOTYPE_ID, cx, scope, sealed);
}
protected String toSource(Context cx, Scriptable scope, Object[] args)
throws JavaScriptException
{
// Emulation of SpiderMonkey behavior
Object name = ScriptableObject.getProperty(this, "name");
Object message = ScriptableObject.getProperty(this, "message");
Object fileName = ScriptableObject.getProperty(this, "fileName");
Object lineNumber = ScriptableObject.getProperty(this, "lineNumber");
StringBuffer sb = new StringBuffer();
sb.append("(new ");
if (name == NOT_FOUND) {
name = Undefined.instance;
}
sb.append(ScriptRuntime.toString(name));
sb.append("(");
if (message != NOT_FOUND
|| fileName != NOT_FOUND
|| lineNumber != NOT_FOUND)
{
if (message == NOT_FOUND) {
message = "";
}
sb.append(ScriptRuntime.uneval(cx, scope, message));
if (fileName != NOT_FOUND || lineNumber != NOT_FOUND) {
sb.append(", ");
if (fileName == NOT_FOUND) {
fileName = "";
}
sb.append(ScriptRuntime.uneval(cx, scope, fileName));
if (lineNumber != NOT_FOUND) {
int line = ScriptRuntime.toInt32(lineNumber);
if (line != 0) {
sb.append(", ");
sb.append(ScriptRuntime.toString(line));
}
}
}
}
sb.append("))");
return sb.toString();
protected int getIdDefaultAttributes(int id) {
if (id == Id_message || id == Id_name) { return EMPTY; }
return super.getIdDefaultAttributes(id);
}
static NativeError make(Context cx, Scriptable scope, IdFunction ctorObj,
Object[] args)
{
Scriptable proto = (Scriptable)(ctorObj.get("prototype", ctorObj));
NativeError obj = new NativeError();
obj.setPrototype(proto);
obj.setParentScope(scope);
if (args.length >= 1) {
ScriptableObject.putProperty(obj, "message",
ScriptRuntime.toString(args[0]));
if (args.length >= 2) {
ScriptableObject.putProperty(obj, "fileName", args[1]);
if (args.length >= 3) {
int line = ScriptRuntime.toInt32(args[2]);
ScriptableObject.putProperty(obj, "lineNumber",
new Integer(line));
}
}
}
return obj;
protected boolean hasIdValue(int id) {
if (id == Id_message) { return messageValue != NOT_FOUND; }
if (id == Id_name) { return nameValue != NOT_FOUND; }
return super.hasIdValue(id);
}
public int methodArity(int methodId)
{
protected Object getIdValue(int id) {
if (id == Id_message) { return messageValue; }
if (id == Id_name) { return nameValue; }
return super.getIdValue(id);
}
protected void setIdValue(int id, Object value) {
if (id == Id_message) { messageValue = value; return; }
if (id == Id_name) { nameValue = value; return; }
super.setIdValue(id, value);
}
protected void deleteIdValue(int id) {
if (id == Id_message) { messageValue = NOT_FOUND; return; }
if (id == Id_name) { nameValue = NOT_FOUND; return; }
super.deleteIdValue(id);
}
public int methodArity(int methodId) {
if (prototypeFlag) {
if (methodId == Id_constructor) return 1;
if (methodId == Id_toString) return 0;
@@ -140,50 +97,90 @@ final class NativeError extends IdScriptable
{
if (prototypeFlag) {
if (methodId == Id_constructor) {
return make(cx, scope, f, args);
return jsConstructor(cx, args, f, thisObj == null);
}
else if (methodId == Id_toString) {
return js_toString(thisObj);
return realThis(thisObj, f).toString();
}
}
return super.execMethod(methodId, f, cx, scope, thisObj, args);
}
private static String js_toString(Scriptable thisObj)
{
return getString(thisObj, "name")+": "+getString(thisObj, "message");
private NativeError realThis(Scriptable thisObj, IdFunction f) {
while (!(thisObj instanceof NativeError)) {
thisObj = nextInstanceCheck(thisObj, f, true);
}
return (NativeError)thisObj;
}
public String getClassName()
private static Object jsConstructor(Context cx, Object[] args,
Function funObj, boolean inNewExpr)
{
return "Error";
NativeError result = new NativeError();
if (args.length >= 1)
result.messageValue = ScriptRuntime.toString(args[0]);
result.setPrototype(getClassPrototype(funObj, "Error"));
return result;
}
public String getClassName() {
return "Error";
}
public String toString()
{
return js_toString(this);
public String toString() {
// The "name" property is usually just defined in the prototype,
// so use getProperty to fetch it.
Object name = ScriptableObject.getProperty(this, "name");
if (name == NOT_FOUND)
name = Undefined.instance;
return name + ": " + getMessage();
}
private static String getString(Scriptable obj, String id)
{
Object value = ScriptableObject.getProperty(obj, id);
if (value == NOT_FOUND) return "";
return ScriptRuntime.toString(value);
public String getName() {
Object val = nameValue;
return ScriptRuntime.toString(val != NOT_FOUND ? val
: Undefined.instance);
}
public String getMessage() {
Object val = messageValue;
return ScriptRuntime.toString(val != NOT_FOUND ? val
: Undefined.instance);
}
protected String getIdName(int id)
{
protected int maxInstanceId() { return MAX_INSTANCE_ID; }
protected String getIdName(int id) {
if (id == Id_message) { return "message"; }
if (id == Id_name) { return "name"; }
if (prototypeFlag) {
if (id == Id_constructor) return "constructor";
if (id == Id_toString) return "toString";
}
return null;
return null;
}
// #string_id_map#
protected int mapNameToId(String s)
{
private static final int
Id_message = 1,
Id_name = 2,
MAX_INSTANCE_ID = 2;
protected int mapNameToId(String s) {
int id;
if (!prototypeFlag) { return 0; }
// #generated# Last update: 2001-05-19 21:55:23 CEST
L0: { id = 0; String X = null;
int s_length = s.length();
if (s_length==4) { X="name";id=Id_name; }
else if (s_length==7) { X="message";id=Id_message; }
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
// #/string_id_map#
if (id != 0 || !prototypeFlag) { return id; }
// #string_id_map#
// #generated# Last update: 2001-05-19 21:55:23 CEST
@@ -198,12 +195,15 @@ final class NativeError extends IdScriptable
}
private static final int
Id_constructor = 1,
Id_toString = 2,
MAX_PROTOTYPE_ID = 2;
Id_constructor = MAX_INSTANCE_ID + 1,
Id_toString = MAX_INSTANCE_ID + 2,
MAX_PROTOTYPE_ID = MAX_INSTANCE_ID + 2;
// #/string_id_map#
private Object messageValue = NOT_FOUND;
private Object nameValue = NOT_FOUND;
private boolean prototypeFlag;
}

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