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