PHP code example of yosymfony / parser-utils

1. Go to this page and download the library: Download yosymfony/parser-utils library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yosymfony / parser-utils example snippets


use Yosymfony\ParserUtils\BasicLexer;

$lexer = new BasicLexer([
    '/^([0-9]+)/x' => 'T_NUMBER',
    '/^(\+)/x' => 'T_PLUS',
    '/^(-)/x' => 'T_MINUS',
    '/^\s+/' => 'T_SPACE',  // We do not surround it with parentheses because
                            // this is not meaningful for us in this case
]);

use Yosymfony\ParserUtils\AbstractParser;

class Parser extends AbstractParser
{
    protected function parseImplementation(TokenStream $stream)
    {
        $result = $stream->matchNext('T_NUMBER');

        while ($stream->isNextAny(['T_PLUS', 'T_MINUS'])) {
            switch ($stream->moveNext()->getName()) {
                case 'T_PLUS':
                    $result += $stream->matchNext('T_NUMBER');
                    break;
                case 'T_MINUS':
                    $result -= $stream->matchNext('T_NUMBER');
                    break;
                default:
                    throw new SyntaxErrorException("Something went wrong");
                    break;
            }
        }

        return $result;
    }
}

$parser = new Parser($lexer);
$parser->parse('1 + 1');          // 2

$lexer = new BasicLexer([...]);
$lexer->generateNewlineTokens()
      ->setNewlineTokenName('T_NL');

$lexer->tokenize('...');

$lexer = new BasicLexer([...]);
$lexer->generateEosToken()
      ->setEosTokenName('T_MY_EOS');

$lexer->tokenize('...');