001 /* 002 * Created on Sep 14, 2003 by Ravi Mohan 003 * 004 */ 005 package aima.logic.common; 006 007 import java.io.Reader; 008 import java.io.StringReader; 009 010 /** 011 * @author Ravi Mohan 012 * 013 */ 014 015 public abstract class Lexer { 016 protected abstract Token nextToken(); 017 018 protected Reader input; 019 020 protected int lookAhead = 1; 021 022 protected int[] lookAheadBuffer; 023 024 public void setInput(String inputString) { 025 lookAheadBuffer = new int[lookAhead]; 026 this.input = new StringReader(inputString); 027 fillLookAheadBuffer(); 028 } 029 030 protected void fillLookAheadBuffer() { 031 try { 032 lookAheadBuffer[0] = (char) input.read(); 033 } catch (Exception e) { 034 e.printStackTrace(); 035 } 036 037 } 038 039 protected char lookAhead(int position) { 040 return (char) lookAheadBuffer[position - 1]; 041 } 042 043 protected boolean isEndOfFile(int i) { 044 return (-1 == i); 045 } 046 047 protected void loadNextCharacterFromInput() { 048 049 boolean eofEncountered = false; 050 for (int i = 0; i < lookAhead - 1; i++) { 051 052 lookAheadBuffer[i] = lookAheadBuffer[i + 1]; 053 if (isEndOfFile(lookAheadBuffer[i])) { 054 eofEncountered = true; 055 break; 056 } 057 } 058 if (!eofEncountered) { 059 try { 060 lookAheadBuffer[lookAhead - 1] = input.read(); 061 } catch (Exception e) { 062 e.printStackTrace(); 063 } 064 } 065 066 } 067 068 protected void consume() { 069 loadNextCharacterFromInput(); 070 } 071 072 public void clear() { 073 this.input = null; 074 lookAheadBuffer = null; 075 076 } 077 078 }