rebuildParsers.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. // check for kmyacc.exe binary in this directory, otherwise fall back to global name
  14. $kmyacc = __DIR__ . '/kmyacc.exe';
  15. if (!file_exists($kmyacc)) {
  16. $kmyacc = 'kmyacc';
  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 = trim(shell_exec("$kmyacc $additionalArgs -l -m $skeletonFile -p $name $tmpGrammarFile 2>&1"));
  48. echo "Output: \"$output\"\n";
  49. $resultCode = file_get_contents($tmpResultFile);
  50. $resultCode = removeTrailingWhitespace($resultCode);
  51. ensureDirExists($resultDir);
  52. file_put_contents("$resultDir/$name.php", $resultCode);
  53. unlink($tmpResultFile);
  54. echo "Building token definition.\n";
  55. $output = trim(shell_exec("$kmyacc -l -m $tokensTemplate $tmpGrammarFile 2>&1"));
  56. assert($output === '');
  57. rename($tmpResultFile, $tokensResultsFile);
  58. if (!$optionKeepTmpGrammar) {
  59. unlink($tmpGrammarFile);
  60. }
  61. }
  62. ///////////////////////////////
  63. /// Preprocessing functions ///
  64. ///////////////////////////////
  65. function resolveNodes($code) {
  66. return preg_replace_callback(
  67. '~\b(?<name>[A-Z][a-zA-Z_\\\\]++)\s*' . PARAMS . '~',
  68. function($matches) {
  69. // recurse
  70. $matches['params'] = resolveNodes($matches['params']);
  71. $params = magicSplit(
  72. '(?:' . PARAMS . '|' . ARGS . ')(*SKIP)(*FAIL)|,',
  73. $matches['params']
  74. );
  75. $paramCode = '';
  76. foreach ($params as $param) {
  77. $paramCode .= $param . ', ';
  78. }
  79. return 'new ' . $matches['name'] . '(' . $paramCode . 'attributes())';
  80. },
  81. $code
  82. );
  83. }
  84. function resolveMacros($code) {
  85. return preg_replace_callback(
  86. '~\b(?<!::|->)(?!array\()(?<name>[a-z][A-Za-z]++)' . ARGS . '~',
  87. function($matches) {
  88. // recurse
  89. $matches['args'] = resolveMacros($matches['args']);
  90. $name = $matches['name'];
  91. $args = magicSplit(
  92. '(?:' . PARAMS . '|' . ARGS . ')(*SKIP)(*FAIL)|,',
  93. $matches['args']
  94. );
  95. if ('attributes' == $name) {
  96. assertArgs(0, $args, $name);
  97. return '$this->startAttributeStack[#1] + $this->endAttributes';
  98. }
  99. if ('stackAttributes' == $name) {
  100. assertArgs(1, $args, $name);
  101. return '$this->startAttributeStack[' . $args[0] . ']'
  102. . ' + $this->endAttributeStack[' . $args[0] . ']';
  103. }
  104. if ('init' == $name) {
  105. return '$$ = array(' . implode(', ', $args) . ')';
  106. }
  107. if ('push' == $name) {
  108. assertArgs(2, $args, $name);
  109. return $args[0] . '[] = ' . $args[1] . '; $$ = ' . $args[0];
  110. }
  111. if ('pushNormalizing' == $name) {
  112. assertArgs(2, $args, $name);
  113. return 'if (is_array(' . $args[1] . ')) { $$ = array_merge(' . $args[0] . ', ' . $args[1] . '); }'
  114. . ' else { ' . $args[0] . '[] = ' . $args[1] . '; $$ = ' . $args[0] . '; }';
  115. }
  116. if ('toArray' == $name) {
  117. assertArgs(1, $args, $name);
  118. return 'is_array(' . $args[0] . ') ? ' . $args[0] . ' : array(' . $args[0] . ')';
  119. }
  120. if ('parseVar' == $name) {
  121. assertArgs(1, $args, $name);
  122. return 'substr(' . $args[0] . ', 1)';
  123. }
  124. if ('parseEncapsed' == $name) {
  125. assertArgs(3, $args, $name);
  126. return 'foreach (' . $args[0] . ' as $s) { if ($s instanceof Node\Scalar\EncapsedStringPart) {'
  127. . ' $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, ' . $args[1] . ', ' . $args[2] . '); } }';
  128. }
  129. if ('makeNop' == $name) {
  130. assertArgs(3, $args, $name);
  131. return '$startAttributes = ' . $args[1] . ';'
  132. . ' if (isset($startAttributes[\'comments\']))'
  133. . ' { ' . $args[0] . ' = new Stmt\Nop($startAttributes + ' . $args[2] . '); }'
  134. . ' else { ' . $args[0] . ' = null; }';
  135. }
  136. if ('strKind' == $name) {
  137. assertArgs(1, $args, $name);
  138. return '(' . $args[0] . '[0] === "\'" || (' . $args[0] . '[1] === "\'" && '
  139. . '(' . $args[0] . '[0] === \'b\' || ' . $args[0] . '[0] === \'B\')) '
  140. . '? Scalar\String_::KIND_SINGLE_QUOTED : Scalar\String_::KIND_DOUBLE_QUOTED)';
  141. }
  142. if ('prependLeadingComments' == $name) {
  143. assertArgs(1, $args, $name);
  144. return '$attrs = $this->startAttributeStack[#1]; $stmts = ' . $args[0] . '; '
  145. . 'if (!empty($attrs[\'comments\'])) {'
  146. . '$stmts[0]->setAttribute(\'comments\', '
  147. . 'array_merge($attrs[\'comments\'], $stmts[0]->getAttribute(\'comments\', []))); }';
  148. }
  149. return $matches[0];
  150. },
  151. $code
  152. );
  153. }
  154. function assertArgs($num, $args, $name) {
  155. if ($num != count($args)) {
  156. die('Wrong argument count for ' . $name . '().');
  157. }
  158. }
  159. function resolveStackAccess($code) {
  160. $code = preg_replace('/\$\d+/', '$this->semStack[$0]', $code);
  161. $code = preg_replace('/#(\d+)/', '$$1', $code);
  162. return $code;
  163. }
  164. function removeTrailingWhitespace($code) {
  165. $lines = explode("\n", $code);
  166. $lines = array_map('rtrim', $lines);
  167. return implode("\n", $lines);
  168. }
  169. function ensureDirExists($dir) {
  170. if (!is_dir($dir)) {
  171. mkdir($dir, 0777, true);
  172. }
  173. }
  174. //////////////////////////////
  175. /// Regex helper functions ///
  176. //////////////////////////////
  177. function regex($regex) {
  178. return '~' . LIB . '(?:' . str_replace('~', '\~', $regex) . ')~';
  179. }
  180. function magicSplit($regex, $string) {
  181. $pieces = preg_split(regex('(?:(?&string)|(?&comment)|(?&code))(*SKIP)(*FAIL)|' . $regex), $string);
  182. foreach ($pieces as &$piece) {
  183. $piece = trim($piece);
  184. }
  185. if ($pieces === ['']) {
  186. return [];
  187. }
  188. return $pieces;
  189. }