Main.java revision 1574:1597de0e19e3
1/* 2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package jdk.nashorn.tools.jjs; 27 28import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; 29 30import java.awt.Desktop; 31import java.awt.GraphicsEnvironment; 32import java.io.BufferedReader; 33import java.io.File; 34import java.io.InputStream; 35import java.io.InputStreamReader; 36import java.io.IOException; 37import java.io.OutputStream; 38import java.io.PrintWriter; 39import java.net.URI; 40import java.util.concurrent.Callable; 41import java.util.function.Consumer; 42import java.util.function.Function; 43import jdk.internal.jline.console.completer.Completer; 44import jdk.internal.jline.console.UserInterruptException; 45import jdk.nashorn.api.scripting.NashornException; 46import jdk.nashorn.internal.objects.Global; 47import jdk.nashorn.internal.objects.NativeJava; 48import jdk.nashorn.internal.runtime.Context; 49import jdk.nashorn.internal.runtime.NativeJavaPackage; 50import jdk.nashorn.internal.runtime.JSType; 51import jdk.nashorn.internal.runtime.Property; 52import jdk.nashorn.internal.runtime.ScriptEnvironment; 53import jdk.nashorn.internal.runtime.ScriptFunction; 54import jdk.nashorn.internal.runtime.ScriptRuntime; 55import jdk.nashorn.tools.Shell; 56 57/** 58 * Interactive command line Shell for Nashorn. 59 */ 60public final class Main extends Shell { 61 private Main() {} 62 63 static final boolean DEBUG = Boolean.getBoolean("nashorn.jjs.debug"); 64 static final boolean HEADLESS = GraphicsEnvironment.isHeadless(); 65 66 // file where history is persisted. 67 private static final File HIST_FILE = new File(new File(System.getProperty("user.home")), ".jjs.history"); 68 69 /** 70 * Main entry point with the default input, output and error streams. 71 * 72 * @param args The command line arguments 73 */ 74 public static void main(final String[] args) { 75 try { 76 final int exitCode = main(System.in, System.out, System.err, args); 77 if (exitCode != SUCCESS) { 78 System.exit(exitCode); 79 } 80 } catch (final IOException e) { 81 System.err.println(e); //bootstrapping, Context.err may not exist 82 System.exit(IO_ERROR); 83 } 84 } 85 86 /** 87 * Starting point for executing a {@code Shell}. Starts a shell with the 88 * given arguments and streams and lets it run until exit. 89 * 90 * @param in input stream for Shell 91 * @param out output stream for Shell 92 * @param err error stream for Shell 93 * @param args arguments to Shell 94 * 95 * @return exit code 96 * 97 * @throws IOException if there's a problem setting up the streams 98 */ 99 public static int main(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException { 100 return new Main().run(in, out, err, args); 101 } 102 103 104 /** 105 * read-eval-print loop for Nashorn shell. 106 * 107 * @param context the nashorn context 108 * @param global global scope object to use 109 * @return return code 110 */ 111 protected int readEvalPrint(final Context context, final Global global) { 112 final ScriptEnvironment env = context.getEnv(); 113 final String prompt = bundle.getString("shell.prompt"); 114 final String prompt2 = bundle.getString("shell.prompt2"); 115 final PrintWriter err = context.getErr(); 116 final Global oldGlobal = Context.getGlobal(); 117 final boolean globalChanged = (oldGlobal != global); 118 final PropertiesHelper propsHelper = new PropertiesHelper(env._classpath); 119 final NashornCompleter completer = new NashornCompleter(context, global, this, propsHelper); 120 121 try (final Console in = new Console(System.in, System.out, HIST_FILE, completer, 122 str -> { 123 try { 124 final Object res = context.eval(global, str, global, "<shell>"); 125 if (res != null && res != UNDEFINED) { 126 // Special case Java types: show the javadoc for the class. 127 if (NativeJava.isType(UNDEFINED, res)) { 128 final String typeName = NativeJava.typeName(UNDEFINED, res).toString(); 129 final String url = typeName.replace('.', '/').replace('$', '.') + ".html"; 130 openBrowserForJavadoc(url); 131 } else if (res instanceof NativeJavaPackage) { 132 final String pkgName = ((NativeJavaPackage)res).getName(); 133 final String url = pkgName.replace('.', '/') + "/package-summary.html"; 134 openBrowserForJavadoc(url); 135 } else if (res instanceof ScriptFunction) { 136 return ((ScriptFunction)res).getDocumentation(); 137 } 138 139 // FIXME: better than toString for other cases? 140 return JSType.toString(res); 141 } 142 } catch (Exception ignored) { 143 } 144 return null; 145 })) { 146 147 if (globalChanged) { 148 Context.setGlobal(global); 149 } 150 151 global.addShellBuiltins(); 152 153 if (System.getSecurityManager() == null) { 154 final Consumer<String> evaluator = str -> { 155 // could be called from different thread (GUI), we need to handle Context set/reset 156 final Global _oldGlobal = Context.getGlobal(); 157 final boolean _globalChanged = (oldGlobal != global); 158 if (_globalChanged) { 159 Context.setGlobal(global); 160 } 161 try { 162 evalImpl(context, global, str, err, env._dump_on_error); 163 } finally { 164 if (_globalChanged) { 165 Context.setGlobal(_oldGlobal); 166 } 167 } 168 }; 169 170 // expose history object for reflecting on command line history 171 global.addOwnProperty("history", Property.NOT_ENUMERABLE, new HistoryObject(in.getHistory(), err, evaluator)); 172 173 // 'edit' command 174 global.addOwnProperty("edit", Property.NOT_ENUMERABLE, new EditObject(in, err::println, evaluator)); 175 } 176 177 while (true) { 178 String source = ""; 179 try { 180 source = in.readLine(prompt); 181 } catch (final IOException ioe) { 182 err.println(ioe.toString()); 183 if (env._dump_on_error) { 184 ioe.printStackTrace(err); 185 } 186 return IO_ERROR; 187 } catch (final UserInterruptException ex) { 188 break; 189 } 190 191 if (source == null) { 192 break; 193 } 194 195 if (source.isEmpty()) { 196 continue; 197 } 198 199 try { 200 final Object res = context.eval(global, source, global, "<shell>"); 201 if (res != UNDEFINED) { 202 err.println(toString(res, global)); 203 } 204 } catch (final Exception exp) { 205 // Is this a ECMAScript SyntaxError at last column (of the single line)? 206 // If so, it is because parser expected more input but got EOF. Try to 207 // to more lines from the user (multiline edit support). 208 209 if (completer.isSyntaxErrorAt(exp, 1, source.length())) { 210 final String fullSrc = completer.readMoreLines(source, exp, in, prompt2, err); 211 212 // check if we succeeded in getting complete code. 213 if (fullSrc != null && !fullSrc.isEmpty()) { 214 evalImpl(context, global, fullSrc, err, env._dump_on_error); 215 } // else ignore, error reported already by 'completer.readMoreLines' 216 } else { 217 218 // can't read more lines to have parseable/complete code. 219 err.println(exp); 220 if (env._dump_on_error) { 221 exp.printStackTrace(err); 222 } 223 } 224 } 225 } 226 } catch (final Exception e) { 227 err.println(e); 228 if (env._dump_on_error) { 229 e.printStackTrace(err); 230 } 231 } finally { 232 if (globalChanged) { 233 Context.setGlobal(oldGlobal); 234 } 235 try { 236 propsHelper.close(); 237 } catch (final Exception exp) { 238 if (DEBUG) { 239 exp.printStackTrace(); 240 } 241 } 242 } 243 244 return SUCCESS; 245 } 246 247 static String getMessage(final String id) { 248 return bundle.getString(id); 249 } 250 251 private void evalImpl(final Context context, final Global global, final String source, 252 final PrintWriter err, final boolean doe) { 253 try { 254 final Object res = context.eval(global, source, global, "<shell>"); 255 if (res != UNDEFINED) { 256 err.println(JSType.toString(res)); 257 } 258 } catch (final Exception e) { 259 err.println(e); 260 if (doe) { 261 e.printStackTrace(err); 262 } 263 } 264 } 265 266 // FIXME: needs to be changed to use javase 9 docs later 267 private static String JAVADOC_BASE = "http://download.java.net/jdk9/docs/api/"; 268 269 private static void openBrowserForJavadoc(String relativeUrl) { 270 try { 271 final URI uri = new URI(JAVADOC_BASE + relativeUrl); 272 Desktop.getDesktop().browse(uri); 273 } catch (Exception ignored) { 274 } 275 } 276} 277