lex

#!/usr/bin/php
<?php

// supports being in root dir, vendor/, vendor/bin, vendor/taeluf/lexer 
if (file_exists(__DIR__.'/vendor/autoload.php')){
    require(__DIR__.'/vendor/autoload.php');
} else if (file_exists(__DIR__.'/../vendor/autoload.php')){
    require(__DIR__.'/../vendor/autoload.php');
} else if (file_exists(__DIR__.'/../../vendor/autoload.php')){
    require(__DIR__.'/../../vendor/autoload.php');
} else if (file_exists(__DIR__.'/../../../vendor/autoload.php')){
    require(__DIR__.'/../../vendor/autoload.php');
} 
// I'm concerned this would be unexpected and cause weird results
// else if (file_exists(getcwd().'/vendor/autoload.php')){
    // require(getcwd().'/vendor/autoload.php');
// }


$cli = new \Tlf\Cli(getcwd(), $argv);
$cli->load_stdin();

$cli->load_command('main', 
    function(\Tlf\Cli $cli, array $args){
        $cli->call_command('help');
    },
    "Show the help menu"
);


$cli->load_command('file help', function(){echo 'HAAAALP';});
$cli->load_command('file',
    function(\Tlf\Cli $cli, array $args){
        $file = $args['--'][0] ?? null;
        $full_path = $cli->pwd.'/'.$file;

        if (!is_file($full_path)){
            $cli->notice("File not found.","File '$file' does not exist in '".basename($cli->pwd)."/'");
            return;
        }

        print_r($args);
        // exit;

        $helper = new \Tlf\Lexer\Helper();
        $lexer = $helper ->get_lexer_for_file($full_path);
        $lexer->useCache = array_key_exists('nocache', $args) ? false : true; 
        $lexer->debug = array_key_exists('debug',$args) ? true : false; 
        $lexer->stop_loop = isset($args['stop_at']) ? (int)$args['stop_at'] : -1; 

        if ($lexer->debug)ob_start();
        $ast = $lexer->lexFile($full_path);
        if ($lexer->debug)ob_end_clean();

        $json = json_encode($ast->getTree(), JSON_PRETTY_PRINT);

        echo "\n\n";
        echo $json;
        echo "\n\n";
    },
    "Parse a file and output the ast as json. Pass relative path to file to parse."
);

$cli->execute();