1 // Derived from org.mozilla.javascript.TokenStream [NPL]
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/
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.
14 * The Initial Developer of the Original Code is Netscape
15 * Communications Corporation.
17 * Contributor(s): Roger Lawrence, Mike McCabe
23 /** Lexes a stream of characters into a stream of Tokens */
24 class Lexer implements Tokens {
27 public static void main(String[] s) throws Exception {
28 Lexer l = new Lexer(new InputStreamReader(System.in), "stdin", 0);
30 while((tok = l.getToken()) != -1) System.out.println(codeToString[tok]);
33 /** the token that was just parsed */
36 /** if the token just parsed was a NUMBER, this is the numeric value */
37 protected Number number = null;
39 /** if the token just parsed was a NAME or STRING, this is the string value */
40 protected String string = null;
42 /** the line number of the current token */
43 protected int line = 0;
45 /** the column number of the current token */
46 protected int col = 0;
48 /** the name of the source code file being lexed */
49 protected String sourceName;
51 private SmartReader in;
52 public Lexer(Reader r, String sourceName, int line) throws IOException {
53 this.sourceName = sourceName;
55 in = new SmartReader(r);
59 // Predicates ///////////////////////////////////////////////////////////////////////
61 private static boolean isAlpha(int c) { return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); }
62 private static boolean isDigit(int c) { return (c >= '0' && c <= '9'); }
63 private static int xDigitToInt(int c) {
64 if ('0' <= c && c <= '9') return c - '0';
65 else if ('a' <= c && c <= 'f') return c - ('a' - 10);
66 else if ('A' <= c && c <= 'F') return c - ('A' - 10);
71 // Token Subtype Handlers /////////////////////////////////////////////////////////
73 private int getKeyword(String s) throws IOException {
76 case 2: c=s.charAt(1);
77 if (c=='f') { if (s.charAt(0)=='i') return IF; }
78 else if (c=='n') { if (s.charAt(0)=='i') return IN; }
79 else if (c=='o') { if (s.charAt(0)=='d') return DO; }
81 case 3: switch (s.charAt(0)) {
82 case 'a': if (s.charAt(2)=='d' && s.charAt(1)=='n') return AND; break;
83 case 'f': if (s.charAt(2)=='r' && s.charAt(1)=='o') return FOR; break;
84 case 'i': if (s.charAt(2)=='t' && s.charAt(1)=='n') return RESERVED;
85 case 'n': if (s.charAt(2)=='w' && s.charAt(1)=='e') return RESERVED;
86 case 't': if (s.charAt(2)=='y' && s.charAt(1)=='r') return TRY; break;
87 case 'v': if (s.charAt(2)=='r' && s.charAt(1)=='a') return VAR; break;
89 case 4: switch (s.charAt(0)) {
90 case 'b': return s.equals("byte") ? RESERVED : -1;
91 case 'c': c=s.charAt(3);
92 if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='a') return CASE; }
93 else if (c=='r') { if (s.charAt(2)=='a' && s.charAt(1)=='h') return RESERVED; }
95 case 'e': c=s.charAt(3);
96 if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='l') return ELSE; }
97 else if (c=='m') { if (s.charAt(2)=='u' && s.charAt(1)=='n') return RESERVED; }
99 case 'g': return s.equals("goto") ? RESERVED : -1;
100 case 'l': return s.equals("long") ? RESERVED : -1;
101 case 'n': return s.equals("null") ? NULL : -1;
102 case 't': c=s.charAt(3);
103 if (c=='e') { if (s.charAt(2)=='u' && s.charAt(1)=='r') return TRUE; }
104 else if (c=='s') { if (s.charAt(2)=='i' && s.charAt(1)=='h') return THIS; }
106 case 'w': if (s.equals("with")) return RESERVED; else return -1;
107 case 'v': if (s.equals("void")) return RESERVED; else return -1;
109 case 5: switch (s.charAt(2)) {
110 case 'a': return s.equals("class") ? RESERVED : -1;
111 case 'e': return s.equals("break") ? BREAK : -1;
112 case 'i': return s.equals("while") ? WHILE : -1;
113 case 'l': return s.equals("false") ? FALSE : -1;
114 case 'n': c=s.charAt(0);
115 if (s.equals("const")) return RESERVED;
116 else if (s.equals("final")) return RESERVED;
118 case 'o': c=s.charAt(0);
119 if (c == 'c') return s.equals("float") ? RESERVED : -1;
120 else if (c=='s') return s.equals("final") ? RESERVED : -1;
122 case 'p': return s.equals("super") ? RESERVED : -1;
123 case 'r': return s.equals("throw") ? THROW : -1;
124 case 't': return s.equals("catch") ? CATCH : -1;
126 case 6: switch (s.charAt(1)) {
127 case 'a': return s.equals("class") ? RESERVED : -1;
128 case 'e': c=s.charAt(0);
129 if (s.equals("delete")) return RESERVED;
130 else if (c=='r') return s.equals("return") ? RETURN : -1;
132 case 'h': return s.equals("throws") ? RESERVED : -1;
133 case 'o': return s.equals("double") ? RESERVED : -1;
134 case 's': return s.equals("assert") ? ASSERT : -1;
135 case 'u': return s.equals("public") ? RESERVED : -1;
136 case 'w': return s.equals("switch") ? SWITCH : -1;
137 case 'y': return s.equals("typeof") ? TYPEOF : -1;
139 case 7: switch (s.charAt(1)) {
140 case 'a': return s.equals("package") ? RESERVED : -1;
141 case 'e': return s.equals("default") ? DEFAULT : -1;
142 case 'i': return s.equals("finally") ? FINALLY : -1;
143 case 'o': return s.equals("boolean") ? RESERVED : -1;
144 case 'r': return s.equals("private") ? RESERVED : -1;
145 case 'x': return s.equals("extends") ? RESERVED : -1;
147 case 8: switch (s.charAt(0)) {
148 case 'a': return s.equals("abstract") ? RESERVED : -1;
149 case 'c': return s.equals("continue") ? CONTINUE : -1;
150 case 'd': return s.equals("debugger") ? RESERVED : -1;
151 case 'f': return s.equals("function") ? FUNCTION : -1;
152 case 'v': return s.equals("volatile") ? RESERVED : -1;
154 case 9: c=s.charAt(0);
155 if (c=='i') return s.equals("interface") ? RESERVED : -1;
156 else if (c=='p') return s.equals("protected") ? RESERVED : -1;
157 else if (c=='t') return s.equals("transient") ? RESERVED : -1;
159 case 10: c=s.charAt(1);
160 if (c=='m') return s.equals("implements") ? RESERVED : -1;
161 else if (c=='n' && s.equals("instanceof")) return RESERVED;
163 case 12: return s.equals("synchronized") ? RESERVED : -1;
168 private int getIdentifier(int c) throws IOException {
170 while (Character.isJavaIdentifierPart((char)(c = in.read())));
172 String str = in.getString();
173 int result = getKeyword(str);
174 if (result == RESERVED) throw new LexerException("The reserved word \"" + str + "\" is not permitted in XWT scripts");
175 if (result != -1) return result;
176 this.string = str.intern();
180 private int getNumber(int c) throws IOException {
183 double dval = Double.NaN;
185 boolean isInteger = true;
187 // figure out what base we're using
189 if (Character.toLowerCase((char)(c = in.read())) == 'x') { base = 16; in.startString(); }
190 else if (isDigit(c)) base = 8;
193 while (0 <= xDigitToInt(c) && !(base < 16 && isAlpha(c))) c = in.read();
194 if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
196 if (c == '.') do { c = in.read(); } while (isDigit(c));
197 if (c == 'e' || c == 'E') {
199 if (c == '+' || c == '-') c = in.read();
200 if (!isDigit(c)) throw new LexerException("float listeral did not have an exponent value");
201 do { c = in.read(); } while (isDigit(c));
206 String numString = in.getString();
207 if (base == 10 && !isInteger) {
208 try { dval = (Double.valueOf(numString)).doubleValue(); }
209 catch (NumberFormatException ex) { throw new LexerException("invalid numeric literal: \"" + numString + "\""); }
212 longval = Long.parseLong(numString, base);
213 dval = (double)longval;
215 dval = Double.parseDouble(numString);
216 longval = (long) dval;
217 if (longval == dval) isInteger = true;
221 if (!isInteger) this.number = new Double(dval);
222 else if (Byte.MIN_VALUE <= longval && longval <= Byte.MAX_VALUE) this.number = new Byte((byte)longval);
223 else if (Short.MIN_VALUE <= longval && longval <= Short.MAX_VALUE) this.number = new Short((short)longval);
224 else if (Integer.MIN_VALUE <= longval && longval <= Integer.MAX_VALUE) this.number = new Integer((int)longval);
225 else this.number = new Double(longval);
229 private int getString(int c) throws IOException {
230 StringBuffer stringBuf = null;
234 in.startString(); // start after the first "
235 while(c != quoteChar) {
236 if (c == '\n' || c == -1) throw new LexerException("unterminated string literal");
238 if (stringBuf == null) {
239 in.unread(); // Don't include the backslash
240 stringBuf = new StringBuffer(in.getString());
243 switch (c = in.read()) {
244 case 'b': c = '\b'; break;
245 case 'f': c = '\f'; break;
246 case 'n': c = '\n'; break;
247 case 'r': c = '\r'; break;
248 case 't': c = '\t'; break;
249 case 'v': c = '\u000B'; break;
250 case '\\': c = '\\'; break;
253 for(int i=0; i<4; i++) {
255 if (!((ci >= '0' && ci <= '9') || (ci >= 'a' && ci <= 'f') || (ci >= 'A' && ci <= 'F')))
256 throw new LexerException("illegal character '" + ((char)c) + "' in \\u unicode escape sequence");
257 v = (v << 8) | Integer.parseInt(ci + "", 16);
263 // just use the character that was escaped
267 if (stringBuf != null) stringBuf.append((char) c);
270 if (stringBuf != null) this.string = stringBuf.toString().intern();
272 in.unread(); // miss the trailing "
273 this.string = in.getString().intern();
279 public int _getToken() throws IOException {
281 do { c = in.read(); } while (c == '\u0020' || c == '\u0009' || c == '\u000C' || c == '\u000B' || c == '\n' );
282 if (c == -1) return -1;
283 if (c == '\\' || Character.isJavaIdentifierStart((char)c)) return getIdentifier(c);
284 if (isDigit(c) || (c == '.' && isDigit(in.peek()))) return getNumber(c);
285 if (c == '"' || c == '\'') return getString(c);
287 case ';': return SEMI;
294 case ',': return COMMA;
295 case '?': return HOOK;
296 case ':': return COLON;
297 case '.': return DOT;
298 case '|': return in.match('|') ? OR : (in.match('=') ? ASSIGN_BITOR : BITOR);
299 case '^': return in.match('=') ? ASSIGN_BITXOR : BITXOR;
300 case '&': return in.match('&') ? AND : in.match('=') ? ASSIGN_BITAND : BITAND;
301 case '=': return !in.match('=') ? ASSIGN : in.match('=') ? SHEQ : EQ;
302 case '!': return !in.match('=') ? BANG : in.match('=') ? SHNE : NE;
303 case '%': return in.match('=') ? ASSIGN_MOD : MOD;
304 case '~': return BITNOT;
305 case '+': return in.match('=') ? ASSIGN_ADD : in.match('+') ? INC : ADD;
306 case '-': return in.match('=') ? ASSIGN_SUB: in.match('-') ? DEC : SUB;
307 case '*': return in.match('=') ? ASSIGN_MUL : MUL;
308 case '<': return !in.match('<') ? (in.match('=') ? LE : LT) : in.match('=') ? ASSIGN_LSH : LSH;
309 case '>': return !in.match('>') ? (in.match('=') ? GE : GT) :
310 in.match('>') ? (in.match('=') ? ASSIGN_URSH : URSH) : (in.match('=') ? ASSIGN_RSH : RSH);
312 if (in.match('=')) return ASSIGN_DIV;
313 if (in.match('/')) { while ((c = in.read()) != -1 && c != '\n'); in.unread(); return getToken(); }
314 if (!in.match('*')) return DIV;
315 while ((c = in.read()) != -1 && !(c == '*' && in.match('/'))) {
316 if (c == '\n' || c != '/' || !in.match('*')) continue;
317 if (in.match('/')) return getToken();
318 throw new LexerException("nested comments are not permitted");
320 if (c == -1) throw new LexerException("unterminated comment");
321 return getToken(); // `goto retry'
322 default: throw new LexerException("illegal character: \'" + ((char)c) + "\'");
327 // SmartReader ////////////////////////////////////////////////////////////////
329 /** a Reader that tracks line numbers and can push back tokens */
330 private class SmartReader {
331 PushbackReader reader = null;
334 public SmartReader(Reader r) { reader = new PushbackReader(r); }
335 public void unread() throws IOException { unread((char)lastread); }
336 public void unread(char c) throws IOException {
338 if (accumulator != null) accumulator.setLength(accumulator.length() - 1);
340 public boolean match(char c) throws IOException { if (peek() == c) { reader.read(); return true; } else return false; }
341 public int peek() throws IOException {
342 int peeked = reader.read();
343 if (peeked != -1) reader.unread((char)peeked);
346 public int read() throws IOException {
347 lastread = reader.read();
348 if (accumulator != null) accumulator.append((char)lastread);
349 if (lastread != '\n' && lastread != '\r') col++;
350 if (lastread == '\n') { line++; col = 0; }
354 // FEATURE: could be much more efficient
355 StringBuffer accumulator = null;
356 public void startString() {
357 accumulator = new StringBuffer();
358 accumulator.append((char)lastread);
360 public String getString() throws IOException {
361 String ret = accumulator.toString();
368 // Token PushBack code ////////////////////////////////////////////////////////////
370 private int pushBackDepth = 0;
371 private int[] pushBackInts = new int[10];
372 private Object[] pushBackObjects = new Object[10];
374 /** push back a token */
375 public void pushBackToken(int op, Object obj) {
376 if (pushBackDepth >= pushBackInts.length - 1) {
377 int[] newInts = new int[pushBackInts.length * 2];
378 System.arraycopy(pushBackInts, 0, newInts, 0, pushBackInts.length);
379 pushBackInts = newInts;
380 Object[] newObjects = new Object[pushBackObjects.length * 2];
381 System.arraycopy(pushBackObjects, 0, newObjects, 0, pushBackObjects.length);
382 pushBackObjects = newObjects;
384 pushBackInts[pushBackDepth] = op;
385 pushBackObjects[pushBackDepth] = obj;
389 /** push back the most recently read token */
390 public void pushBackToken() { pushBackToken(op, number != null ? (Object)number : (Object)string); }
392 /** read a token but leave it in the stream */
393 public int peekToken() throws IOException {
394 int ret = getToken();
400 public int getToken() throws IOException {
403 if (pushBackDepth == 0) return op = _getToken();
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;
413 class LexerException extends IOException {
414 public LexerException(String s) { super(sourceName + ":" + line + "," + col + ": " + s); }