PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
APPENDIX B ■ A SIMPLE PARSER

$scanresult = $statement->scan( $scanner );


if (! $scanresult || $scanner->tokenType() != \gi\parse\Scanner::EOF ) {
$msg = "";
$msg .= " line: {$scanner->line_no()} ";
$msg .= " char: {$scanner->char_no()}";
$msg .= " token: {$scanner->token()}\n";
throw new Exception( $msg );
}


$this->interpreter = $scanner->getContext()->popResult();
}


function expression() {
if (! isset( $this->expression ) ) {
$this->expression = new \gi\parse\SequenceParse();
$this->expression->add( $this->operand() );
$bools = new \gi\parse\RepetitionParse( );
$whichbool = new \gi\parse\AlternationParse();
$whichbool->add( $this->orExpr() );
$whichbool->add( $this->andExpr() );
$bools->add( $whichbool );
$this->expression->add( $bools );
}
return $this->expression;
}


function orExpr() {
$or = new \gi\parse\SequenceParse( );
$or->add( new \gi\parse\WordParse('or') )->discard();
$or->add( $this->operand() );
$or->setHandler( new BooleanOrHandler() );
return $or;
}


function andExpr() {
$and = new \gi\parse\SequenceParse();
$and->add( new \gi\parse\WordParse('and') )->discard();
$and->add( $this->operand() );
$and->setHandler( new BooleanAndHandler() );
return $and;
}


function operand() {
if (! isset( $this->operand ) ) {
$this->operand = new \gi\parse\SequenceParse( );
$comp = new \gi\parse\AlternationParse( );
$exp = new \gi\parse\SequenceParse( );
$exp->add( new \gi\parse\CharacterParse( '(' ))->discard();
$exp->add( $this->expression() );
$exp->add( new \gi\parse\CharacterParse( ')' ))->discard();
$comp->add( $exp );
$comp->add( new \gi\parse\StringLiteralParse() )

Free download pdf