From 572cd73a92eb8d580f872e7432b3c0739b2edb9b Mon Sep 17 00:00:00 2001 From: Kijin Sung Date: Mon, 11 Jan 2016 17:51:36 +0900 Subject: [PATCH] Remove obsolete build instructions and minify tool --- tools/README.md | 68 - tools/minify/cssmin/CSSmin.php | 729 ---------- tools/minify/jsminplus/changelog.txt | 62 - tools/minify/jsminplus/jsminplus.php | 1981 -------------------------- tools/minify/minify.php | 200 --- 5 files changed, 3040 deletions(-) delete mode 100644 tools/README.md delete mode 100644 tools/minify/cssmin/CSSmin.php delete mode 100644 tools/minify/jsminplus/changelog.txt delete mode 100644 tools/minify/jsminplus/jsminplus.php delete mode 100755 tools/minify/minify.php diff --git a/tools/README.md b/tools/README.md deleted file mode 100644 index 7ad481795..000000000 --- a/tools/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Tools - -## Build -XE패키징을 위해 grunt.js를 이용한 Task로 작성되어 있으며 *nix 환경에서 Node를 구동할 수 있어야 한다. - -### 의존 패키지 설치 (Mac) - -### 1. brew -http://brew.sh 페이지의 'Install Homebrew'를 참고하여 설치 - -### 2. node.js -> brew install node - -### 3. grunt-cli -> npm install -g grunt-cli - -## node 모듈 설치 -grunt task 수행에 필요한 node 모듈의 설치를 먼저 수행한다. - -XE 패키지의 루트… index.php 또는 Gruntfile.js 파일이 있는 곳에서 다음 명령으로 의존 모듈이 자동 설치된다. - -> npm install - -## Build -build 수행 전 Minified 파일이 갱신되도록 패키징 하려는 브랜치에서 아래 Task 중 `grunt minify`를 반드시 먼저 수행하도록 한다. - -build 명령으로 zip, tgz 포맷으로 패키징을 수행하며 지정한 대상의 변경된 파일만을 묶은 changed 파일을 함께 생성한다. - -> grunt build`:from`:`to` - -`from`, `to`에는 commit hash 또는 tag, branch를 지정할 수 있다. 패키지는 `to`에 지정한 대상을 기준으로하며 `from`과 `to`사이에 변경된 파일들 changed 파일을 별도로 생성한다. - -> grunt build:`old_tag`:`current_tag` - -이와 같이 지정하면 `old_tag`로부터 `current_tag` 사이의 변경된 파일만을 묶은 `xe.current_tag.changed.*` 파일과 `xe.current_tag.*`파일을 생성한다. - -`from`을 생략하여 `build:master`(master는 branch이다)와 같이 지정하면 `master`의 최신 상태로 빌드하며 changed 파일을 생성하지 않는다. - -### Build 수행 시 포함하는 패키지 -Build 수행 시 일부 확장 기능을 가져와 함게 패키징한다. 지정한 각 저장소의 master 브랜치로부터 코드를 가져오므로 **Build 수행 전에 각 저장소의 master 상태를 확인하도록 한다.** - -* board 모듈 - * https://github.com/xpressengine/xe-module-board -* krzip 모듈 - * https://github.com/xpressengine/xe-module-krzip -* syndication 모듈 - * https://github.com/xpressengine/xe-module-syndication - -## Task -.js, .css, .php 파일들에 대해 문법 검사 및 권장 코드를 확인할 수 있으며 minify 등의 작업을 수행할 수 있다. - -### Lint -.js, .css, .php 파일에 대해 문법 검사 등을 수행한다. -> grunt lint - -다음과 같이 선택적으로 수행할 수 있다. - -#### JS Lint (jshint) -`lint`가 아닌 `hint`임에 주의. -> grunt jshint - -#### CSS Lint -> grunt csslint - -### Minify -.js, .css 파일의 공백을 지우는 등 minify 동작을 수행할 수 있으며 대상은 Gruntfile.js 파일에 정의되어 있다. - - > grunt minify diff --git a/tools/minify/cssmin/CSSmin.php b/tools/minify/cssmin/CSSmin.php deleted file mode 100644 index a32bb7832..000000000 --- a/tools/minify/cssmin/CSSmin.php +++ /dev/null @@ -1,729 +0,0 @@ - */ - -/*! - * cssmin.php rev 91c5ea5 - * Author: Tubal Martin - http://blog.margenn.com/ - * Repo: https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port - * - * This is a PHP port of the Javascript port of the CSS minification tool - * distributed with YUICompressor, itself a port of the cssmin utility by - * Isaac Schlueter - http://foohack.com/ - * Permission is hereby granted to use the PHP version under the same - * conditions as the YUICompressor. - */ - -/*! - * YUI Compressor - * http://developer.yahoo.com/yui/compressor/ - * Author: Julien Lecomte - http://www.julienlecomte.net/ - * Copyright (c) 2011 Yahoo! Inc. All rights reserved. - * The copyrights embodied in the content of this file are licensed - * by Yahoo! Inc. under the BSD (revised) open source license. - */ - -class CSSmin -{ - const NL = '___YUICSSMIN_PRESERVED_NL___'; - const TOKEN = '___YUICSSMIN_PRESERVED_TOKEN_'; - const COMMENT = '___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_'; - const CLASSCOLON = '___YUICSSMIN_PSEUDOCLASSCOLON___'; - - private $comments; - private $preserved_tokens; - private $memory_limit; - private $max_execution_time; - private $pcre_backtrack_limit; - private $pcre_recursion_limit; - private $raise_php_limits; - - /** - * @param bool|int $raise_php_limits - * If true, PHP settings will be raised if needed - */ - public function __construct($raise_php_limits = TRUE) - { - // Set suggested PHP limits - $this->memory_limit = 128 * 1048576; // 128MB in bytes - $this->max_execution_time = 60; // 1 min - $this->pcre_backtrack_limit = 1000 * 1000; - $this->pcre_recursion_limit = 500 * 1000; - - $this->raise_php_limits = (bool) $raise_php_limits; - } - - /** - * Minify a string of CSS - * @param string $css - * @param int|bool $linebreak_pos - * @return string - */ - public function run($css = '', $linebreak_pos = FALSE) - { - if (empty($css)) { - return ''; - } - - if ($this->raise_php_limits) { - $this->do_raise_php_limits(); - } - - $this->comments = array(); - $this->preserved_tokens = array(); - - $start_index = 0; - $length = strlen($css); - - $css = $this->extract_data_urls($css); - - // collect all comment blocks... - while (($start_index = $this->index_of($css, '/*', $start_index)) >= 0) { - $end_index = $this->index_of($css, '*/', $start_index + 2); - if ($end_index < 0) { - $end_index = $length; - } - $comment_found = $this->str_slice($css, $start_index + 2, $end_index); - $this->comments[] = $comment_found; - $comment_preserve_string = self::COMMENT . (count($this->comments) - 1) . '___'; - $css = $this->str_slice($css, 0, $start_index + 2) . $comment_preserve_string . $this->str_slice($css, $end_index); - // Set correct start_index: Fixes issue #2528130 - $start_index = $end_index + 2 + strlen($comment_preserve_string) - strlen($comment_found); - } - - // preserve strings so their content doesn't get accidentally minified - $css = preg_replace_callback('/(?:"(?:[^\\\\"]|\\\\.|\\\\)*")|'."(?:'(?:[^\\\\']|\\\\.|\\\\)*')/S", array($this, 'replace_string'), $css); - - // Let's divide css code in chunks of 25.000 chars aprox. - // Reason: PHP's PCRE functions like preg_replace have a "backtrack limit" - // of 100.000 chars by default (php < 5.3.7) so if we're dealing with really - // long strings and a (sub)pattern matches a number of chars greater than - // the backtrack limit number (i.e. /(.*)/s) PCRE functions may fail silently - // returning NULL and $css would be empty. - $charset = ''; - $charset_regexp = '/@charset [^;]+;/i'; - $css_chunks = array(); - $css_chunk_length = 25000; // aprox size, not exact - $start_index = 0; - $i = $css_chunk_length; // save initial iterations - $l = strlen($css); - - - // if the number of characters is 25000 or less, do not chunk - if ($l <= $css_chunk_length) { - $css_chunks[] = $css; - } else { - // chunk css code securely - while ($i < $l) { - $i += 50; // save iterations. 500 checks for a closing curly brace } - if ($l - $start_index <= $css_chunk_length || $i >= $l) { - $css_chunks[] = $this->str_slice($css, $start_index); - break; - } - if ($css[$i - 1] === '}' && $i - $start_index > $css_chunk_length) { - // If there are two ending curly braces }} separated or not by spaces, - // join them in the same chunk (i.e. @media blocks) - $next_chunk = substr($css, $i); - if (preg_match('/^\s*\}/', $next_chunk)) { - $i = $i + $this->index_of($next_chunk, '}') + 1; - } - - $css_chunks[] = $this->str_slice($css, $start_index, $i); - $start_index = $i; - } -} -} - -// Minify each chunk -for ($i = 0, $n = count($css_chunks); $i < $n; $i++) { - $css_chunks[$i] = $this->minify($css_chunks[$i], $linebreak_pos); - // Keep the first @charset at-rule found - if (empty($charset) && preg_match($charset_regexp, $css_chunks[$i], $matches)) { - $charset = $matches[0]; - } - // Delete all @charset at-rules - $css_chunks[$i] = preg_replace($charset_regexp, '', $css_chunks[$i]); -} - -// Update the first chunk and push the charset to the top of the file. -$css_chunks[0] = $charset . $css_chunks[0]; - -return implode('', $css_chunks); -} - -/** - * Sets the memory limit for this script - * @param int|string $limit - */ -public function set_memory_limit($limit) -{ - $this->memory_limit = $this->normalize_int($limit); -} - -/** - * Sets the maximum execution time for this script - * @param int|string $seconds - */ -public function set_max_execution_time($seconds) -{ - $this->max_execution_time = (int) $seconds; -} - -/** - * Sets the PCRE backtrack limit for this script - * @param int $limit - */ -public function set_pcre_backtrack_limit($limit) -{ - $this->pcre_backtrack_limit = (int) $limit; -} - -/** - * Sets the PCRE recursion limit for this script - * @param int $limit - */ -public function set_pcre_recursion_limit($limit) -{ - $this->pcre_recursion_limit = (int) $limit; -} - -/** - * Try to configure PHP to use at least the suggested minimum settings - */ -private function do_raise_php_limits() -{ - $php_limits = array( - 'memory_limit' => $this->memory_limit, - 'max_execution_time' => $this->max_execution_time, - 'pcre.backtrack_limit' => $this->pcre_backtrack_limit, - 'pcre.recursion_limit' => $this->pcre_recursion_limit - ); - - // If current settings are higher respect them. - foreach ($php_limits as $name => $suggested) { - $current = $this->normalize_int(ini_get($name)); - // memory_limit exception: allow -1 for "no memory limit". - if ($current > -1 && ($suggested == -1 || $current < $suggested)) { - ini_set($name, $suggested); - } - } -} - -/** - * Does bulk of the minification - * @param string $css - * @param int|bool $linebreak_pos - * @return string - */ -private function minify($css, $linebreak_pos) -{ - // strings are safe, now wrestle the comments - for ($i = 0, $max = count($this->comments); $i < $max; $i++) { - - $token = $this->comments[$i]; - $placeholder = '/' . self::COMMENT . $i . '___/'; - - // ! in the first position of the comment means preserve - // so push to the preserved tokens keeping the ! - if (substr($token, 0, 1) === '!') { - $this->preserved_tokens[] = $token; - $token_tring = self::TOKEN . (count($this->preserved_tokens) - 1) . '___'; - $css = preg_replace($placeholder, $token_tring, $css, 1); - // Preserve new lines for /*! important comments - $css = preg_replace('/\s*[\n\r\f]+\s*(\/\*'. $token_tring .')/S', self::NL.'$1', $css); - $css = preg_replace('/('. $token_tring .'\*\/)\s*[\n\r\f]+\s*/S', '$1'.self::NL, $css); - continue; - } - - // \ in the last position looks like hack for Mac/IE5 - // shorten that to /*\*/ and the next one to /**/ - if (substr($token, (strlen($token) - 1), 1) === '\\') { - $this->preserved_tokens[] = '\\'; - $css = preg_replace($placeholder, self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1); - $i = $i + 1; // attn: advancing the loop - $this->preserved_tokens[] = ''; - $css = preg_replace('/' . self::COMMENT . $i . '___/', self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1); - continue; - } - - // keep empty comments after child selectors (IE7 hack) - // e.g. html >/**/ body - if (strlen($token) === 0) { - $start_index = $this->index_of($css, $this->str_slice($placeholder, 1, -1)); - if ($start_index > 2) { - if (substr($css, $start_index - 3, 1) === '>') { - $this->preserved_tokens[] = ''; - $css = preg_replace($placeholder, self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1); - } - } - } - - // in all other cases kill the comment - $css = preg_replace('/\/\*' . $this->str_slice($placeholder, 1, -1) . '\*\//', '', $css, 1); - } - - - // Normalize all whitespace strings to single spaces. Easier to work with that way. - $css = preg_replace('/\s+/', ' ', $css); - - // Shorten & preserve calculations calc(...) since spaces are important - $css = preg_replace_callback('/calc(\((?:[^\(\)]+|(?1))*\))/i', array($this, 'replace_calc'), $css); - - // Replace positive sign from numbers preceded by : or a white-space before the leading space is removed - // +1.2em to 1.2em, +.8px to .8px, +2% to 2% - $css = preg_replace('/((? -9.0 to -9 - $css = preg_replace('/((?\+\(\)\]\~\=,])/', '$1', $css); - $css = preg_replace('/' . self::CLASSCOLON . '/', ':', $css); - - // retain space for special IE6 cases - $css = preg_replace('/\:first\-(line|letter)(\{|,)/i', ':first-$1 $2', $css); - - // no space after the end of a preserved comment - $css = preg_replace('/\*\/ /', '*/', $css); - - // Put the space back in some cases, to support stuff like - // @media screen and (-webkit-min-device-pixel-ratio:0){ - $css = preg_replace('/\band\(/i', 'and (', $css); - - // Remove the spaces after the things that should not have spaces after them. - $css = preg_replace('/([\!\{\}\:;\>\+\(\[\~\=,])\s+/S', '$1', $css); - - // remove unnecessary semicolons - $css = preg_replace('/;+\}/', '}', $css); - - // Fix for issue: #2528146 - // Restore semicolon if the last property is prefixed with a `*` (lte IE7 hack) - // to avoid issues on Symbian S60 3.x browsers. - $css = preg_replace('/(\*[a-z0-9\-]+\s*\:[^;\}]+)(\})/', '$1;$2', $css); - - // Replace 0 length units 0(px,em,%) with 0. - $css = preg_replace('/((?compress_hex_colors($css); - - // border: none to border:0, outline: none to outline:0 - $css = preg_replace('/(border\-?(?:top|right|bottom|left|)|outline)\:none(;|\})/ieS', "strtolower('$1:0$2')", $css); - - // shorter opacity IE filter - $css = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $css); - - // Remove empty rules. - $css = preg_replace('/[^\};\{\/]+\{\}/S', '', $css); - - // Some source control tools don't like it when files containing lines longer - // than, say 8000 characters, are checked in. The linebreak option is used in - // that case to split long lines after a specific column. - if ($linebreak_pos !== FALSE && (int) $linebreak_pos >= 0) { - $linebreak_pos = (int) $linebreak_pos; - $start_index = $i = 0; - while ($i < strlen($css)) { - $i++; - if ($css[$i - 1] === '}' && $i - $start_index > $linebreak_pos) { - $css = $this->str_slice($css, 0, $i) . "\n" . $this->str_slice($css, $i); - $start_index = $i; - } - } - } - - // Replace multiple semi-colons in a row by a single one - // See SF bug #1980989 - $css = preg_replace('/;;+/', ';', $css); - - // Restore new lines for /*! important comments - $css = preg_replace('/'. self::NL .'/', "\n", $css); - - // restore preserved comments and strings - for ($i = 0, $max = count($this->preserved_tokens); $i < $max; $i++) { - $css = preg_replace('/' . self::TOKEN . $i . '___/', $this->preserved_tokens[$i], $css, 1); - } - - // Trim the final string (for any leading or trailing white spaces) - return trim($css); -} - -/** - * Utility method to replace all data urls with tokens before we start - * compressing, to avoid performance issues running some of the subsequent - * regexes against large strings chunks. - * - * @param string $css - * @return string - */ -private function extract_data_urls($css) -{ - // Leave data urls alone to increase parse performance. - $max_index = strlen($css) - 1; - $append_index = $index = $last_index = $offset = 0; - $sb = array(); - $pattern = '/url\(\s*(["\']?)data\:/i'; - - // Since we need to account for non-base64 data urls, we need to handle - // ' and ) being part of the data string. Hence switching to indexOf, - // to determine whether or not we have matching string terminators and - // handling sb appends directly, instead of using matcher.append* methods. - - while (preg_match($pattern, $css, $m, 0, $offset)) { - $index = $this->index_of($css, $m[0], $offset); - $last_index = $index + strlen($m[0]); - $start_index = $index + 4; // "url(".length() - $end_index = $last_index - 1; - $terminator = $m[1]; // ', " or empty (not quoted) - $found_terminator = FALSE; - - if (strlen($terminator) === 0) { - $terminator = ')'; - } - - while ($found_terminator === FALSE && $end_index+1 <= $max_index) { - $end_index = $this->index_of($css, $terminator, $end_index + 1); - - // endIndex == 0 doesn't really apply here - if ($end_index > 0 && substr($css, $end_index - 1, 1) !== '\\') { - $found_terminator = TRUE; - if (')' != $terminator) { - $end_index = $this->index_of($css, ')', $end_index); - } - } - } - - // Enough searching, start moving stuff over to the buffer - $sb[] = $this->substring($css, $append_index, $index); - - if ($found_terminator) { - $token = $this->substring($css, $start_index, $end_index); - $token = preg_replace('/\s+/', '', $token); - $this->preserved_tokens[] = $token; - - $preserver = 'url(' . self::TOKEN . (count($this->preserved_tokens) - 1) . '___)'; - $sb[] = $preserver; - - $append_index = $end_index + 1; - } else { - // No end terminator found, re-add the whole match. Should we throw/warn here? - $sb[] = $this->substring($css, $index, $last_index); - $append_index = $last_index; - } - - $offset = $last_index; - } - - $sb[] = $this->substring($css, $append_index); - - return implode('', $sb); -} - -/** - * Utility method to compress hex color values of the form #AABBCC to #ABC or short color name. - * - * DOES NOT compress CSS ID selectors which match the above pattern (which would break things). - * e.g. #AddressForm { ... } - * - * DOES NOT compress IE filters, which have hex color values (which would break things). - * e.g. filter: chroma(color="#FFFFFF"); - * - * DOES NOT compress invalid hex values. - * e.g. background-color: #aabbccdd - * - * @param string $css - * @return string - */ -private function compress_hex_colors($css) -{ - // Look for hex colors inside { ... } (to avoid IDs) and which don't have a =, or a " in front of them (to avoid filters) - $pattern = '/(\=\s*?["\']?)?#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])(\}|[^0-9a-f{][^{]*?\})/iS'; - $_index = $index = $last_index = $offset = 0; - $sb = array(); - // See: http://ajaxmin.codeplex.com/wikipage?title=CSS%20Colors - $short_safe = array( - '#808080' => 'gray', - '#008000' => 'green', - '#800000' => 'maroon', - '#000080' => 'navy', - '#808000' => 'olive', - '#800080' => 'purple', - '#c0c0c0' => 'silver', - '#008080' => 'teal', - '#f00' => 'red' - ); - - while (preg_match($pattern, $css, $m, 0, $offset)) { - $index = $this->index_of($css, $m[0], $offset); - $last_index = $index + strlen($m[0]); - $is_filter = (bool) $m[1]; - - $sb[] = $this->substring($css, $_index, $index); - - if ($is_filter) { - // Restore, maintain case, otherwise filter will break - $sb[] = $m[1] . '#' . $m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7]; - } else { - if (strtolower($m[2]) == strtolower($m[3]) && - strtolower($m[4]) == strtolower($m[5]) && - strtolower($m[6]) == strtolower($m[7])) { - // Compress. - $hex = '#' . strtolower($m[3] . $m[5] . $m[7]); - } else { - // Non compressible color, restore but lower case. - $hex = '#' . strtolower($m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7]); - } - // replace Hex colors to short safe color names - $sb[] = array_key_exists($hex, $short_safe) ? $short_safe[$hex] : $hex; - } - - $_index = $offset = $last_index - strlen($m[8]); - } - - $sb[] = $this->substring($css, $_index); - - return implode('', $sb); -} - -/* CALLBACKS - * --------------------------------------------------------------------------------------------- - */ - -private function replace_string($matches) -{ - $match = $matches[0]; - $quote = substr($match, 0, 1); - // Must use addcslashes in PHP to avoid parsing of backslashes - $match = addcslashes($this->str_slice($match, 1, -1), '\\'); - - // maybe the string contains a comment-like substring? - // one, maybe more? put'em back then - if (($pos = $this->index_of($match, self::COMMENT)) >= 0) { - for ($i = 0, $max = count($this->comments); $i < $max; $i++) { - $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1); - } - } - - // minify alpha opacity in filter strings - $match = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $match); - - $this->preserved_tokens[] = $match; - return $quote . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . $quote; - } - - private function replace_colon($matches) - { - return preg_replace('/\:/', self::CLASSCOLON, $matches[0]); - } - - private function replace_calc($matches) - { - $this->preserved_tokens[] = preg_replace('/\s?([\*\/\(\),])\s?/', '$1', $matches[0]); - return self::TOKEN . (count($this->preserved_tokens) - 1) . '___'; - } - - private function rgb_to_hex($matches) - { - // Support for percentage values rgb(100%, 0%, 45%); - if ($this->index_of($matches[1], '%') >= 0){ - $rgbcolors = explode(',', str_replace('%', '', $matches[1])); - for ($i = 0; $i < count($rgbcolors); $i++) { - $rgbcolors[$i] = $this->round_number(floatval($rgbcolors[$i]) * 2.55); - } - } else { - $rgbcolors = explode(',', $matches[1]); - } - - // Values outside the sRGB color space should be clipped (0-255) - for ($i = 0; $i < count($rgbcolors); $i++) { - $rgbcolors[$i] = $this->clamp_number(intval($rgbcolors[$i], 10), 0, 255); - $rgbcolors[$i] = sprintf("%02x", $rgbcolors[$i]); - } - - // Fix for issue #2528093 - if (!preg_match('/[\s\,\);\}]/', $matches[2])){ - $matches[2] = ' ' . $matches[2]; - } - - return '#' . implode('', $rgbcolors) . $matches[2]; - } - -private function hsl_to_hex($matches) -{ - $values = explode(',', str_replace('%', '', $matches[1])); - $h = floatval($values[0]); - $s = floatval($values[1]); - $l = floatval($values[2]); - - // Wrap and clamp, then fraction! - $h = ((($h % 360) + 360) % 360) / 360; - $s = $this->clamp_number($s, 0, 100) / 100; - $l = $this->clamp_number($l, 0, 100) / 100; - - if ($s == 0) { - $r = $g = $b = $this->round_number(255 * $l); - } else { - $v2 = $l < 0.5 ? $l * (1 + $s) : ($l + $s) - ($s * $l); - $v1 = (2 * $l) - $v2; - $r = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h + (1/3))); - $g = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h)); - $b = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h - (1/3))); - } - - return $this->rgb_to_hex(array('', $r.','.$g.','.$b, $matches[2])); -} - -/* HELPERS - * --------------------------------------------------------------------------------------------- - */ - -private function hue_to_rgb($v1, $v2, $vh) -{ - $vh = $vh < 0 ? $vh + 1 : ($vh > 1 ? $vh - 1 : $vh); - if ($vh * 6 < 1) return $v1 + ($v2 - $v1) * 6 * $vh; - if ($vh * 2 < 1) return $v2; - if ($vh * 3 < 2) return $v1 + ($v2 - $v1) * ((2/3) - $vh) * 6; - return $v1; -} - -private function round_number($n) -{ - return intval(floor(floatval($n) + 0.5), 10); -} - -private function clamp_number($n, $min, $max) -{ - return min(max($n, $min), $max); -} - -/** - * PHP port of Javascript's "indexOf" function for strings only - * Author: Tubal Martin http://blog.margenn.com - * - * @param string $haystack - * @param string $needle - * @param int $offset index (optional) - * @return int - */ -private function index_of($haystack, $needle, $offset = 0) -{ - $index = strpos($haystack, $needle, $offset); - - return ($index !== FALSE) ? $index : -1; -} - -/** - * PHP port of Javascript's "substring" function - * Author: Tubal Martin http://blog.margenn.com - * Tests: http://margenn.com/tubal/substring/ - * - * @param string $str - * @param int $from index - * @param int|bool $to index (optional) - * @return string - */ -private function substring($str, $from = 0, $to = FALSE) -{ - if ($to !== FALSE) { - if ($from == $to || ($from <= 0 && $to < 0)) { - return ''; - } - - if ($from > $to) { - $from_copy = $from; - $from = $to; - $to = $from_copy; - } - } - - if ($from < 0) { - $from = 0; - } - - $substring = ($to === FALSE) ? substr($str, $from) : substr($str, $from, $to - $from); - return ($substring === FALSE) ? '' : $substring; -} - -/** - * PHP port of Javascript's "slice" function for strings only - * Author: Tubal Martin http://blog.margenn.com - * Tests: http://margenn.com/tubal/str_slice/ - * - * @param string $str - * @param int $start index - * @param int|bool $end index (optional) - * @return string - */ -private function str_slice($str, $start = 0, $end = FALSE) -{ - if ($end !== FALSE && ($start < 0 || $end <= 0)) { - $max = strlen($str); - - if ($start < 0) { - if (($start = $max + $start) < 0) { - return ''; - } - } - - if ($end < 0) { - if (($end = $max + $end) < 0) { - return ''; - } - } - - if ($end <= $start) { - return ''; - } - } - - $slice = ($end === FALSE) ? substr($str, $start) : substr($str, $start, $end - $start); - return ($slice === FALSE) ? '' : $slice; -} - -/** - * Convert strings like "64M" or "30" to int values - * @param mixed $size - * @return int - */ -private function normalize_int($size) -{ - if (is_string($size)) { - switch (substr($size, -1)) { - case 'M': case 'm': return $size * 1048576; - case 'K': case 'k': return $size * 1024; - case 'G': case 'g': return $size * 1073741824; - } - } - - return (int) $size; -} -} diff --git a/tools/minify/jsminplus/changelog.txt b/tools/minify/jsminplus/changelog.txt deleted file mode 100644 index 3e76d9770..000000000 --- a/tools/minify/jsminplus/changelog.txt +++ /dev/null @@ -1,62 +0,0 @@ -================================================================================ -JSMin+ -================================================================================ -A javascript minification tool written in PHP -by Tweakers.net / Tino Zijdel - -Weblog: http://crisp.tweakblogs.net/blog/cat/716 - -License: MPL 1.1/GPL 2.0/LGPL 2.1 (see sourcecode) - -================================================================================ -VERSION HISTORY -================================================================================ -17-05-2009 - version 1.3 - -- Fixed loop-constructs and if with empty body -- Fixed hook:colon precedence issues (https://bugzilla.mozilla.org/show_bug.cgi?id=492445) -- Combine concats of strings with same quotestyle -- Combine var-statements - --------------------------------------------------------------------------------- -18-04-2009 - version 1.2 - -- Fixed crash in PHP 5.2.9 when matching large comments or strings - (due to PCRE backtracking bug) -- Don't add curly braces around statements for a CASE label -- Always put statements for IF between curly braces when followed by an ELSE -- Save some more bytes by omitting the space between RETURN and the return - expression in certain cases - --------------------------------------------------------------------------------- -12-04-2009 - version 1.1 - -- Improved tokenizer performance by reading smaller chunks for matching -- Bugfix: jumplabels for break/continue statements were not written to output -- Improved stringmatching: cases like '\' and '' now throw unterminated - string literal error -- Fixed linenumber offset bug caused by JScript conditional compilation blocks -- nest() always calls Statement() so no need to use call_user_func() with a parm - --------------------------------------------------------------------------------- -09-04-2009 - version 1.0 - -Initial version - -================================================================================ -KNOWN ISSUES -================================================================================ - -- JScript conditional compilation support is incomplete - -================================================================================ -DOWNLOAD LOCATION -================================================================================ - -Latest version: -version 1.3 : http://files.tweakers.net/jsminplus/jsminplus.zip - -Previous versions: -version 1.2 : http://files.tweakers.net/jsminplus/jsminplus-1.2.zip -version 1.1 : http://files.tweakers.net/jsminplus/jsminplus-1.1.zip -version 1.0 : http://files.tweakers.net/jsminplus/jsminplus-1.0.zip diff --git a/tools/minify/jsminplus/jsminplus.php b/tools/minify/jsminplus/jsminplus.php deleted file mode 100644 index 885edee41..000000000 --- a/tools/minify/jsminplus/jsminplus.php +++ /dev/null @@ -1,1981 +0,0 @@ - */ - -/** - * JSMinPlus version 1.3 - * - * Minifies a javascript file using a javascript parser - * - * This implements a PHP port of Brendan Eich's Narcissus open source javascript engine (in javascript) - * References: http://en.wikipedia.org/wiki/Narcissus_(JavaScript_engine) - * Narcissus sourcecode: http://mxr.mozilla.org/mozilla/source/js/narcissus/ - * JSMinPlus weblog: http://crisp.tweakblogs.net/blog/cat/716 - * - * Tino Zijdel - * - * Usage: $minified = JSMinPlus::minify($script [, $filename]) - * - * Versionlog (see also changelog.txt): - * 17-05-2009 - fixed hook:colon precedence, fixed empty body in loop and if-constructs - * 18-04-2009 - fixed crashbug in PHP 5.2.9 and several other bugfixes - * 12-04-2009 - some small bugfixes and performance improvements - * 09-04-2009 - initial open sourced version 1.0 - * - * Latest version of this script: http://files.tweakers.net/jsminplus/jsminplus.zip - * - */ - -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Narcissus JavaScript engine. - * - * The Initial Developer of the Original Code is - * Brendan Eich . - * Portions created by the Initial Developer are Copyright (C) 2004 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): Tino Zijdel - * PHP port, modifications and minifier routine are (C) 2009 - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('TOKEN_END', 1); -define('TOKEN_NUMBER', 2); -define('TOKEN_IDENTIFIER', 3); -define('TOKEN_STRING', 4); -define('TOKEN_REGEXP', 5); -define('TOKEN_NEWLINE', 6); -define('TOKEN_CONDCOMMENT_START', 7); -define('TOKEN_CONDCOMMENT_END', 8); - -define('JS_SCRIPT', 100); -define('JS_BLOCK', 101); -define('JS_LABEL', 102); -define('JS_FOR_IN', 103); -define('JS_CALL', 104); -define('JS_NEW_WITH_ARGS', 105); -define('JS_INDEX', 106); -define('JS_ARRAY_INIT', 107); -define('JS_OBJECT_INIT', 108); -define('JS_PROPERTY_INIT', 109); -define('JS_GETTER', 110); -define('JS_SETTER', 111); -define('JS_GROUP', 112); -define('JS_LIST', 113); - -define('DECLARED_FORM', 0); -define('EXPRESSED_FORM', 1); -define('STATEMENT_FORM', 2); - -class JSMinPlus -{ - private $parser; - private $reserved = array( - 'break', 'case', 'catch', 'continue', 'default', 'delete', 'do', - 'else', 'finally', 'for', 'function', 'if', 'in', 'instanceof', - 'new', 'return', 'switch', 'this', 'throw', 'try', 'typeof', 'var', - 'void', 'while', 'with', - // Words reserved for future use - 'abstract', 'boolean', 'byte', 'char', 'class', 'const', 'debugger', - 'double', 'enum', 'export', 'extends', 'final', 'float', 'goto', - 'implements', 'import', 'int', 'interface', 'long', 'native', - 'package', 'private', 'protected', 'public', 'short', 'static', - 'super', 'synchronized', 'throws', 'transient', 'volatile', - // These are not reserved, but should be taken into account - // in isValidIdentifier (See jslint source code) - 'arguments', 'eval', 'true', 'false', 'Infinity', 'NaN', 'null', 'undefined' - ); - - private function __construct() - { - $this->parser = new JSParser(); - } - - public static function minify($js, $filename='') - { - static $instance; - - // this is a singleton - if(!$instance) - $instance = new JSMinPlus(); - - return $instance->min($js, $filename); - } - - private function min($js, $filename) - { - try - { - $n = $this->parser->parse($js, $filename, 1); - return $this->parseTree($n); - } - catch(Exception $e) - { - echo $e->getMessage() . "\n"; - } - - return false; - } - - private function parseTree($n, $noBlockGrouping = false) - { - $s = ''; - - switch ($n->type) - { - case KEYWORD_FUNCTION: - $s .= 'function' . ($n->name ? ' ' . $n->name : '') . '('; - $params = $n->params; - for ($i = 0, $j = count($params); $i < $j; $i++) - $s .= ($i ? ',' : '') . $params[$i]; - $s .= '){' . $this->parseTree($n->body, true) . '}'; - break; - - case JS_SCRIPT: - // we do nothing with funDecls or varDecls - $noBlockGrouping = true; - // FALL THROUGH - - case JS_BLOCK: - $childs = $n->treeNodes; - $lastType = 0; - for ($c = 0, $i = 0, $j = count($childs); $i < $j; $i++) - { - $type = $childs[$i]->type; - $t = $this->parseTree($childs[$i]); - if (strlen($t)) - { - if ($c) - { - $s = rtrim($s, ';'); - - if ($type == KEYWORD_FUNCTION && $childs[$i]->functionForm == DECLARED_FORM) - { - // put declared functions on a new line - $s .= "\n"; - } - elseif ($type == KEYWORD_VAR && $type == $lastType) - { - // mutiple var-statements can go into one - $t = ',' . substr($t, 4); - } - else - { - // add terminator - $s .= ';'; - } - } - - $s .= $t; - - $c++; - $lastType = $type; - } - } - - if ($c > 1 && !$noBlockGrouping) - { - $s = '{' . $s . '}'; - } - break; - - case KEYWORD_IF: - $s = 'if(' . $this->parseTree($n->condition) . ')'; - $thenPart = $this->parseTree($n->thenPart); - $elsePart = $n->elsePart ? $this->parseTree($n->elsePart) : null; - - // empty if-statement - if ($thenPart == '') - $thenPart = ';'; - - if ($elsePart) - { - // be carefull and always make a block out of the thenPart; could be more optimized but is a lot of trouble - if ($thenPart != ';' && $thenPart[0] != '{') - $thenPart = '{' . $thenPart . '}'; - - $s .= $thenPart . 'else'; - - // we could check for more, but that hardly ever applies so go for performance - if ($elsePart[0] != '{') - $s .= ' '; - - $s .= $elsePart; - } - else - { - $s .= $thenPart; - } - break; - - case KEYWORD_SWITCH: - $s = 'switch(' . $this->parseTree($n->discriminant) . '){'; - $cases = $n->cases; - for ($i = 0, $j = count($cases); $i < $j; $i++) - { - $case = $cases[$i]; - if ($case->type == KEYWORD_CASE) - $s .= 'case' . ($case->caseLabel->type != TOKEN_STRING ? ' ' : '') . $this->parseTree($case->caseLabel) . ':'; - else - $s .= 'default:'; - - $statement = $this->parseTree($case->statements, true); - if ($statement) - { - $s .= $statement; - // no terminator for last statement - if ($i + 1 < $j) - $s .= ';'; - } - } - $s .= '}'; - break; - - case KEYWORD_FOR: - $s = 'for(' . ($n->setup ? $this->parseTree($n->setup) : '') - . ';' . ($n->condition ? $this->parseTree($n->condition) : '') - . ';' . ($n->update ? $this->parseTree($n->update) : '') . ')'; - - $body = $this->parseTree($n->body); - if ($body == '') - $body = ';'; - - $s .= $body; - break; - - case KEYWORD_WHILE: - $s = 'while(' . $this->parseTree($n->condition) . ')'; - - $body = $this->parseTree($n->body); - if ($body == '') - $body = ';'; - - $s .= $body; - break; - - case JS_FOR_IN: - $s = 'for(' . ($n->varDecl ? $this->parseTree($n->varDecl) : $this->parseTree($n->iterator)) . ' in ' . $this->parseTree($n->object) . ')'; - - $body = $this->parseTree($n->body); - if ($body == '') - $body = ';'; - - $s .= $body; - break; - - case KEYWORD_DO: - $s = 'do{' . $this->parseTree($n->body, true) . '}while(' . $this->parseTree($n->condition) . ')'; - break; - - case KEYWORD_BREAK: - case KEYWORD_CONTINUE: - $s = $n->value . ($n->label ? ' ' . $n->label : ''); - break; - - case KEYWORD_TRY: - $s = 'try{' . $this->parseTree($n->tryBlock, true) . '}'; - $catchClauses = $n->catchClauses; - for ($i = 0, $j = count($catchClauses); $i < $j; $i++) - { - $t = $catchClauses[$i]; - $s .= 'catch(' . $t->varName . ($t->guard ? ' if ' . $this->parseTree($t->guard) : '') . '){' . $this->parseTree($t->block, true) . '}'; - } - if ($n->finallyBlock) - $s .= 'finally{' . $this->parseTree($n->finallyBlock, true) . '}'; - break; - - case KEYWORD_THROW: - $s = 'throw ' . $this->parseTree($n->exception); - break; - - case KEYWORD_RETURN: - $s = 'return'; - if ($n->value) - { - $t = $this->parseTree($n->value); - if (strlen($t)) - { - if ( $t[0] != '(' && $t[0] != '[' && $t[0] != '{' && - $t[0] != '"' && $t[0] != "'" && $t[0] != '/' - ) - $s .= ' '; - - $s .= $t; - } - } - break; - - case KEYWORD_WITH: - $s = 'with(' . $this->parseTree($n->object) . ')' . $this->parseTree($n->body); - break; - - case KEYWORD_VAR: - case KEYWORD_CONST: - $s = $n->value . ' '; - $childs = $n->treeNodes; - for ($i = 0, $j = count($childs); $i < $j; $i++) - { - $t = $childs[$i]; - $s .= ($i ? ',' : '') . $t->name; - $u = $t->initializer; - if ($u) - $s .= '=' . $this->parseTree($u); - } - break; - - case KEYWORD_DEBUGGER: - throw new Exception('NOT IMPLEMENTED: DEBUGGER'); - break; - - case TOKEN_CONDCOMMENT_START: - case TOKEN_CONDCOMMENT_END: - $s = $n->value . ($n->type == TOKEN_CONDCOMMENT_START ? ' ' : ''); - $childs = $n->treeNodes; - for ($i = 0, $j = count($childs); $i < $j; $i++) - $s .= $this->parseTree($childs[$i]); - break; - - case OP_SEMICOLON: - if ($expression = $n->expression) - $s = $this->parseTree($expression); - break; - - case JS_LABEL: - $s = $n->label . ':' . $this->parseTree($n->statement); - break; - - case OP_COMMA: - $childs = $n->treeNodes; - for ($i = 0, $j = count($childs); $i < $j; $i++) - $s .= ($i ? ',' : '') . $this->parseTree($childs[$i]); - break; - - case OP_ASSIGN: - $s = $this->parseTree($n->treeNodes[0]) . $n->value . $this->parseTree($n->treeNodes[1]); - break; - - case OP_HOOK: - $s = $this->parseTree($n->treeNodes[0]) . '?' . $this->parseTree($n->treeNodes[1]) . ':' . $this->parseTree($n->treeNodes[2]); - break; - - case OP_OR: case OP_AND: - case OP_BITWISE_OR: case OP_BITWISE_XOR: case OP_BITWISE_AND: - case OP_EQ: case OP_NE: case OP_STRICT_EQ: case OP_STRICT_NE: - case OP_LT: case OP_LE: case OP_GE: case OP_GT: - case OP_LSH: case OP_RSH: case OP_URSH: - case OP_MUL: case OP_DIV: case OP_MOD: - $s = $this->parseTree($n->treeNodes[0]) . $n->type . $this->parseTree($n->treeNodes[1]); - break; - - case OP_PLUS: - case OP_MINUS: - $left = $this->parseTree($n->treeNodes[0]); - $right = $this->parseTree($n->treeNodes[1]); - - switch ($n->treeNodes[1]->type) - { - case OP_PLUS: - case OP_MINUS: - case OP_INCREMENT: - case OP_DECREMENT: - case OP_UNARY_PLUS: - case OP_UNARY_MINUS: - $s = $left . $n->type . ' ' . $right; - break; - - case TOKEN_STRING: - //combine concatted strings with same quotestyle - if ($n->type == OP_PLUS && substr($left, -1) == $right[0]) - { - $s = substr($left, 0, -1) . substr($right, 1); - break; - } - // FALL THROUGH - - default: - $s = $left . $n->type . $right; - } - break; - - case KEYWORD_IN: - $s = $this->parseTree($n->treeNodes[0]) . ' in ' . $this->parseTree($n->treeNodes[1]); - break; - - case KEYWORD_INSTANCEOF: - $s = $this->parseTree($n->treeNodes[0]) . ' instanceof ' . $this->parseTree($n->treeNodes[1]); - break; - - case KEYWORD_DELETE: - $s = 'delete ' . $this->parseTree($n->treeNodes[0]); - break; - - case KEYWORD_VOID: - $s = 'void(' . $this->parseTree($n->treeNodes[0]) . ')'; - break; - - case KEYWORD_TYPEOF: - $s = 'typeof ' . $this->parseTree($n->treeNodes[0]); - break; - - case OP_NOT: - case OP_BITWISE_NOT: - case OP_UNARY_PLUS: - case OP_UNARY_MINUS: - $s = $n->value . $this->parseTree($n->treeNodes[0]); - break; - - case OP_INCREMENT: - case OP_DECREMENT: - if ($n->postfix) - $s = $this->parseTree($n->treeNodes[0]) . $n->value; - else - $s = $n->value . $this->parseTree($n->treeNodes[0]); - break; - - case OP_DOT: - $s = $this->parseTree($n->treeNodes[0]) . '.' . $this->parseTree($n->treeNodes[1]); - break; - - case JS_INDEX: - $s = $this->parseTree($n->treeNodes[0]); - // See if we can replace named index with a dot saving 3 bytes - if ( $n->treeNodes[0]->type == TOKEN_IDENTIFIER && - $n->treeNodes[1]->type == TOKEN_STRING && - $this->isValidIdentifier(substr($n->treeNodes[1]->value, 1, -1)) - ) - $s .= '.' . substr($n->treeNodes[1]->value, 1, -1); - else - $s .= '[' . $this->parseTree($n->treeNodes[1]) . ']'; - break; - - case JS_LIST: - $childs = $n->treeNodes; - for ($i = 0, $j = count($childs); $i < $j; $i++) - $s .= ($i ? ',' : '') . $this->parseTree($childs[$i]); - break; - - case JS_CALL: - $s = $this->parseTree($n->treeNodes[0]) . '(' . $this->parseTree($n->treeNodes[1]) . ')'; - break; - - case KEYWORD_NEW: - case JS_NEW_WITH_ARGS: - $s = 'new ' . $this->parseTree($n->treeNodes[0]) . '(' . ($n->type == JS_NEW_WITH_ARGS ? $this->parseTree($n->treeNodes[1]) : '') . ')'; - break; - - case JS_ARRAY_INIT: - $s = '['; - $childs = $n->treeNodes; - for ($i = 0, $j = count($childs); $i < $j; $i++) - { - $s .= ($i ? ',' : '') . $this->parseTree($childs[$i]); - } - $s .= ']'; - break; - - case JS_OBJECT_INIT: - $s = '{'; - $childs = $n->treeNodes; - for ($i = 0, $j = count($childs); $i < $j; $i++) - { - $t = $childs[$i]; - if ($i) - $s .= ','; - if ($t->type == JS_PROPERTY_INIT) - { - // Ditch the quotes when the index is a valid identifier - if ( $t->treeNodes[0]->type == TOKEN_STRING && - $this->isValidIdentifier(substr($t->treeNodes[0]->value, 1, -1)) - ) - $s .= substr($t->treeNodes[0]->value, 1, -1); - else - $s .= $t->treeNodes[0]->value; - - $s .= ':' . $this->parseTree($t->treeNodes[1]); - } - else - { - $s .= $t->type == JS_GETTER ? 'get' : 'set'; - $s .= ' ' . $t->name . '('; - $params = $t->params; - for ($i = 0, $j = count($params); $i < $j; $i++) - $s .= ($i ? ',' : '') . $params[$i]; - $s .= '){' . $this->parseTree($t->body, true) . '}'; - } - } - $s .= '}'; - break; - - case KEYWORD_NULL: case KEYWORD_THIS: case KEYWORD_TRUE: case KEYWORD_FALSE: - case TOKEN_IDENTIFIER: case TOKEN_NUMBER: case TOKEN_STRING: case TOKEN_REGEXP: - $s = $n->value; - break; - - case JS_GROUP: - $s = '(' . $this->parseTree($n->treeNodes[0]) . ')'; - break; - - default: - throw new Exception('UNKNOWN TOKEN TYPE: ' . $n->type); - } - - return $s; - } - - private function isValidIdentifier($string) - { - return preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $string) && !in_array($string, $this->reserved); - } -} - -class JSParser -{ - private $t; - - private $opPrecedence = array( - ';' => 0, - ',' => 1, - '=' => 2, '?' => 2, ':' => 2, - // The above all have to have the same precedence, see bug 330975 - '||' => 4, - '&&' => 5, - '|' => 6, - '^' => 7, - '&' => 8, - '==' => 9, '!=' => 9, '===' => 9, '!==' => 9, - '<' => 10, '<=' => 10, '>=' => 10, '>' => 10, 'in' => 10, 'instanceof' => 10, - '<<' => 11, '>>' => 11, '>>>' => 11, - '+' => 12, '-' => 12, - '*' => 13, '/' => 13, '%' => 13, - 'delete' => 14, 'void' => 14, 'typeof' => 14, - '!' => 14, '~' => 14, 'U+' => 14, 'U-' => 14, - '++' => 15, '--' => 15, - 'new' => 16, - '.' => 17, - JS_NEW_WITH_ARGS => 0, JS_INDEX => 0, JS_CALL => 0, - JS_ARRAY_INIT => 0, JS_OBJECT_INIT => 0, JS_GROUP => 0 - ); - - private $opArity = array( - ',' => -2, - '=' => 2, - '?' => 3, - '||' => 2, - '&&' => 2, - '|' => 2, - '^' => 2, - '&' => 2, - '==' => 2, '!=' => 2, '===' => 2, '!==' => 2, - '<' => 2, '<=' => 2, '>=' => 2, '>' => 2, 'in' => 2, 'instanceof' => 2, - '<<' => 2, '>>' => 2, '>>>' => 2, - '+' => 2, '-' => 2, - '*' => 2, '/' => 2, '%' => 2, - 'delete' => 1, 'void' => 1, 'typeof' => 1, - '!' => 1, '~' => 1, 'U+' => 1, 'U-' => 1, - '++' => 1, '--' => 1, - 'new' => 1, - '.' => 2, - JS_NEW_WITH_ARGS => 2, JS_INDEX => 2, JS_CALL => 2, - JS_ARRAY_INIT => 1, JS_OBJECT_INIT => 1, JS_GROUP => 1, - TOKEN_CONDCOMMENT_START => 1, TOKEN_CONDCOMMENT_END => 1 - ); - - public function __construct() - { - $this->t = new JSTokenizer(); - } - - public function parse($s, $f, $l) - { - // initialize tokenizer - $this->t->init($s, $f, $l); - - $x = new JSCompilerContext(false); - $n = $this->Script($x); - if (!$this->t->isDone()) - throw $this->t->newSyntaxError('Syntax error'); - - return $n; - } - - private function Script($x) - { - $n = $this->Statements($x); - $n->type = JS_SCRIPT; - $n->funDecls = $x->funDecls; - $n->varDecls = $x->varDecls; - - return $n; - } - - private function Statements($x) - { - $n = new JSNode($this->t, JS_BLOCK); - array_push($x->stmtStack, $n); - - while (!$this->t->isDone() && $this->t->peek() != OP_RIGHT_CURLY) - $n->addNode($this->Statement($x)); - - array_pop($x->stmtStack); - - return $n; - } - - private function Block($x) - { - $this->t->mustMatch(OP_LEFT_CURLY); - $n = $this->Statements($x); - $this->t->mustMatch(OP_RIGHT_CURLY); - - return $n; - } - - private function Statement($x) - { - $tt = $this->t->get(); - $n2 = null; - - // Cases for statements ending in a right curly return early, avoiding the - // common semicolon insertion magic after this switch. - switch ($tt) - { - case KEYWORD_FUNCTION: - return $this->FunctionDefinition( - $x, - true, - count($x->stmtStack) > 1 ? STATEMENT_FORM : DECLARED_FORM - ); - break; - - case OP_LEFT_CURLY: - $n = $this->Statements($x); - $this->t->mustMatch(OP_RIGHT_CURLY); - return $n; - - case KEYWORD_IF: - $n = new JSNode($this->t); - $n->condition = $this->ParenExpression($x); - array_push($x->stmtStack, $n); - $n->thenPart = $this->Statement($x); - $n->elsePart = $this->t->match(KEYWORD_ELSE) ? $this->Statement($x) : null; - array_pop($x->stmtStack); - return $n; - - case KEYWORD_SWITCH: - $n = new JSNode($this->t); - $this->t->mustMatch(OP_LEFT_PAREN); - $n->discriminant = $this->Expression($x); - $this->t->mustMatch(OP_RIGHT_PAREN); - $n->cases = array(); - $n->defaultIndex = -1; - - array_push($x->stmtStack, $n); - - $this->t->mustMatch(OP_LEFT_CURLY); - - while (($tt = $this->t->get()) != OP_RIGHT_CURLY) - { - switch ($tt) - { - case KEYWORD_DEFAULT: - if ($n->defaultIndex >= 0) - throw $this->t->newSyntaxError('More than one switch default'); - // FALL THROUGH - case KEYWORD_CASE: - $n2 = new JSNode($this->t); - if ($tt == KEYWORD_DEFAULT) - $n->defaultIndex = count($n->cases); - else - $n2->caseLabel = $this->Expression($x, OP_COLON); - break; - default: - throw $this->t->newSyntaxError('Invalid switch case'); - } - - $this->t->mustMatch(OP_COLON); - $n2->statements = new JSNode($this->t, JS_BLOCK); - while (($tt = $this->t->peek()) != KEYWORD_CASE && $tt != KEYWORD_DEFAULT && $tt != OP_RIGHT_CURLY) - $n2->statements->addNode($this->Statement($x)); - - array_push($n->cases, $n2); - } - - array_pop($x->stmtStack); - return $n; - - case KEYWORD_FOR: - $n = new JSNode($this->t); - $n->isLoop = true; - $this->t->mustMatch(OP_LEFT_PAREN); - - if (($tt = $this->t->peek()) != OP_SEMICOLON) - { - $x->inForLoopInit = true; - if ($tt == KEYWORD_VAR || $tt == KEYWORD_CONST) - { - $this->t->get(); - $n2 = $this->Variables($x); - } - else - { - $n2 = $this->Expression($x); - } - $x->inForLoopInit = false; - } - - if ($n2 && $this->t->match(KEYWORD_IN)) - { - $n->type = JS_FOR_IN; - if ($n2->type == KEYWORD_VAR) - { - if (count($n2->treeNodes) != 1) - { - throw $this->t->SyntaxError( - 'Invalid for..in left-hand side', - $this->t->filename, - $n2->lineno - ); - } - - // NB: n2[0].type == IDENTIFIER and n2[0].value == n2[0].name. - $n->iterator = $n2->treeNodes[0]; - $n->varDecl = $n2; - } - else - { - $n->iterator = $n2; - $n->varDecl = null; - } - - $n->object = $this->Expression($x); - } - else - { - $n->setup = $n2 ? $n2 : null; - $this->t->mustMatch(OP_SEMICOLON); - $n->condition = $this->t->peek() == OP_SEMICOLON ? null : $this->Expression($x); - $this->t->mustMatch(OP_SEMICOLON); - $n->update = $this->t->peek() == OP_RIGHT_PAREN ? null : $this->Expression($x); - } - - $this->t->mustMatch(OP_RIGHT_PAREN); - $n->body = $this->nest($x, $n); - return $n; - - case KEYWORD_WHILE: - $n = new JSNode($this->t); - $n->isLoop = true; - $n->condition = $this->ParenExpression($x); - $n->body = $this->nest($x, $n); - return $n; - - case KEYWORD_DO: - $n = new JSNode($this->t); - $n->isLoop = true; - $n->body = $this->nest($x, $n, KEYWORD_WHILE); - $n->condition = $this->ParenExpression($x); - if (!$x->ecmaStrictMode) - { - //