Source Code Cross Referenced for repl.java in  » Scripting » Kawa » kawa » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Scripting » Kawa » kawa 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        package kawa;
002:
003:        import java.io.*;
004:        import java.net.*;
005:        import gnu.mapping.*;
006:        import gnu.expr.*;
007:        import gnu.text.SourceMessages;
008:        import gnu.text.SyntaxException;
009:        import gnu.lists.*;
010:        import java.util.Vector;
011:        import gnu.bytecode.ClassType;
012:
013:        /** Start a "Read-Eval-Print-Loop" for the Kawa Scheme evaluator. */
014:
015:        public class repl extends Procedure0or1 {
016:            public static String compilationTopname = null;
017:
018:            Language language;
019:            static Language previousLanguage;
020:
021:            public repl(Language language) {
022:                this .language = language;
023:            }
024:
025:            public Object apply0() {
026:                Shell.run(language, Environment.getCurrent());
027:                return Values.empty;
028:            }
029:
030:            public Object apply1(Object env) {
031:                Shell.run(language, (Environment) env);
032:                return Values.empty;
033:            }
034:
035:            static void bad_option(String str) {
036:                System.err.println("kawa: bad option '" + str + "'");
037:                printOptions(System.err);
038:                System.exit(-1);
039:            }
040:
041:            public static void printOption(PrintStream out, String option,
042:                    String doc) {
043:                out.print(" ");
044:                out.print(option);
045:
046:                int len = option.length() + 1;
047:                for (int i = 0; i < 30 - len; ++i)
048:                    out.print(" ");
049:                out.print(" ");
050:                out.println(doc);
051:            }
052:
053:            public static void printOptions(PrintStream out) {
054:                out.println("Usage: [java kawa.repl | kawa] [options ...]");
055:                out.println();
056:                out.println(" Generic options:");
057:                printOption(out, "--help", "Show help about options");
058:                printOption(out, "--author", "Show author information");
059:                printOption(out, "--version", "Show version information");
060:                out.println();
061:                out.println(" Options");
062:                printOption(out, "-e <expr>", "Evaluate expression <expr>");
063:                printOption(out, "-c <expr>",
064:                        "Same as -e, but make sure ~/.kawarc.scm is run first");
065:                printOption(out, "-f <filename>", "File to interpret");
066:                printOption(out, "-s| --",
067:                        "Start reading commands interactively from console");
068:                printOption(out, "-w", "Launch the interpreter in a GUI window");
069:                printOption(out, "--server <port>",
070:                        "Start a server accepting telnet connections on <port>");
071:                printOption(out, "--debug-dump-zip",
072:                        "Compiled interactive expressions to a zip archive");
073:                printOption(out, "--debug-print-expr",
074:                        "Print generated internal expressions");
075:                printOption(out, "--debug-print-final-expr",
076:                        "Print expression after any optimizations");
077:                printOption(out, "--debug-error-prints-stack-trace",
078:                        "Print stack trace with errors");
079:                printOption(out, "--debug-warning-prints-stack-trace",
080:                        "Print stack trace with warnings");
081:                printOption(out, "--[no-]full-tailcalls",
082:                        "(Don't) use full tail-calls");
083:                printOption(out, "-C <filename> ...",
084:                        "Compile named files to Java class files");
085:                printOption(out, "--output-format <format>",
086:                        "Use <format> when printing top-level output");
087:                printOption(out, "--<language>",
088:                        "Select source language, one of:");
089:                String[][] languages = Language.getLanguages();
090:                for (int i = 0; i < languages.length; i++) {
091:                    out.print("   ");
092:                    String[] lang = languages[i];
093:                    // skip last entry, which is class name
094:                    int nwords = lang.length - 1;
095:                    for (int j = 0; j < nwords; j++)
096:                        out.print(lang[j] + " ");
097:                    if (i == 0)
098:                        out.print("[default]");
099:                    out.println();
100:                }
101:                out
102:                        .println(" Compilation options, must be specified before -C");
103:                printOption(out, "-d <dirname>",
104:                        "Directory to place .class files in");
105:                printOption(out, "-P <prefix>",
106:                        "Prefix to prepand to class names");
107:                printOption(out, "-T <topname>",
108:                        "name to give to top-level class");
109:
110:                printOption(out, "--main",
111:                        "Generate an application, with a main method");
112:                printOption(out, "--applet", "Generate an applet");
113:                printOption(out, "--servlet", "Generate a servlet");
114:                printOption(out, "--module-static",
115:                        "Top-leval definitions are by default static");
116:
117:                Vector keys = Compilation.options.keys();
118:                for (int i = 0; i < keys.size(); ++i) {
119:                    String name = (String) keys.get(i);
120:                    printOption(out, "--" + name, Compilation.options
121:                            .getDoc(name));
122:                }
123:
124:                out.println();
125:                out
126:                        .println("For more information go to:  http://www.gnu.org/software/kawa/");
127:            }
128:
129:            /** Number of times exitDecrement calls before we exit. */
130:            private static int exitCounter;
131:
132:            /** See exitDecrement. */
133:            public static synchronized void exitIncrement() {
134:                if (exitCounter == 0)
135:                    exitCounter++;
136:                exitCounter++;
137:            }
138:
139:            /** Work around an AWT bug, where AWT threads are non-daemon.
140:             * Thus if you start up AWT, the JVM will wait for the AWT to finish,
141:             * even if there are no other non-daemon threads.
142:             * So call exitIncrement() each time a Freme is created,
143:             * and call exitDecrement() a Frame is closed. */
144:            public static synchronized void exitDecrement() {
145:                int counter = exitCounter;
146:                if (counter > 0) {
147:                    counter--;
148:                    if (counter == 0) {
149:                        System.exit(0);
150:                    } else
151:                        exitCounter = counter;
152:                }
153:            }
154:
155:            public static String[] commandLineArgArray;
156:            public static FVector commandLineArguments;
157:
158:            public static String homeDirectory;
159:
160:            static void checkInitFile() {
161:                /* Set homeDirectory;  if first time called, run ~/.kawarc.scm. */
162:                if (homeDirectory == null) {
163:                    File initFile = null;
164:                    homeDirectory = System.getProperty("user.home");
165:                    Object scmHomeDirectory;
166:                    if (homeDirectory != null) {
167:                        scmHomeDirectory = new FString(homeDirectory);
168:                        String file_separator = System
169:                                .getProperty("file.separator");
170:                        String kawarc_name = "/".equals(file_separator) ? ".kawarc.scm"
171:                                : "kawarc.scm";
172:                        initFile = new File(homeDirectory, kawarc_name);
173:                    } else
174:                        scmHomeDirectory = Boolean.FALSE;
175:                    Environment.getCurrent().put("home-directory",
176:                            scmHomeDirectory);
177:                    if (initFile != null && initFile.exists())
178:                        Shell.runFile(initFile.getPath(), 0);
179:                }
180:            }
181:
182:            public static void setArgs(String[] args, int arg_start) {
183:                int nargs = args.length - arg_start;
184:                Object[] array = new Object[nargs];
185:                if (arg_start == 0)
186:                    commandLineArgArray = args;
187:                else {
188:                    String[] strings = new String[nargs];
189:                    for (int i = nargs; --i >= 0;)
190:                        strings[i] = args[i + arg_start];
191:                    commandLineArgArray = strings;
192:                }
193:                for (int i = nargs; --i >= 0;)
194:                    array[i] = new FString(args[i + arg_start]);
195:                commandLineArguments = new FVector(array); // FIXME scsh has list
196:                // FIXME scsh also has command-line proc
197:                Environment.getCurrent().put("command-line-arguments",
198:                        commandLineArguments);
199:            }
200:
201:            public static void getLanguageFromFilenameExtension(String name) {
202:                if (previousLanguage == null) {
203:                    previousLanguage = Language
204:                            .getInstanceFromFilenameExtension(name);
205:                    if (previousLanguage != null) {
206:                        Language.setDefaults(previousLanguage);
207:                        return;
208:                    }
209:                }
210:                getLanguage();
211:            }
212:
213:            public static void getLanguage() {
214:                if (previousLanguage == null) {
215:                    previousLanguage = Language.getInstance(null);
216:                    Language.setDefaults(previousLanguage);
217:                }
218:            }
219:
220:            static boolean shutdownRegistered = gnu.text.WriterManager.instance
221:                    .registerShutdownHook();
222:
223:            public static int processArgs(String[] args, int iArg, int maxArg) {
224:                boolean something_done = false;
225:                for (; iArg < maxArg; iArg++) {
226:                    String arg = args[iArg];
227:                    if (arg.equals("-c") || arg.equals("-e")) {
228:                        iArg++;
229:                        if (iArg == maxArg)
230:                            bad_option(arg);
231:                        getLanguage();
232:                        setArgs(args, iArg + 1);
233:                        if (arg.equals("-c"))
234:                            checkInitFile();
235:                        Language language = Language.getDefaultLanguage();
236:                        Shell.runString(args[iArg], language, Environment
237:                                .getCurrent());
238:                        something_done = true;
239:                    } else if (arg.equals("-f")) {
240:                        iArg++;
241:                        if (iArg == maxArg)
242:                            bad_option(arg);
243:                        String filename = args[iArg];
244:                        getLanguageFromFilenameExtension(filename);
245:                        setArgs(args, iArg + 1);
246:                        checkInitFile();
247:                        Shell.runFile(filename, 0);
248:                        something_done = true;
249:                    } else if (arg.startsWith("--script")) {
250:                        String count = arg.substring(8);
251:                        iArg++;
252:                        int skipLines = 0;
253:                        if (count.length() > 0) {
254:                            try {
255:                                skipLines = Integer.parseInt(count);
256:                            } catch (Throwable ex) {
257:                                iArg = maxArg; // force bad_option.
258:                            }
259:                        }
260:                        if (iArg == maxArg)
261:                            bad_option(arg);
262:                        String filename = args[iArg];
263:                        getLanguageFromFilenameExtension(filename);
264:                        setArgs(args, iArg + 1);
265:                        checkInitFile();
266:                        Shell.runFile(filename, skipLines);
267:                        return -1;
268:                    } else if (arg.equals("\\")) {
269:                        // Scsh-like "meta-arg".  See Kawa manual (SOON-FIXME).
270:                        if (++iArg == maxArg)
271:                            bad_option(arg);
272:                        String filename = args[iArg];
273:                        InPort freader;
274:                        try {
275:                            InputStream fstream = new BufferedInputStream(
276:                                    new FileInputStream(filename));
277:                            int ch = fstream.read();
278:                            if (ch == '#') {
279:                                StringBuffer sbuf = new StringBuffer(100);
280:                                Vector xargs = new Vector(10);
281:                                int state = 0;
282:                                while (ch != '\n' && ch != '\r' && ch >= 0)
283:                                    ch = fstream.read();
284:                                for (;;) {
285:                                    ch = fstream.read();
286:                                    if (ch < 0) {
287:                                        System.err
288:                                                .println("unexpected end-of-file processing argument line for: '"
289:                                                        + filename + '\'');
290:                                        System.exit(-1);
291:                                    }
292:                                    if (state == 0) {
293:                                        if (ch == '\\' || ch == '\''
294:                                                || ch == '\"') {
295:                                            state = ch;
296:                                            continue;
297:                                        } else if (ch == '\n' || ch == '\r')
298:                                            break;
299:                                        else if (ch == ' ' || ch == '\t') {
300:                                            if (sbuf.length() > 0) {
301:                                                xargs.addElement(sbuf
302:                                                        .toString());
303:                                                sbuf.setLength(0);
304:                                            }
305:                                            continue;
306:                                        }
307:                                    } else if (state == '\\')
308:                                        state = 0;
309:                                    else if (ch == state) {
310:                                        state = 0;
311:                                        continue;
312:                                    }
313:                                    sbuf.append((char) ch);
314:                                }
315:                                if (sbuf.length() > 0)
316:                                    xargs.addElement(sbuf.toString());
317:                                int nxargs = xargs.size();
318:                                if (nxargs > 0) {
319:                                    String[] sargs = new String[nxargs];
320:                                    xargs.copyInto(sargs);
321:                                    int ixarg = processArgs(sargs, 0, nxargs);
322:                                    if (ixarg >= 0 && ixarg < nxargs) { // FIXME
323:                                        System.err.println(""
324:                                                + (nxargs - ixarg)
325:                                                + " unused meta args");
326:                                    }
327:                                }
328:                            }
329:                            getLanguageFromFilenameExtension(filename);
330:                            freader = InPort.openFile(fstream, filename);
331:                            // FIXME adjust line number
332:                            setArgs(args, iArg + 1);
333:                            checkInitFile();
334:                            kawa.standard.load.loadSource(freader, Environment
335:                                    .user(), null);
336:                            return -1;
337:                        } catch (SyntaxException ex) {
338:                            ex.printAll(OutPort.errDefault(), 20);
339:                        } catch (java.io.FileNotFoundException ex) {
340:                            System.err.println("Cannot open file " + filename);
341:                            System.exit(1);
342:                        } catch (Throwable ex) {
343:                            ex.printStackTrace(System.err);
344:                            System.exit(1);
345:                        }
346:                        return -1;
347:                    } else if (arg.equals("-s") || arg.equals("--")) {
348:                        iArg++;
349:                        getLanguage();
350:                        setArgs(args, iArg);
351:                        checkInitFile();
352:                        Shell.run(Language.getDefaultLanguage(), Environment
353:                                .getCurrent());
354:                        return -1;
355:                    } else if (arg.equals("-w")) {
356:                        iArg++;
357:                        getLanguage();
358:                        setArgs(args, iArg);
359:                        checkInitFile();
360:                        // Do this instead of just new GuiConsole in case we have
361:                        // configured --without-awt.
362:                        try {
363:                            Class.forName("kawa.GuiConsole").newInstance();
364:                        } catch (Exception ex) {
365:                            System.err.println("failed to create Kawa window: "
366:                                    + ex);
367:                            System.exit(-1);
368:                        }
369:                        something_done = true;
370:                    } else if (arg.equals("-d")) {
371:                        iArg++;
372:                        if (iArg == maxArg)
373:                            bad_option(arg);
374:                        ModuleManager manager = ModuleManager.getInstance();
375:                        manager.setCompilationDirectory(args[iArg]);
376:                    } else if (arg.equals("-P")) {
377:                        iArg++;
378:                        if (iArg == maxArg)
379:                            bad_option(arg);
380:                        Compilation.classPrefixDefault = args[iArg];
381:                    } else if (arg.equals("-T")) {
382:                        iArg++;
383:                        if (iArg == maxArg)
384:                            bad_option(arg);
385:                        compilationTopname = args[iArg];
386:                    } else if (arg.equals("-C")) {
387:                        ++iArg;
388:                        if (iArg == maxArg)
389:                            bad_option(arg);
390:                        compileFiles(args, iArg, maxArg);
391:                        return -1;
392:                    } else if (arg.equals("--output-format")
393:                            || arg.equals("--format")) {
394:                        if (++iArg == maxArg)
395:                            bad_option(arg);
396:                        Shell.setDefaultFormat(args[iArg]);
397:                    } else if (arg.equals("--connect")) {
398:                        ++iArg;
399:                        if (iArg == maxArg)
400:                            bad_option(arg);
401:                        int port;
402:                        if (args[iArg].equals("-"))
403:                            port = 0;
404:                        else {
405:                            try {
406:                                port = Integer.parseInt(args[iArg]);
407:                            } catch (NumberFormatException ex) {
408:                                bad_option("--connect port#");
409:                                port = -1; // never seen.
410:                            }
411:                        }
412:                        try {
413:                            Socket socket = new Socket(InetAddress
414:                                    .getByName(null), port);
415:                            Telnet conn = new Telnet(socket, true);
416:                            java.io.InputStream sin = conn.getInputStream();
417:                            java.io.OutputStream sout = conn.getOutputStream();
418:                            java.io.PrintStream pout = new PrintStream(sout,
419:                                    true);
420:                            System.setIn(sin);
421:                            System.setOut(pout);
422:                            System.setErr(pout);
423:                        } catch (java.io.IOException ex) {
424:                            ex.printStackTrace(System.err);
425:                            throw new Error(ex.toString());
426:                        }
427:                    } else if (arg.equals("--server")) {
428:                        getLanguage();
429:                        ++iArg;
430:                        if (iArg == maxArg)
431:                            bad_option(arg);
432:                        int port;
433:                        if (args[iArg].equals("-"))
434:                            port = 0;
435:                        else {
436:                            try {
437:                                port = Integer.parseInt(args[iArg]);
438:                            } catch (NumberFormatException ex) {
439:                                bad_option("--server port#");
440:                                port = -1; // never seen.
441:                            }
442:                        }
443:                        try {
444:                            java.net.ServerSocket ssocket = new java.net.ServerSocket(
445:                                    port);
446:                            port = ssocket.getLocalPort();
447:                            System.err.println("Listening on port " + port);
448:                            for (;;) {
449:                                System.err.print("waiting ... ");
450:                                System.err.flush();
451:                                java.net.Socket client = ssocket.accept();
452:                                System.err.println("got connection from "
453:                                        + client.getInetAddress() + " port:"
454:                                        + client.getPort());
455:                                TelnetRepl.serve(Language.getDefaultLanguage(),
456:                                        client);
457:                            }
458:                        } catch (java.io.IOException ex) {
459:                            throw new Error(ex.toString());
460:                        }
461:                    } else if (arg.equals("--main")) {
462:                        Compilation.generateMainDefault = true;
463:                    } else if (arg.equals("--applet")) {
464:                        Compilation.generateAppletDefault = true;
465:                    } else if (arg.equals("--servlet")) {
466:                        Compilation.generateServletDefault = true;
467:                    } else if (arg.equals("--debug-dump-zip")) {
468:                        gnu.expr.ModuleExp.dumpZipPrefix = "kawa-zip-dump-";
469:                    } else if (arg.equals("--debug-print-expr")) {
470:                        Compilation.debugPrintExpr = true;
471:                    } else if (arg.equals("--debug-print-final-expr")) {
472:                        Compilation.debugPrintFinalExpr = true;
473:                    } else if (arg.equals("--debug-error-prints-stack-trace")) {
474:                        SourceMessages.debugStackTraceOnError = true;
475:                    } else if (arg.equals("--debug-warning-prints-stack-trace")) {
476:                        SourceMessages.debugStackTraceOnWarning = true;
477:                    } else if (arg.equals("--module-static")) {
478:                        gnu.expr.Compilation.moduleStatic = 1;
479:                    } else if (arg.equals("--module-static-run")) {
480:                        gnu.expr.Compilation.moduleStatic = 2;
481:                    } else if (arg.equals("--fewer-classes")) {
482:                        gnu.expr.Compilation.fewerClasses = true;
483:                    } else if (arg.equals("--no-inline")
484:                            || arg.equals("--inline=none")) {
485:                        gnu.expr.Compilation.inlineOk = false;
486:                    } else if (arg.equals("--inline")) {
487:                        gnu.expr.Compilation.inlineOk = true;
488:                    } else if (arg.equals("--cps")) {
489:                        Compilation.fewerClasses = true;
490:                        Compilation.defaultCallConvention = Compilation.CALL_WITH_CONTINUATIONS;
491:                    } else if (arg.equals("--full-tailcalls")) {
492:                        Compilation.defaultCallConvention = Compilation.CALL_WITH_TAILCALLS;
493:                    } else if (arg.equals("--no-full-tailcalls")) {
494:                        Compilation.defaultCallConvention = Compilation.CALL_WITH_RETURN;
495:                    } else if (arg.equals("--pedantic")) {
496:                        Language.requirePedantic = true;
497:                    } else if (arg.equals("--help")) {
498:                        printOptions(System.out);
499:                        System.exit(0);
500:                    } else if (arg.equals("--author")) {
501:                        System.out.println("Per Bothner <per@bothner.com>");
502:                        System.exit(0);
503:                    } else if (arg.equals("--version")) {
504:                        System.out.print("Kawa ");
505:                        System.out.print(Version.getVersion());
506:                        System.out.println();
507:                        System.out.println("Copyright (C) 2007 Per Bothner");
508:                        something_done = true;
509:                    } else if (arg.length() > 0 && arg.charAt(0) == '-') { // Check if arg is a known language name.
510:                        String name = arg;
511:                        if (name.length() > 2 && name.charAt(0) == '-')
512:                            name = name
513:                                    .substring(name.charAt(1) == '-' ? 2 : 1);
514:                        Language lang = Language.getInstance(name);
515:                        if (lang != null) {
516:                            if (previousLanguage == null)
517:                                Language.setDefaults(lang);
518:                            else
519:                                Language.setDefaultLanguage(lang);
520:                            previousLanguage = lang;
521:                        } else {
522:                            // See if arg is a valid Compilation option, and if so set it.
523:                            int eq = name.indexOf("=");
524:                            String opt_value;
525:                            if (eq < 0)
526:                                opt_value = null;
527:                            else {
528:                                opt_value = name.substring(eq + 1);
529:                                name = name.substring(0, eq);
530:                            }
531:
532:                            // Convert "--no-xxx" to "--xxx=no":
533:                            boolean startsWithNo = name.startsWith("no-")
534:                                    && name.length() > 3;
535:                            if (opt_value == null && startsWithNo) {
536:                                opt_value = "no";
537:                                name = name.substring(3);
538:                            }
539:
540:                            String msg = Compilation.options.set(name,
541:                                    opt_value);
542:                            if (msg != null) {
543:                                // It wasn't a valid Complation option.
544:                                if (startsWithNo
545:                                        && msg == gnu.text.Options.UNKNOWN)
546:                                    msg = "both '--no-' prefix and '="
547:                                            + opt_value + "' specified";
548:                                if (msg == gnu.text.Options.UNKNOWN) {
549:                                    bad_option(arg);
550:                                } else {
551:                                    System.err.println("kawa: bad option '"
552:                                            + arg + "': " + msg);
553:                                    System.exit(-1);
554:                                }
555:                            }
556:                        }
557:                    } else {
558:                        int ci = arg.indexOf('=');
559:                        if (ci <= 0)
560:                            return iArg;
561:                        String key = arg.substring(0, ci);
562:                        String value = arg.substring(ci + 1);
563:                        for (int i = 0;; i++) {
564:                            String[] propertyField = propertyFields[i];
565:                            if (propertyField == null)
566:                                break;
567:                            if (key.equals(propertyField[0])) {
568:                                String cname = propertyField[1];
569:                                String fname = propertyField[2];
570:                                try {
571:                                    Class clas = Class.forName(cname);
572:                                    ThreadLocation loc = (ThreadLocation) clas
573:                                            .getDeclaredField(fname).get(null);
574:                                    loc.setGlobal(value);
575:                                    break;
576:                                } catch (Throwable ex) {
577:                                    System.err
578:                                            .println("error setting property "
579:                                                    + key + " field " + cname
580:                                                    + '.' + fname + ": " + ex);
581:                                    System.exit(-1);
582:                                }
583:                            }
584:                        }
585:                        Symbol symbol = Symbol.parse(key);
586:                        // Run Language's static initializer.
587:                        Language.getDefaultLanguage();
588:                        Environment current = Environment.getCurrent();
589:                        current.define(symbol, null, value);
590:                    }
591:                }
592:                return something_done ? -1 : iArg;
593:            }
594:
595:            public static void compileFiles(String[] args, int iArg, int maxArg) {
596:                ModuleManager manager = ModuleManager.getInstance();
597:                Compilation[] comps = new Compilation[maxArg - iArg];
598:                ModuleInfo[] infos = new ModuleInfo[maxArg - iArg];
599:                SourceMessages messages = new SourceMessages();
600:                for (int i = iArg; i < maxArg; i++) {
601:                    String arg = args[i];
602:                    getLanguageFromFilenameExtension(arg);
603:                    Language language = Language.getDefaultLanguage();
604:                    try {
605:                        InPort fstream;
606:                        try {
607:                            fstream = InPort.openFile(arg);
608:                        } catch (java.io.FileNotFoundException ex) {
609:                            System.err.println(ex);
610:                            System.exit(-1);
611:                            break; // Kludge to shut up compiler.
612:                        }
613:
614:                        Compilation comp = language.parse(fstream, messages,
615:                                Language.PARSE_PROLOG);
616:
617:                        if (compilationTopname != null) {
618:                            String cname = Compilation
619:                                    .mangleNameIfNeeded(compilationTopname);
620:                            ClassType ctype = new ClassType(cname);
621:                            ModuleExp mexp = comp.getModule();
622:                            mexp.setType(ctype);
623:                            mexp.setName(compilationTopname);
624:                            comp.mainClass = ctype;
625:                        }
626:
627:                        infos[i - iArg] = manager.find(comp);
628:                        comps[i - iArg] = comp;
629:
630:                    } catch (Throwable ex) {
631:                        if (!(ex instanceof  SyntaxException)
632:                                || ((SyntaxException) ex).getMessages() != messages) {
633:                            System.err
634:                                    .println("Internal error while compiling "
635:                                            + arg);
636:                            ex.printStackTrace(System.err);
637:                            System.exit(-1);
638:                        }
639:                    }
640:                    if (messages.seenErrorsOrWarnings()) {
641:                        System.err.println("(compiling " + arg + ')');
642:                        if (messages.checkErrors(System.err, 20))
643:                            System.exit(1);
644:                    }
645:                }
646:
647:                for (int i = iArg; i < maxArg; i++) {
648:                    String arg = args[i];
649:                    Compilation comp = comps[i - iArg];
650:                    try {
651:                        System.err.println("(compiling " + arg + " to "
652:                                + comp.mainClass.getName() + ')');
653:
654:                        infos[i - iArg].loadByStages(Compilation.CLASS_WRITTEN);
655:                        boolean sawErrors = messages.seenErrors();
656:                        messages.checkErrors(System.err, 50);
657:                        if (sawErrors)
658:                            System.exit(-1);
659:                        comps[i - iArg] = comp;
660:                        sawErrors = messages.seenErrors();
661:                        messages.checkErrors(System.err, 50);
662:                        if (sawErrors)
663:                            System.exit(-1);
664:                    } catch (Throwable ex) {
665:                        StringBuffer sbuf = new StringBuffer();
666:                        String file = comp.getFileName();
667:                        int line = comp.getLineNumber();
668:                        if (file != null && line > 0) {
669:                            sbuf.append(file);
670:                            sbuf.append(':');
671:                            sbuf.append(line);
672:                            sbuf.append(": ");
673:                        }
674:                        sbuf.append("internal error while compiling ");
675:                        sbuf.append(arg);
676:                        System.err.println(sbuf.toString());
677:                        ex.printStackTrace(System.err);
678:                        System.exit(-1);
679:                    }
680:                }
681:            }
682:
683:            /** A list of standard command-line fluid names to map to static fields.
684:             * For each entry:
685:             * element 0 is a property name (before the '=' in the comamnd-line);
686:             * element 1 is the name of a class;
687:             * element 2 is the name of a static ThreadLocation field. */
688:            static String[][] propertyFields = {
689:                    { "out:doctype-system", "gnu.xml.XMLPrinter",
690:                            "doctypeSystem" },
691:                    { "out:doctype-public", "gnu.xml.XMLPrinter",
692:                            "doctypePublic" },
693:                    { "out:base", "gnu.kawa.functions.DisplayFormat", "outBase" },
694:                    { "out:radix", "gnu.kawa.functions.DisplayFormat",
695:                            "outRadix" },
696:                    { "out:line-length", "gnu.text.PrettyWriter",
697:                            "lineLengthLoc" },
698:                    { "out:right-margin", "gnu.text.PrettyWriter",
699:                            "lineLengthLoc" },
700:                    { "out:miser-width", "gnu.text.PrettyWriter",
701:                            "miserWidthLoc" },
702:                    { "out:xml-indent", "gnu.xml.XMLPrinter", "indentLoc" },
703:                    { "display:toolkit", "gnu.kawa.models.Display", "myDisplay" },
704:                    null };
705:
706:            public static void main(String args[]) {
707:                try {
708:                    int iArg = processArgs(args, 0, args.length);
709:                    if (iArg < 0)
710:                        return;
711:                    if (iArg < args.length) {
712:                        String filename = args[iArg];
713:                        getLanguageFromFilenameExtension(filename);
714:                        setArgs(args, iArg + 1);
715:                        checkInitFile();
716:                        Shell.runFile(filename, 0);
717:                    } else {
718:                        getLanguage();
719:                        setArgs(args, iArg);
720:                        checkInitFile();
721:                        Shell.run(Language.getDefaultLanguage(), Environment
722:                                .getCurrent());
723:                    }
724:                } finally {
725:                    if (!shutdownRegistered) {
726:                        // Redundant if registerShutdownHook succeeded (e.g on JDK 1.3).
727:                        gnu.mapping.OutPort.runCleanups();
728:                    }
729:                    exitDecrement();
730:                }
731:            }
732:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.