package jdk.nashorn.tools.jjs;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import jdk.internal.jline.console.completer.Completer;
import jdk.internal.jline.console.UserInterruptException;
import jdk.nashorn.api.scripting.NashornException;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.objects.NativeJava;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.NativeJavaPackage;
import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.ScriptEnvironment;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptingFunctions;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.Source;
import jdk.nashorn.tools.Shell;
public final class Main extends Shell {
private Main() {}
private static final String DOC_PROPERTY_NAME = "__doc__";
static final boolean DEBUG = Boolean.getBoolean("nashorn.jjs.debug");
private static final File HIST_FILE = new File(new File(System.getProperty("user.home")), ".jjs.history");
public static void main(final String[] args) {
try {
final int exitCode = main(System.in, System.out, System.err, args);
if (exitCode != SUCCESS) {
System.exit(exitCode);
}
} catch (final IOException e) {
System.err.println(e);
System.exit(IO_ERROR);
}
}
public static int main(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException {
return new Main().run(in, out, err, args);
}
protected int readEvalPrint(final Context context, final Global global) {
final ScriptEnvironment env = context.getEnv();
final String prompt = bundle.getString("shell.prompt");
final String prompt2 = bundle.getString("shell.prompt2");
final PrintWriter err = context.getErr();
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
final PropertiesHelper propsHelper = new PropertiesHelper(context);
if (globalChanged) {
Context.setGlobal(global);
}
final ScriptObject jjsObj = (ScriptObject)context.eval(global, readJJSScript(), global, "<jjs.js>");
final boolean isHeadless = (boolean) ScriptRuntime.apply((ScriptFunction) jjsObj.get("isHeadless"), null);
final ScriptFunction fileChooserFunc = isHeadless? null : (ScriptFunction) jjsObj.get("chooseFile");
final NashornCompleter completer = new NashornCompleter(context, global, this, propsHelper, fileChooserFunc);
final ScriptFunction browseFunc = isHeadless? null : (ScriptFunction) jjsObj.get("browse");
final ScriptFunction javadoc = (ScriptFunction) jjsObj.get("javadoc");
try (final Console in = new Console(System.in, System.out, HIST_FILE, completer,
str -> {
try {
final Object res = context.eval(global, str, global, "<shell>");
if (res != null && res != UNDEFINED) {
if (!isHeadless && NativeJava.isType(UNDEFINED, res)) {
final String typeName = NativeJava.typeName(UNDEFINED, res).toString();
final String url = typeName.replace('.', '/').replace('$', '.') + ".html";
openBrowserForJavadoc(browseFunc, url);
} else if (!isHeadless && res instanceof NativeJavaPackage) {
final String pkgName = ((NativeJavaPackage)res).getName();
final String url = pkgName.replace('.', '/') + "/package-summary.html";
openBrowserForJavadoc(browseFunc, url);
} else if (NativeJava.isJavaMethod(UNDEFINED, res)) {
ScriptRuntime.apply(javadoc, UNDEFINED, res);
return "";
} else if (res instanceof ScriptObject) {
final ScriptObject sobj = (ScriptObject)res;
if (sobj.has(DOC_PROPERTY_NAME)) {
return toString(sobj.get(DOC_PROPERTY_NAME), global);
} else if (sobj instanceof ScriptFunction) {
return ((ScriptFunction)sobj).getDocumentation();
}
}
return toString(res, global);
}
} catch (Exception ignored) {
}
return null;
})) {
global.addShellBuiltins();
ScriptingFunctions.setReadLineHelper(str-> {
try {
return in.readLine(str);
} catch (final IOException ioExp) {
throw new UncheckedIOException(ioExp);
}
});
if (System.getSecurityManager() == null) {
final Consumer<String> evaluator = str -> {
final Global _oldGlobal = Context.getGlobal();
final boolean _globalChanged = (_oldGlobal != global);
if (_globalChanged) {
Context.setGlobal(global);
}
try {
evalImpl(context, global, str, err, env._dump_on_error);
} finally {
if (_globalChanged) {
Context.setGlobal(_oldGlobal);
}
}
};
global.addOwnProperty("history", Property.NOT_ENUMERABLE, new HistoryObject(in.getHistory(), err, evaluator));
global.addOwnProperty("edit", Property.NOT_ENUMERABLE, new EditObject(in, err::println, evaluator));
}
while (true) {
String source = "";
try {
source = in.readLine(prompt);
} catch (final IOException ioe) {
err.println(ioe.toString());
if (env._dump_on_error) {
ioe.printStackTrace(err);
}
return IO_ERROR;
} catch (final UserInterruptException ex) {
break;
}
if (source == null) {
break;
}
if (source.isEmpty()) {
continue;
}
try {
final Object res = context.eval(global, source, global, "<shell>");
if (res != UNDEFINED) {
err.println(toString(res, global));
}
} catch (final Exception exp) {
if (completer.isSyntaxErrorAt(exp, 1, source.length())) {
final String fullSrc = completer.readMoreLines(source, exp, in, prompt2, err);
if (fullSrc != null && !fullSrc.isEmpty()) {
evalImpl(context, global, fullSrc, err, env._dump_on_error);
}
} else {
err.println(exp);
if (env._dump_on_error) {
exp.printStackTrace(err);
}
}
}
}
} catch (final Exception e) {
err.println(e);
if (env._dump_on_error) {
e.printStackTrace(err);
}
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
try {
propsHelper.close();
} catch (final Exception exp) {
if (DEBUG) {
exp.printStackTrace();
}
}
}
return SUCCESS;
}
static String getMessage(final String id) {
return bundle.getString(id);
}
private void evalImpl(final Context context, final Global global, final String source,
final PrintWriter err, final boolean doe) {
try {
final Object res = context.eval(global, source, global, "<shell>");
if (res != UNDEFINED) {
err.println(toString(res, global));
}
} catch (final Exception e) {
err.println(e);
if (doe) {
e.printStackTrace(err);
}
}
}
private static String JAVADOC_BASE = "https://docs.oracle.com/javase/%d/docs/api/";
private static void openBrowserForJavadoc(ScriptFunction browse, String relativeUrl) {
try {
final URI uri = new URI(String.format(JAVADOC_BASE, Runtime.version().feature()) + relativeUrl);
ScriptRuntime.apply(browse, null, uri);
} catch (Exception ignored) {
}
}
private static String readJJSScript() {
return AccessController.doPrivileged(
new PrivilegedAction<String>() {
@Override
public String run() {
try {
final InputStream resStream = Main.class.getResourceAsStream("resources/jjs.js");
if (resStream == null) {
throw new RuntimeException("resources/jjs.js is missing!");
}
return new String(Source.readFully(resStream));
} catch (final IOException exp) {
throw new RuntimeException(exp);
}
}
});
}
}