1 /* 2 * Copyright (c) 2015, 2018, 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 26 package jdk.nashorn.tools.jjs; 27 28 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; 29 30 import java.io.File; 31 import java.io.InputStream; 32 import java.io.IOException; 33 import java.io.UncheckedIOException; 34 import java.io.OutputStream; 35 import java.io.PrintWriter; 36 import java.net.URI; 37 import java.security.AccessController; 38 import java.security.PrivilegedAction; 39 import java.util.function.Consumer; 40 41 import jdk.internal.org.jline.reader.UserInterruptException; 42 import jdk.nashorn.internal.objects.Global; 43 import jdk.nashorn.internal.objects.NativeJava; 44 import jdk.nashorn.internal.runtime.Context; 45 import jdk.nashorn.internal.runtime.NativeJavaPackage; 46 import jdk.nashorn.internal.runtime.Property; 47 import jdk.nashorn.internal.runtime.ScriptEnvironment; 48 import jdk.nashorn.internal.runtime.ScriptFunction; 49 import jdk.nashorn.internal.runtime.ScriptingFunctions; 50 import jdk.nashorn.internal.runtime.ScriptObject; 51 import jdk.nashorn.internal.runtime.ScriptRuntime; 52 import jdk.nashorn.internal.runtime.Source; 53 import jdk.nashorn.tools.Shell; 54 55 /** 56 * Interactive command line Shell for Nashorn. 57 */ 58 @Deprecated(since="11", forRemoval=true) 59 public final class Main extends Shell { 60 private Main() {} 61 62 private static final String DOC_PROPERTY_NAME = "__doc__"; 63 64 static final boolean DEBUG = Boolean.getBoolean("nashorn.jjs.debug"); 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(context); 119 120 if (globalChanged) { 121 Context.setGlobal(global); 122 } 123 124 // jjs.js is read and evaluated. The result of the evaluation is an "exports" object. This is done 125 // to avoid polluting javascript global scope. These are internal funtions are retrieved from the 126 // 'exports' object and used from here. 127 final ScriptObject jjsObj = (ScriptObject)context.eval(global, readJJSScript(), global, "<jjs.js>"); 128 129 final boolean isHeadless = (boolean) ScriptRuntime.apply((ScriptFunction) jjsObj.get("isHeadless"), null); 130 final ScriptFunction fileChooserFunc = isHeadless? null : (ScriptFunction) jjsObj.get("chooseFile"); 131 132 final NashornCompleter completer = new NashornCompleter(context, global, this, propsHelper, fileChooserFunc); 133 final ScriptFunction browseFunc = isHeadless? null : (ScriptFunction) jjsObj.get("browse"); 134 135 final ScriptFunction javadoc = (ScriptFunction) jjsObj.get("javadoc"); 136 137 try (final Console in = new Console(System.in, System.out, HIST_FILE, completer, 138 str -> { 139 try { 140 final Object res = context.eval(global, str, global, "<shell>"); 141 if (res != null && res != UNDEFINED) { 142 // Special case Java types: show the javadoc for the class. 143 if (!isHeadless && NativeJava.isType(UNDEFINED, res)) { 144 final String typeName = NativeJava.typeName(UNDEFINED, res).toString(); 145 final String url = typeName.replace('.', '/').replace('$', '.') + ".html"; 146 openBrowserForJavadoc(browseFunc, url); 147 } else if (!isHeadless && res instanceof NativeJavaPackage) { 148 final String pkgName = ((NativeJavaPackage)res).getName(); 149 final String url = pkgName.replace('.', '/') + "/package-summary.html"; 150 openBrowserForJavadoc(browseFunc, url); 151 } else if (NativeJava.isJavaMethod(UNDEFINED, res)) { 152 ScriptRuntime.apply(javadoc, UNDEFINED, res); 153 return ""; // javadoc function already prints javadoc 154 } else if (res instanceof ScriptObject) { 155 final ScriptObject sobj = (ScriptObject)res; 156 if (sobj.has(DOC_PROPERTY_NAME)) { 157 return toString(sobj.get(DOC_PROPERTY_NAME), global); 158 } else if (sobj instanceof ScriptFunction) { 159 return ((ScriptFunction)sobj).getDocumentation(); 160 } 161 } 162 163 // FIXME: better than toString for other cases? 164 return toString(res, global); 165 } 166 } catch (Exception ignored) { 167 } 168 return null; 169 })) { 170 171 global.addShellBuiltins(); 172 173 // redefine readLine to use jline Console's readLine! 174 ScriptingFunctions.setReadLineHelper(str-> { 175 try { 176 return in.readUserLine(str); 177 } catch (final IOException ioExp) { 178 throw new UncheckedIOException(ioExp); 179 } 180 }); 181 182 if (System.getSecurityManager() == null) { 183 final Consumer<String> evaluator = str -> { 184 // could be called from different thread (GUI), we need to handle Context set/reset 185 final Global _oldGlobal = Context.getGlobal(); 186 final boolean _globalChanged = (_oldGlobal != global); 187 if (_globalChanged) { 188 Context.setGlobal(global); 189 } 190 try { 191 evalImpl(context, global, str, err, env._dump_on_error); 192 } finally { 193 if (_globalChanged) { 194 Context.setGlobal(_oldGlobal); 195 } 196 } 197 }; 198 199 // expose history object for reflecting on command line history 200 global.addOwnProperty("history", Property.NOT_ENUMERABLE, new HistoryObject(in.getHistory(), err, evaluator)); 201 202 // 'edit' command 203 global.addOwnProperty("edit", Property.NOT_ENUMERABLE, new EditObject(in, err::println, evaluator)); 204 } 205 206 while (true) { 207 String source; 208 try { 209 source = in.readLine(prompt, prompt2); 210 } catch (final IOException ioe) { 211 err.println(ioe.toString()); 212 if (env._dump_on_error) { 213 ioe.printStackTrace(err); 214 } 215 return IO_ERROR; 216 } catch (final UserInterruptException ex) { 217 break; 218 } 219 220 if (source == null) { 221 break; 222 } 223 224 if (source.isEmpty()) { 225 continue; 226 } 227 228 try { 229 final Object res = context.eval(global, source, global, "<shell>"); 230 if (res != UNDEFINED) { 231 err.println(toString(res, global)); 232 } 233 } catch (final Exception exp) { 234 // Is this a ECMAScript SyntaxError at last column (of the single line)? 235 // If so, it is because parser expected more input but got EOF. Try to 236 // to more lines from the user (multiline edit support). 237 238 if (completer.isSyntaxErrorAt(exp, 1, source.length())) { 239 final String fullSrc = completer.readMoreLines(source, exp, in, prompt2, err); 240 241 // check if we succeeded in getting complete code. 242 if (fullSrc != null && !fullSrc.isEmpty()) { 243 evalImpl(context, global, fullSrc, err, env._dump_on_error); 244 } // else ignore, error reported already by 'completer.readMoreLines' 245 } else { 246 247 // can't read more lines to have parseable/complete code. 248 err.println(exp); 249 if (env._dump_on_error) { 250 exp.printStackTrace(err); 251 } 252 } 253 } 254 } 255 } catch (final Exception e) { 256 err.println(e); 257 if (env._dump_on_error) { 258 e.printStackTrace(err); 259 } 260 } finally { 261 if (globalChanged) { 262 Context.setGlobal(oldGlobal); 263 } 264 try { 265 propsHelper.close(); 266 } catch (final Exception exp) { 267 if (DEBUG) { 268 exp.printStackTrace(); 269 } 270 } 271 } 272 273 return SUCCESS; 274 } 275 276 static String getMessage(final String id) { 277 return bundle.getString(id); 278 } 279 280 private void evalImpl(final Context context, final Global global, final String source, 281 final PrintWriter err, final boolean doe) { 282 try { 283 final Object res = context.eval(global, source, global, "<shell>"); 284 if (res != UNDEFINED) { 285 err.println(toString(res, global)); 286 } 287 } catch (final Exception e) { 288 err.println(e); 289 if (doe) { 290 e.printStackTrace(err); 291 } 292 } 293 } 294 295 private static String JAVADOC_BASE = "https://docs.oracle.com/javase/%d/docs/api/"; 296 private static void openBrowserForJavadoc(ScriptFunction browse, String relativeUrl) { 297 try { 298 final URI uri = new URI(String.format(JAVADOC_BASE, Runtime.version().feature()) + relativeUrl); 299 ScriptRuntime.apply(browse, null, uri); 300 } catch (Exception ignored) { 301 } 302 } 303 304 private static String readJJSScript() { 305 return AccessController.doPrivileged( 306 new PrivilegedAction<String>() { 307 @Override 308 public String run() { 309 try { 310 final InputStream resStream = Main.class.getResourceAsStream("resources/jjs.js"); 311 if (resStream == null) { 312 throw new RuntimeException("resources/jjs.js is missing!"); 313 } 314 return new String(Source.readFully(resStream)); 315 } catch (final IOException exp) { 316 throw new RuntimeException(exp); 317 } 318 } 319 }); 320 } 321 }