Skip to content

mohiva/pyramid

Repository files navigation

Mohiva Pyramid

The Mohiva Pyramid project is an operator precedence parser based on the Precedence climbing algorithm described by Theodore Norvell.

Installation

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.

Requirements

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.

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.

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

License

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

About

An operator precedence parser based on the “Precedence climbing” algorithm written in PHP

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages