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 java.awt.GraphicsEnvironment;
  29 import java.io.BufferedReader;
  30 import java.io.File;
  31 import java.io.InputStream;
  32 import java.io.InputStreamReader;
  33 import java.io.IOException;
  34 import java.io.OutputStream;
  35 import java.io.PrintWriter;
  36 import java.util.function.Consumer;
  37 import jdk.internal.jline.console.completer.Completer;
  38 import jdk.internal.jline.console.UserInterruptException;
  39 import jdk.nashorn.api.scripting.NashornException;
  40 import jdk.nashorn.internal.objects.Global;
  41 import jdk.nashorn.internal.runtime.Context;
  42 import jdk.nashorn.internal.runtime.JSType;
  43 import jdk.nashorn.internal.runtime.Property;
  44 import jdk.nashorn.internal.runtime.ScriptEnvironment;
  45 import jdk.nashorn.internal.runtime.ScriptRuntime;
  46 import jdk.nashorn.tools.Shell;
  47 
  48 /**
  49  * Interactive command line Shell for Nashorn.
  50  */
  51 public final class Main extends Shell {
  52     private Main() {}
  53 
  54     static final boolean DEBUG = Boolean.getBoolean("nashorn.jjs.debug");
  55     static final boolean HEADLESS = GraphicsEnvironment.isHeadless();
  56 
  57     // file where history is persisted.
  58     private static final File HIST_FILE = new File(new File(System.getProperty("user.home")), ".jjs.history");
  59 
  60     /**
  61      * Main entry point with the default input, output and error streams.
  62      *
  63      * @param args The command line arguments
  64      */
  65     public static void main(final String[] args) {
  66         try {
  67             final int exitCode = main(System.in, System.out, System.err, args);
  68             if (exitCode != SUCCESS) {
  69                 System.exit(exitCode);
  70             }
  71         } catch (final IOException e) {
  72             System.err.println(e); //bootstrapping, Context.err may not exist
  73             System.exit(IO_ERROR);
  74         }
  75     }
  76 
  77     /**
  78      * Starting point for executing a {@code Shell}. Starts a shell with the
  79      * given arguments and streams and lets it run until exit.
  80      *
  81      * @param in input stream for Shell
  82      * @param out output stream for Shell
  83      * @param err error stream for Shell
  84      * @param args arguments to Shell
  85      *
  86      * @return exit code
  87      *
  88      * @throws IOException if there's a problem setting up the streams
  89      */
  90     public static int main(final InputStream in, final OutputStream out, final OutputStream err, final String[] args) throws IOException {
  91         return new Main().run(in, out, err, args);
  92     }
  93 
  94 
  95     /**
  96      * read-eval-print loop for Nashorn shell.
  97      *
  98      * @param context the nashorn context
  99      * @param global  global scope object to use
 100      * @return return code
 101      */
 102     protected int readEvalPrint(final Context context, final Global global) {
 103         final ScriptEnvironment env = context.getEnv();
 104         final String prompt = bundle.getString("shell.prompt");
 105         final String prompt2 = bundle.getString("shell.prompt2");
 106         final PrintWriter err = context.getErr();
 107         final Global oldGlobal = Context.getGlobal();
 108         final boolean globalChanged = (oldGlobal != global);
 109         final PropertiesHelper propsHelper = new PropertiesHelper(env._classpath);
 110         final NashornCompleter completer = new NashornCompleter(context, global, this, propsHelper);
 111 
 112         try (final Console in = new Console(System.in, System.out, HIST_FILE, completer)) {
 113             if (globalChanged) {
 114                 Context.setGlobal(global);
 115             }
 116 
 117             global.addShellBuiltins();
 118 
 119             if (System.getSecurityManager() == null) {
 120                 final Consumer<String> evaluator = str -> {
 121                     // could be called from different thread (GUI), we need to handle Context set/reset
 122                     final Global _oldGlobal = Context.getGlobal();
 123                     final boolean _globalChanged = (oldGlobal != global);
 124                     if (_globalChanged) {
 125                         Context.setGlobal(global);
 126                     }
 127                     try {
 128                         evalImpl(context, global, str, err, env._dump_on_error);
 129                     } finally {
 130                         if (_globalChanged) {
 131                             Context.setGlobal(_oldGlobal);
 132                         }
 133                     }
 134                 };
 135 
 136                 // expose history object for reflecting on command line history
 137                 global.addOwnProperty("history", Property.NOT_ENUMERABLE, new HistoryObject(in.getHistory(), err, evaluator));
 138 
 139                 // 'edit' command
 140                 global.addOwnProperty("edit", Property.NOT_ENUMERABLE, new EditObject(in, err::println, evaluator));
 141             }
 142 
 143             while (true) {
 144                 String source = "";
 145                 try {
 146                     source = in.readLine(prompt);
 147                 } catch (final IOException ioe) {
 148                     err.println(ioe.toString());
 149                     if (env._dump_on_error) {
 150                         ioe.printStackTrace(err);
 151                     }
 152                     return IO_ERROR;
 153                 } catch (final UserInterruptException ex) {
 154                     break;
 155                 }
 156 
 157                 if (source == null) {
 158                     break;
 159                 }
 160 
 161                 if (source.isEmpty()) {
 162                     continue;
 163                 }
 164 
 165                 try {
 166                     final Object res = context.eval(global, source, global, "<shell>");
 167                     if (res != ScriptRuntime.UNDEFINED) {
 168                         err.println(toString(res, global));
 169                     }
 170                 } catch (final Exception exp) {
 171                     // Is this a ECMAScript SyntaxError at last column (of the single line)?
 172                     // If so, it is because parser expected more input but got EOF. Try to
 173                     // to more lines from the user (multiline edit support).
 174 
 175                     if (completer.isSyntaxErrorAt(exp, 1, source.length())) {
 176                         final String fullSrc = completer.readMoreLines(source, exp, in, prompt2, err);
 177 
 178                         // check if we succeeded in getting complete code.
 179                         if (fullSrc != null && !fullSrc.isEmpty()) {
 180                             evalImpl(context, global, fullSrc, err, env._dump_on_error);
 181                         } // else ignore, error reported already by 'completer.readMoreLines'
 182                     } else {
 183 
 184                         // can't read more lines to have parseable/complete code.
 185                         err.println(exp);
 186                         if (env._dump_on_error) {
 187                             exp.printStackTrace(err);
 188                         }
 189                     }
 190                 }
 191             }
 192         } catch (final Exception e) {
 193             err.println(e);
 194             if (env._dump_on_error) {
 195                 e.printStackTrace(err);
 196             }
 197         } finally {
 198             if (globalChanged) {
 199                 Context.setGlobal(oldGlobal);
 200             }
 201             try {
 202                 propsHelper.close();
 203             } catch (final Exception exp) {
 204                 if (DEBUG) {
 205                     exp.printStackTrace();
 206                 }
 207             }
 208         }
 209 
 210         return SUCCESS;
 211     }
 212 
 213     static String getMessage(final String id) {
 214         return bundle.getString(id);
 215     }
 216 
 217     private void evalImpl(final Context context, final Global global, final String source,
 218             final PrintWriter err, final boolean doe) {
 219         try {
 220             final Object res = context.eval(global, source, global, "<shell>");
 221             if (res != ScriptRuntime.UNDEFINED) {
 222                 err.println(JSType.toString(res));
 223             }
 224         } catch (final Exception e) {
 225             err.println(e);
 226             if (doe) {
 227                 e.printStackTrace(err);
 228             }
 229         }
 230     }
 231 }