php-parse 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env php
  2. <?php
  3. foreach ([__DIR__ . '/../../../autoload.php', __DIR__ . '/../vendor/autoload.php'] as $file) {
  4. if (file_exists($file)) {
  5. require $file;
  6. break;
  7. }
  8. }
  9. ini_set('xdebug.max_nesting_level', 3000);
  10. // Disable XDebug var_dump() output truncation
  11. ini_set('xdebug.var_display_max_children', -1);
  12. ini_set('xdebug.var_display_max_data', -1);
  13. ini_set('xdebug.var_display_max_depth', -1);
  14. list($operations, $files, $attributes) = parseArgs($argv);
  15. /* Dump nodes by default */
  16. if (empty($operations)) {
  17. $operations[] = 'dump';
  18. }
  19. if (empty($files)) {
  20. showHelp("Must specify at least one file.");
  21. }
  22. $lexer = new PhpParser\Lexer\Emulative(['usedAttributes' => [
  23. 'startLine', 'endLine', 'startFilePos', 'endFilePos', 'comments'
  24. ]]);
  25. $parser = (new PhpParser\ParserFactory)->create(
  26. PhpParser\ParserFactory::PREFER_PHP7,
  27. $lexer
  28. );
  29. $dumper = new PhpParser\NodeDumper([
  30. 'dumpComments' => true,
  31. 'dumpPositions' => $attributes['with-positions'],
  32. ]);
  33. $prettyPrinter = new PhpParser\PrettyPrinter\Standard;
  34. $traverser = new PhpParser\NodeTraverser();
  35. $traverser->addVisitor(new PhpParser\NodeVisitor\NameResolver);
  36. foreach ($files as $file) {
  37. if (strpos($file, '<?php') === 0) {
  38. $code = $file;
  39. echo "====> Code $code\n";
  40. } else {
  41. if (!file_exists($file)) {
  42. die("File $file does not exist.\n");
  43. }
  44. $code = file_get_contents($file);
  45. echo "====> File $file:\n";
  46. }
  47. if ($attributes['with-recovery']) {
  48. $errorHandler = new PhpParser\ErrorHandler\Collecting;
  49. $stmts = $parser->parse($code, $errorHandler);
  50. foreach ($errorHandler->getErrors() as $error) {
  51. $message = formatErrorMessage($error, $code, $attributes['with-column-info']);
  52. echo $message . "\n";
  53. }
  54. if (null === $stmts) {
  55. continue;
  56. }
  57. } else {
  58. try {
  59. $stmts = $parser->parse($code);
  60. } catch (PhpParser\Error $error) {
  61. $message = formatErrorMessage($error, $code, $attributes['with-column-info']);
  62. die($message . "\n");
  63. }
  64. }
  65. foreach ($operations as $operation) {
  66. if ('dump' === $operation) {
  67. echo "==> Node dump:\n";
  68. echo $dumper->dump($stmts, $code), "\n";
  69. } elseif ('pretty-print' === $operation) {
  70. echo "==> Pretty print:\n";
  71. echo $prettyPrinter->prettyPrintFile($stmts), "\n";
  72. } elseif ('json-dump' === $operation) {
  73. echo "==> JSON dump:\n";
  74. echo json_encode($stmts, JSON_PRETTY_PRINT), "\n";
  75. } elseif ('var-dump' === $operation) {
  76. echo "==> var_dump():\n";
  77. var_dump($stmts);
  78. } elseif ('resolve-names' === $operation) {
  79. echo "==> Resolved names.\n";
  80. $stmts = $traverser->traverse($stmts);
  81. }
  82. }
  83. }
  84. function formatErrorMessage(PhpParser\Error $e, $code, $withColumnInfo) {
  85. if ($withColumnInfo && $e->hasColumnInfo()) {
  86. return $e->getMessageWithColumnInfo($code);
  87. } else {
  88. return $e->getMessage();
  89. }
  90. }
  91. function showHelp($error = '') {
  92. if ($error) {
  93. echo $error . "\n\n";
  94. }
  95. die(<<<OUTPUT
  96. Usage: php-parse [operations] file1.php [file2.php ...]
  97. or: php-parse [operations] "<?php code"
  98. Turn PHP source code into an abstract syntax tree.
  99. Operations is a list of the following options (--dump by default):
  100. -d, --dump Dump nodes using NodeDumper
  101. -p, --pretty-print Pretty print file using PrettyPrinter\Standard
  102. -j, --json-dump Print json_encode() result
  103. --var-dump var_dump() nodes (for exact structure)
  104. -N, --resolve-names Resolve names using NodeVisitor\NameResolver
  105. -c, --with-column-info Show column-numbers for errors (if available)
  106. -P, --with-positions Show positions in node dumps
  107. -r, --with-recovery Use parsing with error recovery
  108. -h, --help Display this page
  109. Example:
  110. php-parse -d -p -N -d file.php
  111. Dumps nodes, pretty prints them, then resolves names and dumps them again.
  112. OUTPUT
  113. );
  114. }
  115. function parseArgs($args) {
  116. $operations = [];
  117. $files = [];
  118. $attributes = [
  119. 'with-column-info' => false,
  120. 'with-positions' => false,
  121. 'with-recovery' => false,
  122. ];
  123. array_shift($args);
  124. $parseOptions = true;
  125. foreach ($args as $arg) {
  126. if (!$parseOptions) {
  127. $files[] = $arg;
  128. continue;
  129. }
  130. switch ($arg) {
  131. case '--dump':
  132. case '-d':
  133. $operations[] = 'dump';
  134. break;
  135. case '--pretty-print':
  136. case '-p':
  137. $operations[] = 'pretty-print';
  138. break;
  139. case '--json-dump':
  140. case '-j':
  141. $operations[] = 'json-dump';
  142. break;
  143. case '--var-dump':
  144. $operations[] = 'var-dump';
  145. break;
  146. case '--resolve-names':
  147. case '-N';
  148. $operations[] = 'resolve-names';
  149. break;
  150. case '--with-column-info':
  151. case '-c';
  152. $attributes['with-column-info'] = true;
  153. break;
  154. case '--with-positions':
  155. case '-P':
  156. $attributes['with-positions'] = true;
  157. break;
  158. case '--with-recovery':
  159. case '-r':
  160. $attributes['with-recovery'] = true;
  161. break;
  162. case '--help':
  163. case '-h';
  164. showHelp();
  165. break;
  166. case '--':
  167. $parseOptions = false;
  168. break;
  169. default:
  170. if ($arg[0] === '-') {
  171. showHelp("Invalid operation $arg.");
  172. } else {
  173. $files[] = $arg;
  174. }
  175. }
  176. }
  177. return [$operations, $files, $attributes];
  178. }