An operator precedence parser based on the “Precedence climbing” algorithm written in PHP
Switch branches/tags
Nothing to show
Latest commit 946935f Dec 12, 2012 @akkie akkie Merge pull request #18 from akkie/master
Update travis image
Failed to load latest commit information.
src/com/mohiva/pyramid Small performance improvements Dec 6, 2012
.gitignore Use composer for dependency management instead of git submodules Jul 6, 2012
.travis.yml Update travis.yml to use composer Jul 6, 2012
LICENSE.textile Initial commit Jan 5, 2012
README.textile Update README.textile Dec 12, 2012
composer.json Add autoload part to composer json Jul 6, 2012
composer.lock Small performance improvements Dec 6, 2012


Mohiva Pyramid

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 | 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


Mohiva Pyramid needs PHP 5.4 to work.

How to use

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.

Negative 5
+ Positive 5
+ 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 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.

  1. Create your grammar and your precedence table
  2. Create a Lexer class to tokenize your input
  3. Create your nodes and operands
  4. Parse it

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);



This project is Open Source and released under the terms of the New BSD License.