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