face/parser

helper to write parser with php

dev-master 2015-12-04 17:31 UTC

This package is auto-updated.

Last update: 2024-11-06 19:19:15 UTC


README

Latest Stable Version Build Status Test Coverage

Tool to help to create a parser with php. Originally built to parse FQL queries but might be used for anything else.

Usage

    use Face\Parser\RegexpLexer as Lexer;
    use Face\Parser\TokenNavigation;
    
    $lexer = new Lexer();
    
    $lexer->setTokens([
    
        "function"                  => "T_FUNCTION",
        "class"                     => "T_CLASS",
        "[a-zA-Z_][a-zA-Z0-9_]*"    => "T_IDENTIFIER",
        "\\{"                       => "T_L_BRACKET",
        "\\}"                       => "T_R_BRACKET",
        "\\("                       => "T_L_PARENTHESIS",
        "\\)"                       => "T_R_PARENTHESIS",
        ";"                         => "T_SEMICOLON",
        "\\s+"                      => "T_WHITESPACE"
    
    ]);
    
    $string = 'class foo{
        function bar(){}
    }';
    
    $tokenArray = $lexer->tokenize($string);
    
    $tokens = new TokenNavigation($tokenArray);
    
    // Check if the first token is a "class" keyword or throws an exception
    $tokens->expectToBe("T_CLASS");
    
    $tokens->next();
    $tokens->expectToBe("T_IDENTIFIER");
    
    $className = $tokens->current()->getTokenValue();
    
    // while next token is a function keyword
    while($tokens->hasNext() && $tokens->look(1)->is("T_FUNCTION")){
        // Parse the function body
        someFunctionThatParsesTheFunctionAndJumpsToTheNextToken($tokens);
    }