<?php
namespace Tlf\Lexer;
/**
*
*/
class Helper {
/**
* Array of grammar classes
* @key file extension (or identifier) of the language or whatever text is being parsed
* @value class name of a `\Tlf\Lexer\Grammar` instance
*/
public array $grammars = [
'docblock'=>'Tlf\\Lexer\DocblockGrammar',
'php'=>'Tlf\\Lexer\\PhpGrammar',
'bash'=>'Tlf\\Lexer\\BashGrammar',
];
/**
* Create a
*/
public function getAstFromFile(string $file_path): \Tlf\Lexer\Ast {
$lexer = $this->get_lexer_for_file($file_path);
// ob_start();
$ast = $lexer->lexFile($file_path);
// ob_end_clean();
return $ast;
}
/**
* Get a Lexer initialized with the correct grammars.
*
* @param $language_ext the file extension for the language that is being scanned.
*/
public function get_lexer_for(string $language_ext): \Tlf\Lexer {
$language_ext = strtolower($language_ext);
if (!isset($this->grammars[$language_ext])){
$grammars = implode(", ", array_keys($this->grammars));
throw new \Exception("A grammar is not available for '$language_ext'. Available grammars are: $grammars");
}
$grammar_class = $this->grammars[$language_ext];
$grammar = new $grammar_class();
$lexer = new \Tlf\Lexer();
// $lexer->useCache = true;
// $lexer->debug = false;
$lexer->addGrammar($grammar, null, true);
return $lexer;
}
public function get_lexer_for_file(string $file_path): \Tlf\Lexer {
$ext = pathinfo($file_path, PATHINFO_EXTENSION);
return $this->get_lexer_for($ext);
}
}