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