2003/06/09 00:07:40
[org.ibex.core.git] / src / org / xwt / js / Lexer.java
1 // Derived from org.mozilla.javascript.TokenStream [NPL]
2
3 /**
4  * The contents of this file are subject to the Netscape Public
5  * License Version 1.1 (the "License"); you may not use this file
6  * except in compliance with the License. You may obtain a copy of
7  * the License at http://www.mozilla.org/NPL/
8  *
9  * Software distributed under the License is distributed on an "AS
10  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
11  * implied. See the License for the specific language governing
12  * rights and limitations under the License.
13  *
14  * The Initial Developer of the Original Code is Netscape
15  * Communications Corporation.
16  *
17  * Contributor(s): Roger Lawrence, Mike McCabe
18  */
19
20 package org.xwt.js;
21 import java.io.*;
22
23 /** Lexes a stream of characters into a stream of Tokens */
24 class Lexer implements Tokens {
25
26     /** for debugging */
27     public static void main(String[] s) throws Exception {
28         Lexer l = new Lexer(new InputStreamReader(System.in));
29         int tok = 0;
30         while((tok = l.getToken()) != -1) System.out.println(codeToString[tok]);
31     }
32
33     /** the token that was just parsed */
34     protected int op;
35
36     /** if the token just parsed was a NUMBER, this is the numeric value */
37     protected Number number = null;
38
39     /** if the token just parsed was a NAME or STRING, this is the string value */
40     protected String string = null;
41
42     /** the line number of the current token */
43     protected int line = 0;
44
45     /** the column number of the current token */
46     protected int col = 0;
47
48     /** the name of the source code file being lexed */
49     protected String sourceName = "unknown";
50
51     private SmartReader in;
52     public Lexer(Reader r) throws IOException { in = new SmartReader(r); }
53
54
55     // Predicates ///////////////////////////////////////////////////////////////////////
56
57     private static boolean isAlpha(int c) { return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); }
58     private static boolean isDigit(int c) { return (c >= '0' && c <= '9'); }
59     private static int xDigitToInt(int c) {
60         if ('0' <= c && c <= '9') return c - '0';
61         else if ('a' <= c && c <= 'f') return c - ('a' - 10);
62         else if ('A' <= c && c <= 'F') return c - ('A' - 10);
63         else return -1;
64     }
65
66     
67     // Token Subtype Handlers /////////////////////////////////////////////////////////
68
69     private int getKeyword(String s) throws IOException {
70         char c;
71         switch (s.length()) {
72             case 2: c=s.charAt(1);
73                 if (c=='f') { if (s.charAt(0)=='i') return IF; }
74                 else if (c=='n') { if (s.charAt(0)=='i') return IN; }
75                 else if (c=='o') { if (s.charAt(0)=='d') return DO; }
76                 break;
77             case 3: switch (s.charAt(0)) {
78                 case 'a': if (s.charAt(2)=='d' && s.charAt(1)=='n') return AND; break;
79                 case 'f': if (s.charAt(2)=='r' && s.charAt(1)=='o') return FOR; break;
80                 case 'i': if (s.charAt(2)=='t' && s.charAt(1)=='n') return RESERVED;
81                 case 'n': if (s.charAt(2)=='w' && s.charAt(1)=='e') return RESERVED;
82                 case 't': if (s.charAt(2)=='y' && s.charAt(1)=='r') return TRY; break;
83                 case 'v': if (s.charAt(2)=='r' && s.charAt(1)=='a') return VAR; break;
84                 } break;
85             case 4: switch (s.charAt(0)) {
86                 case 'b': return s.equals("byte") ? RESERVED : -1;
87                 case 'c': c=s.charAt(3);
88                     if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='a') return CASE; }
89                     else if (c=='r') { if (s.charAt(2)=='a' && s.charAt(1)=='h') return RESERVED; }
90                     return -1;
91                 case 'e': c=s.charAt(3);
92                     if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='l') return ELSE; }
93                     else if (c=='m') { if (s.charAt(2)=='u' && s.charAt(1)=='n') return RESERVED; }
94                     return -1;
95                 case 'g': return s.equals("goto") ? RESERVED : -1;
96                 case 'l': return s.equals("long") ? RESERVED : -1;
97                 case 'n': return s.equals("null") ? NULL : -1;
98                 case 't': c=s.charAt(3);
99                     if (c=='e') { if (s.charAt(2)=='u' && s.charAt(1)=='r') return TRUE; }
100                     else if (c=='s') { if (s.charAt(2)=='i' && s.charAt(1)=='h') return THIS; }
101                     return -1;
102                 case 'w': if (s.equals("with")) return RESERVED; else return -1;
103                 case 'v': if (s.equals("void")) return RESERVED; else return -1;
104                 } break;
105             case 5: switch (s.charAt(2)) {
106                 case 'a': return s.equals("class") ? RESERVED : -1;
107                 case 'e': return s.equals("break") ? BREAK : -1;
108                 case 'i': return s.equals("while") ? WHILE : -1;
109                 case 'l': return s.equals("false") ? FALSE : -1;
110                 case 'n': c=s.charAt(0);
111                     if (s.equals("const")) return RESERVED;
112                     else if (s.equals("final")) return RESERVED;
113                     return -1;
114                 case 'o': c=s.charAt(0);
115                     if (c == 'c') return s.equals("float") ? RESERVED : -1;
116                     else if (c=='s') return s.equals("final") ? RESERVED : -1;
117                     break;
118                 case 'p': return s.equals("super") ? RESERVED : -1;
119                 case 'r': return s.equals("throw") ? THROW : -1;
120                 case 't': return s.equals("catch") ? CATCH : -1;
121                 } break;
122             case 6: switch (s.charAt(1)) {
123                 case 'a': return s.equals("class") ? RESERVED : -1;
124                 case 'e': c=s.charAt(0);
125                     if (s.equals("delete")) return RESERVED;
126                     else if (c=='r') return s.equals("return") ? RETURN : -1;
127                     break;
128                 case 'h': return s.equals("throws") ? RESERVED : -1;
129                 case 'o': return s.equals("double") ? RESERVED : -1;
130                 case 's': return s.equals("assert") ? ASSERT : -1;
131                 case 'u': return s.equals("public") ? RESERVED : -1;
132                 case 'w': return s.equals("switch") ? SWITCH : -1;
133                 case 'y': return s.equals("typeof") ? TYPEOF : -1;
134                 } break;
135             case 7: switch (s.charAt(1)) {
136                 case 'a': return s.equals("package") ? RESERVED : -1;
137                 case 'e': return s.equals("default") ? DEFAULT : -1;
138                 case 'i': return s.equals("finally") ? FINALLY : -1;
139                 case 'o': return s.equals("boolean") ? RESERVED : -1;
140                 case 'r': return s.equals("private") ? RESERVED : -1;
141                 case 'x': return s.equals("extends") ? RESERVED : -1;
142                 } break;
143             case 8: switch (s.charAt(0)) {
144                 case 'a': return s.equals("abstract") ? RESERVED : -1;
145                 case 'c': return s.equals("continue") ? CONTINUE : -1;
146                 case 'd': return s.equals("debugger") ? RESERVED : -1;
147                 case 'f': return s.equals("function") ? FUNCTION : -1;
148                 case 'v': return s.equals("volatile") ? RESERVED : -1;
149                 } break;
150             case 9: c=s.charAt(0);
151                 if (c=='i') return s.equals("interface") ? RESERVED : -1;
152                 else if (c=='p') return s.equals("protected") ? RESERVED : -1;
153                 else if (c=='t') return s.equals("transient") ? RESERVED : -1;
154                 break;
155             case 10: c=s.charAt(1);
156                 if (c=='m') return s.equals("implements") ? RESERVED : -1;
157                 else if (c=='n' && s.equals("instanceof")) return RESERVED;
158                 break;
159             case 12: return s.equals("synchronized") ? RESERVED : -1;
160             }
161         return -1;
162     }
163
164     private int getIdentifier(int c) throws IOException {
165         in.startString();
166         while (Character.isJavaIdentifierPart((char)(c = in.read())));
167         in.unread();
168         String str = in.getString();
169         int result = getKeyword(str);
170         if (result == RESERVED) throw new LexerException("The reserved word \"" + str + "\" is not permitted in XWT scripts");
171         if (result != -1) return result;
172         this.string = str.intern();
173         return NAME;
174     }
175     
176     private int getNumber(int c) throws IOException {
177         int base = 10;
178         in.startString();
179         double dval = Double.NaN;
180         long longval = 0;
181         boolean isInteger = true;
182         
183         // figure out what base we're using
184         if (c == '0') {
185             if (Character.toLowerCase((char)(c = in.read())) == 'x') { base = 16; in.startString(); }
186             else if (isDigit(c)) base = 8;
187         }
188         
189         while (0 <= xDigitToInt(c) && !(base < 16 && isAlpha(c))) c = in.read();
190         if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
191             isInteger = false;
192             if (c == '.') do { c = in.read(); } while (isDigit(c));
193             if (c == 'e' || c == 'E') {
194                 c = in.read();
195                 if (c == '+' || c == '-') c = in.read();
196                 if (!isDigit(c)) throw new LexerException("float listeral did not have an exponent value");
197                 do { c = in.read(); } while (isDigit(c));
198             }
199         }
200         in.unread();
201
202         String numString = in.getString();
203         if (base == 10 && !isInteger) {
204             try { dval = (Double.valueOf(numString)).doubleValue(); }
205             catch (NumberFormatException ex) { throw new LexerException("invalid numeric literal: \"" + numString + "\""); }
206         } else {
207             if (isInteger) {
208                 longval = Long.parseLong(numString, base);
209                 dval = (double)longval;
210             } else {
211                 dval = Double.parseDouble(numString);
212                 longval = (long) dval;
213                 if (longval == dval) isInteger = true;
214             }
215         }
216         
217         if (!isInteger) this.number = new Double(dval);
218         else if (Byte.MIN_VALUE <= longval && longval <= Byte.MAX_VALUE) this.number = new Byte((byte)longval);
219         else if (Short.MIN_VALUE <= longval && longval <= Short.MAX_VALUE) this.number = new Short((short)longval);
220         else if (Integer.MIN_VALUE <= longval && longval <= Integer.MAX_VALUE) this.number = new Integer((int)longval);
221         else this.number = new Double(longval);
222         return NUMBER;
223     }
224     
225     private int getString(int c) throws IOException {
226         StringBuffer stringBuf = null;
227         int quoteChar = c;
228         int val = 0;
229         c = in.read();
230         in.startString(); // start after the first "
231         while(c != quoteChar) {
232             if (c == '\n' || c == -1) throw new LexerException("unterminated string literal");
233             if (c == '\\') {
234                 if (stringBuf == null) {
235                     in.unread();   // Don't include the backslash
236                     stringBuf = new StringBuffer(in.getString());
237                     in.read();
238                 }
239                 switch (c = in.read()) {
240                 case 'b': c = '\b'; break;
241                 case 'f': c = '\f'; break;
242                 case 'n': c = '\n'; break;
243                 case 'r': c = '\r'; break;
244                 case 't': c = '\t'; break;
245                 case 'v': c = '\u000B'; break;
246                 case '\\': c = '\\'; break;
247                 case 'u': {
248                     int v = 0;
249                     for(int i=0; i<4; i++) {
250                         int ci = in.read();
251                         if (!((ci >= '0' && ci <= '9') || (ci >= 'a' && ci <= 'f') || (ci >= 'A' && ci <= 'F')))
252                             throw new LexerException("illegal character '" + ((char)c) + "' in \\u unicode escape sequence");
253                         v = (v << 8) | Integer.parseInt(ci + "", 16);
254                     }
255                     c = (char)v;
256                     break;
257                 }
258                 default:
259                     // just use the character that was escaped
260                     break;
261                 }
262             }
263             if (stringBuf != null) stringBuf.append((char) c);
264             c = in.read();
265         }
266         if (stringBuf != null) this.string = stringBuf.toString().intern();
267         else {
268             in.unread(); // miss the trailing "
269             this.string = in.getString().intern();
270             in.read();
271         }
272         return STRING;
273     }
274
275     public int _getToken() throws IOException {
276         int c;
277         do { c = in.read(); } while (c == '\u0020' || c == '\u0009' || c == '\u000C' || c == '\u000B' || c == '\n' );
278         if (c == -1) return -1;
279         if (c == '\\' || Character.isJavaIdentifierStart((char)c)) return getIdentifier(c);
280         if (isDigit(c) || (c == '.' && isDigit(in.peek()))) return getNumber(c);
281         if (c == '"' || c == '\'') return getString(c);
282         switch (c) {
283         case ';': return SEMI;
284         case '[': return LB;
285         case ']': return RB;
286         case '{': return LC;
287         case '}': return RC;
288         case '(': return LP;
289         case ')': return RP;
290         case ',': return COMMA;
291         case '?': return HOOK;
292         case ':': return COLON;
293         case '.': return DOT;
294         case '|': return in.match('|') ? OR : (in.match('=') ? ASSIGN_BITOR : BITOR);
295         case '^': return in.match('=') ? ASSIGN_BITXOR : BITXOR;
296         case '&': return in.match('&') ? AND : in.match('=') ? ASSIGN_BITAND : BITAND;
297         case '=': return !in.match('=') ? ASSIGN : in.match('=') ? SHEQ : EQ;
298         case '!': return !in.match('=') ? BANG : in.match('=') ? SHNE : NE;
299         case '%': return in.match('=') ? ASSIGN_MOD : MOD;
300         case '~': return BITNOT;
301         case '+': return in.match('=') ? ASSIGN_ADD : in.match('+') ? INC : ADD;
302         case '-': return in.match('=') ? ASSIGN_SUB: in.match('-') ? DEC : SUB;
303         case '*': return in.match('=') ? ASSIGN_MUL : MUL;
304         case '<': return !in.match('<') ? (in.match('=') ? LE : LT) : in.match('=') ? ASSIGN_LSH : LSH;
305         case '>': return !in.match('>') ? (in.match('=') ? GE : GT) :
306             in.match('>') ? (in.match('=') ? ASSIGN_URSH : URSH) : (in.match('=') ? ASSIGN_RSH : RSH);
307         case '/':
308             if (in.match('=')) return ASSIGN_DIV;
309             if (in.match('/')) { while ((c = in.read()) != -1 && c != '\n'); in.unread(); return getToken(); }
310             if (!in.match('*')) return DIV;
311             while ((c = in.read()) != -1 && !(c == '*' && in.match('/'))) {
312                 if (c == '\n' || c != '/' || !in.match('*')) continue;
313                 if (in.match('/')) return getToken();
314                 throw new LexerException("nested comments are not permitted");
315             }
316             if (c == -1) throw new LexerException("unterminated comment");
317             return getToken();  // `goto retry'
318         default: throw new LexerException("illegal character: \'" + ((char)c) + "\'");
319         }
320     }
321
322
323     // SmartReader ////////////////////////////////////////////////////////////////
324
325     /** a Reader that tracks line numbers and can push back tokens */
326     private class SmartReader {
327         PushbackReader reader = null;
328         int lastread = -1;
329
330         public SmartReader(Reader r) { reader = new PushbackReader(r); }
331         public void unread() throws IOException { unread((char)lastread); }
332         public void unread(char c) throws IOException {
333             reader.unread(c);
334             if (accumulator != null) accumulator.setLength(accumulator.length() - 1);
335         }
336         public boolean match(char c) throws IOException { if (peek() == c) { reader.read(); return true; } else return false; }
337         public int peek() throws IOException {
338             int peeked = reader.read();
339             if (peeked != -1) reader.unread((char)peeked);
340             return peeked;
341         }
342         public int read() throws IOException {
343             lastread = reader.read();
344             if (accumulator != null) accumulator.append((char)lastread);
345             if (lastread != '\n' && lastread != '\r') col++;
346             if (lastread == '\n') { line++; col = 0; }
347             return lastread;
348         }
349
350         // FEATURE: could be much more efficient
351         StringBuffer accumulator = null;
352         public void startString() {
353             accumulator = new StringBuffer();
354             accumulator.append((char)lastread);
355         }
356         public String getString() throws IOException {
357             String ret = accumulator.toString();
358             accumulator = null;
359             return ret;
360         }
361     }
362
363
364     // Token PushBack code ////////////////////////////////////////////////////////////
365
366     private int pushBackDepth = 0;
367     private int[] pushBackInts = new int[10];
368     private Object[] pushBackObjects = new Object[10];
369
370     /** push back a token */
371     public void pushBackToken(int op, Object obj) {
372         if (pushBackDepth >= pushBackInts.length - 1) {
373             int[] newInts = new int[pushBackInts.length * 2];
374             System.arraycopy(pushBackInts, 0, newInts, 0, pushBackInts.length);
375             pushBackInts = newInts;
376             Object[] newObjects = new Object[pushBackObjects.length * 2];
377             System.arraycopy(pushBackObjects, 0, newObjects, 0, pushBackObjects.length);
378             pushBackObjects = newObjects;
379         }
380         pushBackInts[pushBackDepth] = op;
381         pushBackObjects[pushBackDepth] = obj;
382         pushBackDepth++;
383     }
384
385     /** push back the most recently read token */
386     public void pushBackToken() { pushBackToken(op, number != null ? (Object)number : (Object)string); }
387
388     /** read a token but leave it in the stream */
389     public int peekToken() throws IOException {
390         int ret = getToken();
391         pushBackToken();
392         return ret;
393     }
394
395     /** read a token */
396     public int getToken() throws IOException {
397         number = null;
398         string = null;
399         if (pushBackDepth == 0) return _getToken();
400         pushBackDepth--;
401         op = pushBackInts[pushBackDepth];
402         if (pushBackObjects[pushBackDepth] != null) {
403             number = pushBackObjects[pushBackDepth] instanceof Number ? (Number)pushBackObjects[pushBackDepth] : null;
404             string = pushBackObjects[pushBackDepth] instanceof String ? (String)pushBackObjects[pushBackDepth] : null;
405         }
406         return op;
407     }
408
409     class LexerException extends IOException {
410         public LexerException(String s) { super(sourceName + ":" + line + "," + col + ": " + s); }
411     }
412 }