PHP code example of nielssp / parco

1. Go to this page and download the library: Download nielssp/parco 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/ */

    

nielssp / parco example snippets


class Myparser
{
    use \Parco\Combinator\RegexParsers;
}

class Myparser
{
    use \Parco\Combinator\RegexParsers;

    public function expr()
    {
    	return // a parser for expressions
    }

    public function term()
    {
    	return // a parser for terms
    }

    public function factor()
    {
    	return // a parser for factors
    }

    public function number()
    {
    	return // a parser for numbers
    }
}

class MyParser
{
    use \Parco\Combinator\RegexParsers;

    // ...

    public function __invoke($string)
    {
    	return $this->parseAll($this->expr, $string)->get();
    }
}

$myParser = new MyParser();
echo $myParser('1 + 5 - 7 / 2');

$this->elem('a') // exact element
$this->acceptIf(function ($elem) { return $elem instanceof NumberToken; }) // predicate
$this->char('a') // character (RegexParsers)
$this->string('goto') // string (RegexParsers)

$this->regex('/[a-z][a-z0-9]*/i')

$this->seq($this->a, $this->b, $this->c)

$this->a->seqL($this->b)

$this->alt($this->a, $this->b, $this->c)

$this->rep($this->a)

$this->opt($this->a)

$this->regex('/\d+/')->map(function ($digits) {
    return intval($digits);
});

$this->string('true')->withResult(true);

$this->regex('/\d+/')->withFailure('expected an integer');

public function expr()
{
    return $this->seq($this->term, $this->char("-"), $this->term);
}
public function term()
{
    return $this->alt(
    	$this->seq($this->char("("), $this->expr, $this->char(")")),
        $this->number
    );
}

public function expr()
{
    return $this->chainl(
        $this->term,
        $this->char('-')->withResult(function ($left, $right) {
            return $left - $right;
        })
    );
}

$result = $myParser($input);
if (! $result->successful) {
    $lines = explode("\n", $input);
    $line = $result->getInputLine($lines);
    $column = $result->getInputColumn($lines);
    echo 'Syntax Error: ' . $result->message
        . ' on line ' . $line
        . ' column ' . $column . PHP_EOL;
    if ($line > 0) {
        echo $lines[$line - 1] . PHP_EOL;
        echo str_repeat('-', $column - 1) . '^';
    }
}