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