espruino-web-ide
Version:
A Terminal and Graphical code Editor for Espruino JavaScript Microcontrollers
1,510 lines (1,287 loc) • 600 kB
JavaScript
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
'use strict';
var Name, Syntax, estraverse, common;
Name = 'annotate-directive';
estraverse = require('estraverse');
common = require('./common');
Syntax = common.Syntax;
function isDirective(stmt) {
var expr;
if (stmt.type === Syntax.ExpressionStatement) {
expr = stmt.expression;
if (expr.type === Syntax.Literal && typeof expr.value === 'string') {
return true;
}
}
return false;
}
function escapeAllowedCharacter(ch, next) {
var code = ch.charCodeAt(0), hex = code.toString(16), result = '\\';
switch (ch) {
case '\b':
result += 'b';
break;
case '\f':
result += 'f';
break;
case '\t':
result += 't';
break;
default:
if (code > 0xff) {
result += 'u' + '0000'.slice(hex.length) + hex;
} else if (ch === '\u0000' && '0123456789'.indexOf(next) < 0) {
result += '0';
} else if (ch === '\v') {
result += 'v';
} else {
result += 'x' + '00'.slice(hex.length) + hex;
}
break;
}
return result;
}
function escapeDisallowedCharacter(ch) {
var result = '\\';
switch (ch) {
case '\\':
result += '\\';
break;
case '\n':
result += 'n';
break;
case '\r':
result += 'r';
break;
case '\u2028':
result += 'u2028';
break;
case '\u2029':
result += 'u2029';
break;
default:
throw new Error('Incorrectly classified character');
}
return result;
}
function escapeString(str) {
var result = '', i, len, ch;
if (typeof str[0] === 'undefined') {
str = common.stringToArray(str);
}
for (i = 0, len = str.length; i < len; i += 1) {
ch = str[i];
if (ch === '\'') {
result += '\\\'';
continue;
} else if ('\\\n\r\u2028\u2029'.indexOf(ch) >= 0) {
result += escapeDisallowedCharacter(ch);
continue;
} else if (!(ch >= ' ' && ch <= '~')) {
result += escapeAllowedCharacter(ch, str[i + 1]);
continue;
}
result += ch;
}
return result;
}
function annotateDirective(tree, options) {
var result;
result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
estraverse.traverse(result, {
enter: function enter(node, parent) {
var stmt, i, iz;
if (!(node.type === Syntax.Program ||
(node.type === Syntax.BlockStatement && (parent.type === Syntax.FunctionExpression || parent.type === Syntax.FunctionDeclaration)))) {
return;
}
for (i = 0, iz = node.body.length; i < iz; ++i) {
stmt = node.body[i];
if (isDirective(stmt)) {
stmt.type = Syntax.DirectiveStatement;
if (stmt.expression.raw) {
stmt.directive = stmt.expression.raw.substring(1, stmt.expression.raw.length - 1);
stmt.value = stmt.expression.value;
stmt.raw = stmt.expression.raw;
} else {
stmt.directive = escapeString(stmt.expression.value);
stmt.value = stmt.expression.value;
stmt.raw = '\'' + stmt.directive + '\'';
}
delete stmt.expression;
} else {
return;
}
}
}
});
return result;
}
annotateDirective.passName = Name;
module.exports = annotateDirective;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./common":2,"estraverse":129}],2:[function(require,module,exports){
/*!
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint bitwise:true */
(function () {
'use strict';
var Syntax,
isArray,
arrayFrom,
arrayOf,
has,
sameValue,
estraverse,
escope,
esutils;
estraverse = require('estraverse');
escope = require('escope');
esutils = require('esutils');
isArray = require('isarray');
Syntax = estraverse.Syntax;
function isObject(obj) {
return typeof obj === 'object' && obj !== null;
}
has = (function () {
var method = {}.hasOwnProperty;
return function has(obj, prop) {
return method.call(obj, prop);
};
}());
// ES6 Array.from
arrayFrom = (function () {
var slice = Array.prototype.slice;
return function arrayFrom(array) {
return slice.call(array);
};
}());
// ES6 Array.of
arrayOf = (function () {
var slice = Array.prototype.slice;
return function arrayOf() {
return slice.call(arguments);
};
}());
function arrayLast(array) {
return array[array.length - 1];
}
function arrayEmpty(array) {
return array.length === 0;
}
function stringRepeat(str, num) {
var result = '';
for (num |= 0; num > 0; num >>>= 1, str += str) {
if (num & 1) {
result += str;
}
}
return result;
}
// see http://wiki.ecmascript.org/doku.php?id=harmony:egal
// ECMA262 SameValue algorithm
if (Object.is) {
sameValue = Object.is;
} else {
sameValue = function sameValue(x, y) {
if (x === y) {
// 0 === -0, but they are not identical
return x !== 0 || 1 / x === 1 / y;
}
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is a NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN("foo") => true
return x !== x && y !== y;
};
}
function deepCopy(obj) {
function deepCopyInternal(obj, result) {
var key, val;
for (key in obj) {
if (key.lastIndexOf('__', 0) === 0) {
continue;
}
if (obj.hasOwnProperty(key)) {
val = obj[key];
if (typeof val === 'object' && val !== null) {
if (val instanceof RegExp) {
val = new RegExp(val);
} else {
val = deepCopyInternal(val, isArray(val) ? [] : {});
}
}
result[key] = val;
}
}
return result;
}
return deepCopyInternal(obj, isArray(obj) ? [] : {});
}
function assert(cond, text) {
if (!cond) {
throw new Error(text);
}
}
function unreachable() {
throw new Error('Unreachable point. logically broken.');
}
function isIdentifier(name) {
// fallback for ES3
if (esutils.keyword.isKeywordES5(name, true) || esutils.keyword.isRestrictedWord(name)) {
return false;
}
return esutils.keyword.isIdentifierNameES5(name);
}
function mayBeCompletionValue(node, ancestors) {
var i, ancestor;
if (node.type !== Syntax.ExpressionStatement) {
return true;
}
for (i = ancestors.length - 1; i >= 0; --i, node = ancestor) {
ancestor = ancestors[i];
switch (ancestor.type) {
case Syntax.FunctionExpression:
case Syntax.FunctionDeclaration:
return false;
case Syntax.BlockStatement:
case Syntax.Program:
if (arrayLast(ancestor.body) !== node) {
return false;
}
break;
case Syntax.SwitchCase:
if (arrayLast(ancestor.consequent) !== node) {
return false;
}
break;
}
}
return true;
}
function moveLocation(from, to) {
if (from.loc == null) {
return to;
}
to.loc = deepCopy(from.loc);
return to;
}
function deleteLocation(node) {
if (node.hasOwnProperty('loc')) {
return delete node.loc;
}
return false;
}
function convertToEmptyStatement(node) {
var i, iz, keys;
keys = estraverse.VisitorKeys[node.type];
for (i = 0, iz = keys.length; i < iz; ++i) {
delete node[keys[i]];
}
node.type = Syntax.EmptyStatement;
return node;
}
function isNegative(value) {
return value === value && (value < 0 || (value === 0 && 1 / value < 0));
}
function isFunctionBody(node, parent) {
return node.type === Syntax.BlockStatement && (parent.type === Syntax.FunctionDeclaration || parent.type === Syntax.FunctionExpression);
}
function isNumberLiteral(node) {
return node.type === Syntax.Literal && typeof node.value === 'number';
}
function isOptimizedArgument(argument) {
return isNumberLiteral(argument) && String(argument.value).length === 1;
}
function generateNegativeNode(value, node) {
var result;
result = {
type: Syntax.UnaryExpression,
operator: '-',
argument: {
type: Syntax.Literal,
value: -value
}
};
return (node) ? moveLocation(node, result) : result;
}
function isNegativeNode(node) {
return node.type === Syntax.UnaryExpression && node.operator === '-' && isNumberLiteral(node.argument);
}
function generateUndefined(node) {
var result = {
type: Syntax.UnaryExpression,
operator: 'void',
argument: {
type: Syntax.Literal,
value: 0
}
};
return (node) ? moveLocation(node, result) : result;
}
function isUndefined(node) {
return node.type === Syntax.UnaryExpression && node.operator === 'void' && isOptimizedArgument(node.argument);
}
function generateNaN(node) {
var result = {
type: Syntax.BinaryExpression,
operator: '/',
left: {
type: Syntax.Literal,
value: 0
},
right: {
type: Syntax.Literal,
value: 0
}
};
return (node) ? moveLocation(node, result) : result;
}
function isNaNNode(node) {
if (node.type === Syntax.BinaryExpression) {
if (isOptimizedArgument(node.left) && isOptimizedArgument(node.right)) {
return node.left.value === 0 && node.right.value === 0;
}
}
return false;
}
function generateFromValue(value) {
if (typeof value === 'number') {
if (isNaN(value)) {
return generateNaN();
}
if (isNegative(value)) {
return generateNegativeNode(value);
}
}
if (value === undefined) {
return generateUndefined();
}
return {
type: Syntax.Literal,
value: value
};
}
function isReference(node) {
var type = node.type;
return type === Syntax.Identifier || type === Syntax.MemberExpression;
}
// @param last last element of SequenceExpression
// @param parent parent element of SequenceExpression
// @param scope scope
function canExtractSequence(last, parent, scope) {
var ref;
if (parent.type === Syntax.CallExpression) {
if (last.type === Syntax.Identifier) {
if (last.name === 'eval') {
// This becomes direct call to eval.
return false;
}
ref = scope.resolve(last);
return ref && ref.isStatic();
}
return last.type !== Syntax.MemberExpression;
} else if (parent.type === Syntax.UnaryExpression) {
if (parent.operator === 'delete') {
return !isReference(last);
} else if (parent.operator === 'typeof') {
if (last.type === Syntax.Identifier) {
ref = scope.resolve(last);
return ref && ref.isStatic();
}
}
} else if (parent.type === Syntax.UpdateExpression) {
return !isReference(last);
}
return true;
}
function isFunctionNode(node) {
return node.type === Syntax.Program ||
node.type === Syntax.FunctionDeclaration ||
node.type === Syntax.FunctionExpression ||
node.type === Syntax.ArrowFunctionExpression;
}
function delegateVariableDeclarations(stmt, func) {
var decls, target;
decls = [];
estraverse.traverse(stmt, {
enter: function (node) {
var i, iz, decl;
if (node.type === Syntax.VariableDeclaration) {
if (node.kind === 'let' || node.kind === 'const') {
return;
}
for (i = 0, iz = node.declarations.length; i < iz; ++i) {
decl = node.declarations[i];
delete decl.init;
decls.push(decl);
}
return this.skip();
} else if (isFunctionNode(node)) {
return this.skip();
}
}
});
if (!decls.length) {
return null;
}
target = null;
estraverse.traverse(func.body, {
enter: function (node, parent) {
if (node === stmt) {
return this.skip();
}
if (isFunctionNode(node)) {
return this.skip();
}
if (node.type === Syntax.VariableDeclaration && node.kind === 'var') {
// list is not allowed
if (parent.type !== Syntax.ForInStatement) {
target = node;
return this['break']();
}
}
}
});
if (target) {
target.declarations = target.declarations.concat(decls);
return null;
} else {
return {
type: Syntax.VariableDeclaration,
kind: 'var',
declarations: decls
};
}
}
function isScopedDeclaration(node) {
if (node.type === Syntax.VariableDeclaration && (node.kind === 'let' || node.kind === 'const')) {
return true;
} else if (node.type === Syntax.FunctionDeclaration) {
return true;
}
return false;
}
exports.deepCopy = deepCopy;
exports.stringRepeat = stringRepeat;
exports.sameValue = sameValue;
exports.Array = {
from: arrayFrom,
of: arrayOf,
last: arrayLast,
empty: arrayEmpty
};
exports.Object = {
isObject: isObject,
has: has
};
exports.Syntax = Syntax;
exports.assert = assert;
exports.unreachable = unreachable;
exports.isIdentifier = isIdentifier;
exports.moveLocation = moveLocation;
exports.deleteLocation = deleteLocation;
exports.convertToEmptyStatement = convertToEmptyStatement;
exports.mayBeCompletionValue = mayBeCompletionValue;
exports.isNegative = isNegative;
exports.isFunctionNode = isFunctionNode;
exports.isFunctionBody = isFunctionBody;
exports.SpecialNode = {
generateNegative: generateNegativeNode,
isNegative: isNegativeNode,
generateUndefined: generateUndefined,
isUndefined: isUndefined,
generateNaN: generateNaN,
isNaN: isNaNNode,
isReference: isReference,
canExtractSequence: canExtractSequence,
generateFromValue: generateFromValue
};
exports.delegateVariableDeclarations = delegateVariableDeclarations;
exports.isScopedDeclaration = isScopedDeclaration;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"escope":115,"estraverse":129,"esutils":134,"isarray":139}],3:[function(require,module,exports){
/*!
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint bitwise:true */
/*global exports:true*/
(function () {
'use strict';
var camelCase,
esshorten,
estraverse,
esutils,
isArray,
common,
Options,
Syntax,
Pass,
annotateDirective;
camelCase = require('camel-case');
esshorten = require('esshorten2');
estraverse = require('estraverse');
esutils = require('esutils');
isArray = require('isarray');
common = require('./common');
Options = require('./options');
Pass = require('./pass');
annotateDirective = require('./annotate-directive');
Syntax = common.Syntax;
// recover some broken AST
function recover(tree, useDirectiveStatement) {
estraverse.traverse(tree, {
leave: function leave(node) {
if (esutils.ast.isProblematicIfStatement(node)) {
node.consequent = {
type: Syntax.BlockStatement,
body: [ node.consequent ]
};
}
if (!useDirectiveStatement && node.type === Syntax.DirectiveStatement) {
node.type = Syntax.ExpressionStatement;
node.expression = common.moveLocation(node, {
type: Syntax.Literal,
value: node.value,
raw: node.raw
});
delete node.directive;
delete node.value;
delete node.raw;
}
}
});
return tree;
}
function iteration(tree, p, options) {
var i, iz, pass, res, changed, statuses, passes, result;
function addPass(pass) {
var name, camelCaseName;
if (typeof pass !== 'function') {
// automatic lookup pass (esmangle pass format)
name = Object.keys(pass)[0];
pass = pass[name];
}
if (pass.hasOwnProperty('passName')) {
name = pass.passName;
} else {
name = pass.name;
}
camelCaseName = camelCase(name);
if (typeof options.data.passes === 'undefined' ||
options.data.passes[camelCaseName]) {
passes.push(pass);
statuses.push(true);
}
}
function fillStatuses(bool) {
var i, iz;
for (i = 0, iz = statuses.length; i < iz; ++i) {
statuses[i] = bool;
}
}
result = (options.get('destructive')) ? tree : common.deepCopy(tree);
statuses = [];
passes = [];
for (i = 0, iz = p.length; i < iz; ++i) {
addPass(p[i]);
}
do {
changed = false;
for (i = 0, iz = passes.length; i < iz; ++i) {
pass = passes[i];
if (statuses[i]) {
res = pass(result, options);
if (res.modified) {
changed = true;
fillStatuses(true);
} else {
statuses[i] = false;
}
result = res.result;
}
}
} while (changed);
return result;
}
function optimize(tree, pipeline, options) {
var i, iz, j, jz, section, pass, passName;
options = new Options(options);
tree = annotateDirective(tree, new Options({ destructive: options.data.destructive }));
if (null == pipeline) {
pipeline = Pass.__defaultPipeline;
}
for (i = 0, iz = pipeline.length; i < iz; ++i) {
section = pipeline[i];
// simple iterative pass
if (isArray(section)) {
tree = iteration(tree, section, options);
} else if (section.once) {
pass = section.pass;
for (j = 0, jz = pass.length; j < jz; ++j) {
passName = camelCase(pass[j].passName);
if (typeof options.data.passes === 'undefined' ||
options.data.passes[passName]) {
tree = pass[j](tree, options).result;
}
}
}
}
return recover(tree, options.get('directive'));
}
exports.version = require('../package.json').version;
exports.mangle = esshorten.mangle;
exports.optimize = optimize;
exports.pass = Pass;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"../package.json":159,"./annotate-directive":1,"./common":2,"./options":6,"./pass":7,"camel-case":44,"esshorten2":125,"estraverse":129,"esutils":134,"isarray":139}],4:[function(require,module,exports){
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jshint eqeqeq:false*/
(function () {
'use strict';
var Syntax, common;
common = require('./common');
Syntax = common.Syntax;
// constant
function isConstant(node, allowRegExp) {
if (node.type === Syntax.Literal) {
if (typeof node.value === 'object' && node.value !== null) {
// This is RegExp
return allowRegExp;
}
return true;
}
if (node.type === Syntax.UnaryExpression) {
if (node.operator === 'void' || node.operator === 'delete' || node.operator === '!') {
return isConstant(node.argument, true);
}
return isConstant(node.argument, false);
}
if (node.type === Syntax.BinaryExpression) {
if (node.operator === 'in' || node.operator === 'instanceof') {
return false;
}
return isConstant(node.left, false) && isConstant(node.right, false);
}
if (node.type === Syntax.LogicalExpression) {
return isConstant(node.left, true) && isConstant(node.right, true);
}
return false;
}
function getConstant(node) {
if (node.type === Syntax.Literal) {
return node.value;
}
if (node.type === Syntax.UnaryExpression) {
return doUnary(node.operator, getConstant(node.argument));
}
if (node.type === Syntax.BinaryExpression) {
return doBinary(node.operator, getConstant(node.left), getConstant(node.right));
}
if (node.type === Syntax.LogicalExpression) {
return doLogical(node.operator, getConstant(node.left), getConstant(node.right));
}
common.unreachable();
}
function doLogical(operator, left, right) {
if (operator === '||') {
return left || right;
}
if (operator === '&&') {
return left && right;
}
common.unreachable();
}
function doUnary(operator, argument) {
switch (operator) {
case '+':
return +argument;
case '-':
return -argument;
case '~':
return ~argument;
case '!':
return !argument;
case 'delete':
// do delete on constant value (not considering identifier in this tree based constant folding)
return true;
case 'void':
return undefined;
case 'typeof':
return typeof argument;
}
common.unreachable();
}
function doBinary(operator, left, right) {
switch (operator) {
case '|':
return left | right;
case '^':
return left ^ right;
case '&':
return left & right;
case '==':
return left == right;
case '!=':
return left != right;
case '===':
return left === right;
case '!==':
return left !== right;
case '<':
return left < right;
case '>':
return left > right;
case '<=':
return left <= right;
case '>=':
return left >= right;
// case 'in':
// return left in right;
// case 'instanceof':
// return left instanceof right;
case '<<':
return left << right;
case '>>':
return left >> right;
case '>>>':
return left >>> right;
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '%':
return left % right;
}
common.unreachable();
}
exports.constant = {
doBinary: doBinary,
doUnary: doUnary,
doLogical: doLogical,
evaluate: getConstant,
isConstant: isConstant
};
// has side effect
function hasSideEffect(expr, scope) {
function visit(expr) {
var i, iz, ref;
switch (expr.type) {
case Syntax.AssignmentExpression:
return true;
case Syntax.ArrayExpression:
for (i = 0, iz = expr.elements.length; i < iz; ++i) {
if (expr.elements[i] !== null && visit(expr.elements[i])) {
return true;
}
}
return false;
case Syntax.BinaryExpression:
return !isConstant(expr);
case Syntax.CallExpression:
return true;
case Syntax.ConditionalExpression:
return visit(expr.test) || visit(expr.consequent) || visit(expr.alternate);
case Syntax.FunctionExpression:
return false;
case Syntax.Identifier:
ref = scope.resolve(expr);
if (ref && ref.isStatic()) {
return false;
}
return true;
case Syntax.Literal:
return false;
case Syntax.LogicalExpression:
return visit(expr.left) || visit(expr.right);
case Syntax.MemberExpression:
return true;
case Syntax.NewExpression:
return true;
case Syntax.ObjectExpression:
for (i = 0, iz = expr.properties.length; i < iz; ++i) {
if (visit(expr.properties[i])) {
return true;
}
}
return false;
case Syntax.Property:
return visit(expr.value);
case Syntax.SequenceExpression:
for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
if (visit(expr.expressions[i])) {
return true;
}
}
return false;
case Syntax.ThisExpression:
return false;
case Syntax.UnaryExpression:
if (expr.operator === 'void' || expr.operator === 'delete' || expr.operator === 'typeof' || expr.operator === '!') {
return visit(expr.argument);
}
return !isConstant(expr);
case Syntax.UpdateExpression:
return true;
}
return true;
}
return visit(expr);
}
exports.hasSideEffect = hasSideEffect;
// boolean decision
// @return {boolean|null} when indeterminate value comes, returns null
function booleanCondition(expr) {
var ret;
switch (expr.type) {
case Syntax.AssignmentExpression:
return booleanCondition(expr.right);
case Syntax.ArrayExpression:
return true;
case Syntax.BinaryExpression:
if (isConstant(expr)) {
return !!getConstant(expr);
}
return null;
case Syntax.CallExpression:
return null;
case Syntax.ConditionalExpression:
ret = booleanCondition(expr.test);
if (ret === true) {
return booleanCondition(expr.consequent);
}
if (ret === false) {
return booleanCondition(expr.alternate);
}
ret = booleanCondition(expr.consequent);
if (ret === booleanCondition(expr.alternate)) {
return ret;
}
return null;
case Syntax.FunctionExpression:
return true;
case Syntax.Identifier:
return null;
case Syntax.Literal:
return !!getConstant(expr);
case Syntax.LogicalExpression:
if (expr.operator === '&&') {
ret = booleanCondition(expr.left);
if (ret === null) {
return null;
}
if (!ret) {
return false;
}
return booleanCondition(expr.right);
} else {
ret = booleanCondition(expr.left);
if (ret === null) {
return null;
}
if (ret) {
return true;
}
return booleanCondition(expr.right);
}
return null;
case Syntax.MemberExpression:
return null;
case Syntax.NewExpression:
// always return object
return true;
case Syntax.ObjectExpression:
return true;
case Syntax.Property:
common.unreachable();
return null;
case Syntax.SequenceExpression:
return booleanCondition(common.Array.last(expr.expressions));
case Syntax.ThisExpression:
// in strict mode, this may be null / undefined
return null;
case Syntax.UnaryExpression:
if (expr.operator === 'void') {
return false;
}
if (expr.operator === 'typeof') {
return true;
}
if (expr.operator === '!') {
ret = booleanCondition(expr.argument);
if (ret === null) {
return null;
}
return !ret;
}
if (isConstant(expr)) {
return !!getConstant(expr);
}
return null;
case Syntax.UpdateExpression:
return null;
}
return null;
}
exports.booleanCondition = booleanCondition;
}());
},{"./common":2}],5:[function(require,module,exports){
(function (global){
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*global module:true*/
(function () {
'use strict';
var Map;
if (typeof global.Map !== 'undefined') {
// ES6 Map
Map = global.Map;
} else {
Map = function Map() {
this.__data = {};
};
Map.prototype.get = function MapGet(key) {
key = '$' + key;
if (this.__data.hasOwnProperty(key)) {
return this.__data[key];
}
};
Map.prototype.has = function MapHas(key) {
key = '$' + key;
return this.__data.hasOwnProperty(key);
};
Map.prototype.set = function MapSet(key, val) {
key = '$' + key;
this.__data[key] = val;
};
Map.prototype['delete'] = function MapDelete(key) {
key = '$' + key;
return delete this.__data[key];
};
Map.prototype.clear = function MapClear() {
this.__data = {};
};
Map.prototype.forEach = function MapForEach(callback, thisArg) {
var real, key;
for (real in this.__data) {
if (this.__data.hasOwnProperty(real)) {
key = real.substring(1);
callback.call(thisArg, this.__data[real], key, this);
}
}
};
Map.prototype.keys = function MapKeys() {
var real, result;
result = [];
for (real in this.__data) {
if (this.__data.hasOwnProperty(real)) {
result.push(real.substring(1));
}
}
return result;
};
Map.prototype.values = function MapValues() {
var real, result;
result = [];
for (real in this.__data) {
if (this.__data.hasOwnProperty(real)) {
result.push(this.__data[real]);
}
}
return result;
};
Map.prototype.items = function MapItems() {
var real, result;
result = [];
for (real in this.__data) {
if (this.__data.hasOwnProperty(real)) {
result.push([real.substring(1), this.__data[real]]);
}
}
return result;
};
}
module.exports = Map;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],6:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint bitwise:true */
(function () {
'use strict';
var common;
common = require('./common');
function extend(result, update) {
var prop, lhs, rhs;
for (prop in update) {
if (!common.Object.has(update, prop)) {
continue;
}
if (prop in result) {
lhs = result[prop];
rhs = update[prop];
if (common.Object.isObject(rhs) && common.Object.isObject(lhs)) {
result[prop] = extend(lhs, rhs);
} else {
result[prop] = update[prop];
}
} else {
result[prop] = update[prop];
}
}
return result;
}
function Options(override) {
var defaults = {
destructive: true,
preserveCompletionValue: false,
legacy: true,
topLevelContext: 'global', // Specifies 'global', 'module', 'function' etc.
inStrictCode: false // Top level is strict or not
};
if (override == null) {
this.data = defaults;
return;
}
this.data = extend(defaults, override);
}
// options.get(name, {
// pathName: pathName
// });
Options.prototype.get = function get(name, details) {
var local;
if (details != null) {
if (common.Object.has(details, 'pathName')) {
local = this.data[details.pathName];
if (local != null && common.Object.has(local, name)) {
return local[name];
}
}
}
return this.data[name];
};
module.exports = Options;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
},{"./common":2}],7:[function(require,module,exports){
/*
Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint bitwise:true */
/*global exports:true*/
(function () {
'use strict';
var query, Registry, pass, post, common;
common = require('./common');
query = require('./query');
Registry = {};
Registry.__direct = {};
// initialization
function initialize(kind, passes) {
var i, iz, pass;
Registry[kind] = {};
for (i = 0, iz = passes.length; i < iz; ++i) {
pass = passes[i];
common.assert(Registry[kind][pass.passName] == null, 'don\'t create duplicate pass names');
Registry[kind][pass.passName] = pass;
}
common.assert(Registry.__direct[pass.passName] == null, 'don\'t create duplicate pass names');
Registry.__direct[pass.passName] = pass;
}
pass = [
require('./pass/hoist-variable-to-arguments'),
require('./pass/transform-dynamic-to-static-property-access'),
require('./pass/transform-dynamic-to-static-property-definition'),
require('./pass/transform-immediate-function-call'),
require('./pass/transform-logical-association'),
require('./pass/reordering-function-declarations'),
require('./pass/remove-unused-label'),
require('./pass/remove-empty-statement'),
require('./pass/remove-wasted-blocks'),
require('./pass/transform-to-compound-assignment'),
require('./pass/transform-to-sequence-expression'),
require('./pass/transform-branch-to-expression'),
require('./pass/transform-typeof-undefined'),
require('./pass/reduce-sequence-expression'),
require('./pass/reduce-branch-jump'),
require('./pass/reduce-multiple-if-statements'),
require('./pass/dead-code-elimination'),
require('./pass/remove-side-effect-free-expressions'),
require('./pass/remove-context-sensitive-expressions'),
require('./pass/tree-based-constant-folding'),
require('./pass/concatenate-variable-definition'),
require('./pass/drop-variable-definition'),
require('./pass/remove-unreachable-branch'),
require('./pass/eliminate-duplicate-function-declarations'),
require('./pass/typeof-prefix-comparison'),
require('./pass/top-level-variable-declaration-to-assignment'),
];
post = [
require('./post/transform-static-to-dynamic-property-access'),
require('./post/transform-infinity'),
require('./post/rewrite-boolean'),
require('./post/rewrite-conditional-expression'),
require('./post/omit-parens-in-void-context-iife')
];
initialize('pass', pass);
initialize('post', post);
function passRequire(name) {
if (common.Object.has(Registry.__direct, name)) {
return Registry.__direct[name];
}
return query.get(Registry, name.split('/'));
}
exports.require = passRequire;
exports.Registry = Registry;
// CAUTION:(Constellation)
// This API would be changed
exports.__defaultPipeline = [
pass,
{
once: true,
pass: post
}
];
}());
},{"./common":2,"./pass/concatenate-variable-definition":8,"./pass/dead-code-elimination":9,"./pass/drop-variable-definition":10,"./pass/eliminate-duplicate-function-declarations":11,"./pass/hoist-variable-to-arguments":12,"./pass/reduce-branch-jump":13,"./pass/reduce-multiple-if-statements":14,"./pass/reduce-sequence-expression":15,"./pass/remove-context-sensitive-expressions":16,"./pass/remove-empty-statement":17,"./pass/remove-side-effect-free-expressions":18,"./pass/remove-unreachable-branch":19,"./pass/remove-unused-label":20,"./pass/remove-wasted-blocks":21,"./pass/reordering-function-declarations":22,"./pass/top-level-variable-declaration-to-assignment":23,"./pass/transform-branch-to-expression":24,"./pass/transform-dynamic-to-