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