Further modules included.
[yaffs-website] / web / modules / contrib / advagg / advagg_js_minify / jsqueeze.inc
1 <?php
2 // @codingStandardsIgnoreFile
3 // @ignore comment_docblock_file:file
4 // @ignore style_curly_braces:file
5 // @ignore style_string_spacing:file
6 // @ignore style_else_spacing:file
7 // @ignore comment_comment_docblock_missing:file
8 // @ignore comment_comment_eg:file
9 // @ignore production_code:file
10 // @ignore druplart_unary:file
11 // @ignore style_uppercase_constants:file
12 // @ignore comment_comment_space:file
13 // @ignore druplart_conditional_assignment:file
14 // @ignore style_paren_spacing:file
15 // @ignore style_no_tabs:file
16 // @ignore comment_docblock_comment:file
17 // @ignore comment_comment_indent:file
18 // @ignore style_comma_spacing:file
19 // @ignore style_elseif:file
20 // @ignore :file
21
22 /*
23  * Copyright (C) 2015 Nicolas Grekas - p@tchwork.com
24  *
25  * This library is free software; you can redistribute it and/or modify it
26  * under the terms of the (at your option):
27  * Apache License v2.0 (see provided LICENCE.ASL20 file), or
28  * GNU General Public License v2.0 (see provided LICENCE.GPLv2 file).
29  */
30
31 namespace Patchwork;
32
33 /*
34 *
35 * This class shrinks Javascript code
36 * (a process called minification nowadays)
37 *
38 * Should work with most valid Javascript code,
39 * even when semi-colons are missing.
40 *
41 * Features:
42 * - Removes comments and white spaces.
43 * - Renames every local vars, typically to a single character.
44 * - Renames also global vars, methods and properties, but only if they
45 *   are marked special by some naming convention. By default, special
46 *   var names begin with one or more "$", or with a single "_".
47 * - Renames also local/global vars found in strings,
48 *   but only if they are marked special.
49 * - Keep Microsoft's conditional comments.
50 * - Output is optimized for later HTTP compression.
51 *
52 * Notes:
53 * - Source code must be parse error free before processing.
54 * - In order to maximise later HTTP compression (deflate, gzip),
55 *   new variables names are chosen by considering closures,
56 *   variables' frequency and characters' frequency.
57 * - If you use with/eval then be careful.
58 *
59 * Bonus:
60 * - Replaces false/true by !1/!0
61 * - Replaces new Array/Object by []/{}
62 * - Merges consecutive "var" declarations with commas
63 * - Merges consecutive concatened strings
64 * - Fix a bug in Safari's parser (http://forums.asp.net/thread/1585609.aspx)
65 * - Can replace optional semi-colons by line feeds,
66 *   thus facilitating output debugging.
67 * - Keep important comments marked with /*!...
68 * - Treats three semi-colons ;;; like single-line comments
69 *   (http://dean.edwards.name/packer/2/usage/#triple-semi-colon).
70 * - Fix special catch scope across browsers
71 * - Work around buggy-handling of named function expressions in IE<=8
72 *
73 * TODO?
74 * - foo['bar'] => foo.bar
75 * - {'foo':'bar'} => {foo:'bar'}
76 * - Dead code removal (never used function)
77 * - Munge primitives: var WINDOW=window, etc.
78 */
79
80 class JSqueeze
81 {
82     const
83
84     SPECIAL_VAR_PACKER = '(\$+[a-zA-Z_]|_[a-zA-Z0-9$])[a-zA-Z0-9_$]*';
85
86     public
87
88     $charFreq;
89
90     protected
91
92     $strings,
93     $closures,
94     $str0,
95     $str1,
96     $argFreq,
97     $specialVarRx,
98     $keepImportantComments,
99
100     $varRx = '(?:[a-zA-Z_$])[a-zA-Z0-9_$]*',
101     $reserved = array(
102         'abstract','as','boolean','break','byte','case','catch','char','class',
103         'const','continue','debugger','default','delete','do','double','else',
104         'enum','export','extends','false','final','finally','float','for',
105         'function','goto','if','implements','import','in','instanceof','int',
106         'long','native','new','null','package','private','protected','public',
107         'return','short','static','super','switch','synchronized','this',
108         'throw','throws','transient','true','try','typeof','var','void',
109         'while','with','yield','let','interface',
110     );
111
112
113     function __construct()
114     {
115         $this->reserved = array_flip($this->reserved);
116         $this->charFreq = array_fill(0, 256, 0);
117     }
118
119     /**
120      * Squeezes a JavaScript source code.
121      *
122      * Set $singleLine to false if you want optional
123      * semi-colons to be replaced by line feeds.
124      *
125      * Set $keepImportantComments to false if you want /*! comments to be removed.
126      *
127      * $specialVarRx defines the regular expression of special variables names
128      * for global vars, methods, properties and in string substitution.
129      * Set it to false if you don't want any.
130      *
131      * If the analysed javascript source contains a single line comment like
132      * this one, then the directive will overwrite $specialVarRx:
133      *
134      * // jsqueeze.specialVarRx = your_special_var_regexp_here
135      *
136      * Only the first directive is parsed, others are ignored. It is not possible
137      * to redefine $specialVarRx in the middle of the javascript source.
138      *
139      * Example:
140      * $parser = new JSqueeze;
141      * $squeezed_js = $parser->squeeze($fat_js);
142      */
143
144     function squeeze($code, $singleLine = true, $keepImportantComments = true, $specialVarRx = false)
145     {
146         $code = trim($code);
147         if ('' === $code) return '';
148
149         $this->argFreq = array(-1 => 0);
150         $this->specialVarRx = $specialVarRx;
151         $this->keepImportantComments = !!$keepImportantComments;
152
153         if (preg_match("#//[ \t]*jsqueeze\.specialVarRx[ \t]*=[ \t]*([\"']?)(.*)\1#i", $code, $key))
154         {
155             if (!$key[1])
156             {
157                 $key[2] = trim($key[2]);
158                 $key[1] = strtolower($key[2]);
159                 $key[1] = $key[1] && $key[1] != 'false' && $key[1] != 'none' && $key[1] != 'off';
160             }
161
162             $this->specialVarRx = $key[1] ? $key[2] : false;
163         }
164
165         // Remove capturing parentheses
166         $this->specialVarRx && $this->specialVarRx = preg_replace('/(?<!\\\\)((?:\\\\\\\\)*)\((?!\?)/', '(?:', $this->specialVarRx);
167
168         false !== strpos($code, "\r"          ) && $code = strtr(str_replace("\r\n", "\n", $code), "\r", "\n");
169         false !== strpos($code, "\xC2\x85"    ) && $code = str_replace("\xC2\x85"    , "\n", $code); // Next Line
170         false !== strpos($code, "\xE2\x80\xA8") && $code = str_replace("\xE2\x80\xA8", "\n", $code); // Line Separator
171         false !== strpos($code, "\xE2\x80\xA9") && $code = str_replace("\xE2\x80\xA9", "\n", $code); // Paragraph Separator
172
173         list($code, $this->strings ) = $this->extractStrings( $code);
174         list($code, $this->closures) = $this->extractClosures($code);
175
176         $key = "//''\"\"#0'"; // This crap has a wonderful property: it can not happen in any valid javascript, even in strings
177         $this->closures[$key] =& $code;
178
179         $tree = array($key => array('parent' => false));
180         $this->makeVars($code, $tree[$key], $key);
181         $this->renameVars($tree[$key], true);
182
183         $code = substr($tree[$key]['code'], 1);
184         $code = preg_replace("'\breturn !'", 'return!', $code);
185         $code = preg_replace("'\}(?=(else|while)[^\$.a-zA-Z0-9_])'", "}\r", $code);
186         $code = str_replace(array_keys($this->strings), array_values($this->strings), $code);
187
188         if ($singleLine) $code = strtr($code, "\n", ';');
189         else $code = str_replace("\n", ";\n", $code);
190         false !== strpos($code, "\r") && $code = strtr(trim($code), "\r", "\n");
191
192         // Cleanup memory
193         $this->charFreq = array_fill(0, 256, 0);
194         $this->strings = $this->closures = $this->argFreq = array();
195         $this->str0 = $this->str1 = '';
196
197         return $code;
198     }
199
200
201     protected function extractStrings($f)
202     {
203         if ($cc_on = false !== strpos($f, '@cc_on'))
204         {
205             // Protect conditional comments from being removed
206             $f = str_replace('#', '##', $f);
207             $f = str_replace('/*@', '1#@', $f);
208             $f = preg_replace("'//@([^\n]+)'", '2#@$1@#3', $f);
209             $f = str_replace('@*/', '@#1', $f);
210         }
211
212         $len = strlen($f);
213         $code = str_repeat(' ', $len);
214         $j = 0;
215
216         $strings = array();
217         $K = 0;
218
219         $instr = false;
220
221         $q = array(
222             "'", '"',
223             "'" => 0,
224             '"' => 0,
225         );
226
227         // Extract strings, removes comments
228         for ($i = 0; $i < $len; ++$i)
229         {
230             if ($instr)
231             {
232                 if ('//' == $instr)
233                 {
234                     if ("\n" == $f[$i])
235                     {
236                         $f[$i--] = ' ';
237                         $instr = false;
238                     }
239                 }
240                 else if ($f[$i] == $instr || ('/' == $f[$i] && "/'" == $instr))
241                 {
242                     if ('!' == $instr) ;
243                     else if ('*' == $instr)
244                     {
245                         if ('/' == $f[$i+1])
246                         {
247                             ++$i;
248                             $instr = false;
249                         }
250                     }
251                     else
252                     {
253                         if ("/'" == $instr)
254                         {
255                             while (isset ($f[$i+1]) && false !== strpos('gmi', $f[$i+1])) $s[] = $f[$i++];
256                             $s[] = $f[$i];
257                         }
258
259                         $instr = false;
260                     }
261                 }
262                 else if ('*' == $instr) ;
263                 else if ('!' == $instr)
264                 {
265                     if ('*' == $f[$i] && '/' == $f[$i+1])
266                     {
267                         $s[] = "*/\r";
268                         ++$i;
269                         $instr = false;
270                     }
271                     else if ("\n" == $f[$i]) $s[] = "\r";
272                     else $s[] = $f[$i];
273                 }
274                 else if ('\\' == $f[$i])
275                 {
276                     ++$i;
277
278                     if ("\n" != $f[$i])
279                     {
280                         isset($q[$f[$i]]) && ++$q[$f[$i]];
281                         $s[] = '\\' . $f[$i];
282                     }
283                 }
284                 else if ('[' == $f[$i] && "/'" == $instr)
285                 {
286                     $instr = '/[';
287                     $s[] = '[';
288                 }
289                 else if (']' == $f[$i] && '/[' == $instr)
290                 {
291                     $instr = "/'";
292                     $s[] = ']';
293                 }
294                 else if ("'" == $f[$i] || '"' == $f[$i])
295                 {
296                     ++$q[$f[$i]];
297                     $s[] = '\\' . $f[$i];
298                 }
299                 else $s[] = $f[$i];
300             }
301             else switch ($f[$i])
302             {
303             case ';':
304                 // Remove triple semi-colon
305                 if ($i>0 && ';' == $f[$i-1] && $i+1 < $len && ';' == $f[$i+1]) $f[$i] = $f[$i+1] = '/';
306                 else
307                 {
308                     $code[++$j] = ';';
309                     break;
310                 }
311
312             case '/':
313                 if ('*' == $f[$i+1])
314                 {
315                     ++$i;
316                     $instr = '*';
317
318                     if ($this->keepImportantComments && '!' == $f[$i+1])
319                     {
320                         ++$i;
321                         // no break here
322                     }
323                     else break;
324                 }
325                 else if ('/' == $f[$i+1])
326                 {
327                     ++$i;
328                     $instr = '//';
329                     break;
330                 }
331                 else
332                 {
333                     $a = $j && ' ' == $code[$j] ? $code[$j-1] : $code[$j];
334                     if (false !== strpos('-!%&;<=>~:^+|,(*?[{ ', $a)
335                         || (false !== strpos('oenfd', $a)
336                         && preg_match(
337                             "'(?<![\$.a-zA-Z0-9_])(do|else|return|typeof|yield) ?$'",
338                             substr($code, $j-7, 8)
339                         )))
340                     {
341                         $key = "//''\"\"" . $K++ . $instr = "/'";
342                         $a = $j;
343                         $code .= $key;
344                         while (isset($key[++$j-$a-1])) $code[$j] = $key[$j-$a-1]; --$j;
345                         isset($s) && ($s = implode('', $s)) && $cc_on && $this->restoreCc($s);
346                         $strings[$key] = array('/');
347                         $s =& $strings[$key];
348                     }
349                     else $code[++$j] = '/';
350
351                     break;
352                 }
353
354             case "'":
355             case '"':
356                 $instr = $f[$i];
357                 $key = "//''\"\"" . $K++ . ('!' == $instr ? ']' : "'");
358                 $a = $j;
359                 $code .= $key;
360                 while (isset($key[++$j-$a-1])) $code[$j] = $key[$j-$a-1]; --$j;
361                 isset($s) && ($s = implode('', $s)) && $cc_on && $this->restoreCc($s);
362                 $strings[$key] = array();
363                 $s =& $strings[$key];
364                 '!' == $instr && $s[] = "\r/*!";
365
366                 break;
367
368             case "\n":
369                 if ($j > 5)
370                 {
371                     ' ' == $code[$j] && --$j;
372
373                     $code[++$j] =
374                         false !== strpos('kend', $code[$j-1])
375                             && preg_match(
376                                 "'(?<![\$.a-zA-Z0-9_])(break|continue|return|yield) ?$'",
377                                 substr($code, $j-8, 9)
378                             )
379                         ? ';' : ' ';
380
381                     break;
382                 }
383
384             case "\t": $f[$i] = ' ';
385             case ' ':
386                 if (!$j || ' ' == $code[$j]) break;
387
388             default:
389                 $code[++$j] = $f[$i];
390             }
391         }
392
393         isset($s) && ($s = implode('', $s)) && $cc_on && $this->restoreCc($s);
394         unset($s);
395
396         $code = substr($code, 0, $j+1);
397         $cc_on && $this->restoreCc($code, false);
398
399         // Protect wanted spaces and remove unwanted ones
400         $code = str_replace('- -', "-\x7F-", $code);
401         $code = str_replace('+ +', "+\x7F+", $code);
402         $code = preg_replace("'(\d)\s+\.\s*([a-zA-Z\$_[(])'", "$1\x7F.$2", $code);
403         $code = preg_replace("# ([-!%&;<=>~:.^+|,()*?[\]{}/']+)#", '$1', $code);
404         $code = preg_replace( "#([-!%&;<=>~:.^+|,()*?[\]{}/]+) #", '$1', $code);
405
406         // Replace new Array/Object by []/{}
407         false !== strpos($code, 'new Array' ) && $code = preg_replace( "'new Array(?:\(\)|([;\])},:]))'", '[]$1', $code);
408         false !== strpos($code, 'new Object') && $code = preg_replace("'new Object(?:\(\)|([;\])},:]))'", '{}$1', $code);
409
410         // Add missing semi-colons after curly braces
411         // This adds more semi-colons than strictly needed,
412         // but it seems that later gzipping is favorable to the repetition of "};"
413         $code = preg_replace("'\}(?![:,;.()\[\]}\|&]|(else|catch|finally|while)[^\$.a-zA-Z0-9_])'", '};', $code);
414
415         // Tag possible empty instruction for easy detection
416         $code = preg_replace("'(?<![\$.a-zA-Z0-9_])if\('"   , '1#(', $code);
417         $code = preg_replace("'(?<![\$.a-zA-Z0-9_])for\('"  , '2#(', $code);
418         $code = preg_replace("'(?<![\$.a-zA-Z0-9_])while\('", '3#(', $code);
419
420         $forPool = array();
421         $instrPool = array();
422         $s = 0;
423
424         $f = array();
425         $j = -1;
426
427         // Remove as much semi-colon as possible
428         $len = strlen($code);
429         for ($i = 0; $i < $len; ++$i)
430         {
431             switch ($code[$i])
432             {
433             case '(':
434                 if ($j>=0 && "\n" == $f[$j]) $f[$j] = ';';
435
436                 ++$s;
437
438                 if ($i && '#' == $code[$i-1])
439                 {
440                     $instrPool[$s - 1] = 1;
441                     if ('2' == $code[$i-2]) $forPool[$s] = 1;
442                 }
443
444                 $f[++$j] = '(';
445                 break;
446
447             case ']':
448             case ')':
449                 if ($i+1 < $len && !isset($forPool[$s]) && !isset($instrPool[$s-1]) && preg_match("'[a-zA-Z0-9_\$]'", $code[$i+1]))
450                 {
451                     $f[$j] .= $code[$i];
452                     $f[++$j] = "\n";
453                 }
454                 else $f[++$j] = $code[$i];
455
456                 if (')' == $code[$i])
457                 {
458                     unset($forPool[$s]);
459                     --$s;
460                 }
461
462                 continue 2;
463
464             case '}':
465                 if ("\n" == $f[$j]) $f[$j] = '}';
466                 else $f[++$j] = '}';
467                 break;
468
469             case ';':
470                 if (isset($forPool[$s]) || isset($instrPool[$s])) $f[++$j] = ';';
471                 else if ($j>=0 && "\n" != $f[$j] && ';' != $f[$j]) $f[++$j] = "\n";
472
473                 break;
474
475             case '#':
476                 switch ($f[$j])
477                 {
478                 case '1': $f[$j] = 'if';    break 2;
479                 case '2': $f[$j] = 'for';   break 2;
480                 case '3': $f[$j] = 'while'; break 2;
481                 }
482
483             case '[';
484                 if ($j>=0 && "\n" == $f[$j]) $f[$j] = ';';
485
486             default: $f[++$j] = $code[$i];
487             }
488
489             unset($instrPool[$s]);
490         }
491
492         $f = implode('', $f);
493         $cc_on && $f = str_replace('@#3', "\n", $f);
494
495         // Fix "else ;" empty instructions
496         $f = preg_replace("'(?<![\$.a-zA-Z0-9_])else\n'", "\n", $f);
497
498         $r1 = array( // keywords with a direct object
499             'case','delete','do','else','function','in','instanceof','break',
500             'new','return','throw','typeof','var','void','yield','let','if',
501             'const',
502         );
503
504         $r2 = array( // keywords with a subject
505             'in','instanceof',
506         );
507
508         // Fix missing semi-colons
509         $f = preg_replace("'(?<!(?<![a-zA-Z0-9_\$])" . implode(')(?<!(?<![a-zA-Z0-9_\$])', $r1) . ") (?!(" . implode('|', $r2) . ")(?![a-zA-Z0-9_\$]))'", "\n", $f);
510         $f = preg_replace("'(?<!(?<![a-zA-Z0-9_\$])do)(?<!(?<![a-zA-Z0-9_\$])else) if\('", "\nif(", $f);
511         $f = preg_replace("'(?<=--|\+\+)(?<![a-zA-Z0-9_\$])(" . implode('|', $r1) . ")(?![a-zA-Z0-9_\$])'", "\n$1", $f);
512         $f = preg_replace("'(?<![a-zA-Z0-9_\$])for\neach\('", 'for each(', $f);
513         $f = preg_replace("'(?<![a-zA-Z0-9_\$])\n(" . implode('|', $r2) . ")(?![a-zA-Z0-9_\$])'", '$1', $f);
514
515         // Merge strings
516         if ($q["'"] > $q['"']) $q = array($q[1], $q[0]);
517         $f = preg_replace("#//''\"\"[0-9]+'#", $q[0] . '$0' . $q[0], $f);
518         strpos($f, $q[0] . '+' . $q[0]) && $f = str_replace($q[0] . '+' . $q[0], '', $f);
519         $len = count($strings);
520         foreach ($strings as $r1 => &$r2)
521         {
522             $r2 = "/'" == substr($r1, -2)
523                 ? str_replace(array("\\'", '\\"'), array("'", '"'), $r2)
524                 : str_replace('\\' . $q[1], $q[1], $r2);
525         }
526
527         // Restore wanted spaces
528         $f = strtr($f, "\x7F", ' ');
529
530         return array($f, $strings);
531     }
532
533     protected function extractClosures($code)
534     {
535         $code = ';' . $code;
536
537         $this->argFreq[-1] += substr_count($code, '}catch(');
538
539         if ($this->argFreq[-1])
540         {
541             // Special catch scope handling
542
543             // FIXME: this implementation doesn't work with nested catch scopes who need
544             // access to their parent's caught variable (but who needs that?).
545
546             $f = preg_split("@}catch\(({$this->varRx})@", $code, -1, PREG_SPLIT_DELIM_CAPTURE);
547
548             $code = 'catch$scope$var' . mt_rand();
549             $this->specialVarRx = $this->specialVarRx ? '(?:' . $this->specialVarRx . '|' . preg_quote($code) . ')' : preg_quote($code);
550             $i = count($f) - 1;
551
552             while ($i)
553             {
554                 $c = 1;
555                 $j = 0;
556                 $l = strlen($f[$i]);
557
558                 while ($c && $j < $l)
559                 {
560                     $s = $f[$i][$j++];
561                     $c += '(' == $s ? 1 : (')' == $s ? -1 : 0);
562                 }
563
564                 if (!$c) do
565                 {
566                     $s = $f[$i][$j++];
567                     $c += '{' == $s ? 1 : ('}' == $s ? -1 : 0);
568                 }
569                 while ($c && $j < $l);
570
571                 $c = preg_quote($f[$i-1], '#');
572                 $f[$i-2] .= '}catch(' . preg_replace("#([.,{]?)(?<![a-zA-Z0-9_\$@]){$c}\\b#", '$1' . $code, $f[$i-1] . substr($f[$i], 0, $j)) . substr($f[$i], $j);
573
574                 unset($f[$i--], $f[$i--]);
575             }
576
577             $code = $f[0];
578         }
579
580         $f = preg_split("'(?<![a-zA-Z0-9_\$])(function[ (].*?\{)'", $code, -1, PREG_SPLIT_DELIM_CAPTURE);
581         $i = count($f) - 1;
582         $closures = array();
583
584         while ($i)
585         {
586             $c = 1;
587             $j = 0;
588             $l = strlen($f[$i]);
589
590             while ($c && $j < $l)
591             {
592                 $s = $f[$i][$j++];
593                 $c += '{' == $s ? 1 : ('}' == $s ? -1 : 0);
594             }
595
596             switch (substr($f[$i-2], -1))
597             {
598             default: if (false !== $c = strpos($f[$i-1], ' ', 8)) break;
599             case false: case "\n": case ';': case '{': case '}': case ')': case ']':
600                 $c = strpos($f[$i-1], '(', 8);
601             }
602
603             $l = "//''\"\"#$i'";
604             $code = substr($f[$i-1], $c);
605             $closures[$l] = $code . substr($f[$i], 0, $j);
606             $f[$i-2] .= substr($f[$i-1], 0, $c) . $l . substr($f[$i], $j);
607
608             if ('(){' !== $code)
609             {
610                 $j = substr_count($code, ',');
611                 do isset($this->argFreq[$j]) ? ++$this->argFreq[$j] : $this->argFreq[$j] = 1;
612                 while ($j--);
613             }
614
615             $i -= 2;
616         }
617
618         return array($f[0], $closures);
619     }
620
621     protected function makeVars($closure, &$tree, $key)
622     {
623         $tree['code'] =& $closure;
624         $tree['nfe'] = false;
625         $tree['used'] = array();
626         $tree['local'] = array();
627
628         // Replace multiple "var" declarations by a single one
629         $closure = preg_replace_callback("'(?<=[\n\{\}])var [^\n\{\}]+(?:\nvar [^\n\{\}]+)+'", array(&$this, 'mergeVarDeclarations'), $closure);
630
631         // Get all local vars (functions, arguments and "var" prefixed)
632
633         $vars =& $tree['local'];
634
635         if (preg_match("'^( [^(]*)?\((.*?)\)\{'", $closure, $v))
636         {
637             if ($v[1])
638             {
639                 $vars[$tree['nfe'] = substr($v[1], 1)] = -1;
640                 $tree['parent']['local'][';' . $key] =& $vars[$tree['nfe']];
641             }
642
643             if ($v[2])
644             {
645                 $i = 0;
646                 $v = explode(',', $v[2]);
647                 foreach ($v as $w) $vars[$w] = $this->argFreq[$i++] - 1; // Give a bonus to argument variables
648             }
649         }
650
651         $v = preg_split("'(?<![\$.a-zA-Z0-9_])var '", $closure);
652         if ($i = count($v) - 1)
653         {
654             $w = array();
655
656             while ($i)
657             {
658                 $j = $c = 0;
659                 $l = strlen($v[$i]);
660
661                 while ($j < $l)
662                 {
663                     switch ($v[$i][$j])
664                     {
665                     case '(': case '[': case '{':
666                         ++$c;
667                         break;
668
669                     case ')': case ']': case '}':
670                         if ($c-- <= 0) break 2;
671                         break;
672
673                     case ';': case "\n":
674                         if (!$c) break 2;
675
676                     default:
677                         $c || $w[] = $v[$i][$j];
678                     }
679
680                     ++$j;
681                 }
682
683                 $w[] = ',';
684                 --$i;
685             }
686
687             $v = explode(',', implode('', $w));
688             foreach ($v as $w) if (preg_match("'^{$this->varRx}'", $w, $v)) isset($vars[$v[0]]) || $vars[$v[0]] = 0;
689         }
690
691         if (preg_match_all("@function ({$this->varRx})//''\"\"#@", $closure, $v))
692         {
693             foreach ($v[1] as $w) isset($vars[$w]) || $vars[$w] = 0;
694         }
695
696         if ($this->argFreq[-1] && preg_match_all("@}catch\(({$this->varRx})@", $closure, $v))
697         {
698             $v[0] = array();
699             foreach ($v[1] as $w) isset($v[0][$w]) ? ++$v[0][$w] : $v[0][$w] = 1;
700             foreach ($v[0] as $w => $v) $vars[$w] = $this->argFreq[-1] - $v;
701         }
702
703         // Get all used vars, local and non-local
704
705         $vars =& $tree['used'];
706
707         if (preg_match_all("#([.,{]?)(?<![a-zA-Z0-9_\$])({$this->varRx})(:?)#", $closure, $w, PREG_SET_ORDER))
708         {
709             foreach ($w as $k)
710             {
711                 if (',' === $k[1] || '{' === $k[1])
712                 {
713                     if (':' === substr($k[3], -1)) $k = '.' . $k[2];
714                     else $k = $k[2];
715                 }
716                 else $k = $k[1] . $k[2];
717
718                 isset($vars[$k]) ? ++$vars[$k] : $vars[$k] = 1;
719             }
720         }
721
722         if (preg_match_all("#//''\"\"[0-9]+(?:['!]|/')#", $closure, $w)) foreach ($w[0] as $a)
723         {
724             $v = "'" === substr($a, -1) && "/'" !== substr($a, -2) && $this->specialVarRx
725                 ? preg_split("#([.,{]?(?<![a-zA-Z0-9_\$@]){$this->specialVarRx}:?)#", $this->strings[$a], -1, PREG_SPLIT_DELIM_CAPTURE)
726                 : array($this->strings[$a]);
727             $a = count($v);
728
729             for ($i = 0; $i < $a; ++$i)
730             {
731                 $k = $v[$i];
732
733                 if (1 === $i%2)
734                 {
735                     if (',' === $k[0] || '{' === $k[0])
736                     {
737                         if (':' === substr($k, -1)) $k = '.' . substr($k, 1, -1);
738                         else $k = substr($k, 1);
739                     }
740                     else if (':' === substr($k, -1)) $k = substr($k, 0, -1);
741
742                     $w =& $tree;
743
744                     while (isset($w['parent']) && !(isset($w['used'][$k]) || isset($w['local'][$k]))) $w =& $w['parent'];
745
746                     (isset($w['used'][$k]) || isset($w['local'][$k])) && (isset($vars[$k]) ? ++$vars[$k] : $vars[$k] = 1);
747
748                     unset($w);
749                 }
750
751                 if (0 === $i%2 || !isset($vars[$k])) foreach (count_chars($v[$i], 1) as $k => $w) $this->charFreq[$k] += $w;
752             }
753         }
754
755         // Propagate the usage number to parents
756
757         foreach ($vars as $w => $a)
758         {
759             $k =& $tree;
760             $chain = array();
761             do
762             {
763                 $vars =& $k['local'];
764                 $chain[] =& $k;
765                 if (isset($vars[$w]))
766                 {
767                     unset($k['used'][$w]);
768                     if (isset($vars[$w])) $vars[$w] += $a;
769                     else $vars[$w] = $a;
770                     $a = false;
771                     break;
772                 }
773             }
774             while ($k['parent'] && $k =& $k['parent']);
775
776             if ($a && !$k['parent'])
777             {
778                 if (isset($vars[$w])) $vars[$w] += $a;
779                 else $vars[$w] = $a;
780             }
781
782             if (isset($tree['used'][$w]) && isset($vars[$w])) foreach ($chain as &$b)
783             {
784                 isset($b['local'][$w]) || $b['used'][$w] =& $vars[$w];
785             }
786         }
787
788         // Analyse childs
789
790         $tree['childs'] = array();
791         $vars =& $tree['childs'];
792
793         if (preg_match_all("@//''\"\"#[0-9]+'@", $closure, $w))
794         {
795             foreach ($w[0] as $a)
796             {
797                 $vars[$a] = array('parent' => &$tree);
798                 $this->makeVars($this->closures[$a], $vars[$a], $a);
799             }
800         }
801     }
802
803     protected function mergeVarDeclarations($m)
804     {
805         return str_replace("\nvar ", ',', $m[0]);
806     }
807
808     protected function renameVars(&$tree, $root)
809     {
810         if ($root)
811         {
812             $tree['local'] += $tree['used'];
813             $tree['used'] = array();
814
815             foreach ($tree['local'] as $k => $v)
816             {
817                 if ('.' == $k[0]) $k = substr($k, 1);
818
819                 if ('true' === $k) $this->charFreq[48] += $v;
820                 else if ('false' === $k) $this->charFreq[49] += $v;
821                 else if (!$this->specialVarRx || !preg_match("#^{$this->specialVarRx}$#", $k))
822                 {
823                     foreach (count_chars($k, 1) as $k => $w) $this->charFreq[$k] += $w * $v;
824                 }
825                 else if (2 == strlen($k)) $tree['used'][] = $k[1];
826             }
827
828             arsort($this->charFreq);
829
830             $this->str0 = '';
831             $this->str1 = '';
832
833             foreach ($this->charFreq as $k => $v)
834             {
835                 if (!$v) break;
836
837                 $v = chr($k);
838
839                 if ((64 < $k && $k < 91) || (96 < $k && $k < 123)) // A-Z a-z
840                 {
841                     $this->str0 .= $v;
842                     $this->str1 .= $v;
843                 }
844                 else if (47 < $k && $k < 58) // 0-9
845                 {
846                     $this->str1 .= $v;
847                 }
848             }
849
850             if ('' === $this->str0)
851             {
852                 $this->str0 = 'claspemitdbfrugnjvhowkxqyzCLASPEMITDBFRUGNJVHOWKXQYZ';
853                 $this->str1 = $this->str0 . '0123456789';
854             }
855
856             foreach ($tree['local'] as $var => $root)
857             {
858                 if ('.' != substr($var, 0, 1) && isset($tree['local'][".{$var}"])) $tree['local'][$var] += $tree['local'][".{$var}"];
859             }
860
861             foreach ($tree['local'] as $var => $root)
862             {
863                 if ('.' == substr($var, 0, 1) && isset($tree['local'][substr($var, 1)])) $tree['local'][$var] = $tree['local'][substr($var, 1)];
864             }
865
866             arsort($tree['local']);
867
868             foreach ($tree['local'] as $var => $root) switch (substr($var, 0, 1))
869             {
870             case '.':
871                 if (!isset($tree['local'][substr($var, 1)]))
872                 {
873                     $tree['local'][$var] = '#' . ($this->specialVarRx && 3 < strlen($var) && preg_match("'^\.{$this->specialVarRx}$'", $var) ? $this->getNextName($tree) . '$' : substr($var, 1));
874                 }
875                 break;
876
877             case ';': $tree['local'][$var] = 0 === $root ? '' : $this->getNextName($tree);
878             case '#': break;
879
880             default:
881                 $root = $this->specialVarRx && 2 < strlen($var) && preg_match("'^{$this->specialVarRx}$'", $var) ? $this->getNextName($tree) . '$' : $var;
882                 $tree['local'][$var] = $root;
883                 if (isset($tree['local'][".{$var}"])) $tree['local'][".{$var}"] = '#' . $root;
884             }
885
886             foreach ($tree['local'] as $var => $root) $tree['local'][$var] = preg_replace("'^#'", '.', $tree['local'][$var]);
887         }
888         else
889         {
890             arsort($tree['local']);
891             if (false !== $tree['nfe']) $tree['used'][] = $tree['local'][$tree['nfe']];
892
893             foreach ($tree['local'] as $var => $root)
894                 if ($tree['nfe'] !== $var)
895                     $tree['local'][$var] = 0 === $root ? '' : $this->getNextName($tree);
896         }
897
898         $this->local_tree =& $tree['local'];
899         $this->used_tree  =& $tree['used'];
900
901         $tree['code'] = preg_replace_callback("#[.,{ ]?(?<![a-zA-Z0-9_\$@]){$this->varRx}:?#", array(&$this, 'getNewName'), $tree['code']);
902         $this->specialVarRx && $tree['code'] = preg_replace_callback("#//''\"\"[0-9]+'#", array(&$this, 'renameInString'), $tree['code']);
903
904         foreach ($tree['childs'] as $a => &$b)
905         {
906             $this->renameVars($b, false);
907             $tree['code'] = str_replace($a, $b['code'], $tree['code']);
908             unset($tree['childs'][$a]);
909         }
910     }
911
912     protected function renameInString($a)
913     {
914         $b =& $this->strings[$a[0]];
915         unset($this->strings[$a[0]]);
916
917         return preg_replace_callback(
918             "#[.,{]?(?<![a-zA-Z0-9_\$@]){$this->specialVarRx}:?#",
919             array(&$this, 'getNewName'),
920             $b
921         );
922     }
923
924     protected function getNewName($m)
925     {
926         $m = $m[0];
927
928         $pre = '.' === $m[0] ? '.' : '';
929         $post = '';
930
931         if (',' === $m[0] || '{' === $m[0] || ' ' === $m[0])
932         {
933             $pre = $m[0];
934
935             if (':' === substr($m, -1))
936             {
937                 $post = ':';
938                 $m = (' ' !== $m[0] ? '.' : '') . substr($m, 1, -1);
939             }
940             else $m = substr($m, 1);
941         }
942         else if (':' === substr($m, -1))
943         {
944             $post = ':';
945             $m = substr($m, 0, -1);
946         }
947
948         $post = (isset($this->reserved[$m])
949             ? ('true' === $m ? '!0' : ('false' === $m ? '!1': $m))
950             : (
951                   isset($this->local_tree[$m])
952                 ? $this->local_tree[$m]
953                 : (
954                       isset($this->used_tree[$m])
955                     ? $this->used_tree[$m]
956                     : $m
957                 )
958             )
959         ) . $post;
960
961         return '' === $post ? '' : ($pre . ('.' === $post[0] ? substr($post, 1) : $post));
962     }
963
964     protected function getNextName(&$tree = array(), &$counter = false)
965     {
966         if (false === $counter)
967         {
968             $counter =& $tree['counter'];
969             isset($counter) || $counter = -1;
970             $exclude = array_flip($tree['used']);
971         }
972         else $exclude = $tree;
973
974         ++$counter;
975
976         $len0 = strlen($this->str0);
977         $len1 = strlen($this->str0);
978
979         $name = $this->str0[$counter % $len0];
980
981         $i = intval($counter / $len0) - 1;
982         while ($i>=0)
983         {
984             $name .= $this->str1[ $i % $len1 ];
985             $i = intval($i / $len1) - 1;
986         }
987
988         return !(isset($this->reserved[$name]) || isset($exclude[$name])) ? $name : $this->getNextName($exclude, $counter);
989     }
990
991     protected function restoreCc(&$s, $lf = true)
992     {
993         $lf && $s = str_replace('@#3', '', $s);
994
995         $s = str_replace('@#1', '@*/', $s);
996         $s = str_replace('2#@', '//@', $s);
997         $s = str_replace('1#@', '/*@', $s);
998         $s = str_replace('##', '#', $s);
999     }
1000 }