KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > kawa > Shell


1 package kawa;
2
3 import gnu.mapping.*;
4 import gnu.expr.*;
5 import java.io.*;
6 import gnu.text.*;
7 import gnu.lists.*;
8
9 /** Utility functions (static methods) for kawa.repl.
10  * Should probably be merged with kawa.repl. FIXME. */

11
12 public class Shell
13 {
14   private static Class JavaDoc[] noClasses = { };
15   private static Class JavaDoc[] boolClasses = { Boolean.TYPE };
16   private static Class JavaDoc[] xmlPrinterClasses
17     = {gnu.mapping.OutPort.class, java.lang.Object JavaDoc.class };
18   private static Class JavaDoc[] httpPrinterClasses
19     = {gnu.mapping.OutPort.class };
20   private static Object JavaDoc portArg = "(port)";
21
22   /** A table of names of known output formats.
23    * For each entry, the first Object is the format name.
24    * The next entries are a class name, the name of a static method in that
25    * class, and the parameter types (as a Class[] suitable for getMethod).
26    * The remain values are arguments (passed to invoke), except that if an
27    * argument is the spacial value portArg, it is replaced by the
28    * destination OutPort. */

29    
30   static Object JavaDoc[][] formats =
31     {
32       { "scheme", "gnu.kawa.functions.DisplayFormat",
33     "getSchemeFormat", boolClasses,
34     Boolean.FALSE },
35       { "readable-scheme", "gnu.kawa.functions.DisplayFormat",
36     "getSchemeFormat", boolClasses,
37     Boolean.TRUE },
38       { "elisp", "gnu.kawa.functions.DisplayFormat",
39     "getEmacsLispFormat", boolClasses,
40     Boolean.FALSE },
41       { "readable-elisp", "gnu.kawa.functions.DisplayFormat",
42     "getEmacsLispFormat", boolClasses,
43     Boolean.TRUE },
44       { "clisp", "gnu.kawa.functions.DisplayFormat",
45     "getCommonLispFormat", boolClasses,
46     Boolean.FALSE },
47       { "readable-clisp", "gnu.kawa.functions.DisplayFormat",
48     "getCommonLispFormat", boolClasses,
49     Boolean.TRUE },
50       { "commonlisp", "gnu.kawa.functions.DisplayFormat",
51     "getCommonLispFormat", boolClasses,
52     Boolean.FALSE },
53       { "readable-commonlisp", "gnu.kawa.functions.DisplayFormat",
54     "getCommonLispFormat", boolClasses,
55     Boolean.TRUE },
56       { "xml", "gnu.xml.XMLPrinter",
57     "make", xmlPrinterClasses,
58     portArg, null },
59       { "html", "gnu.xml.XMLPrinter",
60     "make", xmlPrinterClasses,
61     portArg, "html" },
62       { "xhtml", "gnu.xml.XMLPrinter",
63     "make", xmlPrinterClasses,
64     portArg, "xhtml" },
65       { "cgi", "gnu.kawa.xml.HttpPrinter",
66     "make", httpPrinterClasses,
67     portArg },
68       { "ignore", "gnu.lists.VoidConsumer",
69     "getInstance", noClasses },
70       { null }
71     };
72
73   public static String JavaDoc defaultFormatName;
74   public static Object JavaDoc[] defaultFormatInfo;
75   public static java.lang.reflect.Method JavaDoc defaultFormatMethod;
76
77   /** Specify the default output format.
78    * @param name The name of the format, as an entry in the formats table.
79    */

80   public static void setDefaultFormat(String JavaDoc name)
81   {
82     name = name.intern();
83     defaultFormatName = name;
84     for (int i = 0; ; i++)
85       {
86     Object JavaDoc[] info = formats[i];
87     Object JavaDoc iname = info[0];
88     if (iname == null)
89       {
90         System.err.println ("kawa: unknown output format '"+name+"'");
91         System.exit (-1);
92       }
93     else if (iname == name)
94       {
95         defaultFormatInfo = info;
96         try
97           {
98         Class JavaDoc formatClass = Class.forName((String JavaDoc) info[1]);
99         defaultFormatMethod
100           = formatClass.getMethod((String JavaDoc) info[2], (Class JavaDoc[]) info[3]);
101         
102           }
103         catch (Throwable JavaDoc ex)
104           {
105         System.err.println("kawa: caught "+ex+" while looking for format '"+name+"'");
106         System.exit (-1);
107           }
108         break;
109       }
110       }
111     if (! defaultFormatInfo[1].equals("gnu.lists.VoidConsumer"))
112       ModuleBody.setMainPrintValues(true);
113   }
114
115   /** Return a Consumer that formats using the appropriate format.
116    * The format is chosen depending on specified defaults.
117    * @param out The output where formatted output is sent to.
118    */

119   public static Consumer getOutputConsumer(OutPort out)
120   {
121     Object JavaDoc[] info = defaultFormatInfo;
122     if (out == null)
123       return VoidConsumer.getInstance();
124     else if (info == null)
125       return Language.getDefaultLanguage().getOutputConsumer(out);
126     try
127       {
128     Object JavaDoc args[] = new Object JavaDoc[info.length - 4];
129     System.arraycopy(info, 4, args, 0, args.length);
130     for (int i = args.length; --i >= 0; )
131       if (args[i] == portArg)
132         args[i] = out;
133     Object JavaDoc format = defaultFormatMethod.invoke(null, args);
134     if (format instanceof AbstractFormat)
135       {
136         out.objectFormat = (AbstractFormat) format;
137         return out;
138       }
139     else
140       return (Consumer) format;
141       }
142     catch (Throwable JavaDoc ex)
143       {
144     throw new RuntimeException JavaDoc("cannot get output-format '"
145                    + defaultFormatName + "' - caught " + ex);
146       }
147   }
148
149   public static void run (Language language, Environment env)
150   {
151     InPort inp = InPort.inDefault ();
152     if (inp instanceof TtyInPort)
153       {
154     Procedure prompter = language.getPrompter();
155     if (prompter != null)
156       ((TtyInPort)inp).setPrompter(prompter);
157       }
158
159     run(language, env, inp, OutPort.outDefault(), OutPort.errDefault());
160   }
161
162   public static void run (Language language, Environment env,
163               InPort inp, OutPort pout, OutPort perr)
164   {
165     Consumer out;
166     AbstractFormat saveFormat = null;
167     if (pout != null)
168       saveFormat = pout.objectFormat;
169     out = getOutputConsumer(pout);
170     try
171       {
172     run(language, env, inp, out, perr, null);
173       }
174     finally
175       {
176     if (pout != null)
177       pout.objectFormat = saveFormat;
178       }
179   }
180
181   public static void run (Language language, Environment env,
182               InPort inp, Consumer out, OutPort perr,
183                           java.net.URL JavaDoc url)
184   {
185     SourceMessages messages = new SourceMessages();
186     Language saveLanguage = Language.getDefaultLanguage();
187     Lexer lexer = language.getLexer(inp, messages);
188     // Wrong for the case of '-f' '-':
189
boolean interactive = inp instanceof TtyInPort;
190     lexer.setInteractive(interactive);
191     CallContext ctx = CallContext.getInstance();
192     Consumer saveConsumer = null;
193     if (out != null)
194       {
195     saveConsumer = ctx.consumer;
196     ctx.consumer = out;
197       }
198     if (language != saveLanguage)
199       Language.setDefaultLanguage(language);
200     try
201       {
202     for (;;)
203       {
204         int opts = Language.PARSE_IMMEDIATE|Language.PARSE_ONE_LINE;
205         try
206           {
207         Compilation comp = language.parse(lexer, opts, null);
208         boolean sawError = messages.checkErrors(perr, 20);
209         if (comp == null) // ??? end-of-file
210
break;
211         if (sawError)
212           continue;
213         comp.getModule().setName("atInteractiveLevel$"
214                      + (++ModuleExp.interactiveCounter));
215
216         // Skip whitespace, in case (read-char) or similar is called:
217
int ch;
218         for (;;)
219           {
220             ch = inp.read();
221             if (ch < 0 || ch == '\r' || ch == '\n')
222               break;
223             if (ch != ' ' && ch != '\t')
224               {
225             inp.unread();
226             break;
227               }
228           }
229
230         if (! ModuleExp.evalModule(env, ctx, comp, url, perr))
231           continue;
232                 if (out instanceof Writer)
233                   ((Writer) out).flush();
234         if (ch < 0)
235           break;
236           }
237         catch (WrongArguments e)
238           {
239         messages.printAll(perr, 20);
240         if (e.usage != null)
241           perr.println("usage: "+e.usage);
242         e.printStackTrace(perr);
243           }
244         catch (java.lang.ClassCastException JavaDoc e)
245           {
246         messages.printAll(perr, 20);
247         perr.println("Invalid parameter, was: "+ e.getMessage());
248         e.printStackTrace(perr);
249           }
250         catch (gnu.text.SyntaxException e)
251           {
252         e.printAll(perr, 20);
253         e.clear();
254         if (! interactive)
255           return;
256           }
257         catch (java.io.IOException JavaDoc e)
258           {
259         messages.printAll(perr, 20);
260         String JavaDoc msg = new SourceError(inp, 'e', "").toString();
261         msg = msg.substring(0, msg.length() - 2);
262         perr.println(msg + " (or later): caught IOException");
263         e.printStackTrace(perr);
264         if (! interactive)
265           return;
266           }
267         catch (Throwable JavaDoc e)
268           {
269         messages.printAll(perr, 20);
270         e.printStackTrace(perr);
271         if (! interactive)
272           return;
273           }
274       }
275       }
276     finally
277       {
278     if (out != null)
279       ctx.consumer = saveConsumer;
280         if (language != saveLanguage)
281           Language.setDefaultLanguage(saveLanguage);
282       }
283   }
284
285   public static void runString (String JavaDoc str, Language language, Environment env)
286   {
287     run(language, env, new CharArrayInPort(str),
288     ModuleBody.getMainPrintValues() ? OutPort.outDefault() : null,
289     OutPort.errDefault());
290   }
291
292   public static void runFile (String JavaDoc fname, int skipLines)
293   {
294     Environment env = Environment.getCurrent();
295     try
296       {
297     if (fname.equals ("-"))
298           {
299             InPort in = InPort.inDefault();
300             while (--skipLines >= 0)
301               in.skipRestOfLine();
302             kawa.standard.load.loadSource(in, env, null);
303           }
304     else
305       kawa.standard.load.apply(fname, env, false, skipLines);
306       }
307     catch (gnu.text.SyntaxException e)
308       {
309     e.printAll(OutPort.errDefault(), 20);
310       }
311     catch (FileNotFoundException e)
312       {
313     System.err.println("Cannot open file "+fname);
314     System.exit(1);
315       }
316     catch (Throwable JavaDoc e)
317       {
318     e.printStackTrace(System.err);
319     System.exit(1);
320       }
321   }
322   
323 }
324
Popular Tags