8187443: Forest Consolidation: Move files to unified layout

Reviewed-by: darcy, ihse
This commit is contained in:
Erik Joelsson 2017-09-12 19:03:39 +02:00
parent 270fe13182
commit 3789983e89
56923 changed files with 3 additions and 15727 deletions

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package jdk.nashorn.api.linker;
import java.util.List;
import jdk.dynalink.linker.GuardingDynamicLinker;
import jdk.dynalink.linker.GuardingDynamicLinkerExporter;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
/**
* This linker exporter is a service provider that exports Nashorn Dynalink
* linkers to external users. Other language runtimes that use Dynalink
* can use the linkers exported by this provider to support tight integration
* of Nashorn objects.
*/
public final class NashornLinkerExporter extends GuardingDynamicLinkerExporter {
/**
* The default constructor.
*/
public NashornLinkerExporter() {}
/**
* Returns a list of exported nashorn specific linkers.
*
* @return list of exported nashorn specific linkers
*/
@Override
public List<GuardingDynamicLinker> get() {
return Bootstrap.getExposedLinkers();
}
}

View file

@ -0,0 +1,226 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
/**
* This is the base class for nashorn ScriptObjectMirror class.
*
* This class can also be subclassed by an arbitrary Java class. Nashorn will
* treat objects of such classes just like nashorn script objects. Usual nashorn
* operations like obj[i], obj.foo, obj.func(), delete obj.foo will be delegated
* to appropriate method call of this class.
*
* @since 1.8u40
*/
public abstract class AbstractJSObject implements JSObject {
/**
* The default constructor.
*/
public AbstractJSObject() {}
/**
* @implSpec This implementation always throws UnsupportedOperationException
*/
@Override
public Object call(final Object thiz, final Object... args) {
throw new UnsupportedOperationException("call");
}
/**
* @implSpec This implementation always throws UnsupportedOperationException
*/
@Override
public Object newObject(final Object... args) {
throw new UnsupportedOperationException("newObject");
}
/**
* @implSpec This imlementation always throws UnsupportedOperationException
*/
@Override
public Object eval(final String s) {
throw new UnsupportedOperationException("eval");
}
/**
* @implSpec This implementation always returns null
*/
@Override
public Object getMember(final String name) {
Objects.requireNonNull(name);
return null;
}
/**
* @implSpec This implementation always returns null
*/
@Override
public Object getSlot(final int index) {
return null;
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean hasMember(final String name) {
Objects.requireNonNull(name);
return false;
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean hasSlot(final int slot) {
return false;
}
/**
* @implSpec This implementation is a no-op
*/
@Override
public void removeMember(final String name) {
Objects.requireNonNull(name);
//empty
}
/**
* @implSpec This implementation is a no-op
*/
@Override
public void setMember(final String name, final Object value) {
Objects.requireNonNull(name);
//empty
}
/**
* @implSpec This implementation is a no-op
*/
@Override
public void setSlot(final int index, final Object value) {
//empty
}
// property and value iteration
/**
* @implSpec This implementation returns empty set
*/
@Override
public Set<String> keySet() {
return Collections.emptySet();
}
/**
* @implSpec This implementation returns empty set
*/
@Override
public Collection<Object> values() {
return Collections.emptySet();
}
// JavaScript instanceof check
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean isInstance(final Object instance) {
return false;
}
@Override
public boolean isInstanceOf(final Object clazz) {
if (clazz instanceof JSObject) {
return ((JSObject)clazz).isInstance(this);
}
return false;
}
@Override
public String getClassName() {
return getClass().getName();
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean isFunction() {
return false;
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean isStrictFunction() {
return false;
}
/**
* @implSpec This implementation always returns false
*/
@Override
public boolean isArray() {
return false;
}
/**
* Returns this object's numeric value.
*
* @return this object's numeric value.
* @deprecated use {@link #getDefaultValue(Class)} with {@link Number} hint instead.
*/
@Override @Deprecated
public double toNumber() {
return Double.NaN;
}
/**
* When passed an {@link AbstractJSObject}, invokes its {@link #getDefaultValue(Class)} method. When passed any
* other {@link JSObject}, it will obtain its {@code [[DefaultValue]]} method as per ECMAScript 5.1 section
* 8.6.2.
*
* @param jsobj the {@link JSObject} whose {@code [[DefaultValue]]} is obtained.
* @param hint the type hint. Should be either {@code null}, {@code Number.class} or {@code String.class}.
* @return this object's default value.
* @throws UnsupportedOperationException if the conversion can't be performed. The engine will convert this
* exception into a JavaScript {@code TypeError}.
* @deprecated use {@link JSObject#getDefaultValue(Class)} instead.
*/
@Deprecated
public static Object getDefaultValue(final JSObject jsobj, final Class<?> hint) {
return jsobj.getDefaultValue(hint);
}
}

View file

@ -0,0 +1,43 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
/**
* Class filter (optional) to be used by nashorn script engine.
* jsr-223 program embedding nashorn script can set ClassFilter instance
* to be used when an engine instance is created.
*
* @since 1.8u40
*/
public interface ClassFilter {
/**
* Should the Java class of the specified name be exposed to scripts?
* @param className is the fully qualified name of the java class being
* checked. This will not be null. Only non-array class names will be
* passed.
* @return true if the java class can be exposed to scripts false otherwise
*/
public boolean exposeToScripts(String className);
}

View file

@ -0,0 +1,55 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import jdk.nashorn.internal.runtime.JSType;
/**
* Default implementation of {@link JSObject#getDefaultValue(Class)}. Isolated into a separate class mostly so
* that we can have private static instances of function name arrays, something we couldn't declare without it
* being visible in {@link JSObject} interface.
*/
class DefaultValueImpl {
private static final String[] DEFAULT_VALUE_FNS_NUMBER = new String[] { "valueOf", "toString" };
private static final String[] DEFAULT_VALUE_FNS_STRING = new String[] { "toString", "valueOf" };
static Object getDefaultValue(final JSObject jsobj, final Class<?> hint) throws UnsupportedOperationException {
final boolean isNumber = hint == null || hint == Number.class;
for(final String methodName: isNumber ? DEFAULT_VALUE_FNS_NUMBER : DEFAULT_VALUE_FNS_STRING) {
final Object objMember = jsobj.getMember(methodName);
if (objMember instanceof JSObject) {
final JSObject member = (JSObject)objMember;
if (member.isFunction()) {
final Object value = member.call(jsobj);
if (JSType.isPrimitive(value)) {
return value;
}
}
}
}
throw new UnsupportedOperationException(isNumber ? "cannot.get.default.number" : "cannot.get.default.string");
}
}

View file

@ -0,0 +1,185 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Formatter is a class to get the type conversion between javascript types and
* java types for the format (sprintf) method working.
*
* <p>In javascript the type for numbers can be different from the format type
* specifier. For format type '%d', '%o', '%x', '%X' double need to be
* converted to integer. For format type 'e', 'E', 'f', 'g', 'G', 'a', 'A'
* integer needs to be converted to double.
*
* <p>Format type "%c" and javascript string needs special handling.
*
* <p>The javascript date objects can be handled if they are type double (the
* related javascript code will convert with Date.getTime() to double). So
* double date types are converted to long.
*
* <p>Pattern and the logic for parameter position: java.util.Formatter
*
*/
final class Formatter {
private Formatter() {
}
/**
* Method which converts javascript types to java types for the
* String.format method (jrunscript function sprintf).
*
* @param format a format string
* @param args arguments referenced by the format specifiers in format
* @return a formatted string
*/
static String format(final String format, final Object[] args) {
final Matcher m = FS_PATTERN.matcher(format);
int positionalParameter = 1;
while (m.find()) {
int index = index(m.group(1));
final boolean previous = isPreviousArgument(m.group(2));
final char conversion = m.group(6).charAt(0);
// skip over some formats
if (index < 0 || previous
|| conversion == 'n' || conversion == '%') {
continue;
}
// index 0 here means take a positional parameter
if (index == 0) {
index = positionalParameter++;
}
// out of index, String.format will handle
if (index > args.length) {
continue;
}
// current argument
final Object arg = args[index - 1];
// for date we convert double to long
if (m.group(5) != null) {
// convert double to long
if (arg instanceof Double) {
args[index - 1] = ((Double) arg).longValue();
}
} else {
// we have to convert some types
switch (conversion) {
case 'd':
case 'o':
case 'x':
case 'X':
if (arg instanceof Double) {
// convert double to long
args[index - 1] = ((Double) arg).longValue();
} else if (arg instanceof String
&& ((String) arg).length() > 0) {
// convert string (first character) to int
args[index - 1] = (int) ((String) arg).charAt(0);
}
break;
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
case 'a':
case 'A':
if (arg instanceof Integer) {
// convert integer to double
args[index - 1] = ((Integer) arg).doubleValue();
}
break;
case 'c':
if (arg instanceof Double) {
// convert double to integer
args[index - 1] = ((Double) arg).intValue();
} else if (arg instanceof String
&& ((String) arg).length() > 0) {
// get the first character from string
args[index - 1] = (int) ((String) arg).charAt(0);
}
break;
default:
break;
}
}
}
return String.format(format, args);
}
/**
* Method to parse the integer of the argument index.
*
* @param s string to parse
* @return -1 if parsing failed, 0 if string is null, > 0 integer
*/
private static int index(final String s) {
int index = -1;
if (s != null) {
try {
index = Integer.parseInt(s.substring(0, s.length() - 1));
} catch (final NumberFormatException e) {
//ignored
}
} else {
index = 0;
}
return index;
}
/**
* Method to check if a string contains '&lt;'. This is used to find out if
* previous parameter is used.
*
* @param s string to check
* @return true if '&lt;' is in the string, else false
*/
private static boolean isPreviousArgument(final String s) {
return (s != null && s.indexOf('<') >= 0);
}
// %[argument_index$][flags][width][.precision][t]conversion
private static final String formatSpecifier =
"%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])";
// compiled format string
private static final Pattern FS_PATTERN;
static {
FS_PATTERN = Pattern.compile(formatSpecifier);
}
}

View file

@ -0,0 +1,210 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import java.util.Collection;
import java.util.Set;
import jdk.nashorn.internal.runtime.JSType;
/**
* This interface can be implemented by an arbitrary Java class. Nashorn will
* treat objects of such classes just like nashorn script objects. Usual nashorn
* operations like obj[i], obj.foo, obj.func(), delete obj.foo will be delegated
* to appropriate method call of this interface.
*
* @since 1.8u40
*/
public interface JSObject {
/**
* Call this object as a JavaScript function. This is equivalent to
* 'func.apply(thiz, args)' in JavaScript.
*
* @param thiz 'this' object to be passed to the function. This may be null.
* @param args arguments to method
* @return result of call
*/
public Object call(final Object thiz, final Object... args);
/**
* Call this 'constructor' JavaScript function to create a new object.
* This is equivalent to 'new func(arg1, arg2...)' in JavaScript.
*
* @param args arguments to method
* @return result of constructor call
*/
public Object newObject(final Object... args);
/**
* Evaluate a JavaScript expression.
*
* @param s JavaScript expression to evaluate
* @return evaluation result
*/
public Object eval(final String s);
/**
* Retrieves a named member of this JavaScript object.
*
* @param name of member
* @return member
* @throws NullPointerException if name is null
*/
public Object getMember(final String name);
/**
* Retrieves an indexed member of this JavaScript object.
*
* @param index index slot to retrieve
* @return member
*/
public Object getSlot(final int index);
/**
* Does this object have a named member?
*
* @param name name of member
* @return true if this object has a member of the given name
*/
public boolean hasMember(final String name);
/**
* Does this object have a indexed property?
*
* @param slot index to check
* @return true if this object has a slot
*/
public boolean hasSlot(final int slot);
/**
* Remove a named member from this JavaScript object
*
* @param name name of the member
* @throws NullPointerException if name is null
*/
public void removeMember(final String name);
/**
* Set a named member in this JavaScript object
*
* @param name name of the member
* @param value value of the member
* @throws NullPointerException if name is null
*/
public void setMember(final String name, final Object value);
/**
* Set an indexed member in this JavaScript object
*
* @param index index of the member slot
* @param value value of the member
*/
public void setSlot(final int index, final Object value);
// property and value iteration
/**
* Returns the set of all property names of this object.
*
* @return set of property names
*/
public Set<String> keySet();
/**
* Returns the set of all property values of this object.
*
* @return set of property values.
*/
public Collection<Object> values();
// JavaScript instanceof check
/**
* Checking whether the given object is an instance of 'this' object.
*
* @param instance instance to check
* @return true if the given 'instance' is an instance of this 'function' object
*/
public boolean isInstance(final Object instance);
/**
* Checking whether this object is an instance of the given 'clazz' object.
*
* @param clazz clazz to check
* @return true if this object is an instance of the given 'clazz'
*/
public boolean isInstanceOf(final Object clazz);
/**
* ECMA [[Class]] property
*
* @return ECMA [[Class]] property value of this object
*/
public String getClassName();
/**
* Is this a function object?
*
* @return if this mirror wraps a ECMAScript function instance
*/
public boolean isFunction();
/**
* Is this a 'use strict' function object?
*
* @return true if this mirror represents a ECMAScript 'use strict' function
*/
public boolean isStrictFunction();
/**
* Is this an array object?
*
* @return if this mirror wraps a ECMAScript array object
*/
public boolean isArray();
/**
* Returns this object's numeric value.
*
* @return this object's numeric value.
* @deprecated use {@link #getDefaultValue(Class)} with {@link Number} hint instead.
*/
@Deprecated
default double toNumber() {
return JSType.toNumber(JSType.toPrimitive(this, Number.class));
}
/**
* Implements this object's {@code [[DefaultValue]]} method as per ECMAScript 5.1 section 8.6.2.
*
* @param hint the type hint. Should be either {@code null}, {@code Number.class} or {@code String.class}.
* @return this object's default value.
* @throws UnsupportedOperationException if the conversion can't be performed. The engine will convert this
* exception into a JavaScript {@code TypeError}.
*/
default Object getDefaultValue(final Class<?> hint) throws UnsupportedOperationException {
return DefaultValueImpl.getDefaultValue(this, hint);
}
}

View file

@ -0,0 +1,296 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import java.util.ArrayList;
import java.util.List;
import jdk.nashorn.internal.codegen.CompilerConstants;
import jdk.nashorn.internal.runtime.ECMAErrors;
import jdk.nashorn.internal.runtime.ScriptObject;
/**
* This is base exception for all Nashorn exceptions. These originate from
* user's ECMAScript code. Example: script parse errors, exceptions thrown from
* scripts. Note that ScriptEngine methods like "eval", "invokeMethod",
* "invokeFunction" will wrap this as ScriptException and throw it. But, there
* are cases where user may need to access this exception (or implementation
* defined subtype of this). For example, if java interface is implemented by a
* script object or Java access to script object properties via java.util.Map
* interface. In these cases, user code will get an instance of this or
* implementation defined subclass.
*
* @since 1.8u40
*/
@SuppressWarnings("serial")
public abstract class NashornException extends RuntimeException {
private static final long serialVersionUID = 1L;
// script file name
private String fileName;
// script line number
private int line;
// are the line and fileName unknown?
private boolean lineAndFileNameUnknown;
// script column number
private int column;
// underlying ECMA error object - lazily initialized
private Object ecmaError;
/**
* Constructor to initialize error message, file name, line and column numbers.
*
* @param msg exception message
* @param fileName file name
* @param line line number
* @param column column number
*/
protected NashornException(final String msg, final String fileName, final int line, final int column) {
this(msg, null, fileName, line, column);
}
/**
* Constructor to initialize error message, cause exception, file name, line and column numbers.
*
* @param msg exception message
* @param cause exception cause
* @param fileName file name
* @param line line number
* @param column column number
*/
protected NashornException(final String msg, final Throwable cause, final String fileName, final int line, final int column) {
super(msg, cause == null ? null : cause);
this.fileName = fileName;
this.line = line;
this.column = column;
}
/**
* Constructor to initialize error message and cause exception.
*
* @param msg exception message
* @param cause exception cause
*/
protected NashornException(final String msg, final Throwable cause) {
super(msg, cause == null ? null : cause);
// Hard luck - no column number info
this.column = -1;
// We can retrieve the line number and file name from the stack trace if needed
this.lineAndFileNameUnknown = true;
}
/**
* Get the source file name for this {@code NashornException}
*
* @return the file name
*/
public final String getFileName() {
ensureLineAndFileName();
return fileName;
}
/**
* Set the source file name for this {@code NashornException}
*
* @param fileName the file name
*/
public final void setFileName(final String fileName) {
this.fileName = fileName;
lineAndFileNameUnknown = false;
}
/**
* Get the line number for this {@code NashornException}
*
* @return the line number
*/
public final int getLineNumber() {
ensureLineAndFileName();
return line;
}
/**
* Set the line number for this {@code NashornException}
*
* @param line the line number
*/
public final void setLineNumber(final int line) {
lineAndFileNameUnknown = false;
this.line = line;
}
/**
* Get the column for this {@code NashornException}
*
* @return the column number
*/
public final int getColumnNumber() {
return column;
}
/**
* Set the column for this {@code NashornException}
*
* @param column the column number
*/
public final void setColumnNumber(final int column) {
this.column = column;
}
/**
* Returns array javascript stack frames from the given exception object.
*
* @param exception exception from which stack frames are retrieved and filtered
* @return array of javascript stack frames
*/
public static StackTraceElement[] getScriptFrames(final Throwable exception) {
final StackTraceElement[] frames = exception.getStackTrace();
final List<StackTraceElement> filtered = new ArrayList<>();
for (final StackTraceElement st : frames) {
if (ECMAErrors.isScriptFrame(st)) {
final String className = "<" + st.getFileName() + ">";
String methodName = st.getMethodName();
if (methodName.equals(CompilerConstants.PROGRAM.symbolName())) {
methodName = "<program>";
} else {
methodName = stripMethodName(methodName);
}
filtered.add(new StackTraceElement(className, methodName,
st.getFileName(), st.getLineNumber()));
}
}
return filtered.toArray(new StackTraceElement[0]);
}
private static String stripMethodName(final String methodName) {
String name = methodName;
final int nestedSeparator = name.lastIndexOf(CompilerConstants.NESTED_FUNCTION_SEPARATOR.symbolName());
if (nestedSeparator >= 0) {
name = name.substring(nestedSeparator + 1);
}
final int idSeparator = name.indexOf(CompilerConstants.ID_FUNCTION_SEPARATOR.symbolName());
if (idSeparator >= 0) {
name = name.substring(0, idSeparator);
}
return name.contains(CompilerConstants.ANON_FUNCTION_PREFIX.symbolName()) ? "<anonymous>" : name;
}
/**
* Return a formatted script stack trace string with frames information separated by '\n'
*
* @param exception exception for which script stack string is returned
* @return formatted stack trace string
*/
public static String getScriptStackString(final Throwable exception) {
final StringBuilder buf = new StringBuilder();
final StackTraceElement[] frames = getScriptFrames(exception);
for (final StackTraceElement st : frames) {
buf.append("\tat ");
buf.append(st.getMethodName());
buf.append(" (");
buf.append(st.getFileName());
buf.append(':');
buf.append(st.getLineNumber());
buf.append(")\n");
}
final int len = buf.length();
// remove trailing '\n'
if (len > 0) {
assert buf.charAt(len - 1) == '\n';
buf.deleteCharAt(len - 1);
}
return buf.toString();
}
/**
* Get the thrown object. Subclass responsibility
* @return thrown object
*/
protected Object getThrown() {
return null;
}
/**
* Initialization function for ECMA errors. Stores the error
* in the ecmaError field of this class. It is only initialized
* once, and then reused
*
* @param global the global
* @return initialized exception
*/
NashornException initEcmaError(final ScriptObject global) {
if (ecmaError != null) {
return this; // initialized already!
}
final Object thrown = getThrown();
if (thrown instanceof ScriptObject) {
setEcmaError(ScriptObjectMirror.wrap(thrown, global));
} else {
setEcmaError(thrown);
}
return this;
}
/**
* Return the underlying ECMA error object, if available.
*
* @return underlying ECMA Error object's mirror or whatever was thrown
* from script such as a String, Number or a Boolean.
*/
public Object getEcmaError() {
return ecmaError;
}
/**
* Return the underlying ECMA error object, if available.
*
* @param ecmaError underlying ECMA Error object's mirror or whatever was thrown
* from script such as a String, Number or a Boolean.
*/
public void setEcmaError(final Object ecmaError) {
this.ecmaError = ecmaError;
}
private void ensureLineAndFileName() {
if (lineAndFileNameUnknown) {
for (final StackTraceElement ste : getStackTrace()) {
if (ECMAErrors.isScriptFrame(ste)) {
// Whatever here is compiled from JavaScript code
fileName = ste.getFileName();
line = ste.getLineNumber();
return;
}
}
lineAndFileNameUnknown = false;
}
}
}

View file

@ -0,0 +1,568 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import static jdk.nashorn.internal.runtime.Source.sourceFor;
import java.io.IOException;
import java.io.Reader;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Objects;
import java.util.ResourceBundle;
import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ErrorManager;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.Source;
import jdk.nashorn.internal.runtime.linker.JavaAdapterFactory;
import jdk.nashorn.internal.runtime.options.Options;
/**
* JSR-223 compliant script engine for Nashorn. Instances are not created directly, but rather returned through
* {@link NashornScriptEngineFactory#getScriptEngine()}. Note that this engine implements the {@link Compilable} and
* {@link Invocable} interfaces, allowing for efficient precompilation and repeated execution of scripts.
* @see NashornScriptEngineFactory
*
* @since 1.8u40
*/
public final class NashornScriptEngine extends AbstractScriptEngine implements Compilable, Invocable {
/**
* Key used to associate Nashorn global object mirror with arbitrary Bindings instance.
*/
public static final String NASHORN_GLOBAL = "nashorn.global";
// commonly used access control context objects
private static AccessControlContext createPermAccCtxt(final String permName) {
final Permissions perms = new Permissions();
perms.add(new RuntimePermission(permName));
return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
}
private static final AccessControlContext CREATE_CONTEXT_ACC_CTXT = createPermAccCtxt(Context.NASHORN_CREATE_CONTEXT);
private static final AccessControlContext CREATE_GLOBAL_ACC_CTXT = createPermAccCtxt(Context.NASHORN_CREATE_GLOBAL);
// the factory that created this engine
private final ScriptEngineFactory factory;
// underlying nashorn Context - 1:1 with engine instance
private final Context nashornContext;
// do we want to share single Nashorn global instance across ENGINE_SCOPEs?
private final boolean _global_per_engine;
// This is the initial default Nashorn global object.
// This is used as "shared" global if above option is true.
private final Global global;
// Nashorn script engine error message management
private static final String MESSAGES_RESOURCE = "jdk.nashorn.api.scripting.resources.Messages";
private static final ResourceBundle MESSAGES_BUNDLE;
static {
MESSAGES_BUNDLE = ResourceBundle.getBundle(MESSAGES_RESOURCE, Locale.getDefault());
}
// helper to get Nashorn script engine error message
private static String getMessage(final String msgId, final String... args) {
try {
return new MessageFormat(MESSAGES_BUNDLE.getString(msgId)).format(args);
} catch (final java.util.MissingResourceException e) {
throw new RuntimeException("no message resource found for message id: "+ msgId);
}
}
NashornScriptEngine(final NashornScriptEngineFactory factory, final String[] args, final ClassLoader appLoader, final ClassFilter classFilter) {
assert args != null : "null argument array";
this.factory = factory;
final Options options = new Options("nashorn");
options.process(args);
// throw ParseException on first error from script
final ErrorManager errMgr = new Context.ThrowErrorManager();
// create new Nashorn Context
this.nashornContext = AccessController.doPrivileged(new PrivilegedAction<Context>() {
@Override
public Context run() {
try {
return new Context(options, errMgr, appLoader, classFilter);
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
}
throw e;
}
}
}, CREATE_CONTEXT_ACC_CTXT);
// cache this option that is used often
this._global_per_engine = nashornContext.getEnv()._global_per_engine;
// create new global object
this.global = createNashornGlobal();
// set the default ENGINE_SCOPE object for the default context
context.setBindings(new ScriptObjectMirror(global, global), ScriptContext.ENGINE_SCOPE);
}
@Override
public Object eval(final Reader reader, final ScriptContext ctxt) throws ScriptException {
return evalImpl(makeSource(reader, ctxt), ctxt);
}
@Override
public Object eval(final String script, final ScriptContext ctxt) throws ScriptException {
return evalImpl(makeSource(script, ctxt), ctxt);
}
@Override
public ScriptEngineFactory getFactory() {
return factory;
}
@Override
public Bindings createBindings() {
if (_global_per_engine) {
// just create normal SimpleBindings.
// We use same 'global' for all Bindings.
return new SimpleBindings();
}
return createGlobalMirror();
}
// Compilable methods
@Override
public CompiledScript compile(final Reader reader) throws ScriptException {
return asCompiledScript(makeSource(reader, context));
}
@Override
public CompiledScript compile(final String str) throws ScriptException {
return asCompiledScript(makeSource(str, context));
}
// Invocable methods
@Override
public Object invokeFunction(final String name, final Object... args)
throws ScriptException, NoSuchMethodException {
return invokeImpl(null, name, args);
}
@Override
public Object invokeMethod(final Object thiz, final String name, final Object... args)
throws ScriptException, NoSuchMethodException {
if (thiz == null) {
throw new IllegalArgumentException(getMessage("thiz.cannot.be.null"));
}
return invokeImpl(thiz, name, args);
}
@Override
public <T> T getInterface(final Class<T> clazz) {
return getInterfaceInner(null, clazz);
}
@Override
public <T> T getInterface(final Object thiz, final Class<T> clazz) {
if (thiz == null) {
throw new IllegalArgumentException(getMessage("thiz.cannot.be.null"));
}
return getInterfaceInner(thiz, clazz);
}
// Implementation only below this point
private static Source makeSource(final Reader reader, final ScriptContext ctxt) throws ScriptException {
try {
return sourceFor(getScriptName(ctxt), reader);
} catch (final IOException e) {
throw new ScriptException(e);
}
}
private static Source makeSource(final String src, final ScriptContext ctxt) {
return sourceFor(getScriptName(ctxt), src);
}
private static String getScriptName(final ScriptContext ctxt) {
final Object val = ctxt.getAttribute(ScriptEngine.FILENAME);
return (val != null) ? val.toString() : "<eval>";
}
private <T> T getInterfaceInner(final Object thiz, final Class<T> clazz) {
assert !(thiz instanceof ScriptObject) : "raw ScriptObject not expected here";
if (clazz == null || !clazz.isInterface()) {
throw new IllegalArgumentException(getMessage("interface.class.expected"));
}
// perform security access check as early as possible
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (! Modifier.isPublic(clazz.getModifiers())) {
throw new SecurityException(getMessage("implementing.non.public.interface", clazz.getName()));
}
Context.checkPackageAccess(clazz);
}
ScriptObject realSelf = null;
Global realGlobal = null;
if(thiz == null) {
// making interface out of global functions
realSelf = realGlobal = getNashornGlobalFrom(context);
} else if (thiz instanceof ScriptObjectMirror) {
final ScriptObjectMirror mirror = (ScriptObjectMirror)thiz;
realSelf = mirror.getScriptObject();
realGlobal = mirror.getHomeGlobal();
if (! isOfContext(realGlobal, nashornContext)) {
throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
}
}
if (realSelf == null) {
throw new IllegalArgumentException(getMessage("interface.on.non.script.object"));
}
try {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != realGlobal);
try {
if (globalChanged) {
Context.setGlobal(realGlobal);
}
if (! isInterfaceImplemented(clazz, realSelf)) {
return null;
}
return clazz.cast(JavaAdapterFactory.getConstructor(realSelf.getClass(), clazz,
MethodHandles.publicLookup()).invoke(realSelf));
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
} catch(final RuntimeException|Error e) {
throw e;
} catch(final Throwable t) {
throw new RuntimeException(t);
}
}
// Retrieve nashorn Global object for a given ScriptContext object
private Global getNashornGlobalFrom(final ScriptContext ctxt) {
if (_global_per_engine) {
// shared single global object for all ENGINE_SCOPE Bindings
return global;
}
final Bindings bindings = ctxt.getBindings(ScriptContext.ENGINE_SCOPE);
// is this Nashorn's own Bindings implementation?
if (bindings instanceof ScriptObjectMirror) {
final Global glob = globalFromMirror((ScriptObjectMirror)bindings);
if (glob != null) {
return glob;
}
}
// Arbitrary user Bindings implementation. Look for NASHORN_GLOBAL in it!
final Object scope = bindings.get(NASHORN_GLOBAL);
if (scope instanceof ScriptObjectMirror) {
final Global glob = globalFromMirror((ScriptObjectMirror)scope);
if (glob != null) {
return glob;
}
}
// We didn't find associated nashorn global mirror in the Bindings given!
// Create new global instance mirror and associate with the Bindings.
final ScriptObjectMirror mirror = createGlobalMirror();
bindings.put(NASHORN_GLOBAL, mirror);
// Since we created this global explicitly for the non-default script context we set the
// current script context in global permanently so that invokes work as expected. See JDK-8150219
mirror.getHomeGlobal().setInitScriptContext(ctxt);
return mirror.getHomeGlobal();
}
// Retrieve nashorn Global object from a given ScriptObjectMirror
private Global globalFromMirror(final ScriptObjectMirror mirror) {
final ScriptObject sobj = mirror.getScriptObject();
if (sobj instanceof Global && isOfContext((Global)sobj, nashornContext)) {
return (Global)sobj;
}
return null;
}
// Create a new ScriptObjectMirror wrapping a newly created Nashorn Global object
private ScriptObjectMirror createGlobalMirror() {
final Global newGlobal = createNashornGlobal();
return new ScriptObjectMirror(newGlobal, newGlobal);
}
// Create a new Nashorn Global object
private Global createNashornGlobal() {
final Global newGlobal = AccessController.doPrivileged(new PrivilegedAction<Global>() {
@Override
public Global run() {
try {
return nashornContext.newGlobal();
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
}
throw e;
}
}
}, CREATE_GLOBAL_ACC_CTXT);
nashornContext.initGlobal(newGlobal, this);
return newGlobal;
}
private Object invokeImpl(final Object selfObject, final String name, final Object... args) throws ScriptException, NoSuchMethodException {
Objects.requireNonNull(name);
assert !(selfObject instanceof ScriptObject) : "raw ScriptObject not expected here";
Global invokeGlobal = null;
ScriptObjectMirror selfMirror = null;
if (selfObject instanceof ScriptObjectMirror) {
selfMirror = (ScriptObjectMirror)selfObject;
if (! isOfContext(selfMirror.getHomeGlobal(), nashornContext)) {
throw new IllegalArgumentException(getMessage("script.object.from.another.engine"));
}
invokeGlobal = selfMirror.getHomeGlobal();
} else if (selfObject == null) {
// selfObject is null => global function call
final Global ctxtGlobal = getNashornGlobalFrom(context);
invokeGlobal = ctxtGlobal;
selfMirror = (ScriptObjectMirror)ScriptObjectMirror.wrap(ctxtGlobal, ctxtGlobal);
}
if (selfMirror != null) {
try {
return ScriptObjectMirror.translateUndefined(selfMirror.callMember(name, args));
} catch (final Exception e) {
final Throwable cause = e.getCause();
if (cause instanceof NoSuchMethodException) {
throw (NoSuchMethodException)cause;
}
throwAsScriptException(e, invokeGlobal);
throw new AssertionError("should not reach here");
}
}
// Non-script object passed as selfObject
throw new IllegalArgumentException(getMessage("interface.on.non.script.object"));
}
private Object evalImpl(final Source src, final ScriptContext ctxt) throws ScriptException {
return evalImpl(compileImpl(src, ctxt), ctxt);
}
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt) throws ScriptException {
return evalImpl(script, ctxt, getNashornGlobalFrom(ctxt));
}
private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != ctxtGlobal);
try {
if (globalChanged) {
Context.setGlobal(ctxtGlobal);
}
final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
ctxtGlobal.setScriptContext(ctxt);
try {
return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
} finally {
ctxtGlobal.setScriptContext(oldCtxt);
}
} catch (final Exception e) {
throwAsScriptException(e, ctxtGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
if (script == null) {
return null;
}
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != ctxtGlobal);
try {
if (globalChanged) {
Context.setGlobal(ctxtGlobal);
}
final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
ctxtGlobal.setScriptContext(ctxt);
try {
return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
} finally {
ctxtGlobal.setScriptContext(oldCtxt);
}
} catch (final Exception e) {
throwAsScriptException(e, ctxtGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
private static void throwAsScriptException(final Exception e, final Global global) throws ScriptException {
if (e instanceof ScriptException) {
throw (ScriptException)e;
} else if (e instanceof NashornException) {
final NashornException ne = (NashornException)e;
final ScriptException se = new ScriptException(
ne.getMessage(), ne.getFileName(),
ne.getLineNumber(), ne.getColumnNumber());
ne.initEcmaError(global);
se.initCause(e);
throw se;
} else if (e instanceof RuntimeException) {
throw (RuntimeException)e;
} else {
// wrap any other exception as ScriptException
throw new ScriptException(e);
}
}
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
final Context.MultiGlobalCompiledScript mgcs;
final ScriptFunction func;
final Global oldGlobal = Context.getGlobal();
final Global newGlobal = getNashornGlobalFrom(context);
final boolean globalChanged = (oldGlobal != newGlobal);
try {
if (globalChanged) {
Context.setGlobal(newGlobal);
}
mgcs = nashornContext.compileScript(source);
func = mgcs.getFunction(newGlobal);
} catch (final Exception e) {
throwAsScriptException(e, newGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
return new CompiledScript() {
@Override
public Object eval(final ScriptContext ctxt) throws ScriptException {
final Global globalObject = getNashornGlobalFrom(ctxt);
// Are we running the script in the same global in which it was compiled?
if (func.getScope() == globalObject) {
return evalImpl(func, ctxt, globalObject);
}
// different global
return evalImpl(mgcs, ctxt, globalObject);
}
@Override
public ScriptEngine getEngine() {
return NashornScriptEngine.this;
}
};
}
private ScriptFunction compileImpl(final Source source, final ScriptContext ctxt) throws ScriptException {
return compileImpl(source, getNashornGlobalFrom(ctxt));
}
private ScriptFunction compileImpl(final Source source, final Global newGlobal) throws ScriptException {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != newGlobal);
try {
if (globalChanged) {
Context.setGlobal(newGlobal);
}
return nashornContext.compileScript(source, newGlobal);
} catch (final Exception e) {
throwAsScriptException(e, newGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
private static boolean isInterfaceImplemented(final Class<?> iface, final ScriptObject sobj) {
for (final Method method : iface.getMethods()) {
// ignore methods of java.lang.Object class
if (method.getDeclaringClass() == Object.class) {
continue;
}
// skip check for default methods - non-abstract, interface methods
if (! Modifier.isAbstract(method.getModifiers())) {
continue;
}
final Object obj = sobj.get(method.getName());
if (! (obj instanceof ScriptFunction)) {
return false;
}
}
return true;
}
private static boolean isOfContext(final Global global, final Context context) {
return global.isOfContext(context);
}
}

View file

@ -0,0 +1,283 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.Version;
/**
* JSR-223 compliant script engine factory for Nashorn. The engine answers for:
* <ul>
* <li>names {@code "nashorn"}, {@code "Nashorn"}, {@code "js"}, {@code "JS"}, {@code "JavaScript"},
* {@code "javascript"}, {@code "ECMAScript"}, and {@code "ecmascript"};</li>
* <li>MIME types {@code "application/javascript"}, {@code "application/ecmascript"}, {@code "text/javascript"}, and
* {@code "text/ecmascript"};</li>
* <li>as well as for the extension {@code "js"}.</li>
* </ul>
* Programs executing in engines created using {@link #getScriptEngine(String[])} will have the passed arguments
* accessible as a global variable named {@code "arguments"}.
*
* @since 1.8u40
*/
public final class NashornScriptEngineFactory implements ScriptEngineFactory {
@Override
public String getEngineName() {
return (String) getParameter(ScriptEngine.ENGINE);
}
@Override
public String getEngineVersion() {
return (String) getParameter(ScriptEngine.ENGINE_VERSION);
}
@Override
public List<String> getExtensions() {
return Collections.unmodifiableList(extensions);
}
@Override
public String getLanguageName() {
return (String) getParameter(ScriptEngine.LANGUAGE);
}
@Override
public String getLanguageVersion() {
return (String) getParameter(ScriptEngine.LANGUAGE_VERSION);
}
@Override
public String getMethodCallSyntax(final String obj, final String method, final String... args) {
final StringBuilder sb = new StringBuilder().append(obj).append('.').append(method).append('(');
final int len = args.length;
if (len > 0) {
sb.append(args[0]);
}
for (int i = 1; i < len; i++) {
sb.append(',').append(args[i]);
}
sb.append(')');
return sb.toString();
}
@Override
public List<String> getMimeTypes() {
return Collections.unmodifiableList(mimeTypes);
}
@Override
public List<String> getNames() {
return Collections.unmodifiableList(names);
}
@Override
public String getOutputStatement(final String toDisplay) {
return "print(" + toDisplay + ")";
}
@Override
public Object getParameter(final String key) {
switch (key) {
case ScriptEngine.NAME:
return "javascript";
case ScriptEngine.ENGINE:
return "Oracle Nashorn";
case ScriptEngine.ENGINE_VERSION:
return Version.version();
case ScriptEngine.LANGUAGE:
return "ECMAScript";
case ScriptEngine.LANGUAGE_VERSION:
return "ECMA - 262 Edition 5.1";
case "THREADING":
// The engine implementation is not thread-safe. Can't be
// used to execute scripts concurrently on multiple threads.
return null;
default:
return null;
}
}
@Override
public String getProgram(final String... statements) {
Objects.requireNonNull(statements);
final StringBuilder sb = new StringBuilder();
for (final String statement : statements) {
sb.append(Objects.requireNonNull(statement)).append(';');
}
return sb.toString();
}
// default options passed to Nashorn script engine
private static final String[] DEFAULT_OPTIONS = new String[] { "-doe" };
@Override
public ScriptEngine getScriptEngine() {
try {
return new NashornScriptEngine(this, DEFAULT_OPTIONS, getAppClassLoader(), null);
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
}
throw e;
}
}
/**
* Create a new Script engine initialized with the given class loader.
*
* @param appLoader class loader to be used as script "app" class loader.
* @return newly created script engine.
* @throws SecurityException
* if the security manager's {@code checkPermission}
* denies {@code RuntimePermission("nashorn.setConfig")}
*/
public ScriptEngine getScriptEngine(final ClassLoader appLoader) {
return newEngine(DEFAULT_OPTIONS, appLoader, null);
}
/**
* Create a new Script engine initialized with the given class filter.
*
* @param classFilter class filter to use.
* @return newly created script engine.
* @throws NullPointerException if {@code classFilter} is {@code null}
* @throws SecurityException
* if the security manager's {@code checkPermission}
* denies {@code RuntimePermission("nashorn.setConfig")}
*/
public ScriptEngine getScriptEngine(final ClassFilter classFilter) {
return newEngine(DEFAULT_OPTIONS, getAppClassLoader(), Objects.requireNonNull(classFilter));
}
/**
* Create a new Script engine initialized with the given arguments.
*
* @param args arguments array passed to script engine.
* @return newly created script engine.
* @throws NullPointerException if {@code args} is {@code null}
* @throws SecurityException
* if the security manager's {@code checkPermission}
* denies {@code RuntimePermission("nashorn.setConfig")}
*/
public ScriptEngine getScriptEngine(final String... args) {
return newEngine(Objects.requireNonNull(args), getAppClassLoader(), null);
}
/**
* Create a new Script engine initialized with the given arguments and the given class loader.
*
* @param args arguments array passed to script engine.
* @param appLoader class loader to be used as script "app" class loader.
* @return newly created script engine.
* @throws NullPointerException if {@code args} is {@code null}
* @throws SecurityException
* if the security manager's {@code checkPermission}
* denies {@code RuntimePermission("nashorn.setConfig")}
*/
public ScriptEngine getScriptEngine(final String[] args, final ClassLoader appLoader) {
return newEngine(Objects.requireNonNull(args), appLoader, null);
}
/**
* Create a new Script engine initialized with the given arguments, class loader and class filter.
*
* @param args arguments array passed to script engine.
* @param appLoader class loader to be used as script "app" class loader.
* @param classFilter class filter to use.
* @return newly created script engine.
* @throws NullPointerException if {@code args} or {@code classFilter} is {@code null}
* @throws SecurityException
* if the security manager's {@code checkPermission}
* denies {@code RuntimePermission("nashorn.setConfig")}
*/
public ScriptEngine getScriptEngine(final String[] args, final ClassLoader appLoader, final ClassFilter classFilter) {
return newEngine(Objects.requireNonNull(args), appLoader, Objects.requireNonNull(classFilter));
}
private ScriptEngine newEngine(final String[] args, final ClassLoader appLoader, final ClassFilter classFilter) {
checkConfigPermission();
try {
return new NashornScriptEngine(this, args, appLoader, classFilter);
} catch (final RuntimeException e) {
if (Context.DEBUG) {
e.printStackTrace();
}
throw e;
}
}
// -- Internals only below this point
private static void checkConfigPermission() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission(Context.NASHORN_SET_CONFIG));
}
}
private static final List<String> names;
private static final List<String> mimeTypes;
private static final List<String> extensions;
static {
names = immutableList(
"nashorn", "Nashorn",
"js", "JS",
"JavaScript", "javascript",
"ECMAScript", "ecmascript"
);
mimeTypes = immutableList(
"application/javascript",
"application/ecmascript",
"text/javascript",
"text/ecmascript"
);
extensions = immutableList("js");
}
private static List<String> immutableList(final String... elements) {
return Collections.unmodifiableList(Arrays.asList(elements));
}
private static ClassLoader getAppClassLoader() {
// Revisit: script engine implementation needs the capability to
// find the class loader of the context in which the script engine
// is running so that classes will be found and loaded properly
final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
return (ccl == null)? NashornScriptEngineFactory.class.getClassLoader() : ccl;
}
}

View file

@ -0,0 +1,921 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import java.nio.ByteBuffer;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.script.Bindings;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.runtime.ConsString;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ECMAException;
import jdk.nashorn.internal.runtime.JSONListAdapter;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.arrays.ArrayData;
import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
/**
* Mirror object that wraps a given Nashorn Script object.
*
* @since 1.8u40
*/
public final class ScriptObjectMirror extends AbstractJSObject implements Bindings {
private static AccessControlContext getContextAccCtxt() {
final Permissions perms = new Permissions();
perms.add(new RuntimePermission(Context.NASHORN_GET_CONTEXT));
return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
}
private static final AccessControlContext GET_CONTEXT_ACC_CTXT = getContextAccCtxt();
private final ScriptObject sobj;
private final Global global;
private final boolean strict;
private final boolean jsonCompatible;
@Override
public boolean equals(final Object other) {
if (other instanceof ScriptObjectMirror) {
return sobj.equals(((ScriptObjectMirror)other).sobj);
}
return false;
}
@Override
public int hashCode() {
return sobj.hashCode();
}
@Override
public String toString() {
return inGlobal(new Callable<String>() {
@Override
public String call() {
return ScriptRuntime.safeToString(sobj);
}
});
}
// JSObject methods
@Override
public Object call(final Object thiz, final Object... args) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
if (sobj instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
final Object self = globalChanged? wrapLikeMe(thiz, oldGlobal) : thiz;
return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)sobj, unwrap(self, global), unwrapArray(modArgs, global)));
}
throw new RuntimeException("not a function: " + toString());
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object newObject(final Object... args) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
if (sobj instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
return wrapLikeMe(ScriptRuntime.construct((ScriptFunction)sobj, unwrapArray(modArgs, global)));
}
throw new RuntimeException("not a constructor: " + toString());
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object eval(final String s) {
return inGlobal(new Callable<Object>() {
@Override
public Object call() {
final Context context = AccessController.doPrivileged(
new PrivilegedAction<Context>() {
@Override
public Context run() {
return Context.getContext();
}
}, GET_CONTEXT_ACC_CTXT);
return wrapLikeMe(context.eval(global, s, sobj, null));
}
});
}
/**
* Call member function
* @param functionName function name
* @param args arguments
* @return return value of function
*/
public Object callMember(final String functionName, final Object... args) {
Objects.requireNonNull(functionName);
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
final Object val = sobj.get(functionName);
if (val instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)val, sobj, unwrapArray(modArgs, global)));
} else if (val instanceof JSObject && ((JSObject)val).isFunction()) {
return ((JSObject)val).call(sobj, args);
}
throw new NoSuchMethodException("No such function " + functionName);
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object getMember(final String name) {
Objects.requireNonNull(name);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.get(name));
}
});
}
@Override
public Object getSlot(final int index) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.get(index));
}
});
}
@Override
public boolean hasMember(final String name) {
Objects.requireNonNull(name);
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.has(name);
}
});
}
@Override
public boolean hasSlot(final int slot) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.has(slot);
}
});
}
@Override
public void removeMember(final String name) {
remove(Objects.requireNonNull(name));
}
@Override
public void setMember(final String name, final Object value) {
put(Objects.requireNonNull(name), value);
}
@Override
public void setSlot(final int index, final Object value) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.set(index, unwrap(value, global), getCallSiteFlags());
return null;
}
});
}
/**
* Nashorn extension: setIndexedPropertiesToExternalArrayData.
* set indexed properties be exposed from a given nio ByteBuffer.
*
* @param buf external buffer - should be a nio ByteBuffer
*/
public void setIndexedPropertiesToExternalArrayData(final ByteBuffer buf) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.setArray(ArrayData.allocate(buf));
return null;
}
});
}
@Override
public boolean isInstance(final Object instance) {
if (! (instance instanceof ScriptObjectMirror)) {
return false;
}
final ScriptObjectMirror mirror = (ScriptObjectMirror)instance;
// if not belongs to my global scope, return false
if (global != mirror.global) {
return false;
}
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isInstance(mirror.sobj);
}
});
}
@Override
public String getClassName() {
return sobj.getClassName();
}
@Override
public boolean isFunction() {
return sobj instanceof ScriptFunction;
}
@Override
public boolean isStrictFunction() {
return isFunction() && ((ScriptFunction)sobj).isStrict();
}
@Override
public boolean isArray() {
return sobj.isArray();
}
// javax.script.Bindings methods
@Override
public void clear() {
inGlobal(new Callable<Object>() {
@Override public Object call() {
sobj.clear(strict);
return null;
}
});
}
@Override
public boolean containsKey(final Object key) {
checkKey(key);
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.containsKey(key);
}
});
}
@Override
public boolean containsValue(final Object value) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.containsValue(unwrap(value, global));
}
});
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return inGlobal(new Callable<Set<Map.Entry<String, Object>>>() {
@Override public Set<Map.Entry<String, Object>> call() {
final Iterator<String> iter = sobj.propertyIterator();
final Set<Map.Entry<String, Object>> entries = new LinkedHashSet<>();
while (iter.hasNext()) {
final String key = iter.next();
final Object value = translateUndefined(wrapLikeMe(sobj.get(key)));
entries.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
}
return Collections.unmodifiableSet(entries);
}
});
}
@Override
public Object get(final Object key) {
checkKey(key);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return translateUndefined(wrapLikeMe(sobj.get(key)));
}
});
}
@Override
public boolean isEmpty() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isEmpty();
}
});
}
@Override
public Set<String> keySet() {
return inGlobal(new Callable<Set<String>>() {
@Override public Set<String> call() {
final Iterator<String> iter = sobj.propertyIterator();
final Set<String> keySet = new LinkedHashSet<>();
while (iter.hasNext()) {
keySet.add(iter.next());
}
return Collections.unmodifiableSet(keySet);
}
});
}
@Override
public Object put(final String key, final Object value) {
checkKey(key);
final ScriptObject oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value;
return translateUndefined(wrapLikeMe(sobj.put(key, unwrap(modValue, global), strict)));
}
});
}
@Override
public void putAll(final Map<? extends String, ? extends Object> map) {
Objects.requireNonNull(map);
final ScriptObject oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
inGlobal(new Callable<Object>() {
@Override public Object call() {
for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
final Object value = entry.getValue();
final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value;
final String key = entry.getKey();
checkKey(key);
sobj.set(key, unwrap(modValue, global), getCallSiteFlags());
}
return null;
}
});
}
@Override
public Object remove(final Object key) {
checkKey(key);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return translateUndefined(wrapLikeMe(sobj.remove(key, strict)));
}
});
}
/**
* Delete a property from this object.
*
* @param key the property to be deleted
*
* @return if the delete was successful or not
*/
public boolean delete(final Object key) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.delete(unwrap(key, global), strict);
}
});
}
@Override
public int size() {
return inGlobal(new Callable<Integer>() {
@Override public Integer call() {
return sobj.size();
}
});
}
@Override
public Collection<Object> values() {
return inGlobal(new Callable<Collection<Object>>() {
@Override public Collection<Object> call() {
final List<Object> values = new ArrayList<>(size());
final Iterator<Object> iter = sobj.valueIterator();
while (iter.hasNext()) {
values.add(translateUndefined(wrapLikeMe(iter.next())));
}
return Collections.unmodifiableList(values);
}
});
}
// Support for ECMAScript Object API on mirrors
/**
* Return the __proto__ of this object.
* @return __proto__ object.
*/
public Object getProto() {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.getProto());
}
});
}
/**
* Set the __proto__ of this object.
* @param proto new proto for this object
*/
public void setProto(final Object proto) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.setPrototypeOf(unwrap(proto, global));
return null;
}
});
}
/**
* ECMA 8.12.1 [[GetOwnProperty]] (P)
*
* @param key property key
*
* @return Returns the Property Descriptor of the named own property of this
* object, or undefined if absent.
*/
public Object getOwnPropertyDescriptor(final String key) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.getOwnPropertyDescriptor(key));
}
});
}
/**
* return an array of own property keys associated with the object.
*
* @param all True if to include non-enumerable keys.
* @return Array of keys.
*/
public String[] getOwnKeys(final boolean all) {
return inGlobal(new Callable<String[]>() {
@Override public String[] call() {
return sobj.getOwnKeys(all);
}
});
}
/**
* Flag this script object as non extensible
*
* @return the object after being made non extensible
*/
public ScriptObjectMirror preventExtensions() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.preventExtensions();
return ScriptObjectMirror.this;
}
});
}
/**
* Check if this script object is extensible
* @return true if extensible
*/
public boolean isExtensible() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isExtensible();
}
});
}
/**
* ECMAScript 15.2.3.8 - seal implementation
* @return the sealed script object
*/
public ScriptObjectMirror seal() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.seal();
return ScriptObjectMirror.this;
}
});
}
/**
* Check whether this script object is sealed
* @return true if sealed
*/
public boolean isSealed() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isSealed();
}
});
}
/**
* ECMA 15.2.39 - freeze implementation. Freeze this script object
* @return the frozen script object
*/
public ScriptObjectMirror freeze() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.freeze();
return ScriptObjectMirror.this;
}
});
}
/**
* Check whether this script object is frozen
* @return true if frozen
*/
public boolean isFrozen() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isFrozen();
}
});
}
/**
* Utility to check if given object is ECMAScript undefined value
*
* @param obj object to check
* @return true if 'obj' is ECMAScript undefined value
*/
public static boolean isUndefined(final Object obj) {
return obj == ScriptRuntime.UNDEFINED;
}
/**
* Utility to convert this script object to the given type.
*
* @param <T> destination type to convert to
* @param type destination type to convert to
* @return converted object
*/
public <T> T to(final Class<T> type) {
return inGlobal(new Callable<T>() {
@Override
public T call() {
return type.cast(ScriptUtils.convert(sobj, type));
}
});
}
/**
* Make a script object mirror on given object if needed.
*
* @param obj object to be wrapped/converted
* @param homeGlobal global to which this object belongs.
* @return wrapped/converted object
*/
public static Object wrap(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, false);
}
/**
* Make a script object mirror on given object if needed. The created wrapper will implement
* the Java {@code List} interface if {@code obj} is a JavaScript {@code Array} object;
* this is compatible with Java JSON libraries expectations. Arrays retrieved through its
* properties (transitively) will also implement the list interface.
*
* @param obj object to be wrapped/converted
* @param homeGlobal global to which this object belongs.
* @return wrapped/converted object
*/
public static Object wrapAsJSONCompatible(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, true);
}
/**
* Make a script object mirror on given object if needed.
*
* @param obj object to be wrapped/converted
* @param homeGlobal global to which this object belongs.
* @param jsonCompatible if true, the created wrapper will implement the Java {@code List} interface if
* {@code obj} is a JavaScript {@code Array} object. Arrays retrieved through its properties (transitively)
* will also implement the list interface.
* @return wrapped/converted object
*/
private static Object wrap(final Object obj, final Object homeGlobal, final boolean jsonCompatible) {
if(obj instanceof ScriptObject) {
if (!(homeGlobal instanceof Global)) {
return obj;
}
final ScriptObject sobj = (ScriptObject)obj;
final Global global = (Global)homeGlobal;
final ScriptObjectMirror mirror = new ScriptObjectMirror(sobj, global, jsonCompatible);
if (jsonCompatible && sobj.isArray()) {
return new JSONListAdapter(mirror, global);
}
return mirror;
} else if(obj instanceof ConsString) {
return obj.toString();
} else if (jsonCompatible && obj instanceof ScriptObjectMirror) {
// Since choosing JSON compatible representation is an explicit decision on user's part, if we're asked to
// wrap a mirror that was not JSON compatible, explicitly create its compatible counterpart following the
// principle of least surprise.
return ((ScriptObjectMirror)obj).asJSONCompatible();
}
return obj;
}
/**
* Wraps the passed object with the same jsonCompatible flag as this mirror.
* @param obj the object
* @param homeGlobal the object's home global.
* @return a wrapper for the object.
*/
private Object wrapLikeMe(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, jsonCompatible);
}
/**
* Wraps the passed object with the same home global and jsonCompatible flag as this mirror.
* @param obj the object
* @return a wrapper for the object.
*/
private Object wrapLikeMe(final Object obj) {
return wrapLikeMe(obj, global);
}
/**
* Unwrap a script object mirror if needed.
*
* @param obj object to be unwrapped
* @param homeGlobal global to which this object belongs
* @return unwrapped object
*/
public static Object unwrap(final Object obj, final Object homeGlobal) {
if (obj instanceof ScriptObjectMirror) {
final ScriptObjectMirror mirror = (ScriptObjectMirror)obj;
return (mirror.global == homeGlobal)? mirror.sobj : obj;
} else if (obj instanceof JSONListAdapter) {
return ((JSONListAdapter)obj).unwrap(homeGlobal);
}
return obj;
}
/**
* Wrap an array of object to script object mirrors if needed.
*
* @param args array to be unwrapped
* @param homeGlobal global to which this object belongs
* @return wrapped array
*/
public static Object[] wrapArray(final Object[] args, final Object homeGlobal) {
return wrapArray(args, homeGlobal, false);
}
private static Object[] wrapArray(final Object[] args, final Object homeGlobal, final boolean jsonCompatible) {
if (args == null || args.length == 0) {
return args;
}
final Object[] newArgs = new Object[args.length];
int index = 0;
for (final Object obj : args) {
newArgs[index] = wrap(obj, homeGlobal, jsonCompatible);
index++;
}
return newArgs;
}
private Object[] wrapArrayLikeMe(final Object[] args, final Object homeGlobal) {
return wrapArray(args, homeGlobal, jsonCompatible);
}
/**
* Unwrap an array of script object mirrors if needed.
*
* @param args array to be unwrapped
* @param homeGlobal global to which this object belongs
* @return unwrapped array
*/
public static Object[] unwrapArray(final Object[] args, final Object homeGlobal) {
if (args == null || args.length == 0) {
return args;
}
final Object[] newArgs = new Object[args.length];
int index = 0;
for (final Object obj : args) {
newArgs[index] = unwrap(obj, homeGlobal);
index++;
}
return newArgs;
}
/**
* Are the given objects mirrors to same underlying object?
*
* @param obj1 first object
* @param obj2 second object
* @return true if obj1 and obj2 are identical script objects or mirrors of it.
*/
public static boolean identical(final Object obj1, final Object obj2) {
final Object o1 = (obj1 instanceof ScriptObjectMirror)?
((ScriptObjectMirror)obj1).sobj : obj1;
final Object o2 = (obj2 instanceof ScriptObjectMirror)?
((ScriptObjectMirror)obj2).sobj : obj2;
return o1 == o2;
}
// package-privates below this.
ScriptObjectMirror(final ScriptObject sobj, final Global global) {
this(sobj, global, false);
}
private ScriptObjectMirror(final ScriptObject sobj, final Global global, final boolean jsonCompatible) {
assert sobj != null : "ScriptObjectMirror on null!";
assert global != null : "home Global is null";
this.sobj = sobj;
this.global = global;
this.strict = global.isStrictContext();
this.jsonCompatible = jsonCompatible;
}
// accessors for script engine
ScriptObject getScriptObject() {
return sobj;
}
Global getHomeGlobal() {
return global;
}
static Object translateUndefined(final Object obj) {
return (obj == ScriptRuntime.UNDEFINED)? null : obj;
}
private int getCallSiteFlags() {
return strict ? NashornCallSiteDescriptor.CALLSITE_STRICT : 0;
}
// internals only below this.
private <V> V inGlobal(final Callable<V> callable) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
if (globalChanged) {
Context.setGlobal(global);
}
try {
return callable.call();
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new AssertionError("Cannot happen", e);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
/**
* Ensures the key is not null, empty string, or a non-String object. The contract of the {@link Bindings}
* interface requires that these are not accepted as keys.
* @param key the key to check
* @throws NullPointerException if key is null
* @throws ClassCastException if key is not a String
* @throws IllegalArgumentException if key is empty string
*/
private static void checkKey(final Object key) {
Objects.requireNonNull(key, "key can not be null");
if (!(key instanceof String)) {
throw new ClassCastException("key should be a String. It is " + key.getClass().getName() + " instead.");
} else if (((String)key).length() == 0) {
throw new IllegalArgumentException("key can not be empty");
}
}
@Override @Deprecated
public double toNumber() {
return inGlobal(new Callable<Double>() {
@Override public Double call() {
return JSType.toNumber(sobj);
}
});
}
@Override
public Object getDefaultValue(final Class<?> hint) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
try {
return sobj.getDefaultValue(hint);
} catch (final ECMAException e) {
// We're catching ECMAException (likely TypeError), and translating it to
// UnsupportedOperationException. This in turn will be translated into TypeError of the
// caller's Global by JSType#toPrimitive(JSObject,Class) therefore ensuring that it's
// recognized as "instanceof TypeError" in the caller.
throw new UnsupportedOperationException(e.getMessage(), e);
}
}
});
}
private ScriptObjectMirror asJSONCompatible() {
if (this.jsonCompatible) {
return this;
}
return new ScriptObjectMirror(sobj, global, true);
}
}

View file

@ -0,0 +1,188 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import java.lang.invoke.MethodHandle;
import jdk.dynalink.beans.StaticClass;
import jdk.dynalink.linker.LinkerServices;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
/**
* Utilities that are to be called from script code.
*
* @since 1.8u40
*/
public final class ScriptUtils {
private ScriptUtils() {}
/**
* Returns AST as JSON compatible string. This is used to
* implement "parse" function in resources/parse.js script.
*
* @param code code to be parsed
* @param name name of the code source (used for location)
* @param includeLoc tells whether to include location information for nodes or not
* @return JSON string representation of AST of the supplied code
*/
public static String parse(final String code, final String name, final boolean includeLoc) {
return ScriptRuntime.parse(code, name, includeLoc);
}
/**
* Method which converts javascript types to java types for the
* String.format method (jrunscript function sprintf).
*
* @param format a format string
* @param args arguments referenced by the format specifiers in format
* @return a formatted string
*/
public static String format(final String format, final Object[] args) {
return Formatter.format(format, args);
}
/**
* Create a wrapper function that calls {@code func} synchronized on {@code sync} or, if that is undefined,
* {@code self}. Used to implement "sync" function in resources/mozilla_compat.js.
*
* @param func the function to wrap
* @param sync the object to synchronize on
* @return a synchronizing wrapper function
* @throws IllegalArgumentException if func does not represent a script function
*/
public static Object makeSynchronizedFunction(final Object func, final Object sync) {
final Object unwrapped = unwrap(func);
if (unwrapped instanceof ScriptFunction) {
return ((ScriptFunction)unwrapped).createSynchronized(unwrap(sync));
}
throw new IllegalArgumentException();
}
/**
* Make a script object mirror on given object if needed.
*
* @param obj object to be wrapped
* @return wrapped object
* @throws IllegalArgumentException if obj cannot be wrapped
*/
public static ScriptObjectMirror wrap(final Object obj) {
if (obj instanceof ScriptObjectMirror) {
return (ScriptObjectMirror)obj;
}
if (obj instanceof ScriptObject) {
final ScriptObject sobj = (ScriptObject)obj;
return (ScriptObjectMirror) ScriptObjectMirror.wrap(sobj, Context.getGlobal());
}
throw new IllegalArgumentException();
}
/**
* Unwrap a script object mirror if needed.
*
* @param obj object to be unwrapped
* @return unwrapped object
*/
public static Object unwrap(final Object obj) {
if (obj instanceof ScriptObjectMirror) {
return ScriptObjectMirror.unwrap(obj, Context.getGlobal());
}
return obj;
}
/**
* Wrap an array of object to script object mirrors if needed.
*
* @param args array to be unwrapped
* @return wrapped array
*/
public static Object[] wrapArray(final Object[] args) {
if (args == null || args.length == 0) {
return args;
}
return ScriptObjectMirror.wrapArray(args, Context.getGlobal());
}
/**
* Unwrap an array of script object mirrors if needed.
*
* @param args array to be unwrapped
* @return unwrapped array
*/
public static Object[] unwrapArray(final Object[] args) {
if (args == null || args.length == 0) {
return args;
}
return ScriptObjectMirror.unwrapArray(args, Context.getGlobal());
}
/**
* Convert the given object to the given type.
*
* @param obj object to be converted
* @param type destination type to convert to. type is either a Class
* or nashorn representation of a Java type returned by Java.type() call in script.
* @return converted object
*/
public static Object convert(final Object obj, final Object type) {
if (obj == null) {
return null;
}
final Class<?> clazz;
if (type instanceof Class) {
clazz = (Class<?>)type;
} else if (type instanceof StaticClass) {
clazz = ((StaticClass)type).getRepresentedClass();
} else {
throw new IllegalArgumentException("type expected");
}
final LinkerServices linker = Bootstrap.getLinkerServices();
final Object objToConvert = unwrap(obj);
final MethodHandle converter = linker.getTypeConverter(objToConvert.getClass(), clazz);
if (converter == null) {
// no supported conversion!
throw new UnsupportedOperationException("conversion not supported");
}
try {
return converter.invoke(objToConvert);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
}
}
}

View file

@ -0,0 +1,121 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.scripting;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Objects;
import jdk.nashorn.internal.runtime.Source;
/**
* A Reader that reads from a URL. Used to make sure that the reader
* reads content from given URL and can be trusted to do so.
*
* @since 1.8u40
*/
public final class URLReader extends Reader {
// underlying URL
private final URL url;
// Charset used to convert
private final Charset cs;
// lazily initialized underlying reader for URL
private Reader reader;
/**
* Constructor
*
* @param url URL for this URLReader
* @throws NullPointerException if url is null
*/
public URLReader(final URL url) {
this(url, (Charset)null);
}
/**
* Constructor
*
* @param url URL for this URLReader
* @param charsetName Name of the Charset used to convert bytes to chars
* @throws NullPointerException if url is null
*/
public URLReader(final URL url, final String charsetName) {
this(url, Charset.forName(charsetName));
}
/**
* Constructor
*
* @param url URL for this URLReader
* @param cs Charset used to convert bytes to chars
* @throws NullPointerException if url is null
*/
public URLReader(final URL url, final Charset cs) {
this.url = Objects.requireNonNull(url);
this.cs = cs;
}
@Override
public int read(final char cbuf[], final int off, final int len) throws IOException {
return getReader().read(cbuf, off, len);
}
@Override
public void close() throws IOException {
getReader().close();
}
/**
* URL of this reader
* @return the URL from which this reader reads.
*/
public URL getURL() {
return url;
}
/**
* Charset used by this reader
*
* @return the Charset used to convert bytes to chars
*/
public Charset getCharset() {
return cs;
}
// lazily initialize char array reader using URL content
private Reader getReader() throws IOException {
synchronized (lock) {
if (reader == null) {
reader = new CharArrayReader(Source.readFully(url, cs));
}
}
return reader;
}
}

View file

@ -0,0 +1,41 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* This package provides the {@code javax.script} integration, which is the preferred way to use Nashorn.
* You will ordinarily do this to obtain an instance of a Nashorn script engine:
* <pre>
* import javax.script.*;
* ...
* ScriptEngine nashornEngine = new ScriptEngineManager().getEngineByName("Nashorn");
* </pre>
* <p>Nashorn script engines implement the optional {@link javax.script.Invocable} and {@link javax.script.Compilable}
* interfaces, allowing for efficient pre-compilation and repeated execution of scripts. In addition,
* this package provides nashorn specific extension classes, interfaces and methods. See
* {@link jdk.nashorn.api.scripting.NashornScriptEngineFactory} for further details.
*
* @since 1.8u40
*/
package jdk.nashorn.api.scripting;

View file

@ -0,0 +1,32 @@
#
# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
thiz.cannot.be.null=script object 'this' for getMethod, getInterface calls can not be null
interface.class.expected=interface Class expected in getInterface
interface.on.non.script.object=getInterface cannot be called on non-script object
no.current.nashorn.global=no current Global instance for nashorn
implementing.non.public.interface=Cannot implement non-public interface: {0}
script.object.from.another.engine=Script object belongs to another script engine

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for an array access expression.
*
* For example:
* <pre>
* <em>expression</em> [ <em>index</em> ]
* </pre>
*
* @since 9
*/
public interface ArrayAccessTree extends ExpressionTree {
/**
* Returns the array that is accessed.
*
* @return the array that is accessed
*/
ExpressionTree getExpression();
/**
* Returns the index of the array element accessed.
*
* @return the index expression
*/
ExpressionTree getIndex();
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.Expression;
final class ArrayAccessTreeImpl extends ExpressionTreeImpl implements ArrayAccessTree {
private final ExpressionTree base, index;
ArrayAccessTreeImpl(final Expression node, final ExpressionTree base, final ExpressionTree index) {
super(node);
this.base = base;
this.index = index;
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.ARRAY_ACCESS;
}
@Override
public ExpressionTree getExpression() {
return base;
}
@Override
public ExpressionTree getIndex() {
return index;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitArrayAccess(this, data);
}
}

View file

@ -0,0 +1,42 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* Represents ECMAScript array literal expression.
*
* @since 9
*/
public interface ArrayLiteralTree extends ExpressionTree {
/**
* Returns the list of Array element expressions.
*
* @return array element expressions
*/
public List<? extends ExpressionTree> getElements();
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.LiteralNode;
final class ArrayLiteralTreeImpl extends ExpressionTreeImpl
implements ArrayLiteralTree {
private final List<? extends ExpressionTree> elements;
ArrayLiteralTreeImpl(final LiteralNode<?> node, final List<? extends ExpressionTree> elements) {
super(node);
this.elements = elements;
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.ARRAY_LITERAL;
}
@Override
public List<? extends ExpressionTree> getElements() {
return elements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitArrayLiteral(this, data);
}
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for an assignment expression.
*
* For example:
* <pre>
* <em>variable</em> = <em>expression</em>
* </pre>
*
* @since 9
*/
public interface AssignmentTree extends ExpressionTree {
/**
* Returns the left hand side (LHS) of this assignment.
*
* @return left hand side (LHS) expression
*/
ExpressionTree getVariable();
/**
* Returns the right hand side (RHS) of this assignment.
*
* @return right hand side (RHS) expression
*/
ExpressionTree getExpression();
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.BinaryNode;
final class AssignmentTreeImpl extends ExpressionTreeImpl implements AssignmentTree {
private final Tree.Kind kind;
private final ExpressionTree var, expr;
AssignmentTreeImpl(final BinaryNode node, final ExpressionTree left, final ExpressionTree right) {
super(node);
assert node.isAssignment() : "assignment node expected";
this.var = left;
this.expr = right;
this.kind = getOperator(node.tokenType());
}
@Override
public Tree.Kind getKind() {
return kind;
}
@Override
public ExpressionTree getVariable() {
return var;
}
@Override
public ExpressionTree getExpression() {
return expr;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitAssignment(this, data);
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a binary expression.
* Use {@link #getKind getKind} to determine the kind of operator.
*
* For example:
* <pre>
* <em>leftOperand</em> <em>operator</em> <em>rightOperand</em>
* </pre>
*
* @since 9
*/
public interface BinaryTree extends ExpressionTree {
/**
* Returns left hand side (LHS) of this binary expression.
*
* @return left hand side (LHS) of this binary expression
*/
ExpressionTree getLeftOperand();
/**
* Returns right hand side (RHS) of this binary expression.
*
* @return right hand side (RHS) of this binary expression
*/
ExpressionTree getRightOperand();
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.BinaryNode;
class BinaryTreeImpl extends ExpressionTreeImpl implements BinaryTree {
private final Tree.Kind kind;
private final ExpressionTree left, right;
BinaryTreeImpl(final BinaryNode node, final ExpressionTree left, final ExpressionTree right) {
super(node);
assert !node.isAssignment() : "assignment node";
this.left = left;
this.right = right;
this.kind = getOperator(node.tokenType());
}
@Override
public Tree.Kind getKind() {
return kind;
}
@Override
public ExpressionTree getLeftOperand() {
return left;
}
@Override
public ExpressionTree getRightOperand() {
return right;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitBinary(this, data);
}
}

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A tree node for a statement block.
*
* For example:
* <pre>
* { }
*
* { <em>statements</em> }
* </pre>
*
* @since 9
*/
public interface BlockTree extends StatementTree {
/**
* Returns the list of statements in this block.
*
* @return the list of statements in this block
*/
List<? extends StatementTree> getStatements();
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.Block;
import jdk.nashorn.internal.ir.BlockStatement;
final class BlockTreeImpl extends StatementTreeImpl implements BlockTree {
private final List<? extends StatementTree> statements;
BlockTreeImpl(final BlockStatement node, final List<? extends StatementTree> statements) {
super(node);
this.statements = statements;
}
BlockTreeImpl(final Block node, final List<? extends StatementTree> statements) {
super(node);
this.statements = statements;
}
@Override
public Kind getKind() {
return Kind.BLOCK;
}
@Override
public List<? extends StatementTree> getStatements() {
return statements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitBlock(this, data);
}
}

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a 'break' statement.
*
* For example:
* <pre>
* break;
*
* break <em>label</em> ;
* </pre>
*
* @since 9
*/
public interface BreakTree extends GotoTree {
/**
* Label associated with this break statement. This is null
* if there is no label associated with this break statement.
*
* @return label associated with this break statement.
*/
@Override
String getLabel();
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.BreakNode;
final class BreakTreeImpl extends StatementTreeImpl implements BreakTree {
private final String label;
BreakTreeImpl(final BreakNode node) {
super(node);
this.label = node.getLabelName();
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.BREAK;
}
@Override
public String getLabel() {
return label;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitBreak(this, data);
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A tree node for a 'case' in a 'switch' statement.
*
* For example:
* <pre>
* case <em>expression</em> :
* <em>statements</em>
*
* default :
* <em>statements</em>
* </pre>
*
* @since 9
*/
public interface CaseTree extends Tree {
/**
* Case expression of this 'case' statement.
*
* @return null if and only if this Case is {@code default:}
*/
ExpressionTree getExpression();
/**
* Return the list of statements for this 'case'.
*
* @return list of statements for this 'case'
*/
List<? extends StatementTree> getStatements();
}

View file

@ -0,0 +1,62 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.CaseNode;
final class CaseTreeImpl extends TreeImpl implements CaseTree {
private final ExpressionTree expression;
private final List<? extends StatementTree> statements;
public CaseTreeImpl(final CaseNode node,
final ExpressionTree expression,
final List<? extends StatementTree> statements) {
super(node);
this.expression = expression;
this.statements = statements;
}
@Override
public Kind getKind() {
return Kind.CASE;
}
@Override
public ExpressionTree getExpression() {
return expression;
}
@Override
public List<? extends StatementTree> getStatements() {
return statements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitCase(this, data);
}
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a 'catch' block in a 'try' statement.
*
* For example:
* <pre>
* catch ( <em>parameter</em> )
* <em>block</em>
* </pre>
*
* @since 9
*/
public interface CatchTree extends Tree {
/**
* Returns the catch parameter identifier or parameter binding pattern of the exception caught.
*
* @return the catch parameter identifier or parameter binding pattern
*/
ExpressionTree getParameter();
/**
* Returns the code block of this catch block.
*
* @return the code block
*/
BlockTree getBlock();
/**
* Returns the optional catch condition expression. This is null
* if this is an unconditional catch statement.
*
* @return the optional catch condition expression.
*/
ExpressionTree getCondition();
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.CatchNode;
final class CatchTreeImpl extends TreeImpl implements CatchTree {
private final ExpressionTree param;
private final BlockTree block;
private final ExpressionTree condition;
CatchTreeImpl(final CatchNode node,
final ExpressionTree param,
final BlockTree block,
final ExpressionTree condition) {
super(node);
this.param = param;
this.block = block;
this.condition = condition;
}
@Override
public Kind getKind() {
return Kind.CATCH;
}
@Override
public ExpressionTree getParameter() {
return param;
}
@Override
public BlockTree getBlock() {
return block;
}
@Override
public ExpressionTree getCondition() {
return condition;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitCatch(this, data);
}
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A tree node that represents a <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-class-definitions">class declaration</a>.
*
* @since 9
*/
public interface ClassDeclarationTree extends StatementTree {
/**
* Class identifier.
*
* @return the class identifier
*/
IdentifierTree getName();
/**
* The expression of the {@code extends} clause. Optional.
*
* @return the class heritage
*/
ExpressionTree getClassHeritage();
/**
* Get the constructor method definition.
*
* @return the constructor
*/
PropertyTree getConstructor();
/**
* Get other property definitions except for the constructor.
*
* @return the class elements
*/
List<? extends PropertyTree> getClassElements();
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.VarNode;
final class ClassDeclarationTreeImpl extends StatementTreeImpl implements ClassDeclarationTree {
private final IdentifierTree name;
private final ExpressionTree classHeritage;
private final PropertyTree constructor;
private final List<? extends PropertyTree> classElements;
ClassDeclarationTreeImpl(final VarNode node, final IdentifierTree name,
final ExpressionTree classHeritage, final PropertyTree constructor,
final List<? extends PropertyTree> classElements) {
super(node);
this.name = name;
this.classHeritage = classHeritage;
this.constructor = constructor;
this.classElements = classElements;
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.CLASS;
}
@Override
public IdentifierTree getName() {
return name;
}
@Override
public ExpressionTree getClassHeritage() {
return classHeritage;
}
@Override
public PropertyTree getConstructor() {
return constructor;
}
@Override
public List<? extends PropertyTree> getClassElements() {
return classElements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitClassDeclaration(this, data);
}
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A tree node that represents a <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-class-definitions">class expression</a>.
*
* @since 9
*/
public interface ClassExpressionTree extends ExpressionTree {
/**
* Class identifier. Optional.
*
* @return the class identifier
*/
IdentifierTree getName();
/**
* The expression of the {@code extends} clause. Optional.
*
* @return the class heritage
*/
ExpressionTree getClassHeritage();
/**
* Get the constructor method definition.
*
* @return the constructor
*/
PropertyTree getConstructor();
/**
* Get other property definitions except for the constructor.
*
* @return the class elements
*/
List<? extends PropertyTree> getClassElements();
}

View file

@ -0,0 +1,76 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.ClassNode;
final class ClassExpressionTreeImpl extends ExpressionTreeImpl implements ClassExpressionTree {
private final IdentifierTree name;
private final ExpressionTree classHeritage;
private final PropertyTree constructor;
private final List<? extends PropertyTree> classElements;
ClassExpressionTreeImpl(final ClassNode cn, final IdentifierTree name,
final ExpressionTree classHeritage, final PropertyTree constructor,
final List<? extends PropertyTree> classElements) {
super(cn);
this.name = name;
this.classHeritage = classHeritage;
this.constructor = constructor;
this.classElements = classElements;
}
@Override
public Kind getKind() {
return Kind.CLASS_EXPRESSION;
}
@Override
public IdentifierTree getName() {
return name;
}
@Override
public ExpressionTree getClassHeritage() {
return classHeritage;
}
@Override
public PropertyTree getConstructor() {
return constructor;
}
@Override
public List<? extends PropertyTree> getClassElements() {
return classElements;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitClassExpression(this, data);
}
}

View file

@ -0,0 +1,73 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* Represents the abstract syntax tree for compilation units (source
* files)
*
* @since 9
*/
public interface CompilationUnitTree extends Tree {
/**
* Return the list of source elements in this compilation unit.
*
* @return the list of source elements in this compilation unit
*/
List<? extends Tree> getSourceElements();
/**
* Return the source name of this script compilation unit.
*
* @return the source name of this script compilation unit
*/
String getSourceName();
/**
* Returns if this is a ECMAScript "strict" compilation unit or not.
*
* @return true if this compilation unit is declared "strict"
*/
boolean isStrict();
/**
* Returns the line map for this compilation unit, if available.
* Returns null if the line map is not available.
*
* @return the line map for this compilation unit
*/
LineMap getLineMap();
/**
* Return the {@link ModuleTree} associated with this compilation unit. This is null,
* if there is no module information from this compilation unit.
*
* @return the Module info or null
*/
ModuleTree getModule();
}

View file

@ -0,0 +1,83 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.FunctionNode;
final class CompilationUnitTreeImpl extends TreeImpl
implements CompilationUnitTree {
private final FunctionNode funcNode;
private final List<? extends Tree> elements;
private final ModuleTree module;
CompilationUnitTreeImpl(final FunctionNode node,
final List<? extends Tree> elements,
final ModuleTree module) {
super(node);
this.funcNode = node;
assert funcNode.getKind() == FunctionNode.Kind.SCRIPT ||
funcNode.getKind() == FunctionNode.Kind.MODULE :
"script or module function expected";
this.elements = elements;
this.module = module;
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.COMPILATION_UNIT;
}
@Override
public List<? extends Tree> getSourceElements() {
return elements;
}
@Override
public String getSourceName() {
return funcNode.getSourceName();
}
@Override
public boolean isStrict() {
return funcNode.isStrict();
}
@Override
public LineMap getLineMap() {
return new LineMapImpl(funcNode.getSource());
}
@Override
public ModuleTree getModule() {
return module;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitCompilationUnit(this, data);
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for compound assignment operator.
* Use {@link #getKind getKind} to determine the kind of operator.
*
* For example:
* <pre>
* <em>variable</em> <em>operator</em> <em>expression</em>
* </pre>
*
* @since 9
*/
public interface CompoundAssignmentTree extends ExpressionTree {
/**
* Returns the left hand side (LHS) of this assignment.
*
* @return left hand side (LHS) expression
*/
ExpressionTree getVariable();
/**
* Returns the right hand side (RHS) of this assignment.
*
* @return right hand side (RHS) expression
*/
ExpressionTree getExpression();
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.BinaryNode;
final class CompoundAssignmentTreeImpl extends ExpressionTreeImpl implements CompoundAssignmentTree {
private final ExpressionTree var, expr;
private final Kind kind;
CompoundAssignmentTreeImpl(final BinaryNode node, final ExpressionTree left, final ExpressionTree right) {
super(node);
assert node.isAssignment() : "not an assignment node";
this.var = left;
this.expr = right;
this.kind = getOperator(node.tokenType());
assert kind != Tree.Kind.ASSIGNMENT : "compound assignment expected";
}
@Override
public Kind getKind() {
return kind;
}
@Override
public ExpressionTree getVariable() {
return var;
}
@Override
public ExpressionTree getExpression() {
return expr;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitCompoundAssignment(this, data);
}
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for the conditional operator ? :.
*
* For example:
* <pre>
* <em>condition</em> ? <em>trueExpression</em> : <em>falseExpression</em>
* </pre>
*
* @since 9
*/
public interface ConditionalExpressionTree extends ExpressionTree {
/**
* Returns the condition expression of this ternary expression.
*
* @return the condition expression
*/
ExpressionTree getCondition();
/**
* Returns the true part of this ternary expression.
*
* @return the 'true' part expression
*/
ExpressionTree getTrueExpression();
/**
* Returns the false part of this ternary expression.
*
* @return the 'false' part expression
*/
ExpressionTree getFalseExpression();
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.TernaryNode;
final class ConditionalExpressionTreeImpl extends ExpressionTreeImpl implements ConditionalExpressionTree {
private final ExpressionTree condExpr, trueExpr, falseExpr;
ConditionalExpressionTreeImpl(final TernaryNode node,
final ExpressionTree condExpr, final ExpressionTree trueExpr,
final ExpressionTree falseExpr) {
super(node);
this.condExpr = condExpr;
this.trueExpr = trueExpr;
this.falseExpr = falseExpr;
}
@Override
public Kind getKind() {
return Kind.CONDITIONAL_EXPRESSION;
}
@Override
public ExpressionTree getCondition() {
return condExpr;
}
@Override
public ExpressionTree getTrueExpression() {
return trueExpr;
}
@Override
public ExpressionTree getFalseExpression() {
return falseExpr;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitConditionalExpression(this, data);
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A mixin for conditional "loop" statements.
*
* @since 9
*/
public interface ConditionalLoopTree extends LoopTree {
/**
* Returns the condition expression of this 'loop' statement.
*
* @return the condition expression
*/
ExpressionTree getCondition();
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a 'continue' statement.
*
* For example:
* <pre>
* continue;
* continue <em>label</em> ;
* </pre>
*
* @since 9
*/
public interface ContinueTree extends GotoTree {
/**
* Label associated with this continue statement. This is null
* if there is no label associated with this continue statement.
*
* @return label associated with this continue statement.
*/
@Override
String getLabel();
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.ContinueNode;
final class ContinueTreeImpl extends StatementTreeImpl implements ContinueTree {
private final String label;
ContinueTreeImpl(final ContinueNode node) {
super(node);
this.label = node.getLabelName();
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.CONTINUE;
}
@Override
public String getLabel() {
return label;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitContinue(this, data);
}
}

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a 'debugger' statement.
*
* For example:
* <pre>
* <em>debugger;</em>
* </pre>
*
* @since 9
*/
public interface DebuggerTree extends StatementTree {
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.DebuggerNode;
final class DebuggerTreeImpl extends StatementTreeImpl implements DebuggerTree {
DebuggerTreeImpl(final DebuggerNode node) {
super(node);
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.DEBUGGER;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitDebugger(this, data);
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.ExpressionStatement;
import jdk.nashorn.internal.parser.TokenType;
// This implementation of VariableTree represents a destructuring declaration
final class DestructuringDeclTreeImpl extends StatementTreeImpl
implements VariableTree {
private final TokenType declType;
private final ExpressionTree lhs;
private final ExpressionTree init;
DestructuringDeclTreeImpl(final ExpressionStatement exprStat, final ExpressionTree lhs, final ExpressionTree init) {
super(exprStat);
assert exprStat.destructuringDeclarationType() != null : "expecting a destructuring decl. statement";
this.declType = exprStat.destructuringDeclarationType();
this.lhs = lhs;
this.init = init;
}
@Override
public Kind getKind() {
return Kind.VARIABLE;
}
@Override
public ExpressionTree getBinding() {
return lhs;
}
@Override
public ExpressionTree getInitializer() {
return init;
}
@Override
public boolean isConst() {
return declType == TokenType.CONST;
}
@Override
public boolean isLet() {
return declType == TokenType.LET;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitVariable(this, data);
}
}

View file

@ -0,0 +1,150 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* Interface for diagnostics from tools. A diagnostic usually reports
* a problem at a specific position in a source file. However, not
* all diagnostics are associated with a position or a file.
*
* <p>A position is a zero-based character offset from the beginning of
* a file. Negative values (except {@link #NOPOS}) are not valid
* positions.
*
* <p>Line and column numbers begin at 1. Negative values (except
* {@link #NOPOS}) and 0 are not valid line or column numbers.
*
* <p>Line terminator is as defined in ECMAScript specification which is one
* of { &#92;u000A, &#92;u000B, &#92;u2028, &#92;u2029 }.
*
* @since 9
*/
public interface Diagnostic {
/**
* Kinds of diagnostics, for example, error or warning.
*
* The kind of a diagnostic can be used to determine how the
* diagnostic should be presented to the user. For example,
* errors might be colored red or prefixed with the word "Error",
* while warnings might be colored yellow or prefixed with the
* word "Warning". There is no requirement that the Kind
* should imply any inherent semantic meaning to the message
* of the diagnostic: for example, a tool might provide an
* option to report all warnings as errors.
*/
enum Kind {
/**
* Problem which prevents the tool's normal completion.
*/
ERROR,
/**
* Problem which does not usually prevent the tool from
* completing normally.
*/
WARNING,
/**
* Problem similar to a warning, but is mandated by the tool's
* specification. For example, the Java&trade; Language
* Specification mandates warnings on certain
* unchecked operations and the use of deprecated methods.
*/
MANDATORY_WARNING,
/**
* Informative message from the tool.
*/
NOTE,
/**
* Diagnostic which does not fit within the other kinds.
*/
OTHER,
}
/**
* Used to signal that no position is available.
*/
public final static long NOPOS = -1;
/**
* Gets the kind of this diagnostic, for example, error or
* warning.
* @return the kind of this diagnostic
*/
Kind getKind();
/**
* Gets a character offset from the beginning of the source object
* associated with this diagnostic that indicates the location of
* the problem. In addition, the following must be true:
*
* <p>{@code getStartPostion() <= getPosition()}
* <p>{@code getPosition() <= getEndPosition()}
*
* @return character offset from beginning of source; {@link
* #NOPOS} if no location is suitable
*/
long getPosition();
/**
* Gets the source file name.
*
* @return the file name or null if not available
*/
String getFileName();
/**
* Gets the line number of the character offset returned by
* {@linkplain #getPosition()}.
*
* @return a line number or {@link #NOPOS} if and only if {@link
* #getPosition()} returns {@link #NOPOS}
*/
long getLineNumber();
/**
* Gets the column number of the character offset returned by
* {@linkplain #getPosition()}.
*
* @return a column number or {@link #NOPOS} if and only if {@link
* #getPosition()} returns {@link #NOPOS}
*/
long getColumnNumber();
/**
* Gets a diagnostic code indicating the type of diagnostic. The
* code is implementation-dependent and might be {@code null}.
*
* @return a diagnostic code
*/
String getCode();
/**
* Gets a message for this diagnostic.
*
* @return a message
*/
String getMessage();
}

View file

@ -0,0 +1,80 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.parser.Token;
import jdk.nashorn.internal.runtime.ParserException;
final class DiagnosticImpl implements Diagnostic {
private final ParserException exp;
private final Kind kind;
DiagnosticImpl(final ParserException exp, final Kind kind) {
this.exp = exp;
this.kind = kind;
}
@Override
public Kind getKind() {
return kind;
}
@Override
public long getPosition() {
return exp.getPosition();
}
@Override
public String getFileName() {
return exp.getFileName();
}
@Override
public long getLineNumber() {
return exp.getLineNumber();
}
@Override
public long getColumnNumber() {
return exp.getColumnNumber();
}
@Override
public String getCode() {
final long token = exp.getToken();
return (token < 0)? null : Token.toString(null, token, true);
}
@Override
public String getMessage() {
return exp.getMessage();
}
@Override
public String toString() {
return getMessage();
}
}

View file

@ -0,0 +1,41 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* Interface for receiving diagnostics from Nashorn parser.
*
* @since 9
*/
@FunctionalInterface
public interface DiagnosticListener {
/**
* Invoked whenever a parsing problem is found.
*
* @param diagnostic additional information errors, warnings detected during parsing.
*/
void report(Diagnostic diagnostic);
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a 'do' statement.
*
* For example:
* <pre>
* do
* <em>statement</em>
* while ( <em>expression</em> );
* </pre>
*
* @since 9
*/
public interface DoWhileLoopTree extends ConditionalLoopTree {
/**
* Returns the condition expression of this do-while statement.
*
* @return the condition expression
*/
@Override
ExpressionTree getCondition();
/**
* The statement contained within this do-while statement.
*
* @return the statement
*/
@Override
StatementTree getStatement();
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.WhileNode;
final class DoWhileLoopTreeImpl extends StatementTreeImpl implements DoWhileLoopTree {
private final ExpressionTree cond;
private final StatementTree stat;
DoWhileLoopTreeImpl(final WhileNode node, final ExpressionTree cond, final StatementTree stat) {
super(node);
assert node.isDoWhile() : "do while expected";
this.cond = cond;
this.stat = stat;
}
@Override
public Kind getKind() {
return Kind.DO_WHILE_LOOP;
}
@Override
public ExpressionTree getCondition() {
return cond;
}
@Override
public StatementTree getStatement() {
return stat;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitDoWhileLoop(this, data);
}
}

View file

@ -0,0 +1,38 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for an empty (skip) statement.
*
* For example:
* <pre>
* ;
* </pre>
*
* @since 9
*/
public interface EmptyStatementTree extends StatementTree {}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.EmptyNode;
final class EmptyStatementTreeImpl extends StatementTreeImpl implements EmptyStatementTree {
EmptyStatementTreeImpl(final EmptyNode node) {
super(node);
}
@Override
public Kind getKind() {
return Kind.EMPTY_STATEMENT;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitEmptyStatement(this, data);
}
}

View file

@ -0,0 +1,34 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node to stand in for a malformed expression.
*
* @since 9
*/
public interface ErroneousTree extends ExpressionTree {
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.ErrorNode;
final class ErroneousTreeImpl extends ExpressionTreeImpl implements ErroneousTree {
ErroneousTreeImpl(final ErrorNode errorNode) {
super(errorNode);
}
@Override
public Kind getKind() {
return Kind.ERROR;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitErroneous(this, data);
}
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A Tree node for export entry in <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-modules">Module information</a>.
*/
public interface ExportEntryTree extends Tree {
/**
* Returns the entry's export name.
*
* @return the export name
*/
public IdentifierTree getExportName();
/**
* Returns the entry's module request.
*
* @return the module request
*/
public IdentifierTree getModuleRequest();
/**
* Returns the entry's import name.
*
* @return the import name
*/
public IdentifierTree getImportName();
/**
* Returns the entry's local name.
*
* @return the local name
*/
public IdentifierTree getLocalName();
}

View file

@ -0,0 +1,109 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import java.util.stream.Collectors;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.Module;
import static jdk.nashorn.api.tree.ModuleTreeImpl.identOrNull;
final class ExportEntryTreeImpl extends TreeImpl implements ExportEntryTree {
private final long startPos, endPos;
private final IdentifierTree exportName;
private final IdentifierTree moduleRequest;
private final IdentifierTree importName;
private final IdentifierTree localName;
private ExportEntryTreeImpl(final long startPos, final long endPos,
final IdentifierTree exportName,
final IdentifierTree moduleRequest,
final IdentifierTree importName,
final IdentifierTree localName) {
super(null); // no underlying Node!
this.startPos = startPos;
this.endPos = endPos;
this.exportName = exportName;
this.moduleRequest = moduleRequest;
this.importName = importName;
this.localName = localName;
}
private static ExportEntryTreeImpl createExportEntry(final Module.ExportEntry entry) {
return new ExportEntryTreeImpl(entry.getStartPosition(),
entry.getEndPosition(),
identOrNull(entry.getExportName()),
identOrNull(entry.getModuleRequest()),
identOrNull(entry.getImportName()),
identOrNull(entry.getLocalName()));
}
static List<ExportEntryTreeImpl> createExportList(final List<Module.ExportEntry> exportList) {
return exportList.stream().
map(ExportEntryTreeImpl::createExportEntry).
collect(Collectors.toList());
}
@Override
public Kind getKind() {
return Tree.Kind.EXPORT_ENTRY;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitExportEntry(this, data);
}
@Override
public long getStartPosition() {
return startPos;
}
@Override
public long getEndPosition() {
return endPos;
}
@Override
public IdentifierTree getExportName() {
return exportName;
}
@Override
public IdentifierTree getModuleRequest() {
return moduleRequest;
}
@Override
public IdentifierTree getImportName() {
return importName;
}
@Override
public IdentifierTree getLocalName() {
return localName;
}
}

View file

@ -0,0 +1,45 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for an expression statement.
*
* For example:
* <pre>
* <em>expression</em> ;
* </pre>
*
* @since 9
*/
public interface ExpressionStatementTree extends StatementTree {
/**
* Returns the expression of this expression statement.
*
* @return the expression
*/
ExpressionTree getExpression();
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.ExpressionStatement;
final class ExpressionStatementTreeImpl extends StatementTreeImpl implements ExpressionStatementTree {
private final ExpressionTree expr;
ExpressionStatementTreeImpl(final ExpressionStatement es, final ExpressionTree expr) {
super(es);
this.expr = expr;
}
@Override
public Kind getKind() {
return Kind.EXPRESSION_STATEMENT;
}
@Override
public ExpressionTree getExpression() {
return expr;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitExpressionStatement(this, data);
}
}

View file

@ -0,0 +1,34 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node used as the base class for the different types of
* expressions.
*
* @since 9
*/
public interface ExpressionTree extends Tree {}

View file

@ -0,0 +1,34 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.Expression;
abstract class ExpressionTreeImpl extends TreeImpl implements ExpressionTree {
ExpressionTreeImpl(final Expression expr) {
super(expr);
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for for..in statement
*
* For example:
* <pre>
* for ( <em>variable</em> in <em>expression</em> )
* <em>statement</em>
* </pre>
*
* @since 9
*/
public interface ForInLoopTree extends LoopTree {
/**
* The for..in left hand side expression.
*
* @return the left hand side expression
*/
ExpressionTree getVariable();
/**
* The object or array being whose properties are iterated.
*
* @return the object or array expression being iterated
*/
ExpressionTree getExpression();
/**
* The statement contained in this for..in statement.
*
* @return the statement
*/
@Override
StatementTree getStatement();
/**
* Returns if this is a for..each..in statement or not.
*
* @return true if this is a for..each..in statement
*/
boolean isForEach();
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.ForNode;
final class ForInLoopTreeImpl extends StatementTreeImpl implements ForInLoopTree {
private final ExpressionTree lhsExpr;
private final ExpressionTree expr;
private final StatementTree stat;
private final boolean forEach;
ForInLoopTreeImpl(final ForNode node,
final ExpressionTree lhsExpr,
final ExpressionTree expr,
final StatementTree stat) {
super(node);
assert node.isForIn() : "for ..in expected";
this.lhsExpr = lhsExpr;
this.expr = expr;
this.stat = stat;
this.forEach = node.isForEach();
}
@Override
public Kind getKind() {
return Kind.FOR_IN_LOOP;
}
@Override
public ExpressionTree getVariable() {
return lhsExpr;
}
@Override
public ExpressionTree getExpression() {
return expr;
}
@Override
public StatementTree getStatement() {
return stat;
}
@Override
public boolean isForEach() {
return forEach;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitForInLoop(this, data);
}
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a basic 'for' loop statement.
*
* For example:
* <pre>
* for ( <em>initializer</em> ; <em>condition</em> ; <em>update</em> )
* <em>statement</em>
* </pre>
*
* @since 9
*/
public interface ForLoopTree extends ConditionalLoopTree {
/**
* Returns the initializer expression of this 'for' statement.
*
* @return the initializer expression
*/
ExpressionTree getInitializer();
/**
* Returns the condition expression of this 'for' statement.
*
* @return the condition expression
*/
@Override
ExpressionTree getCondition();
/**
* Returns the update expression of this 'for' statement.
*
* @return the update expression
*/
ExpressionTree getUpdate();
/**
* Returns the statement contained in this 'for' statement.
*
* @return the statement
*/
@Override
StatementTree getStatement();
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.ForNode;
final class ForLoopTreeImpl extends StatementTreeImpl implements ForLoopTree {
private final ExpressionTree init;
private final ExpressionTree cond;
private final ExpressionTree update;
private final StatementTree stat;
ForLoopTreeImpl(final ForNode node,
final ExpressionTree init,
final ExpressionTree cond,
final ExpressionTree update,
final StatementTree stat) {
super(node);
assert !node.isForIn() : "for statement expected";
this.init = init;
this.cond = cond;
this.update = update;
this.stat = stat;
}
@Override
public Kind getKind() {
return Kind.FOR_LOOP;
}
@Override
public ExpressionTree getInitializer() {
return init;
}
@Override
public ExpressionTree getCondition() {
return cond;
}
@Override
public ExpressionTree getUpdate() {
return update;
}
@Override
public StatementTree getStatement() {
return stat;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitForLoop(this, data);
}
}

View file

@ -0,0 +1,62 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements">for..of statement</a>.
*
* For example:
* <pre>
* for ( <em>variable</em> of <em>expression</em> )
* <em>statement</em>
* </pre>
*
* @since 9
*/
public interface ForOfLoopTree extends LoopTree {
/**
* The for..of left hand side expression.
*
* @return the left hand side expression
*/
ExpressionTree getVariable();
/**
* The object or array being whose properties are iterated.
*
* @return the object or array expression being iterated
*/
ExpressionTree getExpression();
/**
* The statement contained in this for..of statement.
*
* @return the statement
*/
@Override
StatementTree getStatement();
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.ForNode;
final class ForOfLoopTreeImpl extends StatementTreeImpl implements ForOfLoopTree {
private final ExpressionTree lhsExpr;
private final ExpressionTree expr;
private final StatementTree stat;
ForOfLoopTreeImpl(final ForNode node,
final ExpressionTree lhsExpr,
final ExpressionTree expr,
final StatementTree stat) {
super(node);
assert node.isForIn() : "for ..in expected";
this.lhsExpr = lhsExpr;
this.expr = expr;
this.stat = stat;
}
@Override
public Kind getKind() {
return Kind.FOR_IN_LOOP;
}
@Override
public ExpressionTree getVariable() {
return lhsExpr;
}
@Override
public ExpressionTree getExpression() {
return expr;
}
@Override
public StatementTree getStatement() {
return stat;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitForOfLoop(this, data);
}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A tree node for a function call expression.
*
* For example:
* <pre>
* <em>identifier</em> ( <em>arguments</em> )
*
* this . <em>identifier</em> ( <em>arguments</em> )
* </pre>
*
* @since 9
*/
public interface FunctionCallTree extends ExpressionTree {
/**
* Returns the function being called.
*
* @return the function being called
*/
ExpressionTree getFunctionSelect();
/**
* Returns the list of arguments being passed to this function call.
*
* @return the list of argument expressions
*/
List<? extends ExpressionTree> getArguments();
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.CallNode;
class FunctionCallTreeImpl extends ExpressionTreeImpl implements FunctionCallTree {
private final List<? extends ExpressionTree> arguments;
private final ExpressionTree function;
FunctionCallTreeImpl(final CallNode node,
final ExpressionTree function,
final List<? extends ExpressionTree> arguments) {
super(node);
this.function = function;
this.arguments = arguments;
}
@Override
public Kind getKind() {
return Kind.FUNCTION_INVOCATION;
}
@Override
public ExpressionTree getFunctionSelect() {
return function;
}
@Override
public List<? extends ExpressionTree> getArguments() {
return arguments;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitFunctionCall(this, data);
}
}

View file

@ -0,0 +1,83 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A tree node for a <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-function-definitions">function declaration</a>.
*
* For example:
* <pre>
* <em>function</em> <em>name</em>
* ( <em>parameters</em> )
* <em>body</em>
* </pre>
*
* <pre>
* <em>function*</em> <em>name</em>
* ( <em>parameters</em> )
* <em>body</em>
* </pre>
*
* @since 9
*/
public interface FunctionDeclarationTree extends StatementTree {
/**
* Returns the name of the function being declared.
*
* @return name the function declared
*/
IdentifierTree getName();
/**
* Returns the parameters of this function.
*
* @return the list of parameters
*/
List<? extends ExpressionTree> getParameters();
/**
* Returns the body of code of this function.
*
* @return the body of code
*/
BlockTree getBody();
/**
* Is this a strict function?
*
* @return true if this function is strict
*/
boolean isStrict();
/**
* Is this a generator function?
*
* @return true if this is a generator function
*/
boolean isGenerator();
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.VarNode;
final class FunctionDeclarationTreeImpl extends StatementTreeImpl
implements FunctionDeclarationTree {
private final FunctionNode funcNode;
private final IdentifierTree funcName;
private final List<? extends ExpressionTree> params;
private final BlockTree body;
FunctionDeclarationTreeImpl(final VarNode node,
final List<? extends ExpressionTree> params,
final BlockTree body) {
super(node);
assert node.getInit() instanceof FunctionNode : "function expected";
funcNode = (FunctionNode)node.getInit();
assert funcNode.isDeclared() : "function declaration expected";
funcName = funcNode.isAnonymous()? null : new IdentifierTreeImpl(node.getName());
this.params = params;
this.body = body;
}
@Override
public Kind getKind() {
return Kind.FUNCTION;
}
@Override
public IdentifierTree getName() {
return funcName;
}
@Override
public List<? extends ExpressionTree> getParameters() {
return params;
}
@Override
public BlockTree getBody() {
return body;
}
@Override
public boolean isStrict() {
return funcNode.isStrict();
}
@Override
public boolean isGenerator() {
return funcNode.getKind() == FunctionNode.Kind.GENERATOR;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitFunctionDeclaration(this, data);
}
}

View file

@ -0,0 +1,90 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A tree node for <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-function-defining-expressions">function expressions</a> including <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-arrow-function-definitions">arrow functions</a>.
*
* For example:
* <pre>
* <em>var</em> func = <em>function</em>
* ( <em>parameters</em> )
* <em>body</em>
* </pre>
*
* <pre>
* <em>var</em> func = <em>(x) =&gt; x+1</em>
* </pre>
*
* @since 9
*/
public interface FunctionExpressionTree extends ExpressionTree {
/**
* Returns the name of the function being declared.
*
* @return name the function declared
*/
IdentifierTree getName();
/**
* Returns the parameters of this function.
*
* @return the list of parameters
*/
List<? extends ExpressionTree> getParameters();
/**
* Returns the body of this function. This may be a {@link BlockTree} when this
* function has a block body. This is an {@link ExpressionTree} when the function body
* is a concise expression as in an expression arrow, or in an expression closure.
*
* @return the body of this function
*/
Tree getBody();
/**
* Is this a strict function?
*
* @return true if this function is strict
*/
boolean isStrict();
/**
* Is this a arrow function?
*
* @return true if this is a arrow function
*/
boolean isArrow();
/**
* Is this a generator function?
*
* @return true if this is a generator function
*/
boolean isGenerator();
}

View file

@ -0,0 +1,101 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.FunctionNode;
final class FunctionExpressionTreeImpl extends ExpressionTreeImpl
implements FunctionExpressionTree {
private final FunctionNode funcNode;
private final IdentifierTree funcName;
private final List<? extends ExpressionTree> params;
private final Tree body;
FunctionExpressionTreeImpl(final FunctionNode node,
final List<? extends ExpressionTree> params,
final BlockTree body) {
super(node);
funcNode = node;
assert !funcNode.isDeclared() || funcNode.isAnonymous() : "function expression expected";
final FunctionNode.Kind kind = node.getKind();
if (node.isAnonymous() || kind == FunctionNode.Kind.GETTER || kind == FunctionNode.Kind.SETTER) {
funcName = null;
} else {
funcName = new IdentifierTreeImpl(node.getIdent());
}
this.params = params;
if (node.getFlag(FunctionNode.HAS_EXPRESSION_BODY)) {
final StatementTree first = body.getStatements().get(0);
assert first instanceof ReturnTree : "consise func. expression should have a return statement";
this.body = ((ReturnTree)first).getExpression();
} else {
this.body = body;
}
}
@Override
public Tree.Kind getKind() {
return Tree.Kind.FUNCTION_EXPRESSION;
}
@Override
public IdentifierTree getName() {
return funcName;
}
@Override
public List<? extends ExpressionTree> getParameters() {
return params;
}
@Override
public Tree getBody() {
return body;
}
@Override
public boolean isStrict() {
return funcNode.isStrict();
}
@Override
public boolean isArrow() {
return funcNode.getKind() == FunctionNode.Kind.ARROW;
}
@Override
public boolean isGenerator() {
return funcNode.getKind() == FunctionNode.Kind.GENERATOR;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitFunctionExpression(this, data);
}
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a statement that jumps to a target. Note that
* ECMAScript does not support a goto statement. But, this Tree
* type serves as a super interface for {@link BreakTree} and
* {@link ContinueTree}.
*
* @since 9
*/
public interface GotoTree extends StatementTree {
/**
* Label associated with this goto statement. This is null
* if there is no label associated with this goto statement.
*
* @return label associated with this goto statement.
*/
String getLabel();
}

View file

@ -0,0 +1,624 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import jdk.nashorn.internal.ir.AccessNode;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.ir.Block;
import jdk.nashorn.internal.ir.BlockStatement;
import jdk.nashorn.internal.ir.BreakNode;
import jdk.nashorn.internal.ir.CallNode;
import jdk.nashorn.internal.ir.CaseNode;
import jdk.nashorn.internal.ir.CatchNode;
import jdk.nashorn.internal.ir.ClassNode;
import jdk.nashorn.internal.ir.ContinueNode;
import jdk.nashorn.internal.ir.DebuggerNode;
import jdk.nashorn.internal.ir.EmptyNode;
import jdk.nashorn.internal.ir.ErrorNode;
import jdk.nashorn.internal.ir.Expression;
import jdk.nashorn.internal.ir.ExpressionStatement;
import jdk.nashorn.internal.ir.ForNode;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.IfNode;
import jdk.nashorn.internal.ir.IndexNode;
import jdk.nashorn.internal.ir.LabelNode;
import jdk.nashorn.internal.ir.LiteralNode;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.ObjectNode;
import jdk.nashorn.internal.ir.PropertyNode;
import jdk.nashorn.internal.ir.ReturnNode;
import jdk.nashorn.internal.ir.RuntimeNode;
import jdk.nashorn.internal.ir.SplitNode;
import jdk.nashorn.internal.ir.Statement;
import jdk.nashorn.internal.ir.SwitchNode;
import jdk.nashorn.internal.ir.TemplateLiteral;
import jdk.nashorn.internal.ir.TernaryNode;
import jdk.nashorn.internal.ir.ThrowNode;
import jdk.nashorn.internal.ir.TryNode;
import jdk.nashorn.internal.ir.UnaryNode;
import jdk.nashorn.internal.ir.VarNode;
import jdk.nashorn.internal.ir.WhileNode;
import jdk.nashorn.internal.ir.WithNode;
import jdk.nashorn.internal.ir.visitor.SimpleNodeVisitor;
import jdk.nashorn.internal.parser.Lexer;
import jdk.nashorn.internal.parser.TokenType;
/**
* This class translates from nashorn IR Node objects
* to nashorn parser API Tree objects.
*/
final class IRTranslator extends SimpleNodeVisitor {
public IRTranslator() {
}
// currently translated Statement
private StatementTreeImpl curStat;
// currently translated Expression
private ExpressionTreeImpl curExpr;
// entry point for translator
CompilationUnitTree translate(final FunctionNode node) {
if (node == null) {
return null;
}
assert node.getKind() == FunctionNode.Kind.SCRIPT ||
node.getKind() == FunctionNode.Kind.MODULE :
"script or module function expected";
final Block body = node.getBody();
return new CompilationUnitTreeImpl(node,
translateStats(body != null? getOrderedStatements(body.getStatements()) : null),
translateModule(node));
}
@Override
public boolean enterAccessNode(final AccessNode accessNode) {
curExpr = new MemberSelectTreeImpl(accessNode, translateExpr(accessNode.getBase()));
return false;
}
@Override
public boolean enterBlock(final Block block) {
return handleBlock(block, false);
}
@Override
public boolean enterBinaryNode(final BinaryNode binaryNode) {
if (binaryNode.isAssignment()) {
final ExpressionTree srcTree = translateExpr(binaryNode.getAssignmentSource());
final ExpressionTree destTree = translateExpr(binaryNode.getAssignmentDest());
if (binaryNode.isTokenType(TokenType.ASSIGN)) {
curExpr = new AssignmentTreeImpl(binaryNode, destTree, srcTree);
} else {
curExpr = new CompoundAssignmentTreeImpl(binaryNode, destTree, srcTree);
}
} else {
final ExpressionTree leftTree = translateExpr(binaryNode.lhs());
final ExpressionTree rightTree = translateExpr(binaryNode.rhs());
if (binaryNode.isTokenType(TokenType.INSTANCEOF)) {
curExpr = new InstanceOfTreeImpl(binaryNode, leftTree, rightTree);
} else {
curExpr = new BinaryTreeImpl(binaryNode, leftTree, rightTree);
}
}
return false;
}
@Override
public boolean enterBreakNode(final BreakNode breakNode) {
curStat = new BreakTreeImpl(breakNode);
return false;
}
@Override
public boolean enterCallNode(final CallNode callNode) {
curExpr = null;
callNode.getFunction().accept(this);
final ExpressionTree funcTree = curExpr;
final List<? extends ExpressionTree> argTrees = translateExprs(callNode.getArgs());
curExpr = new FunctionCallTreeImpl(callNode, funcTree, argTrees);
return false;
}
@Override
public boolean enterCaseNode(final CaseNode caseNode) {
assert false : "should not reach here!";
return false;
}
@Override
public boolean enterCatchNode(final CatchNode catchNode) {
assert false : "should not reach here";
return false;
}
@Override
public boolean enterContinueNode(final ContinueNode continueNode) {
curStat = new ContinueTreeImpl(continueNode);
return false;
}
@Override
public boolean enterDebuggerNode(final DebuggerNode debuggerNode) {
curStat = new DebuggerTreeImpl(debuggerNode);
return false;
}
@Override
public boolean enterEmptyNode(final EmptyNode emptyNode) {
curStat = new EmptyStatementTreeImpl(emptyNode);
return false;
}
@Override
public boolean enterErrorNode(final ErrorNode errorNode) {
curExpr = new ErroneousTreeImpl(errorNode);
return false;
}
@Override
public boolean enterExpressionStatement(final ExpressionStatement expressionStatement) {
if (expressionStatement.destructuringDeclarationType() != null) {
final ExpressionTree expr = translateExpr(expressionStatement.getExpression());
assert expr instanceof AssignmentTree : "destructuring decl. statement does not have assignment";
final AssignmentTree assign = (AssignmentTree)expr;
curStat = new DestructuringDeclTreeImpl(expressionStatement, assign.getVariable(), assign.getExpression());
} else {
curStat = new ExpressionStatementTreeImpl(expressionStatement,
translateExpr(expressionStatement.getExpression()));
}
return false;
}
@Override
public boolean enterBlockStatement(final BlockStatement blockStatement) {
final Block block = blockStatement.getBlock();
if (blockStatement.isSynthetic()) {
assert block != null && block.getStatements() != null && block.getStatements().size() == 1;
curStat = translateStat(block.getStatements().get(0));
} else {
curStat = new BlockTreeImpl(blockStatement,
translateStats(block != null? block.getStatements() : null));
}
return false;
}
@Override
public boolean enterForNode(final ForNode forNode) {
if (forNode.isForIn()) {
curStat = new ForInLoopTreeImpl(forNode,
translateExpr(forNode.getInit()),
translateExpr(forNode.getModify()),
translateBlock(forNode.getBody()));
} else if (forNode.isForOf()) {
curStat = new ForOfLoopTreeImpl(forNode,
translateExpr(forNode.getInit()),
translateExpr(forNode.getModify()),
translateBlock(forNode.getBody()));
} else {
curStat = new ForLoopTreeImpl(forNode,
translateExpr(forNode.getInit()),
translateExpr(forNode.getTest()),
translateExpr(forNode.getModify()),
translateBlock(forNode.getBody()));
}
return false;
}
@Override
public boolean enterFunctionNode(final FunctionNode functionNode) {
assert !functionNode.isDeclared() || functionNode.isAnonymous() : "should not reach here for function declaration";
final List<? extends ExpressionTree> paramTrees = translateParameters(functionNode);
final BlockTree blockTree = (BlockTree) translateBlock(functionNode.getBody(), true);
curExpr = new FunctionExpressionTreeImpl(functionNode, paramTrees, blockTree);
return false;
}
@Override
public boolean enterIdentNode(final IdentNode identNode) {
curExpr = new IdentifierTreeImpl(identNode);
return false;
}
@Override
public boolean enterIfNode(final IfNode ifNode) {
curStat = new IfTreeImpl(ifNode,
translateExpr(ifNode.getTest()),
translateBlock(ifNode.getPass()),
translateBlock(ifNode.getFail()));
return false;
}
@Override
public boolean enterIndexNode(final IndexNode indexNode) {
curExpr = new ArrayAccessTreeImpl(indexNode,
translateExpr(indexNode.getBase()),
translateExpr(indexNode.getIndex()));
return false;
}
@Override
public boolean enterLabelNode(final LabelNode labelNode) {
curStat = new LabeledStatementTreeImpl(labelNode,
translateBlock(labelNode.getBody()));
return false;
}
@Override
public boolean enterLiteralNode(final LiteralNode<?> literalNode) {
final Object value = literalNode.getValue();
if (value instanceof Lexer.RegexToken) {
curExpr = new RegExpLiteralTreeImpl(literalNode);
} else if (literalNode.isArray()) {
final List<Expression> exprNodes = literalNode.getElementExpressions();
final List<ExpressionTreeImpl> exprTrees = new ArrayList<>(exprNodes.size());
for (final Node node : exprNodes) {
if (node == null) {
exprTrees.add(null);
} else {
curExpr = null;
node.accept(this);
assert curExpr != null : "null for " + node;
exprTrees.add(curExpr);
}
}
curExpr = new ArrayLiteralTreeImpl(literalNode, exprTrees);
} else {
curExpr = new LiteralTreeImpl(literalNode);
}
return false;
}
@Override
public boolean enterObjectNode(final ObjectNode objectNode) {
final List<PropertyNode> propNodes = objectNode.getElements();
final List<? extends PropertyTree> propTrees = translateProperties(propNodes);
curExpr = new ObjectLiteralTreeImpl(objectNode, propTrees);
return false;
}
@Override
public boolean enterPropertyNode(final PropertyNode propertyNode) {
assert false : "should not reach here!";
return false;
}
@Override
public boolean enterReturnNode(final ReturnNode returnNode) {
curStat = new ReturnTreeImpl(returnNode,
translateExpr(returnNode.getExpression()));
return false;
}
@Override
public boolean enterRuntimeNode(final RuntimeNode runtimeNode) {
assert false : "should not reach here: RuntimeNode";
return false;
}
@Override
public boolean enterSplitNode(final SplitNode splitNode) {
assert false : "should not reach here!";
return false;
}
@Override
public boolean enterSwitchNode(final SwitchNode switchNode) {
final List<CaseNode> caseNodes = switchNode.getCases();
final List<CaseTreeImpl> caseTrees = new ArrayList<>(caseNodes.size());
for (final CaseNode caseNode : caseNodes) {
final Block body = caseNode.getBody();
caseTrees.add(
new CaseTreeImpl(caseNode,
translateExpr(caseNode.getTest()),
translateStats(body != null? body.getStatements() : null)));
}
curStat = new SwitchTreeImpl(switchNode,
translateExpr(switchNode.getExpression()),
caseTrees);
return false;
}
@Override
public boolean enterTemplateLiteral(final TemplateLiteral templateLiteral) {
curExpr = new TemplateLiteralTreeImpl(templateLiteral, translateExprs(templateLiteral.getExpressions()));
return false;
}
@Override
public boolean enterTernaryNode(final TernaryNode ternaryNode) {
curExpr = new ConditionalExpressionTreeImpl(ternaryNode,
translateExpr(ternaryNode.getTest()),
translateExpr(ternaryNode.getTrueExpression()),
translateExpr(ternaryNode.getFalseExpression()));
return false;
}
@Override
public boolean enterThrowNode(final ThrowNode throwNode) {
curStat = new ThrowTreeImpl(throwNode,
translateExpr(throwNode.getExpression()));
return false;
}
@Override
public boolean enterTryNode(final TryNode tryNode) {
final List<? extends CatchNode> catchNodes = tryNode.getCatches();
final List<CatchTreeImpl> catchTrees = new ArrayList<>(catchNodes.size());
for (final CatchNode catchNode : catchNodes) {
catchTrees.add(new CatchTreeImpl(catchNode,
translateExpr(catchNode.getException()),
(BlockTree) translateBlock(catchNode.getBody()),
translateExpr(catchNode.getExceptionCondition())));
}
curStat = new TryTreeImpl(tryNode,
(BlockTree) translateBlock(tryNode.getBody()),
catchTrees,
(BlockTree) translateBlock(tryNode.getFinallyBody()));
return false;
}
@Override
public boolean enterUnaryNode(final UnaryNode unaryNode) {
if (unaryNode.isTokenType(TokenType.NEW)) {
curExpr = new NewTreeImpl(unaryNode,
translateExpr(unaryNode.getExpression()));
} else if (unaryNode.isTokenType(TokenType.YIELD) ||
unaryNode.isTokenType(TokenType.YIELD_STAR)) {
curExpr = new YieldTreeImpl(unaryNode,
translateExpr(unaryNode.getExpression()));
} else if (unaryNode.isTokenType(TokenType.SPREAD_ARGUMENT) ||
unaryNode.isTokenType(TokenType.SPREAD_ARRAY)) {
curExpr = new SpreadTreeImpl(unaryNode,
translateExpr(unaryNode.getExpression()));
} else {
curExpr = new UnaryTreeImpl(unaryNode,
translateExpr(unaryNode.getExpression()));
}
return false;
}
@Override
public boolean enterVarNode(final VarNode varNode) {
final Expression initNode = varNode.getInit();
if (initNode instanceof FunctionNode && ((FunctionNode)initNode).isDeclared()) {
final FunctionNode funcNode = (FunctionNode) initNode;
final List<? extends ExpressionTree> paramTrees = translateParameters(funcNode);
final BlockTree blockTree = (BlockTree) translateBlock(funcNode.getBody(), true);
curStat = new FunctionDeclarationTreeImpl(varNode, paramTrees, blockTree);
} else if (initNode instanceof ClassNode && ((ClassNode)initNode).isStatement()) {
final ClassNode classNode = (ClassNode) initNode;
curStat = new ClassDeclarationTreeImpl(varNode,
translateIdent(classNode.getIdent()),
translateExpr(classNode.getClassHeritage()),
translateProperty(classNode.getConstructor()),
translateProperties(classNode.getClassElements()));
} else {
curStat = new VariableTreeImpl(varNode, translateIdent(varNode.getName()), translateExpr(initNode));
}
return false;
}
@Override
public boolean enterWhileNode(final WhileNode whileNode) {
final ExpressionTree condTree = translateExpr(whileNode.getTest());
final StatementTree statTree = translateBlock(whileNode.getBody());
if (whileNode.isDoWhile()) {
curStat = new DoWhileLoopTreeImpl(whileNode, condTree, statTree);
} else {
curStat = new WhileLoopTreeImpl(whileNode, condTree, statTree);
}
return false;
}
@Override
public boolean enterWithNode(final WithNode withNode) {
curStat = new WithTreeImpl(withNode,
translateExpr(withNode.getExpression()),
translateBlock(withNode.getBody()));
return false;
}
/**
* Callback for entering a ClassNode
*
* @param classNode the node
* @return true if traversal should continue and node children be traversed, false otherwise
*/
@Override
public boolean enterClassNode(final ClassNode classNode) {
assert !classNode.isStatement(): "should not reach here for class declaration";
curExpr = new ClassExpressionTreeImpl(classNode,
translateIdent(classNode.getIdent()),
translateExpr(classNode.getClassHeritage()),
translateProperty(classNode.getConstructor()),
translateProperties(classNode.getClassElements()));
return false;
}
private StatementTree translateBlock(final Block blockNode) {
return translateBlock(blockNode, false);
}
private StatementTree translateBlock(final Block blockNode, final boolean sortStats) {
if (blockNode == null) {
return null;
}
curStat = null;
handleBlock(blockNode, sortStats);
return curStat;
}
private boolean handleBlock(final Block block, final boolean sortStats) {
// FIXME: revisit this!
if (block.isSynthetic()) {
final int statCount = block.getStatementCount();
switch (statCount) {
case 0: {
final EmptyNode emptyNode = new EmptyNode(-1, block.getToken(), block.getFinish());
curStat = new EmptyStatementTreeImpl(emptyNode);
return false;
}
case 1: {
curStat = translateStat(block.getStatements().get(0));
return false;
}
default: {
// fall through
break;
}
}
}
final List<? extends Statement> stats = block.getStatements();
curStat = new BlockTreeImpl(block,
translateStats(sortStats? getOrderedStatements(stats) : stats));
return false;
}
private List<? extends Statement> getOrderedStatements(final List<? extends Statement> stats) {
final List<? extends Statement> statList = new ArrayList<>(stats);
statList.sort(Comparator.comparingInt(Node::getSourceOrder));
return statList;
}
private List<? extends StatementTree> translateStats(final List<? extends Statement> stats) {
if (stats == null) {
return null;
}
final List<StatementTreeImpl> statTrees = new ArrayList<>(stats.size());
for (final Statement stat : stats) {
curStat = null;
stat.accept(this);
assert curStat != null;
statTrees.add(curStat);
}
return statTrees;
}
private List<? extends ExpressionTree> translateParameters(final FunctionNode func) {
final Map<IdentNode, Expression> paramExprs = func.getParameterExpressions();
if (paramExprs != null) {
final List<IdentNode> params = func.getParameters();
final List<ExpressionTreeImpl> exprTrees = new ArrayList<>(params.size());
for (final IdentNode ident : params) {
final Expression expr = paramExprs.containsKey(ident)? paramExprs.get(ident) : ident;
curExpr = null;
expr.accept(this);
assert curExpr != null;
exprTrees.add(curExpr);
}
return exprTrees;
} else {
return translateExprs(func.getParameters());
}
}
private List<? extends ExpressionTree> translateExprs(final List<? extends Expression> exprs) {
if (exprs == null) {
return null;
}
final List<ExpressionTreeImpl> exprTrees = new ArrayList<>(exprs.size());
for (final Expression expr : exprs) {
curExpr = null;
expr.accept(this);
assert curExpr != null;
exprTrees.add(curExpr);
}
return exprTrees;
}
private ExpressionTreeImpl translateExpr(final Expression expr) {
if (expr == null) {
return null;
}
curExpr = null;
expr.accept(this);
assert curExpr != null : "null for " + expr;
return curExpr;
}
private StatementTreeImpl translateStat(final Statement stat) {
if (stat == null) {
return null;
}
curStat = null;
stat.accept(this);
assert curStat != null : "null for " + stat;
return curStat;
}
private static IdentifierTree translateIdent(final IdentNode ident) {
return new IdentifierTreeImpl(ident);
}
private List<? extends PropertyTree> translateProperties(final List<PropertyNode> propNodes) {
final List<PropertyTree> propTrees = new ArrayList<>(propNodes.size());
for (final PropertyNode propNode : propNodes) {
propTrees.add(translateProperty(propNode));
}
return propTrees;
}
private PropertyTree translateProperty(final PropertyNode propNode) {
return new PropertyTreeImpl(propNode,
translateExpr(propNode.getKey()),
translateExpr(propNode.getValue()),
(FunctionExpressionTree) translateExpr(propNode.getGetter()),
(FunctionExpressionTree) translateExpr(propNode.getSetter()));
}
private ModuleTree translateModule(final FunctionNode func) {
return func.getKind() == FunctionNode.Kind.MODULE?
ModuleTreeImpl.create(func) : null;
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for an identifier expression.
*
* For example:
* <pre>
* <em>name</em>
* </pre>
*
* @since 9
*/
public interface IdentifierTree extends ExpressionTree {
/**
* Returns the name of this identifier.
*
* @return the name of this identifier
*/
String getName();
/**
* Is this a rest parameter for a function or rest elements of an array?
*
* @return true if this is a rest parameter
*/
boolean isRestParameter();
/**
* Is this super identifier?
*
* @return true if this is super identifier
*/
boolean isSuper();
/**
* Is this 'this' identifier?
*
* @return true if this is 'this' identifier
*/
boolean isThis();
/**
* Is this "*" used in module export entry?
*
* @return true if this "*" used in module export entry?
*/
boolean isStar();
/**
* Is this "default" used in module export entry?
*
* @return true if this 'default' used in module export entry?
*/
boolean isDefault();
/**
* Is this "*default*" used in module export entry?
*
* @return true if this '*default*' used in module export entry?
*/
boolean isStarDefaultStar();
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.Module;
final class IdentifierTreeImpl extends ExpressionTreeImpl implements IdentifierTree {
private final String name;
IdentifierTreeImpl(final IdentNode node) {
super(node);
this.name = node.getName();
}
@Override
public Kind getKind() {
return Kind.IDENTIFIER;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isRestParameter() {
return ((IdentNode)node).isRestParameter();
}
@Override
public boolean isSuper() {
final IdentNode ident = (IdentNode)node;
return ident.isDirectSuper() || "super".equals(ident.getName());
}
@Override
public boolean isThis() {
return "this".equals(((IdentNode)node).getName());
}
@Override
public boolean isStar() {
return Module.STAR_NAME.equals(((IdentNode)node).getName());
}
@Override
public boolean isDefault() {
return Module.DEFAULT_NAME.equals(((IdentNode)node).getName());
}
@Override
public boolean isStarDefaultStar() {
return Module.DEFAULT_EXPORT_BINDING_NAME.equals(((IdentNode)node).getName());
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitIdentifier(this, data);
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for an 'if' statement.
*
* For example:
* <pre>
* if ( <em>condition</em> )
* <em>thenStatement</em>
*
* if ( <em>condition</em> )
* <em>thenStatement</em>
* else
* <em>elseStatement</em>
* </pre>
*
* @since 9
*/
public interface IfTree extends StatementTree {
/**
* Returns the condition expression of this 'if' statement.
*
* @return the condition expression
*/
ExpressionTree getCondition();
/**
* Returns the 'then' statement of this 'if' statement.
*
* @return the 'then' statement
*/
StatementTree getThenStatement();
/**
* Returns the then statement of this 'if' statement.
* null if this if statement has no else branch.
*
* @return the 'else' statement
*/
StatementTree getElseStatement();
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.IfNode;
final class IfTreeImpl extends StatementTreeImpl implements IfTree {
private final ExpressionTree cond;
private final StatementTree thenStat;
private final StatementTree elseStat;
IfTreeImpl(final IfNode node, final ExpressionTree cond,
final StatementTree thenStat, final StatementTree elseStat) {
super(node);
this.cond = cond;
this.thenStat = thenStat;
this.elseStat = elseStat;
}
@Override
public Kind getKind() {
return Kind.IF;
}
@Override
public ExpressionTree getCondition() {
return cond;
}
@Override
public StatementTree getThenStatement() {
return thenStat;
}
/**
* @return null if this if statement has no else branch.
*/
@Override
public StatementTree getElseStatement() {
return elseStat;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitIf(this, data);
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A Tree node for import entry of <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-modules">Module information</a>.
*/
public interface ImportEntryTree extends Tree {
/**
* Returns the entry's module request.
*
* @return the module request
*/
public IdentifierTree getModuleRequest();
/**
* Returns the entry's import name.
*
* @return the import name
*/
public IdentifierTree getImportName();
/**
* Returns the entry's local name.
*
* @return the local name
*/
public IdentifierTree getLocalName();
}

View file

@ -0,0 +1,100 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import java.util.stream.Collectors;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.Module;
import static jdk.nashorn.api.tree.ModuleTreeImpl.identOrNull;
final class ImportEntryTreeImpl extends TreeImpl implements ImportEntryTree {
private final long startPos, endPos;
private final IdentifierTree moduleRequest;
private final IdentifierTree importName;
private final IdentifierTree localName;
private ImportEntryTreeImpl(final long startPos, final long endPos,
final IdentifierTree moduleRequest,
final IdentifierTree importName,
final IdentifierTree localName) {
super(null); // No underlying Node!
this.startPos = startPos;
this.endPos = endPos;
this.moduleRequest = moduleRequest;
this.importName = importName;
this.localName = localName;
}
private static ImportEntryTreeImpl createImportEntry(final Module.ImportEntry entry) {
return new ImportEntryTreeImpl(entry.getStartPosition(),
entry.getEndPosition(),
identOrNull(entry.getModuleRequest()),
identOrNull(entry.getImportName()),
identOrNull(entry.getLocalName()));
}
static List<ImportEntryTreeImpl> createImportList(final List<Module.ImportEntry> importList) {
return importList.stream().
map(ImportEntryTreeImpl::createImportEntry).
collect(Collectors.toList());
}
@Override
public Kind getKind() {
return Tree.Kind.IMPORT_ENTRY;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitImportEntry(this, data);
}
@Override
public long getStartPosition() {
return startPos;
}
@Override
public long getEndPosition() {
return endPos;
}
@Override
public IdentifierTree getModuleRequest() {
return moduleRequest;
}
@Override
public IdentifierTree getImportName() {
return importName;
}
@Override
public IdentifierTree getLocalName() {
return localName;
}
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for an 'instanceof' expression.
*
* For example:
* <pre>
* <em>expression</em> instanceof <em>type</em>
* </pre>
*
* @since 9
*/
public interface InstanceOfTree extends ExpressionTree {
/**
* Returns the expression whose type is being checked.
*
* @return the expression whose type is being checked
*/
ExpressionTree getExpression();
/**
* Returns the type expression.
*
* @return the type expression
*/
Tree getType();
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.parser.TokenType;
final class InstanceOfTreeImpl extends BinaryTreeImpl implements InstanceOfTree {
InstanceOfTreeImpl(final BinaryNode node,
final ExpressionTree expr,
final ExpressionTree type) {
super(node, expr, type);
assert node.isTokenType(TokenType.INSTANCEOF) : "instanceof expected";
}
@Override
public Kind getKind() {
return Kind.INSTANCE_OF;
}
@Override
public ExpressionTree getExpression() {
return getLeftOperand();
}
@Override
public Tree getType() {
return getRightOperand();
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitInstanceOf(this, data);
}
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a labeled statement.
*
* For example:
* <pre>
* <em>label</em> : <em>statement</em>
* </pre>
*
* @since 9
*/
public interface LabeledStatementTree extends StatementTree {
/**
* Returns the label associated with this statement.
*
* @return the label
*/
String getLabel();
/**
* Returns the statement being labeled.
*
* @return the statement labeled
*/
StatementTree getStatement();
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.LabelNode;
final class LabeledStatementTreeImpl extends StatementTreeImpl
implements LabeledStatementTree {
private final String name;
private final StatementTree stat;
LabeledStatementTreeImpl(final LabelNode node, final StatementTree stat) {
super(node);
this.name = node.getLabelName();
this.stat = stat;
}
@Override
public Kind getKind() {
return Kind.LABELED_STATEMENT;
}
@Override
public String getLabel() {
return name;
}
@Override
public StatementTree getStatement() {
return stat;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitLabeledStatement(this, data);
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* Provides methods to convert between character positions and line numbers
* for a compilation unit.
*
* @since 9
*/
public interface LineMap {
/**
* Find the line containing a position; a line termination
* character is on the line it terminates.
*
* @param pos character offset of the position
* @return the line number of pos (first line is 1)
*/
long getLineNumber(long pos);
/**
* Find the column for a character position.
* Tab characters preceding the position on the same line
* will be expanded when calculating the column number.
*
* @param pos character offset of the position
* @return the tab-expanded column number of pos (first column is 1)
*/
long getColumnNumber(long pos);
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.runtime.Source;
final class LineMapImpl implements LineMap {
private final Source source;
LineMapImpl(final Source source) {
this.source = source;
}
@Override
public long getLineNumber(final long pos) {
return source.getLine((int)pos);
}
@Override
public long getColumnNumber(final long pos) {
return source.getColumn((int)pos);
}
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a literal expression.
* Use {@link #getKind getKind} to determine the kind of literal.
*
* For example:
* <pre>
* <em>value</em>
* </pre>
*
* @since 9
*/
public interface LiteralTree extends ExpressionTree {
/**
* Returns the value of this literal.
*
* @return the value of this literal
*/
Object getValue();
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.LiteralNode;
final class LiteralTreeImpl extends ExpressionTreeImpl implements LiteralTree {
private final Object value;
private final Kind kind;
LiteralTreeImpl(final LiteralNode<?> node) {
super(node);
this.kind = literalKind(node);
this.value = node.getValue();
}
@Override
public Kind getKind() {
return kind;
}
@Override
public Object getValue() {
return value;
}
private static Kind literalKind(final LiteralNode<?> node) {
if (node.isBoolean()) {
return Kind.BOOLEAN_LITERAL;
} else if (node.isNumeric()) {
return Kind.NUMBER_LITERAL;
} else if (node.isString()) {
return Kind.STRING_LITERAL;
} else if (node.isNull()) {
return Kind.NULL_LITERAL;
} else {
throw new AssertionError("should not reach here: " + node.getValue());
}
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitLiteral(this, data);
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A mixin for "loop" statements.
*
* @since 9
*/
public interface LoopTree extends StatementTree {
/**
* Returns the statement contained in this 'loop' statement.
*
* @return the statement
*/
StatementTree getStatement();
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a member access expression.
*
* For example:
* <pre>
* <em>expression</em> . <em>identifier</em>
* </pre>
*
* @since 9
*/
public interface MemberSelectTree extends ExpressionTree {
/**
* The object expression whose member is being selected.
*
* @return the object whose member is selected
*/
ExpressionTree getExpression();
/**
* Returns the name of the property.
*
* @return the name of the property
*/
String getIdentifier();
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.AccessNode;
final class MemberSelectTreeImpl extends ExpressionTreeImpl
implements MemberSelectTree {
private final String ident;
private final ExpressionTree expr;
MemberSelectTreeImpl(final AccessNode node, final ExpressionTree expr) {
super(node);
this.ident = node.getProperty();
this.expr = expr;
}
@Override
public Kind getKind() {
return Kind.MEMBER_SELECT;
}
@Override
public ExpressionTree getExpression() {
return expr;
}
@Override
public String getIdentifier() {
return ident;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitMemberSelect(this, data);
}
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* A Tree node for <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-modules">Module information</a>.
*/
public interface ModuleTree extends Tree {
/**
* Returns the list of import entries.
*
* @return the import entries
*/
public List<? extends ImportEntryTree> getImportEntries();
/**
* Returns the list of local export entries.
*
* @return the local export entries
*/
public List<? extends ExportEntryTree> getLocalExportEntries();
/**
* Returns the list of indirect export entries.
*
* @return the indirect export entries
*/
public List<? extends ExportEntryTree> getIndirectExportEntries();
/**
* Returns the list of star export entries.
*
* @return the star export entries
*/
public List<? extends ExportEntryTree> getStarExportEntries();
}

View file

@ -0,0 +1,99 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import java.util.stream.Collectors;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.Module;
import static jdk.nashorn.api.tree.ExportEntryTreeImpl.createExportList;
import static jdk.nashorn.api.tree.ImportEntryTreeImpl.createImportList;
final class ModuleTreeImpl extends TreeImpl implements ModuleTree {
private final Module mod;
private final List<? extends ImportEntryTree> imports;
private final List<? extends ExportEntryTree> localExports;
private final List<? extends ExportEntryTree> indirectExports;
private final List<? extends ExportEntryTree> starExports;
private ModuleTreeImpl(final FunctionNode func,
final List<? extends ImportEntryTree> imports,
final List<? extends ExportEntryTree> localExports,
final List<? extends ExportEntryTree> indirectExports,
final List<? extends ExportEntryTree> starExports) {
super(func);
assert func.getKind() == FunctionNode.Kind.MODULE : "module function node expected";
this.mod = func.getModule();
this.imports = imports;
this.localExports = localExports;
this.indirectExports = indirectExports;
this.starExports = starExports;
}
static ModuleTreeImpl create(final FunctionNode func) {
final Module mod = func.getModule();
return new ModuleTreeImpl(func,
createImportList(mod.getImportEntries()),
createExportList(mod.getLocalExportEntries()),
createExportList(mod.getIndirectExportEntries()),
createExportList(mod.getStarExportEntries()));
}
@Override
public Kind getKind() {
return Tree.Kind.MODULE;
}
@Override
public List<? extends ImportEntryTree> getImportEntries() {
return imports;
}
@Override
public List<? extends ExportEntryTree> getLocalExportEntries() {
return localExports;
}
@Override
public List<? extends ExportEntryTree> getIndirectExportEntries() {
return indirectExports;
}
@Override
public List<? extends ExportEntryTree> getStarExportEntries() {
return starExports;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitModule(this, data);
}
static IdentifierTree identOrNull(final IdentNode node) {
return node != null? new IdentifierTreeImpl(node) : null;
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node to declare a new instance of a class.
*
* For example:
* <pre>
* new <em>identifier</em> ( )
*
* new <em>identifier</em> ( <em>arguments</em> )
* </pre>
*
* @since 9
*/
public interface NewTree extends ExpressionTree {
/**
* Returns the constructor expression of this 'new' expression.
*
* @return the constructor expression of this 'new' expression
*/
ExpressionTree getConstructorExpression();
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import jdk.nashorn.internal.ir.UnaryNode;
import jdk.nashorn.internal.parser.TokenType;
final class NewTreeImpl extends ExpressionTreeImpl implements NewTree {
private final ExpressionTree constrExpr;
NewTreeImpl(final UnaryNode node, final ExpressionTree constrExpr) {
super(node);
assert (node.isTokenType(TokenType.NEW)) : "new expected";
this.constrExpr = constrExpr;
}
@Override
public Kind getKind() {
return Kind.NEW;
}
@Override
public ExpressionTree getConstructorExpression() {
return constrExpr;
}
@Override
public <R, D> R accept(final TreeVisitor<R, D> visitor, final D data) {
return visitor.visitNew(this, data);
}
}

View file

@ -0,0 +1,42 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
/**
* Represents ECMAScript object literal expression.
*
* @since 9
*/
public interface ObjectLiteralTree extends ExpressionTree {
/**
* Returns the list of properties of this object literal.
*
* @return the list of properties of this object literal
*/
public List<? extends PropertyTree> getProperties();
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.util.List;
import jdk.nashorn.internal.ir.ObjectNode;
final class ObjectLiteralTreeImpl extends ExpressionTreeImpl
implements ObjectLiteralTree {
private final List<? extends PropertyTree> props;
ObjectLiteralTreeImpl(final ObjectNode node, final List<? extends PropertyTree> props) {
super(node);
this.props = props;
}
@Override
public Kind getKind() {
return Kind.OBJECT_LITERAL;
}
@Override
public List<? extends PropertyTree> getProperties() {
return props;
}
@Override
public <R,D> R accept(final TreeVisitor<R,D> visitor, final D data) {
return visitor.visitObjectLiteral(this, data);
}
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
/**
* A tree node for a parenthesized expression. Note: parentheses
* not be preserved by the parser.
*
* For example:
* <pre>
* ( <em>expression</em> )
* </pre>
*
* @since 9
*/
public interface ParenthesizedTree extends ExpressionTree {
/**
* Returns the expression within the parenthesis.
*
* @return the expression within the parenthesis
*/
ExpressionTree getExpression();
}

View file

@ -0,0 +1,163 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.api.tree;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.nio.file.Path;
import jdk.nashorn.api.scripting.NashornException;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
/**
* Represents nashorn ECMAScript parser instance.
*
* @since 9
*/
public interface Parser {
/**
* Parses the source file and returns compilation unit tree
*
* @param file source file to parse
* @param listener to receive diagnostic messages from the parser. This can be null.
* if null is passed, a NashornException is thrown on the first parse error.
* @return compilation unit tree
* @throws NullPointerException if file is null
* @throws IOException if parse source read fails
* @throws NashornException is thrown if no listener is supplied and parser encounters error
*/
public CompilationUnitTree parse(final File file, final DiagnosticListener listener) throws IOException, NashornException;
/**
* Parses the source Path and returns compilation unit tree
*
* @param path source Path to parse
* @param listener to receive diagnostic messages from the parser. This can be null.
* if null is passed, a NashornException is thrown on the first parse error.
* @return compilation unit tree
* @throws NullPointerException if path is null
* @throws IOException if parse source read fails
* @throws NashornException is thrown if no listener is supplied and parser encounters error
*/
public CompilationUnitTree parse(final Path path, final DiagnosticListener listener) throws IOException, NashornException;
/**
* Parses the source url and returns compilation unit tree
*
* @param url source file to parse
* @param listener to receive diagnostic messages from the parser. This can be null.
* if null is passed, a NashornException is thrown on the first parse error.
* @return compilation unit tree
* @throws NullPointerException if url is null
* @throws IOException if parse source read fails
* @throws NashornException is thrown if no listener is supplied and parser encounters error
*/
public CompilationUnitTree parse(final URL url, final DiagnosticListener listener) throws IOException, NashornException;
/**
* Parses the reader and returns compilation unit tree
*
* @param name name of the source file to parse
* @param reader from which source is read
* @param listener to receive diagnostic messages from the parser. This can be null.
* if null is passed, a NashornException is thrown on the first parse error.
* @return compilation unit tree
* @throws NullPointerException if name or reader is null
* @throws IOException if parse source read fails
* @throws NashornException is thrown if no listener is supplied and parser encounters error
*/
public CompilationUnitTree parse(final String name, Reader reader, final DiagnosticListener listener) throws IOException, NashornException;
/**
* Parses the string source and returns compilation unit tree
*
* @param name of the source
* @param code string source
* @param listener to receive diagnostic messages from the parser. This can be null.
* if null is passed, a NashornException is thrown on the first parse error.
* @return compilation unit tree
* @throws NullPointerException if name or code is null
* @throws NashornException is thrown if no listener is supplied and parser encounters error
*/
public CompilationUnitTree parse(final String name, String code, final DiagnosticListener listener) throws NashornException;
/**
* Parses the source from script object and returns compilation unit tree
*
* @param scriptObj script object whose script and name properties are used for script source
* @param listener to receive diagnostic messages from the parser. This can be null.
* if null is passed, a NashornException is thrown on the first parse error.
* @return compilation unit tree
* @throws NullPointerException if scriptObj is null
* @throws NashornException is thrown if no listener is supplied and parser encounters error
*/
public CompilationUnitTree parse(final ScriptObjectMirror scriptObj, final DiagnosticListener listener) throws NashornException;
/**
* Factory method to create a new instance of Parser.
*
* @param options configuration options to initialize the Parser.
* Currently the following options are supported:
*
* <dl>
* <dt>"--const-as-var"</dt><dd>treat "const" declaration as "var"</dd>
* <dt>"-dump-on-error" or "-doe"</dt><dd>dump stack trace on error</dd>
* <dt>"--empty-statements"</dt><dd>include empty statement nodes</dd>
* <dt>"--no-syntax-extensions" or "-nse"</dt><dd>disable ECMAScript syntax extensions</dd>
* <dt>"-scripting"</dt><dd>enable scripting mode extensions</dd>
* <dt>"-strict"</dt><dd>enable ECMAScript strict mode</dd>
* <dt>"--language=es6"</dt><dd>enable ECMAScript 6 parsing mode</dd>
* <dt>"--es6-module"</dt><dd>enable ECMAScript 6 module parsing mode. This option implies --language=es6</dd>
* </dl>
*
* @throws NullPointerException if options array or any of its element is null
* @throws IllegalArgumentException on unsupported option value.
* @return a new Parser instance.
*/
public static Parser create(final String... options) throws IllegalArgumentException {
options.getClass();
for (final String opt : options) {
switch (opt) {
case "--const-as-var":
case "-dump-on-error":
case "-doe":
case "--empty-statements":
case "--no-syntax-extensions":
case "-nse":
case "-scripting":
case "-strict":
case "--language=es6":
case "--es6-module":
break;
default:
throw new IllegalArgumentException(opt);
}
}
return new ParserImpl(options);
}
}

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