File: scanner.java

package info (click to toggle)
cup 0.10k-5
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 956 kB
  • ctags: 751
  • sloc: java: 5,623; makefile: 88; csh: 64; sh: 3
file content (63 lines) | stat: -rw-r--r-- 1,885 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Simple Example Scanner Class

package java_cup.simple_calc;

import java_cup.runtime.Symbol;

public class scanner implements java_cup.runtime.Scanner {
  final java.io.InputStream instream;

  public scanner(java.io.InputStream is) throws java.io.IOException {
    instream = is;
  }
  public scanner() throws java.io.IOException { this(System.in); }

  /* single lookahead character */
  protected int next_char = -2;

  /* advance input by one character */
  protected void advance()
    throws java.io.IOException
    { next_char = instream.read(); }

  /* initialize the scanner */
  private void init()
    throws java.io.IOException
    { advance(); }

  /* recognize and return the next complete token */
  public Symbol next_token()
    throws java.io.IOException
    {
      if (next_char==-2) init(); // set stuff up first time we are called.
      for (;;)
        switch (next_char)
	  {
	    case '0': case '1': case '2': case '3': case '4': 
	    case '5': case '6': case '7': case '8': case '9': 
	      /* parse a decimal integer */
	      int i_val = 0;
	      do {
	        i_val = i_val * 10 + (next_char - '0');
	        advance();
	      } while (next_char >= '0' && next_char <= '9');
	    return new Symbol(sym.NUMBER, new Integer(i_val));

	    case ';': advance(); return new Symbol(sym.SEMI);
	    case '+': advance(); return new Symbol(sym.PLUS);
	    case '-': advance(); return new Symbol(sym.MINUS);
	    case '*': advance(); return new Symbol(sym.TIMES);
	    case '/': advance(); return new Symbol(sym.DIVIDE);
	    case '%': advance(); return new Symbol(sym.MOD);
	    case '(': advance(); return new Symbol(sym.LPAREN);
	    case ')': advance(); return new Symbol(sym.RPAREN);

	    case -1: return new Symbol(sym.EOF);

	    default: 
	      /* in this simple scanner we just ignore everything else */
	      advance();
	    break;
	  }
    }
};