Main.java revision 1395:6263188b48de
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
26package jdk.nashorn.tools.jjs;
27
28import java.awt.GraphicsEnvironment;
29import java.io.BufferedReader;
30import java.io.File;
31import java.io.InputStream;
32import java.io.InputStreamReader;
33import java.io.IOException;
34import java.io.OutputStream;
35import java.io.PrintWriter;
36import java.util.function.Consumer;
37import jdk.internal.jline.console.completer.Completer;
38import jdk.internal.jline.console.UserInterruptException;
39import jdk.nashorn.api.scripting.NashornException;
40import jdk.nashorn.internal.objects.Global;
41import jdk.nashorn.internal.runtime.Context;
42import jdk.nashorn.internal.runtime.JSType;
43import jdk.nashorn.internal.runtime.Property;
44import jdk.nashorn.internal.runtime.ScriptEnvironment;
45import jdk.nashorn.internal.runtime.ScriptRuntime;
46import jdk.nashorn.tools.Shell;
47
48/**
49 * Interactive command line Shell for Nashorn.
50 */
51public 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.isEmpty()) {
158                    continue;
159                }
160
161                try {
162                    final Object res = context.eval(global, source, global, "<shell>");
163                    if (res != ScriptRuntime.UNDEFINED) {
164                        err.println(JSType.toString(res));
165                    }
166                } catch (final Exception exp) {
167                    // Is this a ECMAScript SyntaxError at last column (of the single line)?
168                    // If so, it is because parser expected more input but got EOF. Try to
169                    // to more lines from the user (multiline edit support).
170
171                    if (completer.isSyntaxErrorAt(exp, 1, source.length())) {
172                        final String fullSrc = completer.readMoreLines(source, exp, in, prompt2, err);
173
174                        // check if we succeeded in getting complete code.
175                        if (fullSrc != null && !fullSrc.isEmpty()) {
176                            evalImpl(context, global, fullSrc, err, env._dump_on_error);
177                        } // else ignore, error reported already by 'completer.readMoreLines'
178                    } else {
179
180                        // can't read more lines to have parseable/complete code.
181                        err.println(exp);
182                        if (env._dump_on_error) {
183                            exp.printStackTrace(err);
184                        }
185                    }
186                }
187            }
188        } catch (final Exception e) {
189            err.println(e);
190            if (env._dump_on_error) {
191                e.printStackTrace(err);
192            }
193        } finally {
194            if (globalChanged) {
195                Context.setGlobal(oldGlobal);
196            }
197            try {
198                propsHelper.close();
199            } catch (final Exception exp) {
200                if (DEBUG) {
201                    exp.printStackTrace();
202                }
203            }
204        }
205
206        return SUCCESS;
207    }
208
209    static String getMessage(final String id) {
210        return bundle.getString(id);
211    }
212
213    private void evalImpl(final Context context, final Global global, final String source,
214            final PrintWriter err, final boolean doe) {
215        try {
216            final Object res = context.eval(global, source, global, "<shell>");
217            if (res != ScriptRuntime.UNDEFINED) {
218                err.println(JSType.toString(res));
219            }
220        } catch (final Exception e) {
221            err.println(e);
222            if (doe) {
223                e.printStackTrace(err);
224            }
225        }
226    }
227}
228