package parser; import java.io.*; public class Lexer { public static final int EOF = -1; public static final int PLUS = 1; public static final int MULT = 2; public static final int INT = 3; public static final int ID = 4; public static final int PRINT = 5; public static final int EQUALS = 6; public static final int NEWLINE = 7; public static String[] tokenNames = { null, "PLUS", "MULT", "INT", "ID", "PRINT", "EQUALS", "NEWLINE" }; /** Current char of lookahead */ int c; /** Where to pull char from */ InputStream in; public Lexer(InputStream in) throws IOException { this.in = in; consume(); } public Token nextToken() throws IOException { while ( c!=EOF ) { if ( c==' ' || c=='\t' ) { consume(); continue; } if ( c>='0' && c<='9' ) { StringBuffer buf = new StringBuffer(); while ( c>='0' && c<='9' ) { buf.append((char)c); consume(); } return new Token(INT, buf.toString()); } if ( c>='a' && c<='z' ) { StringBuffer buf = new StringBuffer(); while ( c>='a' && c<='z' ) { buf.append((char)c); consume(); } String text = buf.toString(); if ( text.equals("print") ) { return new Token(PRINT); } return new Token(ID, text); } if ( c=='+' ) { consume(); return new Token(PLUS); } if ( c=='*' ) { consume(); return new Token(MULT); } if ( c=='=' ) { consume(); return new Token(EQUALS); } if ( c=='\n' || c=='\r' ) { consume(); return new Token(NEWLINE); } throw new IllegalArgumentException("invalid char"); } return new Token(EOF); } public void consume() throws IOException { c = in.read(); } }