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