rebuildParsers.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. $grammarFileToName = [
  3. __DIR__ . '/php5.y' => 'Php5',
  4. __DIR__ . '/php7.y' => 'Php7',
  5. ];
  6. $tokensFile = __DIR__ . '/tokens.y';
  7. $tokensTemplate = __DIR__ . '/tokens.template';
  8. $skeletonFile = __DIR__ . '/parser.template';
  9. $tmpGrammarFile = __DIR__ . '/tmp_parser.phpy';
  10. $tmpResultFile = __DIR__ . '/tmp_parser.php';
  11. $resultDir = __DIR__ . '/../lib/PhpParser/Parser';
  12. $tokensResultsFile = $resultDir . '/Tokens.php';
  13. $kmyacc = getenv('KMYACC');
  14. if (!$kmyacc) {
  15. // Use phpyacc from dev dependencies by default.
  16. $kmyacc = __DIR__ . '/../vendor/bin/phpyacc';
  17. }
  18. $options = array_flip($argv);
  19. $optionDebug = isset($options['--debug']);
  20. $optionKeepTmpGrammar = isset($options['--keep-tmp-grammar']);
  21. ///////////////////////////////
  22. /// Utility regex constants ///
  23. ///////////////////////////////
  24. const LIB = '(?(DEFINE)
  25. (?<singleQuotedString>\'[^\\\\\']*+(?:\\\\.[^\\\\\']*+)*+\')
  26. (?<doubleQuotedString>"[^\\\\"]*+(?:\\\\.[^\\\\"]*+)*+")
  27. (?<string>(?&singleQuotedString)|(?&doubleQuotedString))
  28. (?<comment>/\*[^*]*+(?:\*(?!/)[^*]*+)*+\*/)
  29. (?<code>\{[^\'"/{}]*+(?:(?:(?&string)|(?&comment)|(?&code)|/)[^\'"/{}]*+)*+})
  30. )';
  31. const PARAMS = '\[(?<params>[^[\]]*+(?:\[(?&params)\][^[\]]*+)*+)\]';
  32. const ARGS = '\((?<args>[^()]*+(?:\((?&args)\)[^()]*+)*+)\)';
  33. ///////////////////
  34. /// Main script ///
  35. ///////////////////
  36. $tokens = file_get_contents($tokensFile);
  37. foreach ($grammarFileToName as $grammarFile => $name) {
  38. echo "Building temporary $name grammar file.\n";
  39. $grammarCode = file_get_contents($grammarFile);
  40. $grammarCode = str_replace('%tokens', $tokens, $grammarCode);
  41. $grammarCode = resolveNodes($grammarCode);
  42. $grammarCode = resolveMacros($grammarCode);
  43. $grammarCode = resolveStackAccess($grammarCode);
  44. file_put_contents($tmpGrammarFile, $grammarCode);
  45. $additionalArgs = $optionDebug ? '-t -v' : '';
  46. echo "Building $name parser.\n";
  47. $output = execCmd("$kmyacc $additionalArgs -m $skeletonFile -p $name $tmpGrammarFile");
  48. $resultCode = file_get_contents($tmpResultFile);
  49. $resultCode = removeTrailingWhitespace($resultCode);
  50. ensureDirExists($resultDir);
  51. file_put_contents("$resultDir/$name.php", $resultCode);
  52. unlink($tmpResultFile);
  53. echo "Building token definition.\n";
  54. $output = execCmd("$kmyacc -m $tokensTemplate $tmpGrammarFile");
  55. rename($tmpResultFile, $tokensResultsFile);
  56. if (!$optionKeepTmpGrammar) {
  57. unlink($tmpGrammarFile);
  58. }
  59. }
  60. ///////////////////////////////
  61. /// Preprocessing functions ///
  62. ///////////////////////////////
  63. function resolveNodes($code) {
  64. return preg_replace_callback(
  65. '~\b(?<name>[A-Z][a-zA-Z_\\\\]++)\s*' . PARAMS . '~',
  66. function($matches) {
  67. // recurse
  68. $matches['params'] = resolveNodes($matches['params']);
  69. $params = magicSplit(
  70. '(?:' . PARAMS . '|' . ARGS . ')(*SKIP)(*FAIL)|,',
  71. $matches['params']
  72. );
  73. $paramCode = '';
  74. foreach ($params as $param) {
  75. $paramCode .= $param . ', ';
  76. }
  77. return 'new ' . $matches['name'] . '(' . $paramCode . 'attributes())';
  78. },
  79. $code
  80. );
  81. }
  82. function resolveMacros($code) {
  83. return preg_replace_callback(
  84. '~\b(?<!::|->)(?!array\()(?<name>[a-z][A-Za-z]++)' . ARGS . '~',
  85. function($matches) {
  86. // recurse
  87. $matches['args'] = resolveMacros($matches['args']);
  88. $name = $matches['name'];
  89. $args = magicSplit(
  90. '(?:' . PARAMS . '|' . ARGS . ')(*SKIP)(*FAIL)|,',
  91. $matches['args']
  92. );
  93. if ('attributes' === $name) {
  94. assertArgs(0, $args, $name);
  95. return '$this->startAttributeStack[#1] + $this->endAttributes';
  96. }
  97. if ('stackAttributes' === $name) {
  98. assertArgs(1, $args, $name);
  99. return '$this->startAttributeStack[' . $args[0] . ']'
  100. . ' + $this->endAttributeStack[' . $args[0] . ']';
  101. }
  102. if ('init' === $name) {
  103. return '$$ = array(' . implode(', ', $args) . ')';
  104. }
  105. if ('push' === $name) {
  106. assertArgs(2, $args, $name);
  107. return $args[0] . '[] = ' . $args[1] . '; $$ = ' . $args[0];
  108. }
  109. if ('pushNormalizing' === $name) {
  110. assertArgs(2, $args, $name);
  111. return 'if (is_array(' . $args[1] . ')) { $$ = array_merge(' . $args[0] . ', ' . $args[1] . '); }'
  112. . ' else { ' . $args[0] . '[] = ' . $args[1] . '; $$ = ' . $args[0] . '; }';
  113. }
  114. if ('toArray' == $name) {
  115. assertArgs(1, $args, $name);
  116. return 'is_array(' . $args[0] . ') ? ' . $args[0] . ' : array(' . $args[0] . ')';
  117. }
  118. if ('parseVar' === $name) {
  119. assertArgs(1, $args, $name);
  120. return 'substr(' . $args[0] . ', 1)';
  121. }
  122. if ('parseEncapsed' === $name) {
  123. assertArgs(3, $args, $name);
  124. return 'foreach (' . $args[0] . ' as $s) { if ($s instanceof Node\Scalar\EncapsedStringPart) {'
  125. . ' $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, ' . $args[1] . ', ' . $args[2] . '); } }';
  126. }
  127. if ('makeNop' === $name) {
  128. assertArgs(3, $args, $name);
  129. return '$startAttributes = ' . $args[1] . ';'
  130. . ' if (isset($startAttributes[\'comments\']))'
  131. . ' { ' . $args[0] . ' = new Stmt\Nop($startAttributes + ' . $args[2] . '); }'
  132. . ' else { ' . $args[0] . ' = null; }';
  133. }
  134. if ('makeZeroLengthNop' == $name) {
  135. assertArgs(2, $args, $name);
  136. return '$startAttributes = ' . $args[1] . ';'
  137. . ' if (isset($startAttributes[\'comments\']))'
  138. . ' { ' . $args[0] . ' = new Stmt\Nop($this->createCommentNopAttributes($startAttributes[\'comments\'])); }'
  139. . ' else { ' . $args[0] . ' = null; }';
  140. }
  141. if ('strKind' === $name) {
  142. assertArgs(1, $args, $name);
  143. return '(' . $args[0] . '[0] === "\'" || (' . $args[0] . '[1] === "\'" && '
  144. . '(' . $args[0] . '[0] === \'b\' || ' . $args[0] . '[0] === \'B\')) '
  145. . '? Scalar\String_::KIND_SINGLE_QUOTED : Scalar\String_::KIND_DOUBLE_QUOTED)';
  146. }
  147. if ('prependLeadingComments' === $name) {
  148. assertArgs(1, $args, $name);
  149. return '$attrs = $this->startAttributeStack[#1]; $stmts = ' . $args[0] . '; '
  150. . 'if (!empty($attrs[\'comments\'])) {'
  151. . '$stmts[0]->setAttribute(\'comments\', '
  152. . 'array_merge($attrs[\'comments\'], $stmts[0]->getAttribute(\'comments\', []))); }';
  153. }
  154. return $matches[0];
  155. },
  156. $code
  157. );
  158. }
  159. function assertArgs($num, $args, $name) {
  160. if ($num != count($args)) {
  161. die('Wrong argument count for ' . $name . '().');
  162. }
  163. }
  164. function resolveStackAccess($code) {
  165. $code = preg_replace('/\$\d+/', '$this->semStack[$0]', $code);
  166. $code = preg_replace('/#(\d+)/', '$$1', $code);
  167. return $code;
  168. }
  169. function removeTrailingWhitespace($code) {
  170. $lines = explode("\n", $code);
  171. $lines = array_map('rtrim', $lines);
  172. return implode("\n", $lines);
  173. }
  174. function ensureDirExists($dir) {
  175. if (!is_dir($dir)) {
  176. mkdir($dir, 0777, true);
  177. }
  178. }
  179. function execCmd($cmd) {
  180. $output = trim(shell_exec("$cmd 2>&1"));
  181. if ($output !== "") {
  182. echo "> " . $cmd . "\n";
  183. echo $output;
  184. }
  185. return $output;
  186. }
  187. //////////////////////////////
  188. /// Regex helper functions ///
  189. //////////////////////////////
  190. function regex($regex) {
  191. return '~' . LIB . '(?:' . str_replace('~', '\~', $regex) . ')~';
  192. }
  193. function magicSplit($regex, $string) {
  194. $pieces = preg_split(regex('(?:(?&string)|(?&comment)|(?&code))(*SKIP)(*FAIL)|' . $regex), $string);
  195. foreach ($pieces as &$piece) {
  196. $piece = trim($piece);
  197. }
  198. if ($pieces === ['']) {
  199. return [];
  200. }
  201. return $pieces;
  202. }