Klasse Parser
Die abstrakte Klasse Parser dient als Basisklasse für alle Parser und Übersetzer.
public abstract class Parser
{
protected static final String LOWER="abcdefghijklmnopqrstuvwxyz";
protected static final String UPPER="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
protected static final String ALPHA=LOWER+UPPER;
protected static final String DIGIT="0123456789";
protected String inputstring;
protected String errormessage;
protected int errorposition;
protected abstract Object compileStartSymbol();
public Object compile(String t)
{
inputstring=t;
Object r=null;
int len=inputstring.length();
errormessage="ok";
errorposition=0;
try
{
r=compileStartSymbol();
if (inputstring.length()>0)
throw new RuntimeException("Zuviele Zeichen:"+inputstring);
}
catch (RuntimeException e)
{
errormessage=e.getMessage();
errorposition=len-inputstring.length();
}
return r;
}
public String getErrorMessage()
{
return errormessage;
}
public int getErrorPosition()
{
return errorposition;
}
protected String lookahead(int k)
{
if (inputstring.length()>=k)
return inputstring.substring(0,k);
return "";
}
protected String lookahead()
{
return lookahead(1);
}
protected boolean comes(String a)
{
return inputstring.startsWith(a);
}
protected void consume(int k)
{
inputstring=inputstring.substring(k);
}
protected void consume(String a)
{
consume(a.length());
}
protected void consumeUntil(String s)
{
while (!comes(s))
consume(1);
}
protected boolean isEmpty()
{
return inputstring.length()==0;
}
protected boolean trymatch(String a)
{
if (comes(a))
{
consume(a);
return true;
}
return false;
}
protected void match(String a)
{
if (!trymatch(a))
throw new RuntimeException("Zeichen "+a+" erwartet");
}
protected String symbol()
{
String s=lookahead();
consume(1);
return s;
}
protected boolean isIn(String a, String set)
{
if (a.length()>0)
return set.indexOf(a)>=0;
return false;
}
protected boolean isLetter(String a)
{
return isIn(a, ALPHA);
}
protected boolean isDigit(String a)
{
return isIn(a, DIGIT);
}
protected boolean comesLetter()
{
return isLetter(lookahead());
}
protected boolean comesDigit()
{
return isDigit(lookahead());
}
protected int digit()
{
return Integer.parseInt(symbol());
}
protected void ignoreBlanks()
{
while (comes(" ") || comes("\r") || comes("\n"))
consume(1);
}
}
[up]
H.W. Lang mail@hwlang.de Impressum Datenschutz
Created: 06.11.2008 Updated: 19.02.2023
Diese Webseiten sind während meiner Lehrtätigkeit an der Hochschule Flensburg entstanden