AstHead.php

<?php

namespace Tlf\Lexer2\StdLib;

/**
 * An interface for programs to interact with the AST on the top of the ast stack.
 */
class AstHead {

    public function __construct(
        protected \Tlf\Lexer2\Program $program
    ){

    }

    /**
     * Stop execution if the head ast is not the root ast.
     */
    public function is_root(): bool {
        if (count($this->program->ast_stack)==1)return true;

        $this->program->execute_commands = false;

        return false;
    }

    /**
     * Stop execution if the head ast is not the given type
     */
    public function is(string $type): bool {
        if ($this->head_ast()->type == $type)return true;
        //echo 'is not!';

        $this->program->execute_commands = false;

        return false;
    }

    public function head_ast(){
        return array_slice($this->program->ast_stack,-1)[0];
    }

    public function create_array(string $key){
        $this->head_ast()->set('People', []);
    }

    public function __get(string $property_name){
        $head = $this->head_ast();
        if (!isset($head->$property_name)){
            $head->$property_name = new \Tlf\Lexer2\ArrayAst('array', ['name'=>$property_name, 'values'=>[]]);
        }

        return $head->$property_name;
    }


}