2a28338df7935f0b9613177ffd9456cc6de857d5
[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") ? GOTO : -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 'v': return s.equals("void") ? RESERVED : -1;
111                 case 'w': return s.equals("with") ? WITH : -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 != -1) return result;
179         this.string = str;
180         return NAME;
181     }
182     
183     private int getNumber(int c) throws IOException {
184         int base = 10;
185         in.startString();
186         double dval = Double.NaN;
187         long longval = 0;
188         boolean isInteger = true;
189         
190         // figure out what base we're using
191         if (c == '0') {
192             if (Character.toLowerCase((char)(c = in.read())) == 'x') { base = 16; in.startString(); }
193             else if (isDigit(c)) base = 8;
194         }
195         
196         while (0 <= xDigitToInt(c) && !(base < 16 && isAlpha(c))) c = in.read();
197         if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
198             isInteger = false;
199             if (c == '.') do { c = in.read(); } while (isDigit(c));
200             if (c == 'e' || c == 'E') {
201                 c = in.read();
202                 if (c == '+' || c == '-') c = in.read();
203                 if (!isDigit(c)) throw new IOException("msg.missing.exponent");
204                 do { c = in.read(); } while (isDigit(c));
205             }
206         }
207         in.unread();
208
209         String numString = in.getString();
210         if (base == 10 && !isInteger) {
211             try { dval = (Double.valueOf(numString)).doubleValue(); }
212             catch (NumberFormatException ex) { throw new IOException("msg.caught.nfe"); }
213         } else {
214             if (isInteger) {
215                 longval = Long.parseLong(numString, base);
216                 dval = (double)longval;
217             } else {
218                 dval = Double.parseDouble(numString);
219                 longval = (long) dval;
220                 if (longval == dval) isInteger = true;
221             }
222         }
223         
224         if (!isInteger) this.number = new Double(dval);
225         else if (Byte.MIN_VALUE <= longval && longval <= Byte.MAX_VALUE) this.number = new Byte((byte)longval);
226         else if (Short.MIN_VALUE <= longval && longval <= Short.MAX_VALUE) this.number = new Short((short)longval);
227         else if (Integer.MIN_VALUE <= longval && longval <= Integer.MAX_VALUE) this.number = new Integer((int)longval);
228         else this.number = new Double(longval);
229         return NUMBER;
230     }
231     
232     private int getString(int c) throws IOException {
233         StringBuffer stringBuf = null;
234         int quoteChar = c;
235         int val = 0;
236         c = in.read();
237         in.startString(); // start after the first "
238         while(c != quoteChar) {
239             if (c == '\n' || c == -1) throw new IOException("msg.unterminated.string.lit");
240             if (c == '\\') {
241                 if (stringBuf == null) {
242                     in.unread();   // Don't include the backslash
243                     stringBuf = new StringBuffer(in.getString());
244                     in.read();
245                 }
246                 switch (c = in.read()) {
247                 case 'b': c = '\b'; break;
248                 case 'f': c = '\f'; break;
249                 case 'n': c = '\n'; break;
250                 case 'r': c = '\r'; break;
251                 case 't': c = '\t'; break;
252                 case 'v': c = '\u000B'; break;
253                 case '\\': c = '\\'; break;
254                 case 'u': {
255                     int v = 0;
256                     for(int i=0; i<4; i++) {
257                         int ci = in.read();
258                         if (!((ci >= '0' && ci <= '9') || (ci >= 'a' && ci <= 'f') || (ci >= 'A' && ci <= 'F')))
259                             throw new IOException("illegal character '" + ((char)c) + "' in \\u unicode escape sequence");
260                         v = (v << 8) | Integer.parseInt(ci + "", 16);
261                     }
262                     c = (char)v;
263                     break;
264                 }
265                 default:
266                     // just use the character that was escaped
267                     break;
268                 }
269             }
270             if (stringBuf != null) stringBuf.append((char) c);
271             c = in.read();
272         }
273         if (stringBuf != null) this.string = stringBuf.toString();
274         else {
275             in.unread(); // miss the trailing "
276             this.string = in.getString();
277             in.read();
278         }
279         return STRING;
280     }
281
282     public int _getToken() throws IOException {
283         int c;
284         do { if ((c = in.read()) == '\n') break; } while (isWhiteSpace(c) || c == '\n');
285         if (c == -1) return -1;
286         if (c == '\\' || Character.isJavaIdentifierStart((char)c)) return getIdentifier(c);
287         if (isDigit(c) || (c == '.' && isDigit(in.peek()))) return getNumber(c);
288         if (c == '"' || c == '\'') return getString(c);
289         switch (c) {
290         case '\n': return EOL;
291         case ';': return SEMI;
292         case '[': return LB;
293         case ']': return RB;
294         case '{': return LC;
295         case '}': return RC;
296         case '(': return LP;
297         case ')': return RP;
298         case ',': return COMMA;
299         case '?': return HOOK;
300         case ':': return COLON;
301         case '.': return DOT;
302         case '|': return in.match('|') ? OR : (in.match('=') ? ASSIGN_BITOR : BITOR);
303         case '^': return in.match('=') ? ASSIGN_BITXOR : BITXOR;
304         case '&': return in.match('&') ? AND : in.match('=') ? ASSIGN_BITAND : BITAND;
305         case '=': return !in.match('=') ? ASSIGN : in.match('=') ? SHEQ : EQ;
306         case '!': return !in.match('=') ? BANG : in.match('=') ? SHNE : NE;
307         case '%': return in.match('=') ? MOD_ASSIGN : MOD;
308         case '~': return BITNOT;
309         case '+': return in.match('=') ? ASSIGN_ADD : in.match('+') ? INC : ADD;
310         case '-': return in.match('=') ? ASSIGN_SUB: in.match('-') ? DEC : SUB;
311         case '*': return in.match('=') ? ASSIGN_MUL : MUL;
312         case '<': return !in.match('<') ?
313                              (in.match('=') ? LE : LT) :
314                              in.match('=') ? ASSIGN_LSH : LSH;
315         case '>': return !in.match('>') ?
316                              (in.match('=') ? GE : GT) :
317                              in.match('>') ?
318                                  (in.match('=') ? ASSIGN_URSH : URSH) :
319                                  (in.match('=') ? ASSIGN_RSH : RSH);
320         case '/':
321             if (in.match('=')) return ASSIGN_DIV;
322             if (in.match('/')) { while ((c = in.read()) != -1 && c != '\n'); in.unread(); return getToken(); }
323             if (!in.match('*')) return DIV;
324             while ((c = in.read()) != -1 && !(c == '*' && in.match('/'))) {
325                 if (c == '\n' || c != '/' || !in.match('*')) continue;
326                 if (in.match('/')) return getToken();
327                 throw new IOException("msg.nested.comment");
328             }
329             if (c == -1) throw new IOException("msg.unterminated.comment");
330             return getToken();  // `goto retry'
331         default: throw new IOException("illegal character: " + ((char)c));
332         }
333     }
334
335     private class SmartReader {
336         PushbackReader reader = null;
337         int lastread = -1;
338
339         public SmartReader(Reader r) { reader = new PushbackReader(r); }
340         public void unread() throws IOException { unread((char)lastread); }
341         public void unread(char c) throws IOException {
342             reader.unread(c);
343             if (accumulator != null) accumulator.setLength(accumulator.length() - 1);
344         }
345         public boolean match(char c) throws IOException { if (peek() == c) { reader.read(); return true; } else return false; }
346         public int peek() throws IOException {
347             int peeked = reader.read();
348             if (peeked != -1) reader.unread((char)peeked);
349             return peeked;
350         }
351         public int read() throws IOException {
352             lastread = reader.read();
353             if (accumulator != null) accumulator.append((char)lastread);
354             if (lastread != '\n' && lastread != '\r') col++;
355             return lastread;
356         }
357
358         // FEATURE: could be much more efficient
359         StringBuffer accumulator = null;
360         public void startString() {
361             accumulator = new StringBuffer();
362             accumulator.append((char)lastread);
363         }
364         public String getString() throws IOException {
365             String ret = accumulator.toString();
366             accumulator = null;
367             return ret;
368         }
369     }
370
371
372     // PushBack Stuff ////////////////////////////////////////////////////////////
373
374     int pushBackDepth = 0;
375     int[] pushBackInts = new int[10];
376     Object[] pushBackObjects = new Object[10];
377
378     public void pushBackToken(int op, Object obj) {
379         if (pushBackDepth >= pushBackInts.length - 1) {
380             int[] newInts = new int[pushBackInts.length * 2];
381             System.arraycopy(pushBackInts, 0, newInts, 0, pushBackInts.length);
382             pushBackInts = newInts;
383             Object[] newObjects = new Object[pushBackObjects.length * 2];
384             System.arraycopy(pushBackObjects, 0, newObjects, 0, pushBackObjects.length);
385             pushBackObjects = newObjects;
386         }
387         pushBackInts[pushBackDepth] = op;
388         pushBackObjects[pushBackDepth] = obj;
389         pushBackDepth++;
390     }
391
392     public void pushBackToken() { pushBackToken(op, number != null ? (Object)number : (Object)string); }
393
394     public int peekToken() throws IOException {
395         int ret = getToken();
396         pushBackToken();
397         return ret;
398     }
399
400     public int getToken() throws IOException {
401         number = null;
402         string = null;
403         if (pushBackDepth > 0) {
404             pushBackDepth--;
405             op = pushBackInts[pushBackDepth];
406             if (pushBackObjects[pushBackDepth] != null) {
407                 number = pushBackObjects[pushBackDepth] instanceof Number ? (Number)pushBackObjects[pushBackDepth] : null;
408                 string = pushBackObjects[pushBackDepth] instanceof String ? (String)pushBackObjects[pushBackDepth] : null;
409             }
410         } else {
411             do {
412                 op = _getToken();
413                 if (op == EOL) { line++; col = 0; }
414             } while (op == EOL);
415         }
416         return op;
417     }
418
419 }