001 /* 002 * Created on Sep 14, 2003 by Ravi Mohan 003 * 004 */ 005 package aima.logic.common; 006 007 /** 008 * @author Ravi Mohan 009 * 010 */ 011 012 public abstract class Parser { 013 014 protected Lexer lexer; 015 016 protected Token[] lookAheadBuffer; 017 018 protected int lookAhead = 3; 019 020 protected void fillLookAheadBuffer() { 021 for (int i = 0; i < lookAhead; i++) { 022 lookAheadBuffer[i] = lexer.nextToken(); 023 } 024 } 025 026 protected Token lookAhead(int i) { 027 return lookAheadBuffer[i - 1]; 028 } 029 030 protected void consume() { 031 loadNextTokenFromInput(); 032 } 033 034 protected void loadNextTokenFromInput() { 035 036 boolean eoiEncountered = false; 037 for (int i = 0; i < lookAhead - 1; i++) { 038 039 lookAheadBuffer[i] = lookAheadBuffer[i + 1]; 040 if (isEndOfInput(lookAheadBuffer[i])) { 041 eoiEncountered = true; 042 break; 043 } 044 } 045 if (!eoiEncountered) { 046 try { 047 lookAheadBuffer[lookAhead - 1] = lexer.nextToken(); 048 } catch (Exception e) { 049 e.printStackTrace(); 050 } 051 } 052 053 } 054 055 protected boolean isEndOfInput(Token t) { 056 return (t.getType() == LogicTokenTypes.EOI); 057 } 058 059 protected void match(String terminalSymbol) { 060 if (lookAhead(1).getText().equals(terminalSymbol)) { 061 consume(); 062 } else { 063 throw new RuntimeException( 064 "Syntax error detected at match. Expected " 065 + terminalSymbol + " but got " 066 + lookAhead(1).getText()); 067 } 068 069 } 070 071 public abstract ParseTreeNode parse(String input); 072 073 }