菜谱项目

rebuildParsers.php 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 ('parseEncapsedDoc' == $name) {
  130. assertArgs(2, $args, $name);
  131. return 'foreach (' . $args[0] . ' as $s) { if ($s instanceof Node\Scalar\EncapsedStringPart) {'
  132. . ' $s->value = Node\Scalar\String_::parseEscapeSequences($s->value, null, ' . $args[1] . '); } }'
  133. . ' $s->value = preg_replace(\'~(\r\n|\n|\r)\z~\', \'\', $s->value);'
  134. . ' if (\'\' === $s->value) array_pop(' . $args[0] . ');';
  135. }
  136. if ('makeNop' == $name) {
  137. assertArgs(2, $args, $name);
  138. return '$startAttributes = ' . $args[1] . ';'
  139. . ' if (isset($startAttributes[\'comments\']))'
  140. . ' { ' . $args[0] . ' = new Stmt\Nop([\'comments\' => $startAttributes[\'comments\']]); }'
  141. . ' else { ' . $args[0] . ' = null; }';
  142. }
  143. if ('strKind' == $name) {
  144. assertArgs(1, $args, $name);
  145. return '(' . $args[0] . '[0] === "\'" || (' . $args[0] . '[1] === "\'" && '
  146. . '(' . $args[0] . '[0] === \'b\' || ' . $args[0] . '[0] === \'B\')) '
  147. . '? Scalar\String_::KIND_SINGLE_QUOTED : Scalar\String_::KIND_DOUBLE_QUOTED)';
  148. }
  149. if ('setDocStringAttrs' == $name) {
  150. assertArgs(2, $args, $name);
  151. return $args[0] . '[\'kind\'] = strpos(' . $args[1] . ', "\'") === false '
  152. . '? Scalar\String_::KIND_HEREDOC : Scalar\String_::KIND_NOWDOC; '
  153. . 'preg_match(\'/\A[bB]?<<<[ \t]*[\\\'"]?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)[\\\'"]?(?:\r\n|\n|\r)\z/\', ' . $args[1] . ', $matches); '
  154. . $args[0] . '[\'docLabel\'] = $matches[1];';
  155. }
  156. if ('prependLeadingComments' == $name) {
  157. assertArgs(1, $args, $name);
  158. return '$attrs = $this->startAttributeStack[#1]; $stmts = ' . $args[0] . '; '
  159. . 'if (!empty($attrs[\'comments\'])) {'
  160. . '$stmts[0]->setAttribute(\'comments\', '
  161. . 'array_merge($attrs[\'comments\'], $stmts[0]->getAttribute(\'comments\', []))); }';
  162. }
  163. return $matches[0];
  164. },
  165. $code
  166. );
  167. }
  168. function assertArgs($num, $args, $name) {
  169. if ($num != count($args)) {
  170. die('Wrong argument count for ' . $name . '().');
  171. }
  172. }
  173. function resolveStackAccess($code) {
  174. $code = preg_replace('/\$\d+/', '$this->semStack[$0]', $code);
  175. $code = preg_replace('/#(\d+)/', '$$1', $code);
  176. return $code;
  177. }
  178. function removeTrailingWhitespace($code) {
  179. $lines = explode("\n", $code);
  180. $lines = array_map('rtrim', $lines);
  181. return implode("\n", $lines);
  182. }
  183. function ensureDirExists($dir) {
  184. if (!is_dir($dir)) {
  185. mkdir($dir, 0777, true);
  186. }
  187. }
  188. //////////////////////////////
  189. /// Regex helper functions ///
  190. //////////////////////////////
  191. function regex($regex) {
  192. return '~' . LIB . '(?:' . str_replace('~', '\~', $regex) . ')~';
  193. }
  194. function magicSplit($regex, $string) {
  195. $pieces = preg_split(regex('(?:(?&string)|(?&comment)|(?&code))(*SKIP)(*FAIL)|' . $regex), $string);
  196. foreach ($pieces as &$piece) {
  197. $piece = trim($piece);
  198. }
  199. if ($pieces === ['']) {
  200. return [];
  201. }
  202. return $pieces;
  203. }