File: Main.java

package info (click to toggle)
rhino 1.5.R2-2
  • links: PTS
  • area: contrib
  • in suites: woody
  • size: 2,892 kB
  • ctags: 4,275
  • sloc: java: 38,225; xml: 208; makefile: 48; sh: 8
file content (380 lines) | stat: -rw-r--r-- 13,993 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * The contents of this file are subject to the Netscape Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/NPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is Rhino code, released
 * May 6, 1998.
 *
 * The Initial Developer of the Original Code is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1997-1999 Netscape Communications Corporation. All
 * Rights Reserved.
 *
 * Contributor(s): 
 * Patrick Beard
 * Norris Boyd
 * Rob Ginda
 * Kurt Westerfeld
 *
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU Public License (the "GPL"), in which case the
 * provisions of the GPL are applicable instead of those above.
 * If you wish to allow use of your version of this file only
 * under the terms of the GPL and not to allow others to use your
 * version of this file under the NPL, indicate your decision by
 * deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL.  If you do not delete
 * the provisions above, a recipient may use your version of this
 * file under either the NPL or the GPL.
 */

package org.mozilla.javascript.tools.shell;

import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.ToolErrorReporter;

/**
 * The shell program.
 *
 * Can execute scripts interactively or in batch mode at the command line.
 * An example of controlling the JavaScript engine.
 *
 * @author Norris Boyd
 */
public class Main {

    /**
     * Main entry point.
     *
     * Process arguments as would a normal Java program. Also
     * create a new Context and associate it with the current thread.
     * Then set up the execution environment and begin to
     * execute scripts.
     */
    public static void main(String args[]) {
        int result = exec(args);
        if (result != 0)
            System.exit(result);
    }
    
    /**
     *  Execute the given arguments, but don't System.exit at the end.
     */
    public static int exec(String args[]) {
        Context cx = Context.enter();
        // Create the top-level scope object.
        global = new Global(cx);
        errorReporter = new ToolErrorReporter(false, global.getErr());
        cx.setErrorReporter(errorReporter);

        args = processOptions(cx, args);

        int skip = 0;
        if (fileList.size() == 0 && args.length > 0) {
            skip = 1;
            fileList.addElement(args[0]);
        }
        if (processStdin)
            fileList.addElement(null);

        // get the command line arguments after the name of the script,
        // and define "arguments" array in the top-level object
        Object[] array = args;
        if (args.length > 0) {
            int length = args.length - skip;
            array = new Object[length];
            System.arraycopy(args, skip, array, 0, length);
        }
        Scriptable argsObj = cx.newArray(global, array);
        global.defineProperty("arguments", argsObj,
                              ScriptableObject.DONTENUM);
        
        for (int i=0; i < fileList.size(); i++) {
            processSource(cx, (String) fileList.get(i));
        }

        cx.exit();
        return exitCode;
    }

    /**
     * Parse arguments.
     */
    public static String[] processOptions(Context cx, String args[]) {
        cx.setTargetPackage("");    // default to no package
        for (int i=0; i < args.length; i++) {
            String arg = args[i];
            if (!arg.startsWith("-")) {
                processStdin = false;
                String[] result = new String[args.length - i];
                System.arraycopy(args, i, result, 0, args.length - i);
                return result;
            }
            if (arg.equals("-version")) {
                if (++i == args.length)
                    usage(arg);
                double d = cx.toNumber(args[i]);
                if (d != d)
                    usage(arg);
                cx.setLanguageVersion((int) d);
                continue;
            }
            if (arg.equals("-opt") || arg.equals("-O")) {
                if (++i == args.length)
                    usage(arg);
                double d = cx.toNumber(args[i]);
                if (d != d)
                    usage(arg);
                cx.setOptimizationLevel((int)d);
                continue;
            }
            if (arg.equals("-e")) {
                processStdin = false;
                if (++i == args.length)
                    usage(arg);
                Reader reader = new StringReader(args[i]);
                evaluateReader(cx, global, reader, "<command>", 1);
                continue;
            }
            if (arg.equals("-w")) {
                errorReporter.setIsReportingWarnings(true);
                continue;
            }
            if (arg.equals("-f")) {
                processStdin = false;
                if (++i == args.length)
                    usage(arg);
                fileList.addElement(args[i].equals("-") ? null : args[i]);
                continue;
            }
            usage(arg);
        }
        return new String[0];
    }

    /**
     * Print a usage message.
     */
    public static void usage(String s) {
        p(ToolErrorReporter.getMessage("msg.shell.usage", s));
        System.exit(1);
    }

    /**
     * Evaluate JavaScript source.
     *
     * @param cx the current context
     * @param filename the name of the file to compile, or null
     *                 for interactive mode.
     */
    public static void processSource(Context cx, String filename) {
        if (filename == null || filename.equals("-")) {
            // Use the interpreter for interactive input
            cx.setOptimizationLevel(-1);
            
            BufferedReader in = new BufferedReader
                (new InputStreamReader(global.getIn()));
            int lineno = 1;
            boolean hitEOF = false;
            while (!hitEOF) {
                int startline = lineno;
                if (filename == null)
                    global.getErr().print("js> ");
                global.getErr().flush();
                String source = "";
                    
                // Collect lines of source to compile.
                while (true) {
                    String newline;
                    try {
                        newline = in.readLine();
                    }
                    catch (IOException ioe) {
                        global.getErr().println(ioe.toString());
                        break;
                    }
                    if (newline == null) {
                        hitEOF = true;
                        break;
                    }
                    source = source + newline + "\n";
                    lineno++;
                    if (cx.stringIsCompilableUnit(source))
                        break;
                }
                Reader reader = new StringReader(source);
                Object result = evaluateReader(cx, global, reader, 
                                               "<stdin>", startline);
                if (result != cx.getUndefinedValue()) {
                    try {
                        global.getErr().println(cx.toString(result));
                    } catch (EcmaError ee) {
                        String msg = ToolErrorReporter.getMessage(
                            "msg.uncaughtJSException", ee.toString());
                        exitCode = EXITCODE_RUNTIME_ERROR;
                        if (ee.getSourceName() != null) {
                            Context.reportError(msg, ee.getSourceName(), 
                                                ee.getLineNumber(), 
                                                ee.getLineSource(), 
                                                ee.getColumnNumber());
                        } else {
                            Context.reportError(msg);
                        }
                    }
                }
                NativeArray h = global.history;
                h.put((int)h.jsGet_length(), h, source);
            }
            global.getErr().println();
        } else processFile(cx, global, filename);
        System.gc();
    }
    
    public static void processFile(Context cx, Scriptable scope,
                                   String filename)
    {
            Reader in = null;
            try {
                in = new PushbackReader(new FileReader(filename));
                int c = in.read();
                // Support the executable script #! syntax:  If
                // the first line begins with a '#', treat the whole
                // line as a comment.
                if (c == '#') {
                    while ((c = in.read()) != -1) {
                        if (c == '\n' || c == '\r')
                            break;
                    }
                    ((PushbackReader) in).unread(c);
                } else {
                    // No '#' line, just reopen the file and forget it
                    // ever happened.  OPT closing and reopening
                    // undoubtedly carries some cost.  Is this faster
                    // or slower than leaving the PushbackReader
                    // around?
                    in.close();
                    in = new FileReader(filename);
                }
                filename = new java.io.File(filename).getCanonicalPath();
            }
            catch (FileNotFoundException ex) {
                Context.reportError(ToolErrorReporter.getMessage(
                    "msg.couldnt.open",
                    filename));
                exitCode = EXITCODE_FILE_NOT_FOUND;
                return;
            } catch (IOException ioe) {
                global.getErr().println(ioe.toString());
            }
            
            // Here we evalute the entire contents of the file as
            // a script. Text is printed only if the print() function
            // is called.
            evaluateReader(cx, scope, in, filename, 1);
    }

    public static Object evaluateReader(Context cx, Scriptable scope, 
                                        Reader in, String sourceName, 
                                        int lineno)
    {
        Object result = cx.getUndefinedValue();
        try {
            result = cx.evaluateReader(scope, in, sourceName, lineno, null);
        }
        catch (WrappedException we) {
            global.getErr().println(we.getWrappedException().toString());
            we.printStackTrace();
        }
        catch (EcmaError ee) {
            String msg = ToolErrorReporter.getMessage(
                "msg.uncaughtJSException", ee.toString());
            exitCode = EXITCODE_RUNTIME_ERROR;
            if (ee.getSourceName() != null) {
                Context.reportError(msg, ee.getSourceName(), 
                                    ee.getLineNumber(), 
                                    ee.getLineSource(), 
                                    ee.getColumnNumber());
            } else {
                Context.reportError(msg);
            }
        }
        catch (EvaluatorException ee) {
            // Already printed message.
            exitCode = EXITCODE_RUNTIME_ERROR;
        }
        catch (JavaScriptException jse) {
	    	// Need to propagate ThreadDeath exceptions.
	    	Object value = jse.getValue();
	    	if (value instanceof ThreadDeath)
	    		throw (ThreadDeath) value;
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(ToolErrorReporter.getMessage(
                "msg.uncaughtJSException",
                jse.getMessage()));
        }
        catch (IOException ioe) {
            global.getErr().println(ioe.toString());
        }
        finally {
            try {
                in.close();
            }
            catch (IOException ioe) {
                global.getErr().println(ioe.toString());
            }
        }
        return result;
    }

    private static void p(String s) {
        global.getOut().println(s);
    }
    
    public static ScriptableObject getScope() {
        return global;
    }

    public static InputStream getIn() {
        return Global.getInstance(global).getIn();
    }
    
    public static void setIn(InputStream in) {
        Global.getInstance(global).setIn(in);
    }

    public static PrintStream getOut() {
        return Global.getInstance(global).getOut();
    }
    
    public static void setOut(PrintStream out) {
        Global.getInstance(global).setOut(out);
    }

    public static PrintStream getErr() { 
        return Global.getInstance(global).getErr();
    }

    public static void setErr(PrintStream err) {
        Global.getInstance(global).setErr(err);
    }

    static protected ToolErrorReporter errorReporter;
    static protected Global global;
    static protected int exitCode = 0;
    static private final int EXITCODE_RUNTIME_ERROR = 3;
    static private final int EXITCODE_FILE_NOT_FOUND = 4;
    //static private DebugShell debugShell;
    static boolean processStdin = true;
    static Vector fileList = new Vector(5);
}