StarterGrammar.php

<?php

namespace Tlf\Lexer\Test\Src;

/** 
 * An extremely simple grammar that builds sets of arglist from `(arg1,arg2,c) (list2_arg1,arg2)` 
 *
 * Basically just a proof of concept 
 */
class StarterGrammar extends \Tlf\Lexer\Grammar {

    // use Starter\LanguageDirectives;
    use Starter\OtherDirectives;

    /** The actual array of directives, built during onGrammarAdded() */
    public $directives;

    /** Defaults to 'startergrammar' */
    public function getNamespace(){return 'starter';}

    /** Combine the directives from traits */
    public function buildDirectives(){
        $this->directives = array_merge(
            // $this->_language_directives,
            $this->_other_directives,
        );
    }

    public function onGrammarAdded(\Tlf\Lexer $lexer){
        $this->buildDirectives();
        /** The first directive(s) to listen for. We're looking for an opening `(` */
        $lexer->addDirective($this->getDirectives(':parenthesis')['parenthesis']);
        // you can add more directives
    }

    public function onLexerStart(\Tlf\Lexer $lexer,\Tlf\Lexer\Ast $ast,\Tlf\Lexer\Token $token){
        // $lexer->addGrammar(new DocblockGrammar()); //if your language uses docblocks

        /** Just an example of setting an empty namespace at the start, so that all files have a namespace, even if its empty. */
        if ($ast->type=='file'){
            $ast->set('namespace', '');
        }
    }

    /** A method this grammar uses as an instruction to trim() the buffer */
    public function trimBuffer(\Tlf\Lexer $lexer, \Tlf\Lexer\Ast $ast, \Tlf\Lexer\Token $token, \stdClass $directive, array $args){
        $token->setBuffer(trim($token->buffer()));
    }
}