Klasse Parser
Die Klasse Parser dient als Basisklasse für alle Parser und Übersetzer. Eine von Parser abgeleitete Klasse muss die Funktion startSymbol implementieren. Die Funktion compile der Klasse Parser übersetzt einen String, indem sie die Funktion startSymbol der abgeleiteten Klasse aufruft.
<?php
class Parser
{
protected $ALPHA="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
protected $DIGIT="0123456789";
protected $errormessage;
protected $errorposition;
public $inputstring;
public function compile($t)
{
$this->inputstring=$t;
$len=strlen($t);
$result="";
$this->errormessage="ok";
$this->errorposition=0;
try
{
$result=$this->startSymbol();
if (!$this->isEmpty())
throw new Exception("Zu viele Zeichen: $this->inputstring");
}
catch (Exception $e)
{
$this->errormessage=$e->getMessage();
$this->errorposition=strlen($this->inputstring);
}
$this->errorposition=$len-$this->errorposition;
return $result;
}
public function getErrorMessage()
{
return $this->errormessage;
}
public function getErrorPosition()
{
return $this->errorposition;
}
protected function lookahead($k=1)
{
if (strlen($this->inputstring)>=$k)
return substr($this->inputstring, 0, $k);
return "";
}
protected function comes($a)
{
return !$this->isEmpty() && strpos($this->inputstring, $a)===0;
}
protected function consume($k=1)
{
$this->inputstring=substr($this->inputstring, $k);
}
protected function symbol()
{
$s=$this->lookahead();
$this->consume();
return $s;
}
protected function trymatch($a)
{
if ($this->comes($a))
{
$this->consume(strlen($a));
return $a;
}
return "";
}
protected function match($a)
{
if ($this->trymatch($a))
return $a;
else
throw new Exception("Symbol $a erwartet");
}
protected function isEmpty()
{
return strlen($this->inputstring)==0;
}
protected function isLetter($a)
{
return strpos($this->ALPHA, $a)!==false;
}
protected function isDigit($a)
{
return strpos($this->DIGIT, $a)!==false;
}
protected function isCRLF($a)
{
return strpos("\r\n", $a)!==false;
}
protected function comesLetter()
{
return !$this->isEmpty() && $this->isLetter($this->lookahead());
}
protected function comesDigit()
{
return !$this->isEmpty() && $this->isDigit($this->lookahead());
}
protected function comesCRLF()
{
return !$this->isEmpty() && $this->isCRLF($this->lookahead());
}
protected function ignorespaces()
{
while ($this->comes(" "))
$this->consume();
return " ";
}
protected function ignoreCRLFs()
{
while ($this->comesCRLF())
$this->consume();
}
protected function ignoreBlanks()
{
while ($this->comes(" ") || $this->comesCRLF())
$this->consume();
return " ";
}
}
?>
[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