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