rebuildParsers.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. require __DIR__ . '/phpyLang.php';
  3. $grammarFileToName = [
  4. __DIR__ . '/php5.y' => 'Php5',
  5. __DIR__ . '/php7.y' => 'Php7',
  6. ];
  7. $tokensFile = __DIR__ . '/tokens.y';
  8. $tokensTemplate = __DIR__ . '/tokens.template';
  9. $skeletonFile = __DIR__ . '/parser.template';
  10. $tmpGrammarFile = __DIR__ . '/tmp_parser.phpy';
  11. $tmpResultFile = __DIR__ . '/tmp_parser.php';
  12. $resultDir = __DIR__ . '/../lib/PhpParser/Parser';
  13. $tokensResultsFile = $resultDir . '/Tokens.php';
  14. $kmyacc = getenv('KMYACC');
  15. if (!$kmyacc) {
  16. // Use phpyacc from dev dependencies by default.
  17. $kmyacc = __DIR__ . '/../vendor/bin/phpyacc';
  18. }
  19. $options = array_flip($argv);
  20. $optionDebug = isset($options['--debug']);
  21. $optionKeepTmpGrammar = isset($options['--keep-tmp-grammar']);
  22. ///////////////////
  23. /// Main script ///
  24. ///////////////////
  25. $tokens = file_get_contents($tokensFile);
  26. foreach ($grammarFileToName as $grammarFile => $name) {
  27. echo "Building temporary $name grammar file.\n";
  28. $grammarCode = file_get_contents($grammarFile);
  29. $grammarCode = str_replace('%tokens', $tokens, $grammarCode);
  30. $grammarCode = preprocessGrammar($grammarCode);
  31. file_put_contents($tmpGrammarFile, $grammarCode);
  32. $additionalArgs = $optionDebug ? '-t -v' : '';
  33. echo "Building $name parser.\n";
  34. $output = execCmd("$kmyacc $additionalArgs -m $skeletonFile -p $name $tmpGrammarFile");
  35. $resultCode = file_get_contents($tmpResultFile);
  36. $resultCode = removeTrailingWhitespace($resultCode);
  37. ensureDirExists($resultDir);
  38. file_put_contents("$resultDir/$name.php", $resultCode);
  39. unlink($tmpResultFile);
  40. echo "Building token definition.\n";
  41. $output = execCmd("$kmyacc -m $tokensTemplate $tmpGrammarFile");
  42. rename($tmpResultFile, $tokensResultsFile);
  43. if (!$optionKeepTmpGrammar) {
  44. unlink($tmpGrammarFile);
  45. }
  46. }
  47. ////////////////////////////////
  48. /// Utility helper functions ///
  49. ////////////////////////////////
  50. function ensureDirExists($dir) {
  51. if (!is_dir($dir)) {
  52. mkdir($dir, 0777, true);
  53. }
  54. }
  55. function execCmd($cmd) {
  56. $output = trim(shell_exec("$cmd 2>&1"));
  57. if ($output !== "") {
  58. echo "> " . $cmd . "\n";
  59. echo $output;
  60. }
  61. return $output;
  62. }