PHP code example of railt / compiler

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

    

railt / compiler example snippets


use Railt\Component\Io\File;
use Railt\Component\Compiler\Compiler;

$parser = Compiler::load(File::fromSources('

/**
 * Grammar sources
 */
%token T_DIGIT      \d
%token T_PLUS       \+
%skip  T_WHITESPACE \s+

#Sum
  : <T_DIGIT> ::T_PLUS:: <T_DIGIT> 
  ;

'));

echo $parser->parse(File::fromSources('2 + 2'));

$compiler = Compiler::load(File::fromPathname('path/to/grammar.pp2'));

$compiler->setNamespace('Example')
    ->setClassName('Parser')
    ->saveTo(__DIR__);
xml
<Ast>
  <Sum offset="0">
    <T_DIGIT offset="0">2</T_DIGIT>
    <T_DIGIT offset="2">2</T_DIGIT>
  </Sum>
</Ast>
xml
<Ast>
  <Expression offset="0">
    <T_DIGIT offset="0">4</T_DIGIT>
    <Addition offset="2">
      <T_DIGIT offset="4">8</T_DIGIT>
      <Subtraction offset="6">
        <T_DIGIT offset="8">15</T_DIGIT>
        <Multiplication offset="11">
          <T_DIGIT offset="13">16</T_DIGIT>
          <Division offset="16">
            <T_DIGIT offset="18">23</T_DIGIT>
            <Addition offset="21">
              <T_DIGIT offset="23">-42</T_DIGIT>
            </Addition>
          </Division>
        </Multiplication>
      </Subtraction>
    </Addition>
  </Expression>
</Ast>