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