The Mohiva Pyramid project is an operator precedence parser based on the Precedence climbing algorithm described by Theodore Norvell.
You can install the library through composer.
1. Add mohiva/pyramid
as a dependency to your composer.json
file:
{
"require": {
"mohiva/pyramid": "dev-master"
}
}
2. Download and install Composer:
curl -s http://getcomposer.org/installer | php
3. Install your dependencies:
php composer.phar install
4. Use Composer’s autoloader
Composer comes with an autoloader for all vendor packages. You can use it if you add the following line to your bootstrap file.
require 'vendor/autoload.php';
For more information about composer please visit getcomposer.org.
Mohiva Pyramid needs PHP 5.4 to work.
The library comes with an example of how to use it. This example uses a simple grammar. It’s a very simple calculator with the following precedence table.
Unary | ||
– | Negative | 5 |
+ | Positive | 5 |
Binary | |||
+ | Addition | 2 | left associative |
– | Subtraction | 2 | left associative |
* | Multiplication | 3 | left associative |
/ | Division | 3 | left associative |
% | Modulo | 3 | left associative |
^ | Exponentiation | 4 | right associative |
Ternary | |||
?: | Ternary if | 1 | right associative |
The calculator can deal with parentheses, integer and floating-point values.
So lets talk about the steps to create your own language.
- Create your grammar and your precedence table
- Create a Lexer class to tokenize your input
- Create your nodes and operands
- Parse it
<?php
use com\mohiva\pyramid\Parser;
use com\mohiva\pyramid\example\Lexer;
use com\mohiva\pyramid\example\Grammar;
$lexer = new Lexer();
$stream = $lexer->scan('1.1 + 1.5');
$parser = new Parser(new Grammar());
$node = $parser->parse($stream);
$node->evaluate();
This project is Open Source and released under the terms of the New BSD License.