jsminplus.inc

  1. cis7 sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc
  2. cle7 sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc
  3. ecd7 sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc
  4. elmsmedia7 sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc
  5. harmony7 sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc
  6. icor7 sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc
  7. meedjum_blog7 sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc
  8. mooc7 sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc

JSMinPlus version 1.4

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 <crisp@tweakers.net>

Usage: $minified = JSMinPlus::minify($script [, $filename])

Versionlog (see also changelog.txt): 23-07-2011 - remove dynamic creation of OP_* and KEYWORD_* defines and declare them on top reduce memory footprint by minifying by block-scope some small byte-saving and performance improvements 12-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

Constants

Classes

File

sites/all/modules/ulmus/advagg/advagg_js_compress/jsminplus.inc
View source
  1. <?php
  2. /**
  3. * JSMinPlus version 1.4
  4. *
  5. * Minifies a javascript file using a javascript parser
  6. *
  7. * This implements a PHP port of Brendan Eich's Narcissus open source javascript engine (in javascript)
  8. * References: http://en.wikipedia.org/wiki/Narcissus_(JavaScript_engine)
  9. * Narcissus sourcecode: http://mxr.mozilla.org/mozilla/source/js/narcissus/
  10. * JSMinPlus weblog: http://crisp.tweakblogs.net/blog/cat/716
  11. *
  12. * Tino Zijdel <crisp@tweakers.net>
  13. *
  14. * Usage: $minified = JSMinPlus::minify($script [, $filename])
  15. *
  16. * Versionlog (see also changelog.txt):
  17. * 23-07-2011 - remove dynamic creation of OP_* and KEYWORD_* defines and declare them on top
  18. * reduce memory footprint by minifying by block-scope
  19. * some small byte-saving and performance improvements
  20. * 12-05-2009 - fixed hook:colon precedence, fixed empty body in loop and if-constructs
  21. * 18-04-2009 - fixed crashbug in PHP 5.2.9 and several other bugfixes
  22. * 12-04-2009 - some small bugfixes and performance improvements
  23. * 09-04-2009 - initial open sourced version 1.0
  24. *
  25. * Latest version of this script: http://files.tweakers.net/jsminplus/jsminplus.zip
  26. *
  27. * @file
  28. */
  29. /* ***** BEGIN LICENSE BLOCK *****
  30. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  31. *
  32. * The contents of this file are subject to the Mozilla Public License Version
  33. * 1.1 (the "License"); you may not use this file except in compliance with
  34. * the License. You may obtain a copy of the License at
  35. * http://www.mozilla.org/MPL/
  36. *
  37. * Software distributed under the License is distributed on an "AS IS" basis,
  38. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  39. * for the specific language governing rights and limitations under the
  40. * License.
  41. *
  42. * The Original Code is the Narcissus JavaScript engine.
  43. *
  44. * The Initial Developer of the Original Code is
  45. * Brendan Eich <brendan@mozilla.org>.
  46. * Portions created by the Initial Developer are Copyright (C) 2004
  47. * the Initial Developer. All Rights Reserved.
  48. *
  49. * Contributor(s): Tino Zijdel <crisp@tweakers.net>
  50. * PHP port, modifications and minifier routine are (C) 2009-2011
  51. *
  52. * Alternatively, the contents of this file may be used under the terms of
  53. * either the GNU General Public License Version 2 or later (the "GPL"), or
  54. * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  55. * in which case the provisions of the GPL or the LGPL are applicable instead
  56. * of those above. If you wish to allow use of your version of this file only
  57. * under the terms of either the GPL or the LGPL, and not to allow others to
  58. * use your version of this file under the terms of the MPL, indicate your
  59. * decision by deleting the provisions above and replace them with the notice
  60. * and other provisions required by the GPL or the LGPL. If you do not delete
  61. * the provisions above, a recipient may use your version of this file under
  62. * the terms of any one of the MPL, the GPL or the LGPL.
  63. *
  64. * ***** END LICENSE BLOCK ***** */
  65. define('TOKEN_END', 1);
  66. define('TOKEN_NUMBER', 2);
  67. define('TOKEN_IDENTIFIER', 3);
  68. define('TOKEN_STRING', 4);
  69. define('TOKEN_REGEXP', 5);
  70. define('TOKEN_NEWLINE', 6);
  71. define('TOKEN_CONDCOMMENT_START', 7);
  72. define('TOKEN_CONDCOMMENT_END', 8);
  73. define('JS_SCRIPT', 100);
  74. define('JS_BLOCK', 101);
  75. define('JS_LABEL', 102);
  76. define('JS_FOR_IN', 103);
  77. define('JS_CALL', 104);
  78. define('JS_NEW_WITH_ARGS', 105);
  79. define('JS_INDEX', 106);
  80. define('JS_ARRAY_INIT', 107);
  81. define('JS_OBJECT_INIT', 108);
  82. define('JS_PROPERTY_INIT', 109);
  83. define('JS_GETTER', 110);
  84. define('JS_SETTER', 111);
  85. define('JS_GROUP', 112);
  86. define('JS_LIST', 113);
  87. define('JS_MINIFIED', 999);
  88. define('DECLARED_FORM', 0);
  89. define('EXPRESSED_FORM', 1);
  90. define('STATEMENT_FORM', 2);
  91. /* Operators */
  92. define('OP_SEMICOLON', ';');
  93. define('OP_COMMA', ',');
  94. define('OP_HOOK', '?');
  95. define('OP_COLON', ':');
  96. define('OP_OR', '||');
  97. define('OP_AND', '&&');
  98. define('OP_BITWISE_OR', '|');
  99. define('OP_BITWISE_XOR', '^');
  100. define('OP_BITWISE_AND', '&');
  101. define('OP_STRICT_EQ', '===');
  102. define('OP_EQ', '==');
  103. define('OP_ASSIGN', '=');
  104. define('OP_STRICT_NE', '!==');
  105. define('OP_NE', '!=');
  106. define('OP_LSH', '<<');
  107. define('OP_LE', '<=');
  108. define('OP_LT', '<');
  109. define('OP_URSH', '>>>');
  110. define('OP_RSH', '>>');
  111. define('OP_GE', '>=');
  112. define('OP_GT', '>');
  113. define('OP_INCREMENT', '++');
  114. define('OP_DECREMENT', '--');
  115. define('OP_PLUS', '+');
  116. define('OP_MINUS', '-');
  117. define('OP_MUL', '*');
  118. define('OP_DIV', '/');
  119. define('OP_MOD', '%');
  120. define('OP_NOT', '!');
  121. define('OP_BITWISE_NOT', '~');
  122. define('OP_DOT', '.');
  123. define('OP_LEFT_BRACKET', '[');
  124. define('OP_RIGHT_BRACKET', ']');
  125. define('OP_LEFT_CURLY', '{');
  126. define('OP_RIGHT_CURLY', '}');
  127. define('OP_LEFT_PAREN', '(');
  128. define('OP_RIGHT_PAREN', ')');
  129. define('OP_CONDCOMMENT_END', '@*/');
  130. define('OP_UNARY_PLUS', 'U+');
  131. define('OP_UNARY_MINUS', 'U-');
  132. /* Keywords */
  133. define('KEYWORD_BREAK', 'break');
  134. define('KEYWORD_CASE', 'case');
  135. define('KEYWORD_CATCH', 'catch');
  136. define('KEYWORD_CONST', 'const');
  137. define('KEYWORD_CONTINUE', 'continue');
  138. define('KEYWORD_DEBUGGER', 'debugger');
  139. define('KEYWORD_DEFAULT', 'default');
  140. define('KEYWORD_DELETE', 'delete');
  141. define('KEYWORD_DO', 'do');
  142. define('KEYWORD_ELSE', 'else');
  143. define('KEYWORD_ENUM', 'enum');
  144. define('KEYWORD_FALSE', 'false');
  145. define('KEYWORD_FINALLY', 'finally');
  146. define('KEYWORD_FOR', 'for');
  147. define('KEYWORD_FUNCTION', 'function');
  148. define('KEYWORD_IF', 'if');
  149. define('KEYWORD_IN', 'in');
  150. define('KEYWORD_INSTANCEOF', 'instanceof');
  151. define('KEYWORD_NEW', 'new');
  152. define('KEYWORD_NULL', 'null');
  153. define('KEYWORD_RETURN', 'return');
  154. define('KEYWORD_SWITCH', 'switch');
  155. define('KEYWORD_THIS', 'this');
  156. define('KEYWORD_THROW', 'throw');
  157. define('KEYWORD_TRUE', 'true');
  158. define('KEYWORD_TRY', 'try');
  159. define('KEYWORD_TYPEOF', 'typeof');
  160. define('KEYWORD_VAR', 'var');
  161. define('KEYWORD_VOID', 'void');
  162. define('KEYWORD_WHILE', 'while');
  163. define('KEYWORD_WITH', 'with');
  164. class JSMinPlus {
  165. private $parser;
  166. private $reserved = array(
  167. 'break',
  168. 'case',
  169. 'catch',
  170. 'continue',
  171. 'default',
  172. 'delete',
  173. 'do',
  174. 'else',
  175. 'finally',
  176. 'for',
  177. 'function',
  178. 'if',
  179. 'in',
  180. 'instanceof',
  181. 'new',
  182. 'return',
  183. 'switch',
  184. 'this',
  185. 'throw',
  186. 'try',
  187. 'typeof',
  188. 'var',
  189. 'void',
  190. 'while',
  191. 'with',
  192. // Words reserved for future use
  193. 'abstract',
  194. 'boolean',
  195. 'byte',
  196. 'char',
  197. 'class',
  198. 'const',
  199. 'debugger',
  200. 'double',
  201. 'enum',
  202. 'export',
  203. 'extends',
  204. 'final',
  205. 'float',
  206. 'goto',
  207. 'implements',
  208. 'import',
  209. 'int',
  210. 'interface',
  211. 'long',
  212. 'native',
  213. 'package',
  214. 'private',
  215. 'protected',
  216. 'public',
  217. 'short',
  218. 'static',
  219. 'super',
  220. 'synchronized',
  221. 'throws',
  222. 'transient',
  223. 'volatile',
  224. // These are not reserved, but should be taken into account
  225. // in isValidIdentifier (See jslint source code)
  226. 'arguments',
  227. 'eval',
  228. 'true',
  229. 'false',
  230. 'Infinity',
  231. 'NaN',
  232. 'null',
  233. 'undefined',
  234. );
  235. private function __construct() {
  236. $this->parser = new JSParser($this);
  237. }
  238. public static function minify($js, $filename = '') {
  239. static $instance;
  240. // this is a singleton
  241. if (!$instance) {
  242. $instance = new JSMinPlus();
  243. }
  244. return $instance->min($js, $filename);
  245. }
  246. private function min($js, $filename) {
  247. try {
  248. $n = $this->parser->parse($js, $filename, 1);
  249. return $this->parseTree($n);
  250. }
  251. catch (Exception $e) {
  252. echo $e->getMessage() . "\n";
  253. }
  254. return false;
  255. }
  256. public function parseTree($n, $noBlockGrouping = false) {
  257. $s = '';
  258. switch ($n->type) {
  259. case JS_MINIFIED:
  260. $s = $n->value;
  261. break;
  262. case JS_SCRIPT:
  263. // we do nothing yet with funDecls or varDecls
  264. $noBlockGrouping = true;
  265. // FALL THROUGH
  266. case JS_BLOCK:
  267. $childs = $n->treeNodes;
  268. $lastType = 0;
  269. for ($c = 0, $i = 0, $j = count($childs); $i < $j; $i++) {
  270. $type = $childs[$i]->type;
  271. $t = $this->parseTree($childs[$i]);
  272. if (strlen($t)) {
  273. if ($c) {
  274. $s = rtrim($s, ';');
  275. if ($type == KEYWORD_FUNCTION && $childs[$i]->functionForm == DECLARED_FORM) {
  276. // put declared functions on a new line
  277. $s .= "\n";
  278. }
  279. elseif ($type == KEYWORD_VAR && $type == $lastType) {
  280. // multiple var-statements can go into one
  281. $t = ',' . substr($t, 4);
  282. }
  283. else {
  284. // add terminator
  285. $s .= ';';
  286. }
  287. }
  288. $s .= $t;
  289. $c++;
  290. $lastType = $type;
  291. }
  292. }
  293. if ($c > 1 && !$noBlockGrouping) {
  294. $s = '{' . $s . '}';
  295. }
  296. break;
  297. case KEYWORD_FUNCTION:
  298. $s .= 'function' . ($n->name ? ' ' . $n->name : '') . '(';
  299. $params = $n->params;
  300. for ($i = 0, $j = count($params); $i < $j; $i++) {
  301. $s .= ($i ? ',' : '') . $params[$i];
  302. }
  303. $s .= '){' . $this->parseTree($n->body, true) . '}';
  304. break;
  305. case KEYWORD_IF:
  306. $s = 'if(' . $this->parseTree($n->condition) . ')';
  307. $thenPart = $this->parseTree($n->thenPart);
  308. $elsePart = $n->elsePart ? $this->parseTree($n->elsePart) : null;
  309. // empty if-statement
  310. if ($thenPart == '') {
  311. $thenPart = ';';
  312. }
  313. if ($elsePart) {
  314. // be careful and always make a block out of the thenPart; could be more optimized but is a lot of trouble
  315. if ($thenPart != ';' && $thenPart[0] != '{') {
  316. $thenPart = '{' . $thenPart . '}';
  317. }
  318. $s .= $thenPart . 'else';
  319. // we could check for more, but that hardly ever applies so go for performance
  320. if ($elsePart[0] != '{') {
  321. $s .= ' ';
  322. }
  323. $s .= $elsePart;
  324. }
  325. else {
  326. $s .= $thenPart;
  327. }
  328. break;
  329. case KEYWORD_SWITCH:
  330. $s = 'switch(' . $this->parseTree($n->discriminant) . '){';
  331. $cases = $n->cases;
  332. for ($i = 0, $j = count($cases); $i < $j; $i++) {
  333. $case = $cases[$i];
  334. if ($case->type == KEYWORD_CASE) {
  335. $s .= 'case' . ($case->caseLabel->type != TOKEN_STRING ? ' ' : '') . $this->parseTree($case->caseLabel) . ':';
  336. }
  337. else {
  338. $s .= 'default:';
  339. }
  340. $statement = $this->parseTree($case->statements, true);
  341. if ($statement) {
  342. $s .= $statement;
  343. // no terminator for last statement
  344. if ($i + 1 < $j) {
  345. $s .= ';';
  346. }
  347. }
  348. }
  349. $s .= '}';
  350. break;
  351. case KEYWORD_FOR:
  352. $s = 'for(' . ($n->setup ? $this->parseTree($n->setup) : '')
  353. . ';' . ($n->condition ? $this->parseTree($n->condition) : '')
  354. . ';' . ($n->update ? $this->parseTree($n->update) : '') . ')';
  355. $body = $this->parseTree($n->body);
  356. if ($body == '') {
  357. $body = ';';
  358. }
  359. $s .= $body;
  360. break;
  361. case KEYWORD_WHILE:
  362. $s = 'while(' . $this->parseTree($n->condition) . ')';
  363. $body = $this->parseTree($n->body);
  364. if ($body == '') {
  365. $body = ';';
  366. }
  367. $s .= $body;
  368. break;
  369. case JS_FOR_IN:
  370. $s = 'for(' . ($n->varDecl ? $this->parseTree($n->varDecl) : $this->parseTree($n->iterator)) . ' in ' . $this->parseTree($n->object) . ')';
  371. $body = $this->parseTree($n->body);
  372. if ($body == '') {
  373. $body = ';';
  374. }
  375. $s .= $body;
  376. break;
  377. case KEYWORD_DO:
  378. $s = 'do{' . $this->parseTree($n->body, true) . '}while(' . $this->parseTree($n->condition) . ')';
  379. break;
  380. case KEYWORD_BREAK:
  381. case KEYWORD_CONTINUE:
  382. $s = $n->value . ($n->label ? ' ' . $n->label : '');
  383. break;
  384. case KEYWORD_TRY:
  385. $s = 'try{' . $this->parseTree($n->tryBlock, true) . '}';
  386. $catchClauses = $n->catchClauses;
  387. for ($i = 0, $j = count($catchClauses); $i < $j; $i++) {
  388. $t = $catchClauses[$i];
  389. $s .= 'catch(' . $t->varName . ($t->guard ? ' if ' . $this->parseTree($t->guard) : '') . '){' . $this->parseTree($t->block, true) . '}';
  390. }
  391. if ($n->finallyBlock) {
  392. $s .= 'finally{' . $this->parseTree($n->finallyBlock, true) . '}';
  393. }
  394. break;
  395. case KEYWORD_THROW:
  396. case KEYWORD_RETURN:
  397. $s = $n->type;
  398. if ($n->value) {
  399. $t = $this->parseTree($n->value);
  400. if (strlen($t)) {
  401. if ($this->isWordChar($t[0]) || $t[0] == '\\') {
  402. $s .= ' ';
  403. }
  404. $s .= $t;
  405. }
  406. }
  407. break;
  408. case KEYWORD_WITH:
  409. $s = 'with(' . $this->parseTree($n->object) . ')' . $this->parseTree($n->body);
  410. break;
  411. case KEYWORD_VAR:
  412. case KEYWORD_CONST:
  413. $s = $n->value . ' ';
  414. $childs = $n->treeNodes;
  415. for ($i = 0, $j = count($childs); $i < $j; $i++) {
  416. $t = $childs[$i];
  417. $s .= ($i ? ',' : '') . $t->name;
  418. $u = $t->initializer;
  419. if ($u) {
  420. $s .= '=' . $this->parseTree($u);
  421. }
  422. }
  423. break;
  424. case KEYWORD_IN:
  425. case KEYWORD_INSTANCEOF:
  426. $left = $this->parseTree($n->treeNodes[0]);
  427. $right = $this->parseTree($n->treeNodes[1]);
  428. $s = $left;
  429. if ($this->isWordChar(substr($left, -1))) {
  430. $s .= ' ';
  431. }
  432. $s .= $n->type;
  433. if ($this->isWordChar($right[0]) || $right[0] == '\\') {
  434. $s .= ' ';
  435. }
  436. $s .= $right;
  437. break;
  438. case KEYWORD_DELETE:
  439. case KEYWORD_TYPEOF:
  440. $right = $this->parseTree($n->treeNodes[0]);
  441. $s = $n->type;
  442. if ($this->isWordChar($right[0]) || $right[0] == '\\') {
  443. $s .= ' ';
  444. }
  445. $s .= $right;
  446. break;
  447. case KEYWORD_VOID:
  448. $s = 'void(' . $this->parseTree($n->treeNodes[0]) . ')';
  449. break;
  450. case KEYWORD_DEBUGGER:
  451. throw new Exception('NOT IMPLEMENTED: DEBUGGER');
  452. break;
  453. case TOKEN_CONDCOMMENT_START:
  454. case TOKEN_CONDCOMMENT_END:
  455. $s = $n->value . ($n->type == TOKEN_CONDCOMMENT_START ? ' ' : '');
  456. $childs = $n->treeNodes;
  457. for ($i = 0, $j = count($childs); $i < $j; $i++) {
  458. $s .= $this->parseTree($childs[$i]);
  459. }
  460. break;
  461. case OP_SEMICOLON:
  462. if ($expression = $n->expression) {
  463. $s = $this->parseTree($expression);
  464. }
  465. break;
  466. case JS_LABEL:
  467. $s = $n->label . ':' . $this->parseTree($n->statement);
  468. break;
  469. case OP_COMMA:
  470. $childs = $n->treeNodes;
  471. for ($i = 0, $j = count($childs); $i < $j; $i++) {
  472. $s .= ($i ? ',' : '') . $this->parseTree($childs[$i]);
  473. }
  474. break;
  475. case OP_ASSIGN:
  476. $s = $this->parseTree($n->treeNodes[0]) . $n->value . $this->parseTree($n->treeNodes[1]);
  477. break;
  478. case OP_HOOK:
  479. $s = $this->parseTree($n->treeNodes[0]) . '?' . $this->parseTree($n->treeNodes[1]) . ':' . $this->parseTree($n->treeNodes[2]);
  480. break;
  481. case OP_OR:
  482. case OP_AND:
  483. case OP_BITWISE_OR:
  484. case OP_BITWISE_XOR:
  485. case OP_BITWISE_AND:
  486. case OP_EQ:
  487. case OP_NE:
  488. case OP_STRICT_EQ:
  489. case OP_STRICT_NE:
  490. case OP_LT:
  491. case OP_LE:
  492. case OP_GE:
  493. case OP_GT:
  494. case OP_LSH:
  495. case OP_RSH:
  496. case OP_URSH:
  497. case OP_MUL:
  498. case OP_DIV:
  499. case OP_MOD:
  500. $s = $this->parseTree($n->treeNodes[0]) . $n->type . $this->parseTree($n->treeNodes[1]);
  501. break;
  502. case OP_PLUS:
  503. case OP_MINUS:
  504. $left = $this->parseTree($n->treeNodes[0]);
  505. $right = $this->parseTree($n->treeNodes[1]);
  506. switch ($n->treeNodes[1]->type) {
  507. case OP_PLUS:
  508. case OP_MINUS:
  509. case OP_INCREMENT:
  510. case OP_DECREMENT:
  511. case OP_UNARY_PLUS:
  512. case OP_UNARY_MINUS:
  513. $s = $left . $n->type . ' ' . $right;
  514. break;
  515. case TOKEN_STRING:
  516. //combine concatenated strings with same quote style
  517. if ($n->type == OP_PLUS && substr($left, -1) == $right[0]) {
  518. $s = substr($left, 0, -1) . substr($right, 1);
  519. break;
  520. }
  521. // FALL THROUGH
  522. default:
  523. $s = $left . $n->type . $right;
  524. }
  525. break;
  526. case OP_NOT:
  527. case OP_BITWISE_NOT:
  528. case OP_UNARY_PLUS:
  529. case OP_UNARY_MINUS:
  530. $s = $n->value . $this->parseTree($n->treeNodes[0]);
  531. break;
  532. case OP_INCREMENT:
  533. case OP_DECREMENT:
  534. if ($n->postfix) {
  535. $s = $this->parseTree($n->treeNodes[0]) . $n->value;
  536. }
  537. else {
  538. $s = $n->value . $this->parseTree($n->treeNodes[0]);
  539. }
  540. break;
  541. case OP_DOT:
  542. $s = $this->parseTree($n->treeNodes[0]) . '.' . $this->parseTree($n->treeNodes[1]);
  543. break;
  544. case JS_INDEX:
  545. $s = $this->parseTree($n->treeNodes[0]);
  546. // See if we can replace named index with a dot saving 3 bytes
  547. if ( $n->treeNodes[0]->type == TOKEN_IDENTIFIER &&
  548. $n->treeNodes[1]->type == TOKEN_STRING &&
  549. $this->isValidIdentifier(substr($n->treeNodes[1]->value, 1, -1))
  550. ) {
  551. $s .= '.' . substr($n->treeNodes[1]->value, 1, -1);
  552. }
  553. else {
  554. $s .= '[' . $this->parseTree($n->treeNodes[1]) . ']';
  555. }
  556. break;
  557. case JS_LIST:
  558. $childs = $n->treeNodes;
  559. for ($i = 0, $j = count($childs); $i < $j; $i++) {
  560. $s .= ($i ? ',' : '') . $this->parseTree($childs[$i]);
  561. }
  562. break;
  563. case JS_CALL:
  564. $s = $this->parseTree($n->treeNodes[0]) . '(' . $this->parseTree($n->treeNodes[1]) . ')';
  565. break;
  566. case KEYWORD_NEW:
  567. case JS_NEW_WITH_ARGS:
  568. $s = 'new ' . $this->parseTree($n->treeNodes[0]) . '(' . ($n->type == JS_NEW_WITH_ARGS ? $this->parseTree($n->treeNodes[1]) : '') . ')';
  569. break;
  570. case JS_ARRAY_INIT:
  571. $s = '[';
  572. $childs = $n->treeNodes;
  573. for ($i = 0, $j = count($childs); $i < $j; $i++) {
  574. $s .= ($i ? ',' : '') . $this->parseTree($childs[$i]);
  575. }
  576. $s .= ']';
  577. break;
  578. case JS_OBJECT_INIT:
  579. $s = '{';
  580. $childs = $n->treeNodes;
  581. for ($i = 0, $j = count($childs); $i < $j; $i++) {
  582. $t = $childs[$i];
  583. if ($i) {
  584. $s .= ',';
  585. }
  586. if ($t->type == JS_PROPERTY_INIT) {
  587. // Ditch the quotes when the index is a valid identifier
  588. if ( $t->treeNodes[0]->type == TOKEN_STRING &&
  589. $this->isValidIdentifier(substr($t->treeNodes[0]->value, 1, -1))
  590. ) {
  591. $s .= substr($t->treeNodes[0]->value, 1, -1);
  592. }
  593. else {
  594. $s .= $t->treeNodes[0]->value;
  595. }
  596. $s .= ':' . $this->parseTree($t->treeNodes[1]);
  597. }
  598. else {
  599. $s .= $t->type == JS_GETTER ? 'get' : 'set';
  600. $s .= ' ' . $t->name . '(';
  601. $params = $t->params;
  602. for ($i = 0, $j = count($params); $i < $j; $i++) {
  603. $s .= ($i ? ',' : '') . $params[$i];
  604. }
  605. $s .= '){' . $this->parseTree($t->body, true) . '}';
  606. }
  607. }
  608. $s .= '}';
  609. break;
  610. case TOKEN_NUMBER:
  611. $s = $n->value;
  612. if (preg_match('/^([1-9]+)(0{3,})$/', $s, $m)) {
  613. $s = $m[1] . 'e' . strlen($m[2]);
  614. }
  615. break;
  616. case KEYWORD_NULL:
  617. case KEYWORD_THIS:
  618. case KEYWORD_TRUE:
  619. case KEYWORD_FALSE:
  620. case TOKEN_IDENTIFIER:
  621. case TOKEN_STRING:
  622. case TOKEN_REGEXP:
  623. $s = $n->value;
  624. break;
  625. case JS_GROUP:
  626. if (in_array(
  627. $n->treeNodes[0]->type,
  628. array(
  629. JS_ARRAY_INIT,
  630. JS_OBJECT_INIT,
  631. JS_GROUP,
  632. TOKEN_NUMBER,
  633. TOKEN_STRING,
  634. TOKEN_REGEXP,
  635. TOKEN_IDENTIFIER,
  636. KEYWORD_NULL,
  637. KEYWORD_THIS,
  638. KEYWORD_TRUE,
  639. KEYWORD_FALSE,
  640. )
  641. )) {
  642. $s = $this->parseTree($n->treeNodes[0]);
  643. }
  644. else {
  645. $s = '(' . $this->parseTree($n->treeNodes[0]) . ')';
  646. }
  647. break;
  648. default:
  649. throw new Exception('UNKNOWN TOKEN TYPE: ' . $n->type);
  650. }
  651. return $s;
  652. }
  653. private function isValidIdentifier($string) {
  654. return preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $string) && !in_array($string, $this->reserved);
  655. }
  656. private function isWordChar($char) {
  657. return $char == '_' || $char == '$' || ctype_alnum($char);
  658. }
  659. }
  660. class JSParser {
  661. private $t;
  662. private $minifier;
  663. private $opPrecedence = array(
  664. ';' => 0,
  665. ',' => 1,
  666. '=' => 2,
  667. '?' => 2,
  668. ':' => 2,
  669. // The above all have to have the same precedence, see bug 330975
  670. '||' => 4,
  671. '&&' => 5,
  672. '|' => 6,
  673. '^' => 7,
  674. '&' => 8,
  675. '==' => 9,
  676. '!=' => 9,
  677. '===' => 9,
  678. '!==' => 9,
  679. '<' => 10,
  680. '<=' => 10,
  681. '>=' => 10,
  682. '>' => 10,
  683. 'in' => 10,
  684. 'instanceof' => 10,
  685. '<<' => 11,
  686. '>>' => 11,
  687. '>>>' => 11,
  688. '+' => 12,
  689. '-' => 12,
  690. '*' => 13,
  691. '/' => 13,
  692. '%' => 13,
  693. 'delete' => 14,
  694. 'void' => 14,
  695. 'typeof' => 14,
  696. '!' => 14,
  697. '~' => 14,
  698. 'U+' => 14,
  699. 'U-' => 14,
  700. '++' => 15,
  701. '--' => 15,
  702. 'new' => 16,
  703. '.' => 17,
  704. JS_NEW_WITH_ARGS => 0,
  705. JS_INDEX => 0,
  706. JS_CALL => 0,
  707. JS_ARRAY_INIT => 0,
  708. JS_OBJECT_INIT => 0,
  709. JS_GROUP => 0,
  710. );
  711. private $opArity = array(
  712. ',' => -2,
  713. '=' => 2,
  714. '?' => 3,
  715. '||' => 2,
  716. '&&' => 2,
  717. '|' => 2,
  718. '^' => 2,
  719. '&' => 2,
  720. '==' => 2,
  721. '!=' => 2,
  722. '===' => 2,
  723. '!==' => 2,
  724. '<' => 2,
  725. '<=' => 2,
  726. '>=' => 2,
  727. '>' => 2,
  728. 'in' => 2,
  729. 'instanceof' => 2,
  730. '<<' => 2,
  731. '>>' => 2,
  732. '>>>' => 2,
  733. '+' => 2,
  734. '-' => 2,
  735. '*' => 2,
  736. '/' => 2,
  737. '%' => 2,
  738. 'delete' => 1,
  739. 'void' => 1,
  740. 'typeof' => 1,
  741. '!' => 1,
  742. '~' => 1,
  743. 'U+' => 1,
  744. 'U-' => 1,
  745. '++' => 1,
  746. '--' => 1,
  747. 'new' => 1,
  748. '.' => 2,
  749. JS_NEW_WITH_ARGS => 2,
  750. JS_INDEX => 2,
  751. JS_CALL => 2,
  752. JS_ARRAY_INIT => 1,
  753. JS_OBJECT_INIT => 1,
  754. JS_GROUP => 1,
  755. TOKEN_CONDCOMMENT_START => 1,
  756. TOKEN_CONDCOMMENT_END => 1,
  757. );
  758. public function __construct($minifier = null) {
  759. $this->minifier = $minifier;
  760. $this->t = new JSTokenizer();
  761. }
  762. public function parse($s, $f, $l) {
  763. // initialize tokenizer
  764. $this->t->init($s, $f, $l);
  765. $x = new JSCompilerContext(false);
  766. $n = $this->Script($x);
  767. if (!$this->t->isDone()) {
  768. throw $this->t->newSyntaxError('Syntax error');
  769. }
  770. return $n;
  771. }
  772. private function Script($x) {
  773. $n = $this->Statements($x);
  774. $n->type = JS_SCRIPT;
  775. $n->funDecls = $x->funDecls;
  776. $n->varDecls = $x->varDecls;
  777. // minify by scope
  778. if ($this->minifier) {
  779. $n->value = $this->minifier->parseTree($n);
  780. // clear tree from node to save memory
  781. $n->treeNodes = null;
  782. $n->funDecls = null;
  783. $n->varDecls = null;
  784. $n->type = JS_MINIFIED;
  785. }
  786. return $n;
  787. }
  788. private function Statements($x) {
  789. $n = new JSNode($this->t, JS_BLOCK);
  790. array_push($x->stmtStack, $n);
  791. while (!$this->t->isDone() && $this->t->peek() != OP_RIGHT_CURLY) {
  792. $n->addNode($this->Statement($x));
  793. }
  794. array_pop($x->stmtStack);
  795. return $n;
  796. }
  797. private function Block($x) {
  798. $this->t->mustMatch(OP_LEFT_CURLY);
  799. $n = $this->Statements($x);
  800. $this->t->mustMatch(OP_RIGHT_CURLY);
  801. return $n;
  802. }
  803. private function Statement($x) {
  804. $tt = $this->t->get();
  805. $n2 = null;
  806. // Cases for statements ending in a right curly return early, avoiding the
  807. // common semicolon insertion magic after this switch.
  808. switch ($tt) {
  809. case KEYWORD_FUNCTION:
  810. return $this->FunctionDefinition(
  811. $x,
  812. true,
  813. count($x->stmtStack) > 1 ? STATEMENT_FORM : DECLARED_FORM
  814. );
  815. break;
  816. case OP_LEFT_CURLY:
  817. $n = $this->Statements($x);
  818. $this->t->mustMatch(OP_RIGHT_CURLY);
  819. return $n;
  820. case KEYWORD_IF:
  821. $n = new JSNode($this->t);
  822. $n->condition = $this->ParenExpression($x);
  823. array_push($x->stmtStack, $n);
  824. $n->thenPart = $this->Statement($x);
  825. $n->elsePart = $this->t->match(KEYWORD_ELSE) ? $this->Statement($x) : null;
  826. array_pop($x->stmtStack);
  827. return $n;
  828. case KEYWORD_SWITCH:
  829. $n = new JSNode($this->t);
  830. $this->t->mustMatch(OP_LEFT_PAREN);
  831. $n->discriminant = $this->Expression($x);
  832. $this->t->mustMatch(OP_RIGHT_PAREN);
  833. $n->cases = array();
  834. $n->defaultIndex = -1;
  835. array_push($x->stmtStack, $n);
  836. $this->t->mustMatch(OP_LEFT_CURLY);
  837. while (($tt = $this->t->get()) != OP_RIGHT_CURLY) {
  838. switch ($tt) {
  839. case KEYWORD_DEFAULT:
  840. if ($n->defaultIndex >= 0) {
  841. throw $this->t->newSyntaxError('More than one switch default');
  842. }
  843. // FALL THROUGH
  844. case KEYWORD_CASE:
  845. $n2 = new JSNode($this->t);
  846. if ($tt == KEYWORD_DEFAULT) {
  847. $n->defaultIndex = count($n->cases);
  848. }
  849. else {
  850. $n2->caseLabel = $this->Expression($x, OP_COLON);
  851. }
  852. break;
  853. default:
  854. throw $this->t->newSyntaxError('Invalid switch case');
  855. }
  856. $this->t->mustMatch(OP_COLON);
  857. $n2->statements = new JSNode($this->t, JS_BLOCK);
  858. while (($tt = $this->t->peek()) != KEYWORD_CASE && $tt != KEYWORD_DEFAULT && $tt != OP_RIGHT_CURLY) {
  859. $n2->statements->addNode($this->Statement($x));
  860. }
  861. array_push($n->cases, $n2);
  862. }
  863. array_pop($x->stmtStack);
  864. return $n;
  865. case KEYWORD_FOR:
  866. $n = new JSNode($this->t);
  867. $n->isLoop = true;
  868. $this->t->mustMatch(OP_LEFT_PAREN);
  869. if (($tt = $this->t->peek()) != OP_SEMICOLON) {
  870. $x->inForLoopInit = true;
  871. if ($tt == KEYWORD_VAR || $tt == KEYWORD_CONST) {
  872. $this->t->get();
  873. $n2 = $this->Variables($x);
  874. }
  875. else {
  876. $n2 = $this->Expression($x);
  877. }
  878. $x->inForLoopInit = false;
  879. }
  880. if ($n2 && $this->t->match(KEYWORD_IN)) {
  881. $n->type = JS_FOR_IN;
  882. if ($n2->type == KEYWORD_VAR) {
  883. if (count($n2->treeNodes) != 1) {
  884. throw $this->t->SyntaxError(
  885. 'Invalid for..in left-hand side',
  886. $this->t->filename,
  887. $n2->lineno
  888. );
  889. }
  890. // NB: n2[0].type == IDENTIFIER and n2[0].value == n2[0].name.
  891. $n->iterator = $n2->treeNodes[0];
  892. $n->varDecl = $n2;
  893. }
  894. else {
  895. $n->iterator = $n2;
  896. $n->varDecl = null;
  897. }
  898. $n->object = $this->Expression($x);
  899. }
  900. else {
  901. $n->setup = $n2 ? $n2 : null;
  902. $this->t->mustMatch(OP_SEMICOLON);
  903. $n->condition = $this->t->peek() == OP_SEMICOLON ? null : $this->Expression($x);
  904. $this->t->mustMatch(OP_SEMICOLON);
  905. $n->update = $this->t->peek() == OP_RIGHT_PAREN ? null : $this->Expression($x);
  906. }
  907. $this->t->mustMatch(OP_RIGHT_PAREN);
  908. $n->body = $this->nest($x, $n);
  909. return $n;
  910. case KEYWORD_WHILE:
  911. $n = new JSNode($this->t);
  912. $n->isLoop = true;
  913. $n->condition = $this->ParenExpression($x);
  914. $n->body = $this->nest($x, $n);
  915. return $n;
  916. case KEYWORD_DO:
  917. $n = new JSNode($this->t);
  918. $n->isLoop = true;
  919. $n->body = $this->nest($x, $n, KEYWORD_WHILE);
  920. $n->condition = $this->ParenExpression($x);
  921. if (!$x->ecmaStrictMode) {
  922. // <script language="JavaScript"> (without version hints) may need
  923. // automatic semicolon insertion without a newline after do-while.
  924. // See http://bugzilla.mozilla.org/show_bug.cgi?id=238945.
  925. $this->t->match(OP_SEMICOLON);
  926. return $n;
  927. }
  928. break;
  929. case KEYWORD_BREAK:
  930. case KEYWORD_CONTINUE:
  931. $n = new JSNode($this->t);
  932. if ($this->t->peekOnSameLine() == TOKEN_IDENTIFIER) {
  933. $this->t->get();
  934. $n->label = $this->t->currentToken()->value;
  935. }
  936. $ss = $x->stmtStack;
  937. $i = count($ss);
  938. $label = $n->label;
  939. if ($label) {
  940. do {
  941. if (--$i < 0) {
  942. throw $this->t->newSyntaxError('Label not found');
  943. }
  944. } while ($ss[$i]->label != $label);
  945. }
  946. else {
  947. do {
  948. if (--$i < 0) {
  949. throw $this->t->newSyntaxError('Invalid ' . $tt);
  950. }
  951. } while (!$ss[$i]->isLoop && ($tt != KEYWORD_BREAK || $ss[$i]->type != KEYWORD_SWITCH));
  952. }
  953. $n->target = $ss[$i];
  954. break;
  955. case KEYWORD_TRY:
  956. $n = new JSNode($this->t);
  957. $n->tryBlock = $this->Block($x);
  958. $n->catchClauses = array();
  959. while ($this->t->match(KEYWORD_CATCH)) {
  960. $n2 = new JSNode($this->t);
  961. $this->t->mustMatch(OP_LEFT_PAREN);
  962. $n2->varName = $this->t->mustMatch(TOKEN_IDENTIFIER)->value;
  963. if ($this->t->match(KEYWORD_IF)) {
  964. if ($x->ecmaStrictMode) {
  965. throw $this->t->newSyntaxError('Illegal catch guard');
  966. }
  967. if (count($n->catchClauses) && !end($n->catchClauses)->guard) {
  968. throw $this->t->newSyntaxError('Guarded catch after unguarded');
  969. }
  970. $n2->guard = $this->Expression($x);
  971. }
  972. else {
  973. $n2->guard = null;
  974. }
  975. $this->t->mustMatch(OP_RIGHT_PAREN);
  976. $n2->block = $this->Block($x);
  977. array_push($n->catchClauses, $n2);
  978. }
  979. if ($this->t->match(KEYWORD_FINALLY)) {
  980. $n->finallyBlock = $this->Block($x);
  981. }
  982. if (!count($n->catchClauses) && !$n->finallyBlock) {
  983. throw $this->t->newSyntaxError('Invalid try statement');
  984. }
  985. return $n;
  986. case KEYWORD_CATCH:
  987. case KEYWORD_FINALLY:
  988. throw $this->t->newSyntaxError($tt + ' without preceding try');
  989. case KEYWORD_THROW:
  990. $n = new JSNode($this->t);
  991. $n->value = $this->Expression($x);
  992. break;
  993. case KEYWORD_RETURN:
  994. if (!$x->inFunction) {
  995. throw $this->t->newSyntaxError('Invalid return');
  996. }
  997. $n = new JSNode($this->t);
  998. $tt = $this->t->peekOnSameLine();
  999. if ($tt != TOKEN_END && $tt != TOKEN_NEWLINE && $tt != OP_SEMICOLON && $tt != OP_RIGHT_CURLY) {
  1000. $n->value = $this->Expression($x);
  1001. }
  1002. else {
  1003. $n->value = null;
  1004. }
  1005. break;
  1006. case KEYWORD_WITH:
  1007. $n = new JSNode($this->t);
  1008. $n->object = $this->ParenExpression($x);
  1009. $n->body = $this->nest($x, $n);
  1010. return $n;
  1011. case KEYWORD_VAR:
  1012. case KEYWORD_CONST:
  1013. $n = $this->Variables($x);
  1014. break;
  1015. case TOKEN_CONDCOMMENT_START:
  1016. case TOKEN_CONDCOMMENT_END:
  1017. $n = new JSNode($this->t);
  1018. return $n;
  1019. case KEYWORD_DEBUGGER:
  1020. $n = new JSNode($this->t);
  1021. break;
  1022. case TOKEN_NEWLINE:
  1023. case OP_SEMICOLON:
  1024. $n = new JSNode($this->t, OP_SEMICOLON);
  1025. $n->expression = null;
  1026. return $n;
  1027. default:
  1028. if ($tt == TOKEN_IDENTIFIER) {
  1029. $this->t->scanOperand = false;
  1030. $tt = $this->t->peek();
  1031. $this->t->scanOperand = true;
  1032. if ($tt == OP_COLON) {
  1033. $label = $this->t->currentToken()->value;
  1034. $ss = $x->stmtStack;
  1035. for ($i = count($ss) - 1; $i >= 0; --$i) {
  1036. if ($ss[$i]->label == $label) {
  1037. throw $this->t->newSyntaxError('Duplicate label');
  1038. }
  1039. }
  1040. $this->t->get();
  1041. $n = new JSNode($this->t, JS_LABEL);
  1042. $n->label = $label;
  1043. $n->statement = $this->nest($x, $n);
  1044. return $n;
  1045. }
  1046. }
  1047. $n = new JSNode($this->t, OP_SEMICOLON);
  1048. $this->t->unget();
  1049. $n->expression = $this->Expression($x);
  1050. $n->end = $n->expression->end;
  1051. break;
  1052. }
  1053. if ($this->t->lineno == $this->t->currentToken()->lineno) {
  1054. $tt = $this->t->peekOnSameLine();
  1055. if ($tt != TOKEN_END && $tt != TOKEN_NEWLINE && $tt != OP_SEMICOLON && $tt != OP_RIGHT_CURLY) {
  1056. throw $this->t->newSyntaxError('Missing ; before statement');
  1057. }
  1058. }
  1059. $this->t->match(OP_SEMICOLON);
  1060. return $n;
  1061. }
  1062. private function FunctionDefinition($x, $requireName, $functionForm) {
  1063. $f = new JSNode($this->t);
  1064. if ($f->type != KEYWORD_FUNCTION) {
  1065. $f->type = ($f->value == 'get') ? JS_GETTER : JS_SETTER;
  1066. }
  1067. if ($this->t->match(TOKEN_IDENTIFIER)) {
  1068. $f->name = $this->t->currentToken()->value;
  1069. }
  1070. elseif ($requireName) {
  1071. throw $this->t->newSyntaxError('Missing function identifier');
  1072. }
  1073. $this->t->mustMatch(OP_LEFT_PAREN);
  1074. $f->params = array();
  1075. while (($tt = $this->t->get()) != OP_RIGHT_PAREN) {
  1076. if ($tt != TOKEN_IDENTIFIER) {
  1077. throw $this->t->newSyntaxError('Missing formal parameter');
  1078. }
  1079. array_push($f->params, $this->t->currentToken()->value);
  1080. if ($this->t->peek() != OP_RIGHT_PAREN) {
  1081. $this->t->mustMatch(OP_COMMA);
  1082. }
  1083. }
  1084. $this->t->mustMatch(OP_LEFT_CURLY);
  1085. $x2 = new JSCompilerContext(true);
  1086. $f->body = $this->Script($x2);
  1087. $this->t->mustMatch(OP_RIGHT_CURLY);
  1088. $f->end = $this->t->currentToken()->end;
  1089. $f->functionForm = $functionForm;
  1090. if ($functionForm == DECLARED_FORM) {
  1091. array_push($x->funDecls, $f);
  1092. }
  1093. return $f;
  1094. }
  1095. private function Variables($x) {
  1096. $n = new JSNode($this->t);
  1097. do {
  1098. $this->t->mustMatch(TOKEN_IDENTIFIER);
  1099. $n2 = new JSNode($this->t);
  1100. $n2->name = $n2->value;
  1101. if ($this->t->match(OP_ASSIGN)) {
  1102. if ($this->t->currentToken()->assignOp) {
  1103. throw $this->t->newSyntaxError('Invalid variable initialization');
  1104. }
  1105. $n2->initializer = $this->Expression($x, OP_COMMA);
  1106. }
  1107. $n2->readOnly = $n->type == KEYWORD_CONST;
  1108. $n->addNode($n2);
  1109. array_push($x->varDecls, $n2);
  1110. } while ($this->t->match(OP_COMMA));
  1111. return $n;
  1112. }
  1113. private function Expression($x, $stop = false) {
  1114. $operators = array();
  1115. $operands = array();
  1116. $n = false;
  1117. $bl = $x->bracketLevel;
  1118. $cl = $x->curlyLevel;
  1119. $pl = $x->parenLevel;
  1120. $hl = $x->hookLevel;
  1121. while (($tt = $this->t->get()) != TOKEN_END) {
  1122. if ($tt == $stop &&
  1123. $x->bracketLevel == $bl &&
  1124. $x->curlyLevel == $cl &&
  1125. $x->parenLevel == $pl &&
  1126. $x->hookLevel == $hl
  1127. ) {
  1128. // Stop only if tt matches the optional stop parameter, and that
  1129. // token is not quoted by some kind of bracket.
  1130. break;
  1131. }
  1132. switch ($tt) {
  1133. case OP_SEMICOLON:
  1134. // NB: cannot be empty, Statement handled that.
  1135. break 2;
  1136. case OP_HOOK:
  1137. if ($this->t->scanOperand) {
  1138. break 2;
  1139. }
  1140. while ( !empty($operators) &&
  1141. $this->opPrecedence[end($operators)->type] > $this->opPrecedence[$tt]
  1142. ) {
  1143. $this->reduce($operators, $operands);
  1144. }
  1145. array_push($operators, new JSNode($this->t));
  1146. ++$x->hookLevel;
  1147. $this->t->scanOperand = true;
  1148. $n = $this->Expression($x);
  1149. if (!$this->t->match(OP_COLON)) {
  1150. break 2;
  1151. }
  1152. --$x->hookLevel;
  1153. array_push($operands, $n);
  1154. break;
  1155. case OP_COLON:
  1156. if ($x->hookLevel) {
  1157. break 2;
  1158. }
  1159. throw $this->t->newSyntaxError('Invalid label');
  1160. break;
  1161. case OP_ASSIGN:
  1162. if ($this->t->scanOperand) {
  1163. break 2;
  1164. }
  1165. // Use >, not >=, for right-associative ASSIGN
  1166. while ( !empty($operators) &&
  1167. $this->opPrecedence[end($operators)->type] > $this->opPrecedence[$tt]
  1168. ) {
  1169. $this->reduce($operators, $operands);
  1170. }
  1171. array_push($operators, new JSNode($this->t));
  1172. end($operands)->assignOp = $this->t->currentToken()->assignOp;
  1173. $this->t->scanOperand = true;
  1174. break;
  1175. case KEYWORD_IN:
  1176. // An in operator should not be parsed if we're parsing the head of
  1177. // a for (...) loop, unless it is in the then part of a conditional
  1178. // expression, or parenthesized somehow.
  1179. if ($x->inForLoopInit && !$x->hookLevel &&
  1180. !$x->bracketLevel && !$x->curlyLevel &&
  1181. !$x->parenLevel
  1182. ) {
  1183. break 2;
  1184. }
  1185. // FALL THROUGH
  1186. case OP_COMMA:
  1187. // A comma operator should not be parsed if we're parsing the then part
  1188. // of a conditional expression unless it's parenthesized somehow.
  1189. if ($tt == OP_COMMA && $x->hookLevel &&
  1190. !$x->bracketLevel && !$x->curlyLevel &&
  1191. !$x->parenLevel
  1192. ) {
  1193. break 2;
  1194. }
  1195. // Treat comma as left-associative so reduce can fold left-heavy
  1196. // COMMA trees into a single array.
  1197. // FALL THROUGH
  1198. case OP_OR:
  1199. case OP_AND:
  1200. case OP_BITWISE_OR:
  1201. case OP_BITWISE_XOR:
  1202. case OP_BITWISE_AND:
  1203. case OP_EQ:
  1204. case OP_NE:
  1205. case OP_STRICT_EQ:
  1206. case OP_STRICT_NE:
  1207. case OP_LT:
  1208. case OP_LE:
  1209. case OP_GE:
  1210. case OP_GT:
  1211. case KEYWORD_INSTANCEOF:
  1212. case OP_LSH:
  1213. case OP_RSH:
  1214. case OP_URSH:
  1215. case OP_PLUS:
  1216. case OP_MINUS:
  1217. case OP_MUL:
  1218. case OP_DIV:
  1219. case OP_MOD:
  1220. case OP_DOT:
  1221. if ($this->t->scanOperand) {
  1222. break 2;
  1223. }
  1224. while ( !empty($operators) &&
  1225. $this->opPrecedence[end($operators)->type] >= $this->opPrecedence[$tt]
  1226. ) {
  1227. $this->reduce($operators, $operands);
  1228. }
  1229. if ($tt == OP_DOT) {
  1230. $this->t->mustMatch(TOKEN_IDENTIFIER);
  1231. array_push($operands, new JSNode($this->t, OP_DOT, array_pop($operands), new JSNode($this->t)));
  1232. }
  1233. else {
  1234. array_push($operators, new JSNode($this->t));
  1235. $this->t->scanOperand = true;
  1236. }
  1237. break;
  1238. case KEYWORD_DELETE:
  1239. case KEYWORD_VOID:
  1240. case KEYWORD_TYPEOF:
  1241. case OP_NOT:
  1242. case OP_BITWISE_NOT:
  1243. case OP_UNARY_PLUS:
  1244. case OP_UNARY_MINUS:
  1245. case KEYWORD_NEW:
  1246. if (!$this->t->scanOperand) {
  1247. break 2;
  1248. }
  1249. array_push($operators, new JSNode($this->t));
  1250. break;
  1251. case OP_INCREMENT:
  1252. case OP_DECREMENT:
  1253. if ($this->t->scanOperand) {
  1254. array_push($operators, new JSNode($this->t)); // prefix increment or decrement
  1255. }
  1256. else {
  1257. // Don't cross a line boundary for postfix {in,de}crement.
  1258. $t = $this->t->tokens[($this->t->tokenIndex + $this->t->lookahead - 1) & 3];
  1259. if ($t && $t->lineno != $this->t->lineno) {
  1260. break 2;
  1261. }
  1262. if (!empty($operators)) {
  1263. // Use >, not >=, so postfix has higher precedence than prefix.
  1264. while ($this->opPrecedence[end($operators)->type] > $this->opPrecedence[$tt]) {
  1265. $this->reduce($operators, $operands);
  1266. }
  1267. }
  1268. $n = new JSNode($this->t, $tt, array_pop($operands));
  1269. $n->postfix = true;
  1270. array_push($operands, $n);
  1271. }
  1272. break;
  1273. case KEYWORD_FUNCTION:
  1274. if (!$this->t->scanOperand) {
  1275. break 2;
  1276. }
  1277. array_push($operands, $this->FunctionDefinition($x, false, EXPRESSED_FORM));
  1278. $this->t->scanOperand = false;
  1279. break;
  1280. case KEYWORD_NULL:
  1281. case KEYWORD_THIS:
  1282. case KEYWORD_TRUE:
  1283. case KEYWORD_FALSE:
  1284. case TOKEN_IDENTIFIER:
  1285. case TOKEN_NUMBER:
  1286. case TOKEN_STRING:
  1287. case TOKEN_REGEXP:
  1288. if (!$this->t->scanOperand) {
  1289. break 2;
  1290. }
  1291. array_push($operands, new JSNode($this->t));
  1292. $this->t->scanOperand = false;
  1293. break;
  1294. case TOKEN_CONDCOMMENT_START:
  1295. case TOKEN_CONDCOMMENT_END:
  1296. if ($this->t->scanOperand) {
  1297. array_push($operators, new JSNode($this->t));
  1298. }
  1299. else {
  1300. array_push($operands, new JSNode($this->t));
  1301. }
  1302. break;
  1303. case OP_LEFT_BRACKET:
  1304. if ($this->t->scanOperand) {
  1305. // Array initialiser. Parse using recursive descent, as the
  1306. // sub-grammar here is not an operator grammar.
  1307. $n = new JSNode($this->t, JS_ARRAY_INIT);
  1308. while (($tt = $this->t->peek()) != OP_RIGHT_BRACKET) {
  1309. if ($tt == OP_COMMA) {
  1310. $this->t->get();
  1311. $n->addNode(null);
  1312. continue;
  1313. }
  1314. $n->addNode($this->Expression($x, OP_COMMA));
  1315. if (!$this->t->match(OP_COMMA)) {
  1316. break;
  1317. }
  1318. }
  1319. $this->t->mustMatch(OP_RIGHT_BRACKET);
  1320. array_push($operands, $n);
  1321. $this->t->scanOperand = false;
  1322. }
  1323. else {
  1324. // Property indexing operator.
  1325. array_push($operators, new JSNode($this->t, JS_INDEX));
  1326. $this->t->scanOperand = true;
  1327. ++$x->bracketLevel;
  1328. }
  1329. break;
  1330. case OP_RIGHT_BRACKET:
  1331. if ($this->t->scanOperand || $x->bracketLevel == $bl) {
  1332. break 2;
  1333. }
  1334. while ($this->reduce($operators, $operands)->type != JS_INDEX) {
  1335. continue;
  1336. }
  1337. --$x->bracketLevel;
  1338. break;
  1339. case OP_LEFT_CURLY:
  1340. if (!$this->t->scanOperand) {
  1341. break 2;
  1342. }
  1343. // Object initialiser. As for array initialisers (see above),
  1344. // parse using recursive descent.
  1345. ++$x->curlyLevel;
  1346. $n = new JSNode($this->t, JS_OBJECT_INIT);
  1347. while (!$this->t->match(OP_RIGHT_CURLY)) {
  1348. do {
  1349. $tt = $this->t->get();
  1350. $tv = $this->t->currentToken()->value;
  1351. if (($tv == 'get' || $tv == 'set') && $this->t->peek() == TOKEN_IDENTIFIER) {
  1352. if ($x->ecmaStrictMode) {
  1353. throw $this->t->newSyntaxError('Illegal property accessor');
  1354. }
  1355. $n->addNode($this->FunctionDefinition($x, true, EXPRESSED_FORM));
  1356. }
  1357. else {
  1358. switch ($tt) {
  1359. case TOKEN_IDENTIFIER:
  1360. case TOKEN_NUMBER:
  1361. case TOKEN_STRING:
  1362. $id = new JSNode($this->t);
  1363. break;
  1364. case OP_RIGHT_CURLY:
  1365. if ($x->ecmaStrictMode) {
  1366. throw $this->t->newSyntaxError('Illegal trailing ,');
  1367. }
  1368. break 3;
  1369. default:
  1370. throw $this->t->newSyntaxError('Invalid property name');
  1371. }
  1372. $this->t->mustMatch(OP_COLON);
  1373. $n->addNode(new JSNode($this->t, JS_PROPERTY_INIT, $id, $this->Expression($x, OP_COMMA)));
  1374. }
  1375. } while ($this->t->match(OP_COMMA));
  1376. $this->t->mustMatch(OP_RIGHT_CURLY);
  1377. break;
  1378. }
  1379. array_push($operands, $n);
  1380. $this->t->scanOperand = false;
  1381. --$x->curlyLevel;
  1382. break;
  1383. case OP_RIGHT_CURLY:
  1384. if (!$this->t->scanOperand && $x->curlyLevel != $cl) {
  1385. throw new Exception('PANIC: right curly botch');
  1386. }
  1387. break 2;
  1388. case OP_LEFT_PAREN:
  1389. if ($this->t->scanOperand) {
  1390. array_push($operators, new JSNode($this->t, JS_GROUP));
  1391. }
  1392. else {
  1393. while ( !empty($operators) &&
  1394. $this->opPrecedence[end($operators)->type] > $this->opPrecedence[KEYWORD_NEW]
  1395. ) {
  1396. $this->reduce($operators, $operands);
  1397. }
  1398. // Handle () now, to regularize the n-ary case for n > 0.
  1399. // We must set scanOperand in case there are arguments and
  1400. // the first one is a regexp or unary+/-.
  1401. $n = end($operators);
  1402. $this->t->scanOperand = true;
  1403. if ($this->t->match(OP_RIGHT_PAREN)) {
  1404. if ($n && $n->type == KEYWORD_NEW) {
  1405. array_pop($operators);
  1406. $n->addNode(array_pop($operands));
  1407. }
  1408. else {
  1409. $n = new JSNode($this->t, JS_CALL, array_pop($operands), new JSNode($this->t, JS_LIST));
  1410. }
  1411. array_push($operands, $n);
  1412. $this->t->scanOperand = false;
  1413. break;
  1414. }
  1415. if ($n && $n->type == KEYWORD_NEW) {
  1416. $n->type = JS_NEW_WITH_ARGS;
  1417. }
  1418. else {
  1419. array_push($operators, new JSNode($this->t, JS_CALL));
  1420. }
  1421. }
  1422. ++$x->parenLevel;
  1423. break;
  1424. case OP_RIGHT_PAREN:
  1425. if ($this->t->scanOperand || $x->parenLevel == $pl) {
  1426. break 2;
  1427. }
  1428. while (($tt = $this->reduce($operators, $operands)->type) != JS_GROUP &&
  1429. $tt != JS_CALL && $tt != JS_NEW_WITH_ARGS
  1430. ) {
  1431. continue;
  1432. }
  1433. if ($tt != JS_GROUP) {
  1434. $n = end($operands);
  1435. if ($n->treeNodes[1]->type != OP_COMMA) {
  1436. $n->treeNodes[1] = new JSNode($this->t, JS_LIST, $n->treeNodes[1]);
  1437. }
  1438. else {
  1439. $n->treeNodes[1]->type = JS_LIST;
  1440. }
  1441. }
  1442. --$x->parenLevel;
  1443. break;
  1444. // Automatic semicolon insertion means we may scan across a newline
  1445. // and into the beginning of another statement. If so, break out of
  1446. // the while loop and let the t.scanOperand logic handle errors.
  1447. default:
  1448. break 2;
  1449. }
  1450. }
  1451. if ($x->hookLevel != $hl) {
  1452. throw $this->t->newSyntaxError('Missing : in conditional expression');
  1453. }
  1454. if ($x->parenLevel != $pl) {
  1455. throw $this->t->newSyntaxError('Missing ) in parenthetical');
  1456. }
  1457. if ($x->bracketLevel != $bl) {
  1458. throw $this->t->newSyntaxError('Missing ] in index expression');
  1459. }
  1460. if ($this->t->scanOperand) {
  1461. throw $this->t->newSyntaxError('Missing operand');
  1462. }
  1463. // Resume default mode, scanning for operands, not operators.
  1464. $this->t->scanOperand = true;
  1465. $this->t->unget();
  1466. while (count($operators)) {
  1467. $this->reduce($operators, $operands);
  1468. }
  1469. return array_pop($operands);
  1470. }
  1471. private function ParenExpression($x) {
  1472. $this->t->mustMatch(OP_LEFT_PAREN);
  1473. $n = $this->Expression($x);
  1474. $this->t->mustMatch(OP_RIGHT_PAREN);
  1475. return $n;
  1476. }
  1477. // Statement stack and nested statement handler.
  1478. private function nest($x, $node, $end = false) {
  1479. array_push($x->stmtStack, $node);
  1480. $n = $this->statement($x);
  1481. array_pop($x->stmtStack);
  1482. if ($end) {
  1483. $this->t->mustMatch($end);
  1484. }
  1485. return $n;
  1486. }
  1487. private function reduce(&$operators, &$operands) {
  1488. $n = array_pop($operators);
  1489. $op = $n->type;
  1490. $arity = $this->opArity[$op];
  1491. $c = count($operands);
  1492. if ($arity == -2) {
  1493. // Flatten left-associative trees
  1494. if ($c >= 2) {
  1495. $left = $operands[$c - 2];
  1496. if ($left->type == $op) {
  1497. $right = array_pop($operands);
  1498. $left->addNode($right);
  1499. return $left;
  1500. }
  1501. }
  1502. $arity = 2;
  1503. }
  1504. // Always use push to add operands to n, to update start and end
  1505. $a = array_splice($operands, $c - $arity);
  1506. for ($i = 0; $i < $arity; $i++) {
  1507. $n->addNode($a[$i]);
  1508. }
  1509. // Include closing bracket or postfix operator in [start,end]
  1510. $te = $this->t->currentToken()->end;
  1511. if ($n->end < $te) {
  1512. $n->end = $te;
  1513. }
  1514. array_push($operands, $n);
  1515. return $n;
  1516. }
  1517. }
  1518. class JSCompilerContext {
  1519. public $inFunction = false;
  1520. public $inForLoopInit = false;
  1521. public $ecmaStrictMode = false;
  1522. public $bracketLevel = 0;
  1523. public $curlyLevel = 0;
  1524. public $parenLevel = 0;
  1525. public $hookLevel = 0;
  1526. public $stmtStack = array();
  1527. public $funDecls = array();
  1528. public $varDecls = array();
  1529. public function __construct($inFunction) {
  1530. $this->inFunction = $inFunction;
  1531. }
  1532. }
  1533. class JSNode {
  1534. private $type;
  1535. private $value;
  1536. private $lineno;
  1537. private $start;
  1538. private $end;
  1539. public $treeNodes = array();
  1540. public $funDecls = array();
  1541. public $varDecls = array();
  1542. public function __construct($t, $type = 0) {
  1543. if ($token = $t->currentToken()) {
  1544. $this->type = $type ? $type : $token->type;
  1545. $this->value = $token->value;
  1546. $this->lineno = $token->lineno;
  1547. $this->start = $token->start;
  1548. $this->end = $token->end;
  1549. }
  1550. else {
  1551. $this->type = $type;
  1552. $this->lineno = $t->lineno;
  1553. }
  1554. if (($numargs = func_num_args()) > 2) {
  1555. $args = func_get_args();
  1556. for ($i = 2; $i < $numargs; $i++) {
  1557. $this->addNode($args[$i]);
  1558. }
  1559. }
  1560. }
  1561. // we don't want to bloat our object with all kind of specific properties, so we use overloading
  1562. public function __set($name, $value) {
  1563. $this->$name = $value;
  1564. }
  1565. public function __get($name) {
  1566. if (isset($this->$name)) {
  1567. return $this->$name;
  1568. }
  1569. return null;
  1570. }
  1571. public function addNode($node) {
  1572. if ($node !== null) {
  1573. if ($node->start < $this->start) {
  1574. $this->start = $node->start;
  1575. }
  1576. if ($this->end < $node->end) {
  1577. $this->end = $node->end;
  1578. }
  1579. }
  1580. $this->treeNodes[] = $node;
  1581. }
  1582. }
  1583. class JSTokenizer {
  1584. private $cursor = 0;
  1585. private $source;
  1586. public $tokens = array();
  1587. public $tokenIndex = 0;
  1588. public $lookahead = 0;
  1589. public $scanNewlines = false;
  1590. public $scanOperand = true;
  1591. public $filename;
  1592. public $lineno;
  1593. private $keywords = array(
  1594. 'break',
  1595. 'case',
  1596. 'catch',
  1597. 'const',
  1598. 'continue',
  1599. 'debugger',
  1600. 'default',
  1601. 'delete',
  1602. 'do',
  1603. 'else',
  1604. 'enum',
  1605. 'false',
  1606. 'finally',
  1607. 'for',
  1608. 'function',
  1609. 'if',
  1610. 'in',
  1611. 'instanceof',
  1612. 'new',
  1613. 'null',
  1614. 'return',
  1615. 'switch',
  1616. 'this',
  1617. 'throw',
  1618. 'true',
  1619. 'try',
  1620. 'typeof',
  1621. 'var',
  1622. 'void',
  1623. 'while',
  1624. 'with',
  1625. );
  1626. private $opTypeNames = array(
  1627. ';',
  1628. ',',
  1629. '?',
  1630. ':',
  1631. '||',
  1632. '&&',
  1633. '|',
  1634. '^',
  1635. '&',
  1636. '===',
  1637. '==',
  1638. '=',
  1639. '!==',
  1640. '!=',
  1641. '<<',
  1642. '<=',
  1643. '<',
  1644. '>>>',
  1645. '>>',
  1646. '>=',
  1647. '>',
  1648. '++',
  1649. '--',
  1650. '+',
  1651. '-',
  1652. '*',
  1653. '/',
  1654. '%',
  1655. '!',
  1656. '~',
  1657. '.',
  1658. '[',
  1659. ']',
  1660. '{',
  1661. '}',
  1662. '(',
  1663. ')',
  1664. '@*/',
  1665. );
  1666. private $assignOps = array('|', '^', '&', '<<', '>>', '>>>', '+', '-', '*', '/', '%');
  1667. private $opRegExp;
  1668. public function __construct() {
  1669. $this->opRegExp = '#^(' . implode('|', array_map('preg_quote', $this->opTypeNames)) . ')#';
  1670. }
  1671. public function init($source, $filename = '', $lineno = 1) {
  1672. $this->source = $source;
  1673. $this->filename = $filename ? $filename : '[inline]';
  1674. $this->lineno = $lineno;
  1675. $this->cursor = 0;
  1676. $this->tokens = array();
  1677. $this->tokenIndex = 0;
  1678. $this->lookahead = 0;
  1679. $this->scanNewlines = false;
  1680. $this->scanOperand = true;
  1681. }
  1682. public function getInput($chunksize) {
  1683. if ($chunksize) {
  1684. return substr($this->source, $this->cursor, $chunksize);
  1685. }
  1686. return substr($this->source, $this->cursor);
  1687. }
  1688. public function isDone() {
  1689. return $this->peek() == TOKEN_END;
  1690. }
  1691. public function match($tt) {
  1692. return $this->get() == $tt || $this->unget();
  1693. }
  1694. public function mustMatch($tt) {
  1695. if (!$this->match($tt)) {
  1696. throw $this->newSyntaxError('Unexpected token; token ' . $tt . ' expected');
  1697. }
  1698. return $this->currentToken();
  1699. }
  1700. public function peek() {
  1701. if ($this->lookahead) {
  1702. $next = $this->tokens[($this->tokenIndex + $this->lookahead) & 3];
  1703. if ($this->scanNewlines && $next->lineno != $this->lineno) {
  1704. $tt = TOKEN_NEWLINE;
  1705. }
  1706. else {
  1707. $tt = $next->type;
  1708. }
  1709. }
  1710. else {
  1711. $tt = $this->get();
  1712. $this->unget();
  1713. }
  1714. return $tt;
  1715. }
  1716. public function peekOnSameLine() {
  1717. $this->scanNewlines = true;
  1718. $tt = $this->peek();
  1719. $this->scanNewlines = false;
  1720. return $tt;
  1721. }
  1722. public function currentToken() {
  1723. if (!empty($this->tokens)) {
  1724. return $this->tokens[$this->tokenIndex];
  1725. }
  1726. }
  1727. public function get($chunksize = 1000) {
  1728. while ($this->lookahead) {
  1729. $this->lookahead--;
  1730. $this->tokenIndex = ($this->tokenIndex + 1) & 3;
  1731. $token = $this->tokens[$this->tokenIndex];
  1732. if ($token->type != TOKEN_NEWLINE || $this->scanNewlines) {
  1733. return $token->type;
  1734. }
  1735. }
  1736. $conditional_comment = false;
  1737. // strip whitespace and comments
  1738. while (true) {
  1739. $input = $this->getInput($chunksize);
  1740. // whitespace handling; gobble up \r as well (effectively we don't have support for MAC newlines!)
  1741. $re = $this->scanNewlines ? '/^[ \r\t]+/' : '/^\s+/';
  1742. if (preg_match($re, $input, $match)) {
  1743. $spaces = $match[0];
  1744. $spacelen = strlen($spaces);
  1745. $this->cursor += $spacelen;
  1746. if (!$this->scanNewlines) {
  1747. $this->lineno += substr_count($spaces, "\n");
  1748. }
  1749. if ($spacelen == $chunksize) {
  1750. continue; // complete chunk contained whitespace
  1751. }
  1752. $input = $this->getInput($chunksize);
  1753. if ($input == '' || $input[0] != '/') {
  1754. break;
  1755. }
  1756. }
  1757. // Comments
  1758. if (!preg_match('/^\/(?:\*(@(?:cc_on|if|elif|else|end))?.*?\*\/|\/[^\n]*)/s', $input, $match)) {
  1759. if (!$chunksize) {
  1760. break;
  1761. }
  1762. // retry with a full chunk fetch; this also prevents breakage of long regular expressions (which will never match a comment)
  1763. $chunksize = null;
  1764. continue;
  1765. }
  1766. // check if this is a conditional (JScript) comment
  1767. if (!empty($match[1])) {
  1768. $match[0] = '/*' . $match[1];
  1769. $conditional_comment = true;
  1770. break;
  1771. }
  1772. else {
  1773. $this->cursor += strlen($match[0]);
  1774. $this->lineno += substr_count($match[0], "\n");
  1775. }
  1776. }
  1777. if ($input == '') {
  1778. $tt = TOKEN_END;
  1779. $match = array('');
  1780. }
  1781. elseif ($conditional_comment) {
  1782. $tt = TOKEN_CONDCOMMENT_START;
  1783. }
  1784. else {
  1785. switch ($input[0]) {
  1786. case '0':
  1787. // hexadecimal
  1788. if (($input[1] == 'x' || $input[1] == 'X') && preg_match('/^0x[0-9a-f]+/i', $input, $match)) {
  1789. $tt = TOKEN_NUMBER;
  1790. break;
  1791. }
  1792. // FALL THROUGH
  1793. case '1':
  1794. case '2':
  1795. case '3':
  1796. case '4':
  1797. case '5':
  1798. case '6':
  1799. case '7':
  1800. case '8':
  1801. case '9':
  1802. // should always match
  1803. preg_match('/^\d+(?:\.\d*)?(?:[eE][-+]?\d+)?/', $input, $match);
  1804. $tt = TOKEN_NUMBER;
  1805. break;
  1806. case "'":
  1807. if (preg_match('/^\'(?:[^\\\\\'\r\n]++|\\\\(?:.|\r?\n))*\'/', $input, $match)) {
  1808. $tt = TOKEN_STRING;
  1809. }
  1810. else {
  1811. if ($chunksize) {
  1812. return $this->get(null); // retry with a full chunk fetch
  1813. }
  1814. throw $this->newSyntaxError('Unterminated string literal');
  1815. }
  1816. break;
  1817. case '"':
  1818. if (preg_match('/^"(?:[^\\\\"\r\n]++|\\\\(?:.|\r?\n))*"/', $input, $match)) {
  1819. $tt = TOKEN_STRING;
  1820. }
  1821. else {
  1822. if ($chunksize) {
  1823. return $this->get(null); // retry with a full chunk fetch
  1824. }
  1825. throw $this->newSyntaxError('Unterminated string literal');
  1826. }
  1827. break;
  1828. case '/':
  1829. if ($this->scanOperand && preg_match('/^\/((?:\\\\.|\[(?:\\\\.|[^\]])*\]|[^\/])+)\/([gimy]*)/', $input, $match)) {
  1830. $tt = TOKEN_REGEXP;
  1831. break;
  1832. }
  1833. // FALL THROUGH
  1834. case '|':
  1835. case '^':
  1836. case '&':
  1837. case '<':
  1838. case '>':
  1839. case '+':
  1840. case '-':
  1841. case '*':
  1842. case '%':
  1843. case '=':
  1844. case '!':
  1845. // should always match
  1846. preg_match($this->opRegExp, $input, $match);
  1847. $op = $match[0];
  1848. if (in_array($op, $this->assignOps) && $input[strlen($op)] == '=') {
  1849. $tt = OP_ASSIGN;
  1850. $match[0] .= '=';
  1851. }
  1852. else {
  1853. $tt = $op;
  1854. if ($this->scanOperand) {
  1855. if ($op == OP_PLUS) {
  1856. $tt = OP_UNARY_PLUS;
  1857. }
  1858. elseif ($op == OP_MINUS) {
  1859. $tt = OP_UNARY_MINUS;
  1860. }
  1861. }
  1862. $op = null;
  1863. }
  1864. break;
  1865. case '.':
  1866. if (preg_match('/^\.\d+(?:[eE][-+]?\d+)?/', $input, $match)) {
  1867. $tt = TOKEN_NUMBER;
  1868. break;
  1869. }
  1870. // FALL THROUGH
  1871. case ';':
  1872. case ',':
  1873. case '?':
  1874. case ':':
  1875. case '~':
  1876. case '[':
  1877. case ']':
  1878. case '{':
  1879. case '}':
  1880. case '(':
  1881. case ')':
  1882. // these are all single
  1883. $match = array($input[0]);
  1884. $tt = $input[0];
  1885. break;
  1886. case '@':
  1887. // check end of conditional comment
  1888. if (substr($input, 0, 3) == '@*/') {
  1889. $match = array('@*/');
  1890. $tt = TOKEN_CONDCOMMENT_END;
  1891. }
  1892. else {
  1893. throw $this->newSyntaxError('Illegal token');
  1894. }
  1895. break;
  1896. case "\n":
  1897. if ($this->scanNewlines) {
  1898. $match = array("\n");
  1899. $tt = TOKEN_NEWLINE;
  1900. }
  1901. else {
  1902. throw $this->newSyntaxError('Illegal token');
  1903. }
  1904. break;
  1905. default:
  1906. // Fast path for identifiers: word chars followed by whitespace or various other tokens.
  1907. // Note we don't need to exclude digits in the first char, as they've already been found
  1908. // above.
  1909. if (!preg_match('/^[$\w]+(?=[\s\/\|\^\&<>\+\-\*%=!.;,\?:~\[\]\{\}\(\)@])/', $input, $match)) {
  1910. // Character classes per ECMA-262 edition 5.1 section 7.6
  1911. // Per spec, must accept Unicode 3.0, *may* accept later versions.
  1912. // We'll take whatever PCRE understands, which should be more recent.
  1913. $identifierStartChars = "\\p{L}\\p{Nl}" . # UnicodeLetter
  1914. "\$" .
  1915. "_";
  1916. $identifierPartChars = $identifierStartChars .
  1917. "\\p{Mn}\\p{Mc}" . # UnicodeCombiningMark
  1918. "\\p{Nd}" . # UnicodeDigit
  1919. "\\p{Pc}"; # UnicodeConnectorPunctuation
  1920. $unicodeEscape = "\\\\u[0-9A-F-a-f]{4}";
  1921. $identifierRegex = "/^" .
  1922. "(?:[$identifierStartChars]|$unicodeEscape)" .
  1923. "(?:[$identifierPartChars]|$unicodeEscape)*" .
  1924. "/uS";
  1925. if (preg_match($identifierRegex, $input, $match)) {
  1926. if (strpos($match[0], '\\') !== false) {
  1927. // Per ECMA-262 edition 5.1, section 7.6 escape sequences should behave as if they were
  1928. // the original chars, but only within the boundaries of the identifier.
  1929. $decoded = preg_replace_callback('/\\\\u([0-9A-Fa-f]{4})/',
  1930. array(__CLASS__, 'unicodeEscapeCallback'),
  1931. $match[0]);
  1932. // Since our original regex didn't de-escape the originals, we need to check for validity again.
  1933. // No need to worry about token boundaries, as anything outside the identifier is illegal!
  1934. if (!preg_match("/^[$identifierStartChars][$identifierPartChars]*$/u", $decoded)) {
  1935. throw $this->newSyntaxError('Illegal token');
  1936. }
  1937. // Per spec it _ought_ to work to use these escapes for keywords words as well...
  1938. // but IE rejects them as invalid, while Firefox and Chrome treat them as identifiers
  1939. // that don't match the keyword.
  1940. if (in_array($decoded, $this->keywords)) {
  1941. throw $this->newSyntaxError('Illegal token');
  1942. }
  1943. // TODO: save the decoded form for output?
  1944. }
  1945. }
  1946. else {
  1947. throw $this->newSyntaxError('Illegal token');
  1948. }
  1949. }
  1950. $tt = in_array($match[0], $this->keywords) ? $match[0] : TOKEN_IDENTIFIER;
  1951. }
  1952. }
  1953. $this->tokenIndex = ($this->tokenIndex + 1) & 3;
  1954. if (!isset($this->tokens[$this->tokenIndex])) {
  1955. $this->tokens[$this->tokenIndex] = new JSToken();
  1956. }
  1957. $token = $this->tokens[$this->tokenIndex];
  1958. $token->type = $tt;
  1959. if ($tt == OP_ASSIGN) {
  1960. $token->assignOp = $op;
  1961. }
  1962. $token->start = $this->cursor;
  1963. $token->value = $match[0];
  1964. $this->cursor += strlen($match[0]);
  1965. $token->end = $this->cursor;
  1966. $token->lineno = $this->lineno;
  1967. return $tt;
  1968. }
  1969. public function unget() {
  1970. if (++$this->lookahead == 4) {
  1971. throw $this->newSyntaxError('PANIC: too much lookahead!');
  1972. }
  1973. $this->tokenIndex = ($this->tokenIndex - 1) & 3;
  1974. }
  1975. public function newSyntaxError($m) {
  1976. return new Exception('Parse error: ' . $m . ' in file \'' . $this->filename . '\' on line ' . $this->lineno);
  1977. }
  1978. public static function unicodeEscapeCallback($m) {
  1979. return html_entity_decode('&#x' . $m[1]. ';', ENT_QUOTES, 'UTF-8');
  1980. }
  1981. }
  1982. class JSToken {
  1983. public $type;
  1984. public $value;
  1985. public $start;
  1986. public $end;
  1987. public $lineno;
  1988. public $assignOp;
  1989. }
Error | ELMSLN API

Error

×

Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/elmsln_community/api.elmsln.org/includes/common.inc:2791) in drupal_send_headers() (line 1499 of /var/www/html/elmsln_community/api.elmsln.org/includes/bootstrap.inc).
  • Error: Call to undefined function apc_delete() in DrupalAPCCache->clear() (line 289 of /var/www/html/elmsln_community/api.elmsln.org/sites/all/modules/apc/drupal_apc_cache.inc).
The website encountered an unexpected error. Please try again later.