first commit
This commit is contained in:
483
build/node_modules/prepack/lib/serializer/Emitter.js
generated
vendored
Normal file
483
build/node_modules/prepack/lib/serializer/Emitter.js
generated
vendored
Normal file
@@ -0,0 +1,483 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.Emitter = undefined;
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _generator = require("../utils/generator.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _types = require("./types.js");
|
||||
|
||||
var _ResidualFunctions = require("./ResidualFunctions.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
// The emitter keeps track of a stack of what's currently being emitted.
|
||||
// There are two kinds of interesting dependencies the emitter is dealing with:
|
||||
// 1. Value dependencies:
|
||||
// If an emission task depends on the result of another emission task which
|
||||
// is still currently being emitted, then the emission task must be performed later,
|
||||
// once the dependency is available.
|
||||
// To this end, the emitter maintains the `_activeValues` and `_waitingForValues` datastructures.
|
||||
// 2. Generator dependencies:
|
||||
// For each generator, there's a corresponding "body", i.e. a stream of babel statements
|
||||
// that the emitter is appending to.
|
||||
// There's always a "current" body that is currently being emitted to.
|
||||
// There's also a distinguished `mainBody` to which all statements get directly or indirectly appended.
|
||||
// If there are multiple generators/bodies involved, then they form a stack.
|
||||
// Nested bodies are usually composed into an instruction emitted to the outer body.
|
||||
// For example, two nested generators may yield the then and else-branch of an `if` statement.
|
||||
// When an emission is supposed to target a body that is the current body, i.e. when it sits
|
||||
// lower on the stack, then the emission task gets delayed until the next emission task on
|
||||
// the lower body entry is finished.
|
||||
// To this end, the emitter maintains the `_activeGeneratorStack` and `_waitingForBodies` datastructures.
|
||||
var Emitter = exports.Emitter = function () {
|
||||
function Emitter(residualFunctions) {
|
||||
_classCallCheck(this, Emitter);
|
||||
|
||||
var mainBody = { type: "MainGenerator", parentBody: undefined, entries: [] };
|
||||
this._waitingForValues = new Map();
|
||||
this._waitingForBodies = new Map();
|
||||
this._body = mainBody;
|
||||
this._declaredAbstractValues = new Map();
|
||||
this._residualFunctions = residualFunctions;
|
||||
this._activeStack = [];
|
||||
this._activeValues = new Set();
|
||||
this._activeGeneratorStack = [mainBody];
|
||||
this._finalized = false;
|
||||
} // Contains all the active generator bodies in stack order.
|
||||
|
||||
|
||||
_createClass(Emitter, [{
|
||||
key: "beginEmitting",
|
||||
value: function beginEmitting(dependency, targetBody) {
|
||||
var isChild = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
|
||||
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
this._activeStack.push(dependency);
|
||||
if (dependency instanceof _index.Value) {
|
||||
(0, _invariant2.default)(!this._activeValues.has(dependency));
|
||||
this._activeValues.add(dependency);
|
||||
} else if (dependency instanceof _generator.Generator) {
|
||||
(0, _invariant2.default)(!this._activeGeneratorStack.includes(targetBody));
|
||||
this._activeGeneratorStack.push(targetBody);
|
||||
}
|
||||
if (isChild) {
|
||||
targetBody.parentBody = this._body;
|
||||
}
|
||||
var oldBody = this._body;
|
||||
this._body = targetBody;
|
||||
return oldBody;
|
||||
}
|
||||
}, {
|
||||
key: "emit",
|
||||
value: function emit(statement) {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
this._body.entries.push(statement);
|
||||
this._processCurrentBody();
|
||||
}
|
||||
}, {
|
||||
key: "endEmitting",
|
||||
value: function endEmitting(dependency, oldBody) {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
var lastDependency = this._activeStack.pop();
|
||||
(0, _invariant2.default)(dependency === lastDependency);
|
||||
if (dependency instanceof _index.Value) {
|
||||
(0, _invariant2.default)(this._activeValues.has(dependency));
|
||||
this._activeValues.delete(dependency);
|
||||
this._processValue(dependency);
|
||||
} else if (dependency instanceof _generator.Generator) {
|
||||
(0, _invariant2.default)(this._isEmittingActiveGenerator());
|
||||
this._activeGeneratorStack.pop();
|
||||
}
|
||||
var lastBody = this._body;
|
||||
this._body = oldBody;
|
||||
return lastBody;
|
||||
}
|
||||
}, {
|
||||
key: "finalize",
|
||||
value: function finalize() {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
(0, _invariant2.default)(this._activeGeneratorStack.length === 1);
|
||||
(0, _invariant2.default)(this._activeGeneratorStack[0] === this._body);
|
||||
this._processCurrentBody();
|
||||
this._activeGeneratorStack.pop();
|
||||
this._finalized = true;
|
||||
(0, _invariant2.default)(this._waitingForBodies.size === 0);
|
||||
(0, _invariant2.default)(this._waitingForValues.size === 0);
|
||||
(0, _invariant2.default)(this._activeStack.length === 0);
|
||||
(0, _invariant2.default)(this._activeValues.size === 0);
|
||||
(0, _invariant2.default)(this._activeGeneratorStack.length === 0);
|
||||
}
|
||||
/**
|
||||
* Emitter is emitting in two modes:
|
||||
* 1. Emitting to entries in current active generator
|
||||
* 2. Emitting to body of another scope(generator or residual function)
|
||||
* This function checks the first condition above.
|
||||
*/
|
||||
|
||||
}, {
|
||||
key: "_isEmittingActiveGenerator",
|
||||
value: function _isEmittingActiveGenerator() {
|
||||
(0, _invariant2.default)(this._activeGeneratorStack.length > 0);
|
||||
return this._activeGeneratorStack[this._activeGeneratorStack.length - 1] === this._body;
|
||||
}
|
||||
}, {
|
||||
key: "_isGeneratorBody",
|
||||
value: function _isGeneratorBody(body) {
|
||||
return body.type === "MainGenerator" || body.type === "Generator";
|
||||
}
|
||||
}, {
|
||||
key: "_processCurrentBody",
|
||||
value: function _processCurrentBody() {
|
||||
if (!this._isEmittingActiveGenerator()) {
|
||||
return;
|
||||
}
|
||||
var a = this._waitingForBodies.get(this._body);
|
||||
if (a === undefined) return;
|
||||
while (a.length > 0) {
|
||||
var _a$shift = a.shift(),
|
||||
_dependencies = _a$shift.dependencies,
|
||||
_func = _a$shift.func;
|
||||
|
||||
this.emitNowOrAfterWaitingForDependencies(_dependencies, _func);
|
||||
}
|
||||
this._waitingForBodies.delete(this._body);
|
||||
}
|
||||
}, {
|
||||
key: "_processValue",
|
||||
value: function _processValue(value) {
|
||||
var a = this._waitingForValues.get(value);
|
||||
if (a === undefined) return;
|
||||
var currentBody = this._body;
|
||||
while (a.length > 0) {
|
||||
var _a$shift2 = a.shift(),
|
||||
_body = _a$shift2.body,
|
||||
_dependencies2 = _a$shift2.dependencies,
|
||||
_func2 = _a$shift2.func;
|
||||
// If body is not generator body no need to wait for it.
|
||||
|
||||
|
||||
if (this._isGeneratorBody(_body) && _body !== currentBody) {
|
||||
this._emitAfterWaitingForGeneratorBody(_body, _dependencies2, _func2);
|
||||
} else {
|
||||
this.emitNowOrAfterWaitingForDependencies(_dependencies2, _func2, _body);
|
||||
}
|
||||
}
|
||||
this._waitingForValues.delete(value);
|
||||
}
|
||||
|
||||
// Find the first ancestor in input generator body stack that is in current active stack.
|
||||
// It can always find one because the bottom one in the stack is the main generator.
|
||||
|
||||
}, {
|
||||
key: "_getFirstAncestorGeneratorWithActiveBody",
|
||||
value: function _getFirstAncestorGeneratorWithActiveBody(bodyStack) {
|
||||
var _this = this;
|
||||
|
||||
var activeBody = bodyStack.slice().reverse().find(function (body) {
|
||||
return _this._activeGeneratorStack.includes(body);
|
||||
});
|
||||
(0, _invariant2.default)(activeBody);
|
||||
return activeBody;
|
||||
}
|
||||
|
||||
// Serialization of a statement related to a value MUST be delayed if
|
||||
// the creation of the value's identity requires the availability of either:
|
||||
// 1. a time-dependent value that is declared by some generator entry
|
||||
// that has not yet been processed
|
||||
// (tracked by `_declaredAbstractValues`), or
|
||||
// 2. a value that is also currently being serialized
|
||||
// (tracked by `_activeValues`).
|
||||
// 3. a generator body that is higher(near top) in generator body stack.
|
||||
// (tracked by `_activeGeneratorStack`)
|
||||
|
||||
}, {
|
||||
key: "getReasonToWaitForDependencies",
|
||||
value: function getReasonToWaitForDependencies(dependencies) {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
if (Array.isArray(dependencies)) {
|
||||
var values = dependencies;
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = values[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var value = _step.value;
|
||||
|
||||
var _delayReason = this.getReasonToWaitForDependencies(value);
|
||||
if (_delayReason) return _delayReason;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var val = dependencies;
|
||||
if (this._activeValues.has(val)) return val;
|
||||
|
||||
var delayReason = void 0;
|
||||
if (val instanceof _index.BoundFunctionValue) {
|
||||
delayReason = this.getReasonToWaitForDependencies(val.$BoundTargetFunction);
|
||||
if (delayReason) return delayReason;
|
||||
delayReason = this.getReasonToWaitForDependencies(val.$BoundThis);
|
||||
if (delayReason) return delayReason;
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = val.$BoundArguments[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var arg = _step2.value;
|
||||
|
||||
delayReason = this.getReasonToWaitForDependencies(arg);
|
||||
if (delayReason) return delayReason;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (val instanceof _index.FunctionValue) {
|
||||
this._residualFunctions.addFunctionUsage(val, this.getBodyReference());
|
||||
return undefined;
|
||||
} else if (val instanceof _index.AbstractValue) {
|
||||
if (val.hasIdentifier()) {
|
||||
var valSerializeBodyStack = this._declaredAbstractValues.get(val);
|
||||
if (!valSerializeBodyStack) {
|
||||
// Hasn't been serialized yet.
|
||||
return val;
|
||||
} else {
|
||||
// The dependency has already been serialized(declared). But we may still have to wait for
|
||||
// current generator body to be available, under following conditions:
|
||||
// 1. Currently emitting in generator body. -- and
|
||||
// 2. Not emitting in current active generator.(otherwise no need to wait) -- and
|
||||
// 3. Dependency's active ancestor generator body is higher(near top) in generator stack than current body.
|
||||
var valActiveAncestorBody = this._getFirstAncestorGeneratorWithActiveBody(valSerializeBodyStack);
|
||||
(0, _invariant2.default)(this._activeGeneratorStack.includes(valActiveAncestorBody));
|
||||
|
||||
if (this._isGeneratorBody(this._body)) {
|
||||
(0, _invariant2.default)(this._activeGeneratorStack.includes(this._body));
|
||||
if (!this._isEmittingActiveGenerator() && this._activeGeneratorStack.indexOf(valActiveAncestorBody) > this._activeGeneratorStack.indexOf(this._body)) {
|
||||
return this._body;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = val.args[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var _arg = _step3.value;
|
||||
|
||||
delayReason = this.getReasonToWaitForDependencies(_arg);
|
||||
if (delayReason) return delayReason;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (val instanceof _index.ProxyValue) {
|
||||
delayReason = this.getReasonToWaitForDependencies(val.$ProxyTarget);
|
||||
if (delayReason) return delayReason;
|
||||
delayReason = this.getReasonToWaitForDependencies(val.$ProxyHandler);
|
||||
if (delayReason) return delayReason;
|
||||
} else if (val instanceof _index.SymbolValue) {
|
||||
if (val.$Description instanceof _index.Value) {
|
||||
delayReason = this.getReasonToWaitForDependencies(val.$Description);
|
||||
if (delayReason) return delayReason;
|
||||
}
|
||||
} else if (val instanceof _index.ObjectValue) {
|
||||
var kind = val.getKind();
|
||||
switch (kind) {
|
||||
case "Object":
|
||||
var proto = val.$Prototype;
|
||||
if (proto instanceof _index.ObjectValue) {
|
||||
delayReason = this.getReasonToWaitForDependencies(val.$Prototype);
|
||||
if (delayReason) return delayReason;
|
||||
}
|
||||
break;
|
||||
case "Date":
|
||||
(0, _invariant2.default)(val.$DateValue !== undefined);
|
||||
delayReason = this.getReasonToWaitForDependencies(val.$DateValue);
|
||||
if (delayReason) return delayReason;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
// Wait for a known-to-be active value if a condition is met.
|
||||
|
||||
}, {
|
||||
key: "getReasonToWaitForActiveValue",
|
||||
value: function getReasonToWaitForActiveValue(value, condition) {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
(0, _invariant2.default)(this._activeValues.has(value));
|
||||
return condition ? value : undefined;
|
||||
}
|
||||
}, {
|
||||
key: "_shouldEmitWithoutWaiting",
|
||||
value: function _shouldEmitWithoutWaiting(delayReason, targetBody) {
|
||||
/**
|
||||
* We can directly emit without waiting if:
|
||||
* 1. No delayReason
|
||||
* 2. delayReason is a generator body while the target body we are not emitting into is not a generator body.
|
||||
*/
|
||||
return !delayReason || !(delayReason instanceof _index.Value) && this._isGeneratorBody(delayReason) && targetBody !== undefined && !this._isGeneratorBody(targetBody);
|
||||
}
|
||||
}, {
|
||||
key: "emitAfterWaiting",
|
||||
value: function emitAfterWaiting(delayReason, dependencies, func, targetBody) {
|
||||
if (this._shouldEmitWithoutWaiting(delayReason, targetBody)) {
|
||||
if (targetBody === undefined || targetBody === this._body) {
|
||||
// Emit into current body.
|
||||
func();
|
||||
} else {
|
||||
(0, _invariant2.default)(!this._isGeneratorBody(targetBody));
|
||||
var oldBody = this.beginEmitting(targetBody.type, targetBody);
|
||||
func();
|
||||
this.endEmitting(targetBody.type, oldBody);
|
||||
}
|
||||
} else {
|
||||
(0, _invariant2.default)(delayReason !== undefined);
|
||||
if (delayReason instanceof _index.Value) {
|
||||
this._emitAfterWaitingForValue(delayReason, dependencies, targetBody === undefined ? this._body : targetBody, func);
|
||||
} else if (this._isGeneratorBody(delayReason)) {
|
||||
// delayReason is a generator body.
|
||||
this._emitAfterWaitingForGeneratorBody(delayReason, dependencies, func);
|
||||
} else {
|
||||
// Unknown delay reason.
|
||||
(0, _invariant2.default)(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_emitAfterWaitingForValue",
|
||||
value: function _emitAfterWaitingForValue(reason, dependencies, targetBody, func) {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
(0, _invariant2.default)(!(reason instanceof _index.AbstractValue && this._declaredAbstractValues.has(reason)) || this._activeValues.has(reason));
|
||||
var a = this._waitingForValues.get(reason);
|
||||
if (a === undefined) this._waitingForValues.set(reason, a = []);
|
||||
a.push({ body: targetBody, dependencies: dependencies, func: func });
|
||||
}
|
||||
}, {
|
||||
key: "_emitAfterWaitingForGeneratorBody",
|
||||
value: function _emitAfterWaitingForGeneratorBody(reason, dependencies, func) {
|
||||
(0, _invariant2.default)(this._isGeneratorBody(reason));
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
(0, _invariant2.default)(this._activeGeneratorStack.includes(reason));
|
||||
var b = this._waitingForBodies.get(reason);
|
||||
if (b === undefined) this._waitingForBodies.set(reason, b = []);
|
||||
b.push({ dependencies: dependencies, func: func });
|
||||
}
|
||||
}, {
|
||||
key: "emitNowOrAfterWaitingForDependencies",
|
||||
value: function emitNowOrAfterWaitingForDependencies(dependencies, func, targetBody) {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
this.emitAfterWaiting(this.getReasonToWaitForDependencies(dependencies), dependencies, func, targetBody);
|
||||
}
|
||||
}, {
|
||||
key: "_cloneGeneratorStack",
|
||||
value: function _cloneGeneratorStack() {
|
||||
return this._activeGeneratorStack.slice();
|
||||
}
|
||||
}, {
|
||||
key: "declare",
|
||||
value: function declare(value) {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
(0, _invariant2.default)(!this._activeValues.has(value));
|
||||
(0, _invariant2.default)(value.hasIdentifier());
|
||||
(0, _invariant2.default)(this._isEmittingActiveGenerator());
|
||||
this._declaredAbstractValues.set(value, this._cloneGeneratorStack());
|
||||
this._processValue(value);
|
||||
}
|
||||
}, {
|
||||
key: "hasBeenDeclared",
|
||||
value: function hasBeenDeclared(value) {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
return this._declaredAbstractValues.has(value);
|
||||
}
|
||||
}, {
|
||||
key: "getBody",
|
||||
value: function getBody() {
|
||||
return this._body;
|
||||
}
|
||||
}, {
|
||||
key: "isCurrentBodyOffspringOf",
|
||||
value: function isCurrentBodyOffspringOf(targetBody) {
|
||||
var currentBody = this._body;
|
||||
while (currentBody !== undefined) {
|
||||
if (currentBody === targetBody) {
|
||||
return true;
|
||||
}
|
||||
currentBody = currentBody.parentBody;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}, {
|
||||
key: "getBodyReference",
|
||||
value: function getBodyReference() {
|
||||
(0, _invariant2.default)(!this._finalized);
|
||||
return new _types.BodyReference(this._body, this._body.entries.length);
|
||||
}
|
||||
}]);
|
||||
|
||||
return Emitter;
|
||||
}();
|
||||
//# sourceMappingURL=Emitter.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/Emitter.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/Emitter.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
230
build/node_modules/prepack/lib/serializer/LazyObjectsSerializer.js
generated
vendored
Normal file
230
build/node_modules/prepack/lib/serializer/LazyObjectsSerializer.js
generated
vendored
Normal file
@@ -0,0 +1,230 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.LazyObjectsSerializer = undefined;
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _types = require("./types.js");
|
||||
|
||||
var _logger = require("./logger.js");
|
||||
|
||||
var _modules = require("./modules.js");
|
||||
|
||||
var _ResidualHeapInspector = require("./ResidualHeapInspector.js");
|
||||
|
||||
var _ResidualHeapValueIdentifiers = require("./ResidualHeapValueIdentifiers.js");
|
||||
|
||||
var _ResidualHeapSerializer = require("./ResidualHeapSerializer.js");
|
||||
|
||||
var _utils = require("./utils.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
||||
|
||||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var LAZY_OBJECTS_SERIALIZER_BODY_TYPE = "LazyObjectInitializer";
|
||||
|
||||
/**
|
||||
* Serialize objects in lazy mode by leveraging the JS runtime that support this feature.
|
||||
* Objects are serialized into two parts:
|
||||
* 1. All lazy objects are created via lightweight LazyObjectsRuntime.createLazyObject() call.
|
||||
* 2. Lazy objects' property assignments are delayed in a callback function which is registered with the runtime.
|
||||
* lazy objects runtime will execute this callback to hydrate the lazy objects.
|
||||
*
|
||||
* Currently only the raw objects are taking part in the lazy objects feature.
|
||||
* TODO: support for other objects, like array, regex etc...
|
||||
*/
|
||||
|
||||
var LazyObjectsSerializer = exports.LazyObjectsSerializer = function (_ResidualHeapSerializ) {
|
||||
_inherits(LazyObjectsSerializer, _ResidualHeapSerializ);
|
||||
|
||||
function LazyObjectsSerializer(realm, logger, modules, residualHeapValueIdentifiers, residualHeapInspector, residualValues, residualFunctionInstances, residualFunctionInfos, options, referencedDeclaredValues, additionalFunctionValuesAndEffects, additionalFunctionValueInfos, declarativeEnvironmentRecordsBindings, statistics, react) {
|
||||
_classCallCheck(this, LazyObjectsSerializer);
|
||||
|
||||
var _this = _possibleConstructorReturn(this, (LazyObjectsSerializer.__proto__ || Object.getPrototypeOf(LazyObjectsSerializer)).call(this, realm, logger, modules, residualHeapValueIdentifiers, residualHeapInspector, residualValues, residualFunctionInstances, residualFunctionInfos, options, referencedDeclaredValues, additionalFunctionValuesAndEffects, additionalFunctionValueInfos, declarativeEnvironmentRecordsBindings, statistics, react));
|
||||
|
||||
_this._lazyObjectIdSeed = 1;
|
||||
_this._valueLazyIds = new Map();
|
||||
_this._lazyObjectInitializers = new Map();
|
||||
_this._callbackLazyObjectParam = t.identifier("obj");
|
||||
(0, _invariant2.default)(_this._options.lazyObjectsRuntime != null);
|
||||
_this._lazyObjectJSRuntimeName = t.identifier(_this._options.lazyObjectsRuntime);
|
||||
_this._initializationCallbackName = t.identifier("__initializerCallback");
|
||||
return _this;
|
||||
}
|
||||
// Holds object's lazy initializer bodies.
|
||||
// These bodies will be combined into a well-known callback after generator serialization is done and registered with the runtime.
|
||||
|
||||
|
||||
_createClass(LazyObjectsSerializer, [{
|
||||
key: "_getValueLazyId",
|
||||
value: function _getValueLazyId(obj) {
|
||||
var _this2 = this;
|
||||
|
||||
return (0, _utils.getOrDefault)(this._valueLazyIds, obj, function () {
|
||||
return _this2._lazyObjectIdSeed++;
|
||||
});
|
||||
}
|
||||
|
||||
// TODO: change to use _getTarget() to get the lazy objects initializer body.
|
||||
|
||||
}, {
|
||||
key: "_serializeLazyObjectInitializer",
|
||||
value: function _serializeLazyObjectInitializer(obj) {
|
||||
var initializerBody = { type: LAZY_OBJECTS_SERIALIZER_BODY_TYPE, parentBody: undefined, entries: [] };
|
||||
var oldBody = this.emitter.beginEmitting(LAZY_OBJECTS_SERIALIZER_BODY_TYPE, initializerBody);
|
||||
this._emitObjectProperties(obj);
|
||||
this.emitter.endEmitting(LAZY_OBJECTS_SERIALIZER_BODY_TYPE, oldBody);
|
||||
return initializerBody;
|
||||
}
|
||||
}, {
|
||||
key: "_serializeLazyObjectInitializerSwitchCase",
|
||||
value: function _serializeLazyObjectInitializerSwitchCase(obj, initializer) {
|
||||
// TODO: only serialize this switch case if the initializer(property assignment) is not empty.
|
||||
var caseBody = initializer.entries.concat(t.breakStatement());
|
||||
var lazyId = this._getValueLazyId(obj);
|
||||
return t.switchCase(t.numericLiteral(lazyId), caseBody);
|
||||
}
|
||||
}, {
|
||||
key: "_serializeInitializationCallback",
|
||||
value: function _serializeInitializationCallback() {
|
||||
var body = [];
|
||||
|
||||
var switchCases = [];
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = this._lazyObjectInitializers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var _ref = _step.value;
|
||||
|
||||
var _ref2 = _slicedToArray(_ref, 2);
|
||||
|
||||
var obj = _ref2[0];
|
||||
var initializer = _ref2[1];
|
||||
|
||||
switchCases.push(this._serializeLazyObjectInitializerSwitchCase(obj, initializer));
|
||||
}
|
||||
// Default case.
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switchCases.push(t.switchCase(null, [t.throwStatement(t.newExpression(t.identifier("Error"), [t.stringLiteral("Unknown lazy id")]))]));
|
||||
|
||||
var selector = t.identifier("id");
|
||||
body.push(t.switchStatement(selector, switchCases));
|
||||
|
||||
var params = [this._callbackLazyObjectParam, selector];
|
||||
var initializerCallbackFunction = t.functionExpression(null, params, t.blockStatement(body));
|
||||
// TODO: use NameGenerator.
|
||||
return t.variableDeclaration("var", [t.variableDeclarator(this._initializationCallbackName, initializerCallbackFunction)]);
|
||||
}
|
||||
}, {
|
||||
key: "_serializeRegisterInitializationCallback",
|
||||
value: function _serializeRegisterInitializationCallback() {
|
||||
return t.expressionStatement(t.callExpression(t.memberExpression(this._lazyObjectJSRuntimeName, t.identifier("setLazyObjectInitializer")), [this._initializationCallbackName]));
|
||||
}
|
||||
}, {
|
||||
key: "_serializeCreateLazyObject",
|
||||
value: function _serializeCreateLazyObject(obj) {
|
||||
var lazyId = this._getValueLazyId(obj);
|
||||
return t.callExpression(t.memberExpression(this._lazyObjectJSRuntimeName, t.identifier("createLazyObject"), /*computed*/false), [t.numericLiteral(lazyId)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the object currently being emitted is lazy object(inside _lazyObjectInitializers map) and
|
||||
* that its emitting body is the offspring of this lazy object's initializer body.
|
||||
* This is needed because for "lazy1.p = lazy2" case,
|
||||
* we need to replace "lazy1" with "obj" but not for "lazy2".
|
||||
* The offspring checking is needed because object may be emitting in a "ConditionalAssignmentBranch" of
|
||||
* lazy object's initializer body.
|
||||
*/
|
||||
|
||||
}, {
|
||||
key: "_isEmittingIntoLazyObjectInitializerBody",
|
||||
value: function _isEmittingIntoLazyObjectInitializerBody(obj) {
|
||||
var objLazyBody = this._lazyObjectInitializers.get(obj);
|
||||
return objLazyBody !== undefined && this.emitter.isCurrentBodyOffspringOf(objLazyBody);
|
||||
}
|
||||
|
||||
// Override default behavior.
|
||||
// Inside lazy objects callback, the lazy object identifier needs to be replaced with the
|
||||
// parameter passed from the runtime.
|
||||
|
||||
}, {
|
||||
key: "getSerializeObjectIdentifier",
|
||||
value: function getSerializeObjectIdentifier(val) {
|
||||
return val instanceof _index.ObjectValue && this._isEmittingIntoLazyObjectInitializerBody(val) ? this._callbackLazyObjectParam : _get(LazyObjectsSerializer.prototype.__proto__ || Object.getPrototypeOf(LazyObjectsSerializer.prototype), "getSerializeObjectIdentifier", this).call(this, val);
|
||||
}
|
||||
|
||||
// Override default serializer with lazy mode.
|
||||
|
||||
}, {
|
||||
key: "serializeValueRawObject",
|
||||
value: function serializeValueRawObject(obj) {
|
||||
this._lazyObjectInitializers.set(obj, this._serializeLazyObjectInitializer(obj));
|
||||
return this._serializeCreateLazyObject(obj);
|
||||
}
|
||||
|
||||
// Override.
|
||||
// Serialize the initialization callback and its registration in prelude if there are object being lazied.
|
||||
|
||||
}, {
|
||||
key: "postGeneratorSerialization",
|
||||
value: function postGeneratorSerialization() {
|
||||
if (this._lazyObjectInitializers.size > 0) {
|
||||
// Insert initialization callback at the end of prelude code.
|
||||
this.prelude.push(this._serializeInitializationCallback());
|
||||
this.prelude.push(this._serializeRegisterInitializationCallback());
|
||||
}
|
||||
}
|
||||
}]);
|
||||
|
||||
return LazyObjectsSerializer;
|
||||
}(_ResidualHeapSerializer.ResidualHeapSerializer);
|
||||
//# sourceMappingURL=LazyObjectsSerializer.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/LazyObjectsSerializer.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/LazyObjectsSerializer.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
105
build/node_modules/prepack/lib/serializer/LoggingTracer.js
generated
vendored
Normal file
105
build/node_modules/prepack/lib/serializer/LoggingTracer.js
generated
vendored
Normal file
@@ -0,0 +1,105 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.LoggingTracer = undefined;
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
var _environment = require("../environment.js");
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _index = require("../methods/index.js");
|
||||
|
||||
var _completions = require("../completions.js");
|
||||
|
||||
var _index2 = require("../values/index.js");
|
||||
|
||||
var _singletons = require("../singletons.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
||||
|
||||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
function describeValue(realm, v) {
|
||||
if (v instanceof _index2.NumberValue || v instanceof _index2.BooleanValue) return v.value.toString();
|
||||
if (v instanceof _index2.UndefinedValue) return "undefined";
|
||||
if (v instanceof _index2.NullValue) return "null";
|
||||
if (v instanceof _index2.StringValue) return "\"" + v.value + "\""; // TODO: proper escaping
|
||||
if (v instanceof _index2.FunctionValue) return _singletons.To.ToStringPartial(realm, (0, _index.Get)(realm, v, "name")) || "(anonymous function)";
|
||||
if (v instanceof _index2.ObjectValue) return "(some object)";
|
||||
if (v instanceof _index2.AbstractValue) return "(some abstract value)";
|
||||
(0, _invariant2.default)(false);
|
||||
}
|
||||
|
||||
var LoggingTracer = exports.LoggingTracer = function (_Tracer) {
|
||||
_inherits(LoggingTracer, _Tracer);
|
||||
|
||||
function LoggingTracer(realm) {
|
||||
_classCallCheck(this, LoggingTracer);
|
||||
|
||||
var _this = _possibleConstructorReturn(this, (LoggingTracer.__proto__ || Object.getPrototypeOf(LoggingTracer)).call(this));
|
||||
|
||||
_this.realm = realm;
|
||||
_this.nesting = [];
|
||||
return _this;
|
||||
}
|
||||
|
||||
_createClass(LoggingTracer, [{
|
||||
key: "log",
|
||||
value: function log(message) {
|
||||
console.log("[calls] " + this.nesting.map(function (_) {
|
||||
return " ";
|
||||
}).join("") + message);
|
||||
}
|
||||
}, {
|
||||
key: "beginEvaluateForEffects",
|
||||
value: function beginEvaluateForEffects(state) {
|
||||
this.log(">evaluate for effects");
|
||||
this.nesting.push("(evaluate for effects)");
|
||||
}
|
||||
}, {
|
||||
key: "endEvaluateForEffects",
|
||||
value: function endEvaluateForEffects(state, effects) {
|
||||
var name = this.nesting.pop();
|
||||
(0, _invariant2.default)(name === "(evaluate for effects)");
|
||||
this.log("<evaluate for effects");
|
||||
}
|
||||
}, {
|
||||
key: "beforeCall",
|
||||
value: function beforeCall(F, thisArgument, argumentsList, newTarget) {
|
||||
var realm = this.realm;
|
||||
var name = describeValue(realm, F);
|
||||
this.log(">" + name + "(" + argumentsList.map(function (v) {
|
||||
return describeValue(realm, v);
|
||||
}).join(", ") + ")");
|
||||
this.nesting.push(name);
|
||||
}
|
||||
}, {
|
||||
key: "afterCall",
|
||||
value: function afterCall(F, thisArgument, argumentsList, newTarget, result) {
|
||||
var name = this.nesting.pop();
|
||||
this.log("<" + name + (result instanceof _completions.ThrowCompletion ? ": error" : ""));
|
||||
}
|
||||
}]);
|
||||
|
||||
return LoggingTracer;
|
||||
}(_realm.Tracer);
|
||||
//# sourceMappingURL=LoggingTracer.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/LoggingTracer.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/LoggingTracer.js.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/serializer/LoggingTracer.js"],"names":["describeValue","realm","v","value","toString","ToStringPartial","LoggingTracer","nesting","message","console","log","map","join","state","push","effects","name","pop","F","thisArgument","argumentsList","newTarget","result"],"mappings":";;;;;;;;;AAWA;;AACA;;AAEA;;AACA;;AACA;;AAWA;;AACA;;;;;;;;;;+eA5BA;;;;;;;;;AA8BA,SAASA,aAAT,CAAuBC,KAAvB,EAAqCC,CAArC,EAAuD;AACrD,MAAIA,oCAA4BA,iCAAhC,EAA2D,OAAOA,EAAEC,KAAF,CAAQC,QAAR,EAAP;AAC3D,MAAIF,mCAAJ,EAAiC,OAAO,WAAP;AACjC,MAAIA,8BAAJ,EAA4B,OAAO,MAAP;AAC5B,MAAIA,gCAAJ,EAA8B,cAAWA,EAAEC,KAAb,QAJuB,CAIA;AACrD,MAAID,kCAAJ,EAAgC,OAAO,eAAGG,eAAH,CAAmBJ,KAAnB,EAA0B,gBAAIA,KAAJ,EAAWC,CAAX,EAAc,MAAd,CAA1B,KAAoD,sBAA3D;AAChC,MAAIA,gCAAJ,EAA8B,OAAO,eAAP;AAC9B,MAAIA,kCAAJ,EAAgC,OAAO,uBAAP;AAChC,2BAAU,KAAV;AACD;;IAEYI,a,WAAAA,a;;;AACX,yBAAYL,KAAZ,EAA0B;AAAA;;AAAA;;AAExB,UAAKA,KAAL,GAAaA,KAAb;AACA,UAAKM,OAAL,GAAe,EAAf;AAHwB;AAIzB;;;;wBAKGC,O,EAAiB;AACnBC,cAAQC,GAAR,cAAuB,KAAKH,OAAL,CAAaI,GAAb,CAAiB;AAAA,eAAK,IAAL;AAAA,OAAjB,EAA4BC,IAA5B,CAAiC,EAAjC,CAAvB,GAA8DJ,OAA9D;AACD;;;4CAEuBK,K,EAAY;AAClC,WAAKH,GAAL;AACA,WAAKH,OAAL,CAAaO,IAAb,CAAkB,wBAAlB;AACD;;;0CAEqBD,K,EAAYE,O,EAAyB;AACzD,UAAIC,OAAO,KAAKT,OAAL,CAAaU,GAAb,EAAX;AACA,+BAAUD,SAAS,wBAAnB;AACA,WAAKN,GAAL;AACD;;;+BAEUQ,C,EAAkBC,Y,EAA4BC,a,EAA6BC,S,EAA+B;AACnH,UAAIpB,QAAQ,KAAKA,KAAjB;AACA,UAAIe,OAAOhB,cAAcC,KAAd,EAAqBiB,CAArB,CAAX;AACA,WAAKR,GAAL,OAAaM,IAAb,SAAqBI,cAAcT,GAAd,CAAkB;AAAA,eAAKX,cAAcC,KAAd,EAAqBC,CAArB,CAAL;AAAA,OAAlB,EAAgDU,IAAhD,CAAqD,IAArD,CAArB;AACA,WAAKL,OAAL,CAAaO,IAAb,CAAkBE,IAAlB;AACD;;;8BAGCE,C,EACAC,Y,EACAC,a,EACAC,S,EACAC,M,EACA;AACA,UAAIN,OAAO,KAAKT,OAAL,CAAaU,GAAb,EAAX;AACA,WAAKP,GAAL,OAAaM,IAAb,IAAoBM,iDAAoC,SAApC,GAAgD,EAApE;AACD","file":"LoggingTracer.js","sourcesContent":["/**\n * Copyright (c) 2017-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n */\n\n/* @flow */\n\nimport { Reference } from \"../environment.js\";\nimport { Realm, Tracer } from \"../realm.js\";\nimport type { Effects } from \"../realm.js\";\nimport { Get } from \"../methods/index.js\";\nimport { ThrowCompletion, AbruptCompletion } from \"../completions.js\";\nimport {\n FunctionValue,\n Value,\n NumberValue,\n BooleanValue,\n StringValue,\n UndefinedValue,\n NullValue,\n ObjectValue,\n AbstractValue,\n} from \"../values/index.js\";\nimport { To } from \"../singletons.js\";\nimport invariant from \"../invariant.js\";\n\nfunction describeValue(realm: Realm, v: Value): string {\n if (v instanceof NumberValue || v instanceof BooleanValue) return v.value.toString();\n if (v instanceof UndefinedValue) return \"undefined\";\n if (v instanceof NullValue) return \"null\";\n if (v instanceof StringValue) return `\"${v.value}\"`; // TODO: proper escaping\n if (v instanceof FunctionValue) return To.ToStringPartial(realm, Get(realm, v, \"name\")) || \"(anonymous function)\";\n if (v instanceof ObjectValue) return \"(some object)\";\n if (v instanceof AbstractValue) return \"(some abstract value)\";\n invariant(false);\n}\n\nexport class LoggingTracer extends Tracer {\n constructor(realm: Realm) {\n super();\n this.realm = realm;\n this.nesting = [];\n }\n\n realm: Realm;\n nesting: Array<string>;\n\n log(message: string) {\n console.log(`[calls] ${this.nesting.map(_ => \" \").join(\"\")}${message}`);\n }\n\n beginEvaluateForEffects(state: any) {\n this.log(`>evaluate for effects`);\n this.nesting.push(\"(evaluate for effects)\");\n }\n\n endEvaluateForEffects(state: any, effects: void | Effects) {\n let name = this.nesting.pop();\n invariant(name === \"(evaluate for effects)\");\n this.log(`<evaluate for effects`);\n }\n\n beforeCall(F: FunctionValue, thisArgument: void | Value, argumentsList: Array<Value>, newTarget: void | ObjectValue) {\n let realm = this.realm;\n let name = describeValue(realm, F);\n this.log(`>${name}(${argumentsList.map(v => describeValue(realm, v)).join(\", \")})`);\n this.nesting.push(name);\n }\n\n afterCall(\n F: FunctionValue,\n thisArgument: void | Value,\n argumentsList: Array<Value>,\n newTarget: void | ObjectValue,\n result: void | Reference | Value | AbruptCompletion\n ) {\n let name = this.nesting.pop();\n this.log(`<${name}${result instanceof ThrowCompletion ? \": error\" : \"\"}`);\n }\n}\n"]}
|
||||
279
build/node_modules/prepack/lib/serializer/Referentializer.js
generated
vendored
Normal file
279
build/node_modules/prepack/lib/serializer/Referentializer.js
generated
vendored
Normal file
@@ -0,0 +1,279 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.Referentializer = undefined;
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _environment = require("../environment.js");
|
||||
|
||||
var _errors = require("../errors.js");
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
var _generator = require("../utils/generator.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _types = require("./types.js");
|
||||
|
||||
var _utils = require("./utils.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
/*
|
||||
* This class helps fixup names in residual functions for variables that these
|
||||
* functions capture from parent scopes.
|
||||
* For each ReferentializationScope it creates a _get_scope_binding function
|
||||
* that contains the initialization for all of that scope's FunctionInstances
|
||||
* which will contain a switch statement with all the initializations.
|
||||
*/
|
||||
|
||||
|
||||
// Each of these will correspond to a different preludeGenerator and thus will
|
||||
// have different values available for initialization. FunctionValues should
|
||||
// only be additional functions.
|
||||
var Referentializer = exports.Referentializer = function () {
|
||||
function Referentializer(options, scopeNameGenerator, referentializedNameGenerator, statistics) {
|
||||
_classCallCheck(this, Referentializer);
|
||||
|
||||
this._options = options;
|
||||
this.scopeNameGenerator = scopeNameGenerator;
|
||||
this.statistics = statistics;
|
||||
|
||||
this.referentializationState = new Map();
|
||||
this._referentializedNameGenerator = referentializedNameGenerator;
|
||||
}
|
||||
|
||||
_createClass(Referentializer, [{
|
||||
key: "_createReferentializationState",
|
||||
value: function _createReferentializationState() {
|
||||
return {
|
||||
capturedScopeInstanceIdx: 0,
|
||||
capturedScopesArray: t.identifier(this.scopeNameGenerator.generate("main")),
|
||||
capturedScopeAccessFunctionId: t.identifier(this.scopeNameGenerator.generate("get_scope_binding")),
|
||||
serializedScopes: new Map()
|
||||
};
|
||||
}
|
||||
}, {
|
||||
key: "_getReferentializationState",
|
||||
value: function _getReferentializationState(referentializationScope) {
|
||||
return (0, _utils.getOrDefault)(this.referentializationState, referentializationScope, this._createReferentializationState.bind(this));
|
||||
}
|
||||
|
||||
// Generate a shared function for accessing captured scope bindings.
|
||||
// TODO: skip generating this function if the captured scope is not shared by multiple residual functions.
|
||||
|
||||
}, {
|
||||
key: "createCaptureScopeAccessFunction",
|
||||
value: function createCaptureScopeAccessFunction(referentializationScope) {
|
||||
var body = [];
|
||||
var selectorParam = t.identifier("selector");
|
||||
var captured = t.identifier("__captured");
|
||||
var capturedScopesArray = this._getReferentializationState(referentializationScope).capturedScopesArray;
|
||||
var selectorExpression = t.memberExpression(capturedScopesArray, selectorParam, /*Indexer syntax*/true);
|
||||
|
||||
// One switch case for one scope.
|
||||
var cases = [];
|
||||
var serializedScopes = this._getReferentializationState(referentializationScope).serializedScopes;
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = serializedScopes.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var scopeBinding = _step.value;
|
||||
|
||||
var scopeObjectExpression = t.arrayExpression(scopeBinding.initializationValues);
|
||||
cases.push(t.switchCase(t.numericLiteral(scopeBinding.id), [t.expressionStatement(t.assignmentExpression("=", selectorExpression, scopeObjectExpression)), t.breakStatement()]));
|
||||
}
|
||||
// Default case.
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cases.push(t.switchCase(null, [t.throwStatement(t.newExpression(t.identifier("Error"), [t.stringLiteral("Unknown scope selector")]))]));
|
||||
|
||||
body.push(t.variableDeclaration("var", [t.variableDeclarator(captured, selectorExpression)]));
|
||||
body.push(t.ifStatement(t.unaryExpression("!", captured), t.blockStatement([t.switchStatement(selectorParam, cases), t.expressionStatement(t.assignmentExpression("=", captured, selectorExpression))])));
|
||||
body.push(t.returnStatement(captured));
|
||||
var factoryFunction = t.functionExpression(null, [selectorParam], t.blockStatement(body));
|
||||
var accessFunctionId = this._getReferentializationState(referentializationScope).capturedScopeAccessFunctionId;
|
||||
return t.variableDeclaration("var", [t.variableDeclarator(accessFunctionId, factoryFunction)]);
|
||||
}
|
||||
}, {
|
||||
key: "_getSerializedBindingScopeInstance",
|
||||
value: function _getSerializedBindingScopeInstance(residualBinding) {
|
||||
var declarativeEnvironmentRecord = residualBinding.declarativeEnvironmentRecord;
|
||||
var referentializationScope = residualBinding.referencedOnlyFromAdditionalFunctions || "GLOBAL";
|
||||
(0, _invariant2.default)(declarativeEnvironmentRecord);
|
||||
|
||||
// figure out if this is accessed only from additional functions
|
||||
var serializedScopes = this._getReferentializationState(referentializationScope).serializedScopes;
|
||||
var scope = serializedScopes.get(declarativeEnvironmentRecord);
|
||||
if (!scope) {
|
||||
var refState = this._getReferentializationState(referentializationScope);
|
||||
scope = {
|
||||
name: this.scopeNameGenerator.generate(),
|
||||
id: refState.capturedScopeInstanceIdx++,
|
||||
initializationValues: [],
|
||||
containingAdditionalFunction: residualBinding.referencedOnlyFromAdditionalFunctions
|
||||
};
|
||||
serializedScopes.set(declarativeEnvironmentRecord, scope);
|
||||
}
|
||||
|
||||
residualBinding.scope = scope;
|
||||
return scope;
|
||||
}
|
||||
}, {
|
||||
key: "getReferentializedScopeInitialization",
|
||||
value: function getReferentializedScopeInitialization(scope) {
|
||||
var capturedScope = scope.capturedScope;
|
||||
(0, _invariant2.default)(capturedScope);
|
||||
var funcName = this._getReferentializationState(scope.containingAdditionalFunction || "GLOBAL").capturedScopeAccessFunctionId;
|
||||
return [t.variableDeclaration("var", [t.variableDeclarator(t.identifier(capturedScope), t.callExpression(funcName, [t.identifier(scope.name)]))])];
|
||||
}
|
||||
}, {
|
||||
key: "referentializeBinding",
|
||||
value: function referentializeBinding(residualBinding, name, instance) {
|
||||
if (this._options.simpleClosures) {
|
||||
// When simpleClosures is enabled, then space for captured mutable bindings is allocated upfront.
|
||||
var serializedBindingId = t.identifier(this._referentializedNameGenerator.generate(name));
|
||||
var serializedValue = residualBinding.serializedValue;
|
||||
(0, _invariant2.default)(serializedValue);
|
||||
var declar = t.variableDeclaration("var", [t.variableDeclarator(serializedBindingId, serializedValue)]);
|
||||
instance.initializationStatements.push(declar);
|
||||
residualBinding.serializedValue = serializedBindingId;
|
||||
} else {
|
||||
// When simpleClosures is not enabled, then space for captured mutable bindings is allocated lazily.
|
||||
var scope = this._getSerializedBindingScopeInstance(residualBinding);
|
||||
var capturedScope = "__captured" + scope.name;
|
||||
// Save the serialized value for initialization at the top of
|
||||
// the factory.
|
||||
// This can serialize more variables than are necessary to execute
|
||||
// the function because every function serializes every
|
||||
// modified variable of its parent scope. In some cases it could be
|
||||
// an improvement to split these variables into multiple
|
||||
// scopes.
|
||||
var variableIndexInScope = scope.initializationValues.length;
|
||||
(0, _invariant2.default)(residualBinding.serializedValue);
|
||||
scope.initializationValues.push(residualBinding.serializedValue);
|
||||
scope.capturedScope = capturedScope;
|
||||
|
||||
// Replace binding usage with scope references
|
||||
residualBinding.serializedValue = t.memberExpression(t.identifier(capturedScope), t.numericLiteral(variableIndexInScope), true // Array style access.
|
||||
);
|
||||
}
|
||||
|
||||
residualBinding.referentialized = true;
|
||||
this.statistics.referentialized++;
|
||||
}
|
||||
}, {
|
||||
key: "referentialize",
|
||||
value: function referentialize(unbound, instances, shouldReferentializeInstanceFn) {
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = instances[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var instance = _step2.value;
|
||||
|
||||
var residualBindings = instance.residualFunctionBindings;
|
||||
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = unbound[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var name = _step3.value;
|
||||
|
||||
var residualBinding = residualBindings.get(name);
|
||||
(0, _invariant2.default)(residualBinding !== undefined);
|
||||
if (residualBinding.modified) {
|
||||
// Initialize captured scope at function call instead of globally
|
||||
if (!residualBinding.referentialized) {
|
||||
if (!shouldReferentializeInstanceFn(instance)) {
|
||||
// TODO #989: Fix additional functions and referentialization
|
||||
throw new _errors.FatalError("TODO: implement referentialization for prepacked functions");
|
||||
}
|
||||
this.referentializeBinding(residualBinding, name, instance);
|
||||
}
|
||||
|
||||
(0, _invariant2.default)(residualBinding.referentialized);
|
||||
if (residualBinding.declarativeEnvironmentRecord && residualBinding.scope) {
|
||||
instance.scopeInstances.set(residualBinding.scope.name, residualBinding.scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "createCapturedScopesArrayInitialization",
|
||||
value: function createCapturedScopesArrayInitialization(referentializationScope) {
|
||||
return t.variableDeclaration("var", [t.variableDeclarator(this._getReferentializationState(referentializationScope).capturedScopesArray, t.callExpression(t.identifier("Array"), [t.numericLiteral(this._getReferentializationState(referentializationScope).capturedScopeInstanceIdx)]))]);
|
||||
}
|
||||
}]);
|
||||
|
||||
return Referentializer;
|
||||
}();
|
||||
//# sourceMappingURL=Referentializer.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/Referentializer.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/Referentializer.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
406
build/node_modules/prepack/lib/serializer/ResidualFunctionInitializers.js
generated
vendored
Normal file
406
build/node_modules/prepack/lib/serializer/ResidualFunctionInitializers.js
generated
vendored
Normal file
@@ -0,0 +1,406 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.ResidualFunctionInitializers = undefined;
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
var _generator = require("../utils/generator.js");
|
||||
|
||||
var _traverseFast = require("../utils/traverse-fast.js");
|
||||
|
||||
var _traverseFast2 = _interopRequireDefault(_traverseFast);
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _internalizer = require("../utils/internalizer.js");
|
||||
|
||||
var _factorify = require("./factorify.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
// This class manages information about values
|
||||
// which are only referenced by residual functions,
|
||||
// and it provides the ability to generate initialization code for those values that
|
||||
// can be placed into the residual functions.
|
||||
var ResidualFunctionInitializers = exports.ResidualFunctionInitializers = function () {
|
||||
function ResidualFunctionInitializers(locationService, prelude, initializerNameGenerator) {
|
||||
_classCallCheck(this, ResidualFunctionInitializers);
|
||||
|
||||
this.functionInitializerInfos = new Map();
|
||||
this.initializers = new Map();
|
||||
this.sharedInitializers = new Map();
|
||||
this.locationService = locationService;
|
||||
this.initializerNameGenerator = initializerNameGenerator;
|
||||
this.prelude = prelude;
|
||||
}
|
||||
|
||||
_createClass(ResidualFunctionInitializers, [{
|
||||
key: "registerValueOnlyReferencedByResidualFunctions",
|
||||
value: function registerValueOnlyReferencedByResidualFunctions(functionValues, val) {
|
||||
(0, _invariant2.default)(functionValues.length >= 1);
|
||||
var infos = [];
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = functionValues[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var functionValue = _step.value;
|
||||
|
||||
var info = this.functionInitializerInfos.get(functionValue);
|
||||
if (info === undefined) this.functionInitializerInfos.set(functionValue, info = { ownId: this.functionInitializerInfos.size.toString(), initializerIds: new Set() });
|
||||
infos.push(info);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var id = infos.map(function (info) {
|
||||
return info.ownId;
|
||||
}).sort().join();
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = infos[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var info = _step2.value;
|
||||
info.initializerIds.add(id);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var initializer = this.initializers.get(id);
|
||||
if (initializer === undefined) this.initializers.set(id, initializer = {
|
||||
id: id,
|
||||
order: infos.length,
|
||||
values: [],
|
||||
body: { type: "DelayInitializations", parentBody: undefined, entries: [] }
|
||||
});
|
||||
initializer.values.push(val);
|
||||
return initializer.body;
|
||||
}
|
||||
}, {
|
||||
key: "scrubFunctionInitializers",
|
||||
value: function scrubFunctionInitializers() {
|
||||
// Deleting trivial entries in order to avoid creating empty initialization functions that serve no purpose.
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = this.initializers.values()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var initializer = _step3.value;
|
||||
|
||||
if (initializer.body.entries.length === 0) this.initializers.delete(initializer.id);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _iteratorNormalCompletion4 = true;
|
||||
var _didIteratorError4 = false;
|
||||
var _iteratorError4 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator4 = this.functionInitializerInfos[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
|
||||
var _ref = _step4.value;
|
||||
|
||||
var _ref2 = _slicedToArray(_ref, 2);
|
||||
|
||||
var functionValue = _ref2[0];
|
||||
var info = _ref2[1];
|
||||
var _iteratorNormalCompletion5 = true;
|
||||
var _didIteratorError5 = false;
|
||||
var _iteratorError5 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator5 = info.initializerIds[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
|
||||
var _id = _step5.value;
|
||||
|
||||
var _initializer = this.initializers.get(_id);
|
||||
if (_initializer === undefined) {
|
||||
info.initializerIds.delete(_id);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError5 = true;
|
||||
_iteratorError5 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion5 && _iterator5.return) {
|
||||
_iterator5.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError5) {
|
||||
throw _iteratorError5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (info.initializerIds.size === 0) this.functionInitializerInfos.delete(functionValue);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError4 = true;
|
||||
_iteratorError4 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion4 && _iterator4.return) {
|
||||
_iterator4.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError4) {
|
||||
throw _iteratorError4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_conditionalInitialization",
|
||||
value: function _conditionalInitialization(initializedValues, initializationStatements) {
|
||||
if (initializationStatements.length === 1 && t.isIfStatement(initializationStatements[0])) {
|
||||
return initializationStatements[0];
|
||||
}
|
||||
|
||||
// We have some initialization code, and it should only get executed once,
|
||||
// so we are going to guard it.
|
||||
// First, let's see if one of the initialized values is guaranteed to not
|
||||
// be undefined after initialization. In that case, we can use that state-change
|
||||
// to figure out if initialization needs to run.
|
||||
var location = void 0;
|
||||
var _iteratorNormalCompletion6 = true;
|
||||
var _didIteratorError6 = false;
|
||||
var _iteratorError6 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator6 = initializedValues[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
|
||||
var value = _step6.value;
|
||||
|
||||
if (!value.mightBeUndefined()) {
|
||||
location = this.locationService.getLocation(value);
|
||||
if (location !== undefined) break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError6 = true;
|
||||
_iteratorError6 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion6 && _iterator6.return) {
|
||||
_iterator6.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError6) {
|
||||
throw _iteratorError6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (location === undefined) {
|
||||
// Second, if we didn't find a non-undefined value, let's make one up.
|
||||
// It will transition from `undefined` to `null`.
|
||||
location = this.locationService.createLocation();
|
||||
initializationStatements.unshift(t.expressionStatement(t.assignmentExpression("=", location, _internalizer.nullExpression)));
|
||||
}
|
||||
return t.ifStatement(t.binaryExpression("===", location, _internalizer.voidExpression), t.blockStatement(initializationStatements));
|
||||
}
|
||||
}, {
|
||||
key: "hasInitializerStatement",
|
||||
value: function hasInitializerStatement(functionValue) {
|
||||
return !!this.functionInitializerInfos.get(functionValue);
|
||||
}
|
||||
}, {
|
||||
key: "factorifyInitializers",
|
||||
value: function factorifyInitializers(nameGenerator) {
|
||||
var _iteratorNormalCompletion7 = true;
|
||||
var _didIteratorError7 = false;
|
||||
var _iteratorError7 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator7 = this.initializers.values()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
|
||||
var initializer = _step7.value;
|
||||
|
||||
(0, _factorify.factorifyObjects)(initializer.body.entries, nameGenerator);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError7 = true;
|
||||
_iteratorError7 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion7 && _iterator7.return) {
|
||||
_iterator7.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError7) {
|
||||
throw _iteratorError7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "getInitializerStatement",
|
||||
value: function getInitializerStatement(functionValue) {
|
||||
var _this = this;
|
||||
|
||||
var initializerInfo = this.functionInitializerInfos.get(functionValue);
|
||||
if (initializerInfo === undefined) return undefined;
|
||||
|
||||
(0, _invariant2.default)(initializerInfo.initializerIds.size > 0);
|
||||
var ownInitializer = this.initializers.get(initializerInfo.ownId);
|
||||
var initializedValues = void 0;
|
||||
var initializationStatements = [];
|
||||
var initializers = [];
|
||||
var _iteratorNormalCompletion8 = true;
|
||||
var _didIteratorError8 = false;
|
||||
var _iteratorError8 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator8 = initializerInfo.initializerIds[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
|
||||
var initializerId = _step8.value;
|
||||
|
||||
var initializer = this.initializers.get(initializerId);
|
||||
(0, _invariant2.default)(initializer !== undefined);
|
||||
(0, _invariant2.default)(initializer.body.entries.length > 0);
|
||||
initializers.push(initializer);
|
||||
}
|
||||
// Sorting initializers by the number of scopes they are required by.
|
||||
// Note that the scope sets form a lattice, and this sorting effectively
|
||||
// ensures that value initializers that depend on other value initializers
|
||||
// get called in the right order.
|
||||
} catch (err) {
|
||||
_didIteratorError8 = true;
|
||||
_iteratorError8 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion8 && _iterator8.return) {
|
||||
_iterator8.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError8) {
|
||||
throw _iteratorError8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
initializers.sort(function (i, j) {
|
||||
return j.order - i.order;
|
||||
});
|
||||
var _iteratorNormalCompletion9 = true;
|
||||
var _didIteratorError9 = false;
|
||||
var _iteratorError9 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator9 = initializers[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
|
||||
var initializer = _step9.value;
|
||||
|
||||
if (initializerInfo.initializerIds.size === 1 || initializer === ownInitializer) {
|
||||
initializedValues = initializer.values;
|
||||
}
|
||||
if (initializer === ownInitializer) {
|
||||
initializationStatements = initializationStatements.concat(initializer.body.entries);
|
||||
} else {
|
||||
var ast = this.sharedInitializers.get(initializer.id);
|
||||
if (ast === undefined) {
|
||||
(function () {
|
||||
ast = _this._conditionalInitialization(initializer.values, initializer.body.entries);
|
||||
// We inline compact initializers, as calling a function would introduce too much
|
||||
// overhead. To determine if an initializer is compact, we count the number of
|
||||
// nodes in the AST, and check if it exceeds a certain threshold.
|
||||
// TODO #885: Study in more detail which threshold is the best compromise in terms of
|
||||
// code size and performance.
|
||||
var count = 0;
|
||||
(0, _traverseFast2.default)(t.file(t.program([ast])), function (node) {
|
||||
count++;
|
||||
return false;
|
||||
});
|
||||
if (count > 24) {
|
||||
var _id2 = t.identifier(_this.initializerNameGenerator.generate());
|
||||
_this.prelude.push(t.functionDeclaration(_id2, [], t.blockStatement([ast])));
|
||||
ast = t.expressionStatement(t.callExpression(_id2, []));
|
||||
}
|
||||
_this.sharedInitializers.set(initializer.id, ast);
|
||||
})();
|
||||
}
|
||||
initializationStatements.push(ast);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError9 = true;
|
||||
_iteratorError9 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion9 && _iterator9.return) {
|
||||
_iterator9.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError9) {
|
||||
throw _iteratorError9;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this._conditionalInitialization(initializedValues || [], initializationStatements);
|
||||
}
|
||||
}]);
|
||||
|
||||
return ResidualFunctionInitializers;
|
||||
}();
|
||||
//# sourceMappingURL=ResidualFunctionInitializers.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/ResidualFunctionInitializers.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualFunctionInitializers.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1098
build/node_modules/prepack/lib/serializer/ResidualFunctions.js
generated
vendored
Normal file
1098
build/node_modules/prepack/lib/serializer/ResidualFunctions.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
build/node_modules/prepack/lib/serializer/ResidualFunctions.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualFunctions.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
311
build/node_modules/prepack/lib/serializer/ResidualHeapGraphGenerator.js
generated
vendored
Normal file
311
build/node_modules/prepack/lib/serializer/ResidualHeapGraphGenerator.js
generated
vendored
Normal file
@@ -0,0 +1,311 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.ResidualHeapGraphGenerator = undefined;
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _ResidualHeapInspector = require("./ResidualHeapInspector.js");
|
||||
|
||||
var _ResidualHeapVisitor2 = require("./ResidualHeapVisitor.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
||||
|
||||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Generate a visualizable objects graph for Prepack heap.
|
||||
*/
|
||||
var ResidualHeapGraphGenerator = exports.ResidualHeapGraphGenerator = function (_ResidualHeapVisitor) {
|
||||
_inherits(ResidualHeapGraphGenerator, _ResidualHeapVisitor);
|
||||
|
||||
function ResidualHeapGraphGenerator(realm, logger, modules, additionalFunctionValuesAndEffects, valueIdentifiers, valueToEdgeRecord) {
|
||||
_classCallCheck(this, ResidualHeapGraphGenerator);
|
||||
|
||||
var _this = _possibleConstructorReturn(this, (ResidualHeapGraphGenerator.__proto__ || Object.getPrototypeOf(ResidualHeapGraphGenerator)).call(this, realm, logger, modules, additionalFunctionValuesAndEffects));
|
||||
|
||||
_this._valueToEdgeRecord = valueToEdgeRecord;
|
||||
_this._valueIdentifiers = valueIdentifiers;
|
||||
_this._visitedValues = new Set();
|
||||
_this._valueIds = new Map();
|
||||
_this._idSeed = 0;
|
||||
_this._path = [];
|
||||
_this._edges = [];
|
||||
return _this;
|
||||
} // Contains the path of nodes from root to current visiting node.
|
||||
|
||||
|
||||
_createClass(ResidualHeapGraphGenerator, [{
|
||||
key: "preProcessValue",
|
||||
|
||||
|
||||
// Override.
|
||||
value: function preProcessValue(val) {
|
||||
if (this._shouldIgnore(val)) {
|
||||
return true;
|
||||
}
|
||||
this._updateEdge(val);
|
||||
|
||||
if (this._visitedValues.has(val)) {
|
||||
return false; // Already visited.
|
||||
}
|
||||
this._visitedValues.add(val);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Override.
|
||||
|
||||
}, {
|
||||
key: "postProcessValue",
|
||||
value: function postProcessValue(val) {
|
||||
if (this._shouldIgnore(val)) {
|
||||
return;
|
||||
}
|
||||
(0, _invariant2.default)(this._path.length > 0);
|
||||
this._path.pop();
|
||||
}
|
||||
}, {
|
||||
key: "_getValueId",
|
||||
value: function _getValueId(val) {
|
||||
var id = this._valueIds.get(val);
|
||||
if (!id) {
|
||||
this._valueIds.set(val, ++this._idSeed);
|
||||
id = this._idSeed;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
}, {
|
||||
key: "_shouldIgnore",
|
||||
value: function _shouldIgnore(val) {
|
||||
return val instanceof _index.EmptyValue || val.isIntrinsic() || _ResidualHeapInspector.ResidualHeapInspector.isLeaf(val);
|
||||
}
|
||||
}, {
|
||||
key: "_updateEdge",
|
||||
value: function _updateEdge(val) {
|
||||
if (this._path.length > 0) {
|
||||
var parent = this._path[this._path.length - 1];
|
||||
this._edges.push({ fromId: this._getValueId(parent), toId: this._getValueId(val) });
|
||||
}
|
||||
this._path.push(val);
|
||||
}
|
||||
}, {
|
||||
key: "_getValueLabel",
|
||||
value: function _getValueLabel(val) {
|
||||
// TODO: does not use ref count yet, figure out how to best visualize it later.
|
||||
var serializedId = this._valueIdentifiers.getIdentifier(val);
|
||||
(0, _invariant2.default)(serializedId);
|
||||
return val.__originalName ? serializedId.name + "(" + val.__originalName + ")" : serializedId.name;
|
||||
}
|
||||
}, {
|
||||
key: "_generateDotGraphData",
|
||||
value: function _generateDotGraphData(nodes, edges) {
|
||||
var content = "digraph{\n";
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var val = _step.value;
|
||||
|
||||
var nodeId = this._getValueId(val);
|
||||
content += " node" + nodeId + " [shape=" + this._getValueShape(val) + " label=" + this._getValueLabel(val) + "];\n";
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = edges[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var edge = _step2.value;
|
||||
|
||||
content += " node" + edge.fromId + " -> node" + edge.toId + ";\n";
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
content += "}";
|
||||
return content;
|
||||
}
|
||||
}, {
|
||||
key: "_generateVisJSGraphData",
|
||||
value: function _generateVisJSGraphData(nodes, edges) {
|
||||
var nodesData = [];
|
||||
var edgesData = [];
|
||||
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = nodes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var node = _step3.value;
|
||||
|
||||
var nodeId = this._getValueId(node);
|
||||
var nodeData = {
|
||||
id: "" + nodeId,
|
||||
label: this._getValueLabel(node),
|
||||
shape: this._getValueShape(node),
|
||||
color: this._getValueColor(node)
|
||||
};
|
||||
nodesData.push(nodeData);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _iteratorNormalCompletion4 = true;
|
||||
var _didIteratorError4 = false;
|
||||
var _iteratorError4 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator4 = edges.entries()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
|
||||
var _ref = _step4.value;
|
||||
|
||||
var _ref2 = _slicedToArray(_ref, 2);
|
||||
|
||||
var index = _ref2[0];
|
||||
var edge = _ref2[1];
|
||||
|
||||
var edgeData = {
|
||||
id: index,
|
||||
from: "" + edge.fromId,
|
||||
to: "" + edge.toId,
|
||||
arrows: "to"
|
||||
};
|
||||
edgesData.push(edgeData);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError4 = true;
|
||||
_iteratorError4 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion4 && _iterator4.return) {
|
||||
_iterator4.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError4) {
|
||||
throw _iteratorError4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var graphData = {
|
||||
nodes: nodesData,
|
||||
edges: edgesData
|
||||
};
|
||||
return JSON.stringify(graphData);
|
||||
}
|
||||
|
||||
// TODO: find a way to comment the meaning of shape => value mapping in final graph language.
|
||||
|
||||
}, {
|
||||
key: "_getValueShape",
|
||||
value: function _getValueShape(val) {
|
||||
var shape = null;
|
||||
if (val instanceof _index.FunctionValue) {
|
||||
shape = "circle";
|
||||
} else if (val instanceof _index.AbstractValue) {
|
||||
shape = "diamond";
|
||||
} else if (val instanceof _index.ProxyValue) {
|
||||
shape = "triangle";
|
||||
} else if (val instanceof _index.SymbolValue) {
|
||||
shape = "star";
|
||||
} else if (val instanceof _index.ObjectValue) {
|
||||
shape = "box";
|
||||
} else {
|
||||
shape = "ellipse";
|
||||
}
|
||||
return shape;
|
||||
}
|
||||
|
||||
// TODO: find a way to comment the meaning of shape => value mapping in final graph language.
|
||||
|
||||
}, {
|
||||
key: "_getValueColor",
|
||||
value: function _getValueColor(val) {
|
||||
var shape = null;
|
||||
if (val instanceof _index.FunctionValue) {
|
||||
shape = "red";
|
||||
} else if (val instanceof _index.AbstractValue) {
|
||||
shape = "green";
|
||||
} else if (val instanceof _index.ProxyValue) {
|
||||
shape = "orange";
|
||||
} else if (val instanceof _index.SymbolValue) {
|
||||
shape = "yellow";
|
||||
} else if (val instanceof _index.ObjectValue) {
|
||||
shape = "#3BB9FF"; // light blue
|
||||
} else {
|
||||
shape = "grey";
|
||||
}
|
||||
return shape;
|
||||
}
|
||||
}, {
|
||||
key: "generateResult",
|
||||
value: function generateResult(heapGraphFormat) {
|
||||
return heapGraphFormat === "DotLanguage" ? this._generateDotGraphData(this._visitedValues, this._edges) : this._generateVisJSGraphData(this._visitedValues, this._edges);
|
||||
}
|
||||
}]);
|
||||
|
||||
return ResidualHeapGraphGenerator;
|
||||
}(_ResidualHeapVisitor2.ResidualHeapVisitor);
|
||||
//# sourceMappingURL=ResidualHeapGraphGenerator.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/ResidualHeapGraphGenerator.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualHeapGraphGenerator.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
220
build/node_modules/prepack/lib/serializer/ResidualHeapInspector.js
generated
vendored
Normal file
220
build/node_modules/prepack/lib/serializer/ResidualHeapInspector.js
generated
vendored
Normal file
@@ -0,0 +1,220 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.ResidualHeapInspector = undefined;
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _index = require("../methods/index.js");
|
||||
|
||||
var _index2 = require("../values/index.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _logger = require("./logger.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
var ResidualHeapInspector = exports.ResidualHeapInspector = function () {
|
||||
function ResidualHeapInspector(realm, logger) {
|
||||
_classCallCheck(this, ResidualHeapInspector);
|
||||
|
||||
this.realm = realm;
|
||||
this.logger = logger;
|
||||
this.ignoredProperties = new Map();
|
||||
}
|
||||
|
||||
_createClass(ResidualHeapInspector, [{
|
||||
key: "canIgnoreProperty",
|
||||
|
||||
|
||||
// Object properties which have the default value can be ignored by the serializer.
|
||||
value: function canIgnoreProperty(val, key) {
|
||||
var set = this.ignoredProperties.get(val);
|
||||
if (!set) {
|
||||
this.ignoredProperties.set(val, set = this._getIgnoredProperties(val));
|
||||
}
|
||||
return set.has(key);
|
||||
}
|
||||
}, {
|
||||
key: "_getIgnoredProperties",
|
||||
value: function _getIgnoredProperties(val) {
|
||||
var set = new Set();
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = val.properties[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var _ref = _step.value;
|
||||
|
||||
var _ref2 = _slicedToArray(_ref, 2);
|
||||
|
||||
var key = _ref2[0];
|
||||
var propertyBinding = _ref2[1];
|
||||
|
||||
(0, _invariant2.default)(propertyBinding);
|
||||
var desc = propertyBinding.descriptor;
|
||||
if (desc === undefined) continue; //deleted
|
||||
if (this._canIgnoreProperty(val, key, desc)) set.add(key);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
}, {
|
||||
key: "_canIgnoreProperty",
|
||||
value: function _canIgnoreProperty(val, key, desc) {
|
||||
if ((0, _index.IsArray)(this.realm, val)) {
|
||||
if (key === "length" && desc.writable && !desc.enumerable && !desc.configurable) {
|
||||
// length property has the correct descriptor values
|
||||
return true;
|
||||
}
|
||||
} else if (val instanceof _index2.FunctionValue) {
|
||||
if (key === "length") {
|
||||
if (desc.value === undefined) {
|
||||
this.logger.logError(val, "Functions with length accessor properties are not supported in residual heap.");
|
||||
// Rationale: .bind() would call the accessor, which might throw, mutate state, or do whatever...
|
||||
}
|
||||
// length property will be inferred already by the amount of parameters
|
||||
return !desc.writable && !desc.enumerable && desc.configurable && val.hasDefaultLength();
|
||||
}
|
||||
|
||||
if (key === "name") {
|
||||
// TODO #474: Make sure that we retain original function names. Or set name property.
|
||||
// Or ensure that nothing references the name property.
|
||||
// NOTE: with some old runtimes notably JSC, function names are not configurable
|
||||
// For now don't ignore the property if it is different from the function name.
|
||||
// I.e. if it was set explicitly in the code, retain it.
|
||||
if (desc.value !== undefined && !this.realm.isCompatibleWith(this.realm.MOBILE_JSC_VERSION) && (desc.value instanceof _index2.AbstractValue || val.__originalName && val.__originalName !== "" && desc.value.value !== val.__originalName)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Properties `caller` and `arguments` are added to normal functions in non-strict mode to prevent TypeErrors.
|
||||
// Because they are autogenerated, they should be ignored.
|
||||
if (key === "arguments" || key === "caller") {
|
||||
(0, _invariant2.default)(val instanceof _index2.ECMAScriptSourceFunctionValue);
|
||||
if (!val.$Strict && desc.writable && !desc.enumerable && desc.configurable && desc.value instanceof _index2.UndefinedValue && val.$FunctionKind === "normal") return true;
|
||||
}
|
||||
|
||||
// ignore the `prototype` property when it's the right one
|
||||
if (key === "prototype") {
|
||||
if (!desc.configurable && !desc.enumerable && desc.writable && desc.value instanceof _index2.ObjectValue && desc.value.originalConstructor === val) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var kind = val.getKind();
|
||||
switch (kind) {
|
||||
case "RegExp":
|
||||
if (key === "lastIndex" && desc.writable && !desc.enumerable && !desc.configurable) {
|
||||
// length property has the correct descriptor values
|
||||
var v = desc.value;
|
||||
return v instanceof _index2.NumberValue && v.value === 0;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (key === "constructor") {
|
||||
if (desc.configurable && !desc.enumerable && desc.writable && desc.value === val.originalConstructor) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}, {
|
||||
key: "isDefaultPrototype",
|
||||
value: function isDefaultPrototype(prototype) {
|
||||
if (prototype.symbols.size !== 0 || prototype.$Prototype !== this.realm.intrinsics.ObjectPrototype || !prototype.getExtensible()) return false;
|
||||
var foundConstructor = false;
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = prototype.properties.keys()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var name = _step2.value;
|
||||
|
||||
if (name === "constructor" && ResidualHeapInspector.getPropertyValue(prototype, name) === prototype.originalConstructor) foundConstructor = true;else return false;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return foundConstructor;
|
||||
}
|
||||
}], [{
|
||||
key: "isLeaf",
|
||||
value: function isLeaf(val) {
|
||||
if (val instanceof _index2.SymbolValue) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (val instanceof _index2.AbstractValue && val.hasIdentifier()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (val.isIntrinsic()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return val instanceof _index2.PrimitiveValue;
|
||||
}
|
||||
}, {
|
||||
key: "getPropertyValue",
|
||||
value: function getPropertyValue(val, name) {
|
||||
var prototypeBinding = val.properties.get(name);
|
||||
if (prototypeBinding === undefined) return undefined;
|
||||
var prototypeDesc = prototypeBinding.descriptor;
|
||||
if (prototypeDesc === undefined) return undefined;
|
||||
(0, _invariant2.default)(prototypeDesc.value === undefined || prototypeDesc.value instanceof _index2.Value);
|
||||
return prototypeDesc.value;
|
||||
}
|
||||
}]);
|
||||
|
||||
return ResidualHeapInspector;
|
||||
}();
|
||||
//# sourceMappingURL=ResidualHeapInspector.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/ResidualHeapInspector.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualHeapInspector.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
127
build/node_modules/prepack/lib/serializer/ResidualHeapRefCounter.js
generated
vendored
Normal file
127
build/node_modules/prepack/lib/serializer/ResidualHeapRefCounter.js
generated
vendored
Normal file
@@ -0,0 +1,127 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.ResidualHeapRefCounter = undefined;
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _ResidualHeapInspector = require("./ResidualHeapInspector.js");
|
||||
|
||||
var _ResidualHeapVisitor2 = require("./ResidualHeapVisitor.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
||||
|
||||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Record residual heap object's incoming and outgoing reference counts.
|
||||
*/
|
||||
var ResidualHeapRefCounter = exports.ResidualHeapRefCounter = function (_ResidualHeapVisitor) {
|
||||
_inherits(ResidualHeapRefCounter, _ResidualHeapVisitor);
|
||||
|
||||
function ResidualHeapRefCounter(realm, logger, modules, additionalFunctionValuesAndEffects) {
|
||||
_classCallCheck(this, ResidualHeapRefCounter);
|
||||
|
||||
var _this = _possibleConstructorReturn(this, (ResidualHeapRefCounter.__proto__ || Object.getPrototypeOf(ResidualHeapRefCounter)).call(this, realm, logger, modules, additionalFunctionValuesAndEffects));
|
||||
|
||||
_this._valueToEdgeRecord = new Map();
|
||||
_this._path = [];
|
||||
return _this;
|
||||
}
|
||||
|
||||
_createClass(ResidualHeapRefCounter, [{
|
||||
key: "getResult",
|
||||
// Contains the path of nodes from root to current visiting node.
|
||||
|
||||
value: function getResult() {
|
||||
return this._valueToEdgeRecord;
|
||||
}
|
||||
}, {
|
||||
key: "_shouldIgnore",
|
||||
value: function _shouldIgnore(val) {
|
||||
return val instanceof _index.EmptyValue || val.isIntrinsic() || _ResidualHeapInspector.ResidualHeapInspector.isLeaf(val);
|
||||
}
|
||||
}, {
|
||||
key: "preProcessValue",
|
||||
value: function preProcessValue(val) {
|
||||
if (this._shouldIgnore(val)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this._path.length > 0) {
|
||||
this._updateParentOutgoingEdgeCount();
|
||||
}
|
||||
this._path.push(val);
|
||||
|
||||
return this._updateValueIncomingEdgeCount(val);
|
||||
}
|
||||
}, {
|
||||
key: "_updateParentOutgoingEdgeCount",
|
||||
value: function _updateParentOutgoingEdgeCount() {
|
||||
var parent = this._path[this._path.length - 1];
|
||||
var edgeRecord = this._valueToEdgeRecord.get(parent);
|
||||
(0, _invariant2.default)(edgeRecord);
|
||||
++edgeRecord.outGoing;
|
||||
}
|
||||
}, {
|
||||
key: "_updateValueIncomingEdgeCount",
|
||||
value: function _updateValueIncomingEdgeCount(val) {
|
||||
var edgeRecord = this._valueToEdgeRecord.get(val);
|
||||
if (edgeRecord === undefined) {
|
||||
this._valueToEdgeRecord.set(val, {
|
||||
inComing: 1,
|
||||
outGoing: 0
|
||||
});
|
||||
return true;
|
||||
} else {
|
||||
++edgeRecord.inComing;
|
||||
return false; // visited node, skip its children.
|
||||
}
|
||||
}
|
||||
|
||||
// Override.
|
||||
|
||||
}, {
|
||||
key: "postProcessValue",
|
||||
value: function postProcessValue(val) {
|
||||
if (this._shouldIgnore(val)) {
|
||||
return;
|
||||
}
|
||||
(0, _invariant2.default)(this._path.length > 0);
|
||||
this._path.pop();
|
||||
}
|
||||
|
||||
// Override.
|
||||
|
||||
}, {
|
||||
key: "visitRoots",
|
||||
value: function visitRoots() {
|
||||
_get(ResidualHeapRefCounter.prototype.__proto__ || Object.getPrototypeOf(ResidualHeapRefCounter.prototype), "visitRoots", this).call(this);
|
||||
(0, _invariant2.default)(this._path.length === 0, "Path should be balanced empty after traversal.");
|
||||
}
|
||||
}]);
|
||||
|
||||
return ResidualHeapRefCounter;
|
||||
}(_ResidualHeapVisitor2.ResidualHeapVisitor);
|
||||
//# sourceMappingURL=ResidualHeapRefCounter.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/ResidualHeapRefCounter.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualHeapRefCounter.js.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/serializer/ResidualHeapRefCounter.js"],"names":["ResidualHeapRefCounter","realm","logger","modules","additionalFunctionValuesAndEffects","_valueToEdgeRecord","Map","_path","val","isIntrinsic","isLeaf","_shouldIgnore","length","_updateParentOutgoingEdgeCount","push","_updateValueIncomingEdgeCount","parent","edgeRecord","get","outGoing","undefined","set","inComing","pop"],"mappings":";;;;;;;;;;;AAgBA;;;;AACA;;AACA;;AACA;;;;;;;;+eAnBA;;;;;;;;;AAqBA;;;IAGaA,sB,WAAAA,sB;;;AACX,kCACEC,KADF,EAEEC,MAFF,EAGEC,OAHF,EAIEC,kCAJF,EAKE;AAAA;;AAAA,gJACMH,KADN,EACaC,MADb,EACqBC,OADrB,EAC8BC,kCAD9B;;AAEA,UAAKC,kBAAL,GAA0B,IAAIC,GAAJ,EAA1B;AACA,UAAKC,KAAL,GAAa,EAAb;AAHA;AAID;;;;AAGoB;;gCAEmB;AACtC,aAAO,KAAKF,kBAAZ;AACD;;;kCAEaG,G,EAAqB;AACjC,aAAOA,oCAA6BA,IAAIC,WAAJ,EAA7B,IAAkD,6CAAsBC,MAAtB,CAA6BF,GAA7B,CAAzD;AACD;;;oCAEeA,G,EAAqB;AACnC,UAAI,KAAKG,aAAL,CAAmBH,GAAnB,CAAJ,EAA6B;AAC3B,eAAO,KAAP;AACD;;AAED,UAAI,KAAKD,KAAL,CAAWK,MAAX,GAAoB,CAAxB,EAA2B;AACzB,aAAKC,8BAAL;AACD;AACD,WAAKN,KAAL,CAAWO,IAAX,CAAgBN,GAAhB;;AAEA,aAAO,KAAKO,6BAAL,CAAmCP,GAAnC,CAAP;AACD;;;qDAEgC;AAC/B,UAAMQ,SAAS,KAAKT,KAAL,CAAW,KAAKA,KAAL,CAAWK,MAAX,GAAoB,CAA/B,CAAf;AACA,UAAMK,aAAa,KAAKZ,kBAAL,CAAwBa,GAAxB,CAA4BF,MAA5B,CAAnB;AACA,+BAAUC,UAAV;AACA,QAAEA,WAAWE,QAAb;AACD;;;kDAE6BX,G,EAAqB;AACjD,UAAIS,aAAa,KAAKZ,kBAAL,CAAwBa,GAAxB,CAA4BV,GAA5B,CAAjB;AACA,UAAIS,eAAeG,SAAnB,EAA8B;AAC5B,aAAKf,kBAAL,CAAwBgB,GAAxB,CAA4Bb,GAA5B,EAAiC;AAC/Bc,oBAAU,CADqB;AAE/BH,oBAAU;AAFqB,SAAjC;AAIA,eAAO,IAAP;AACD,OAND,MAMO;AACL,UAAEF,WAAWK,QAAb;AACA,eAAO,KAAP,CAFK,CAES;AACf;AACF;;AAED;;;;qCACiBd,G,EAAY;AAC3B,UAAI,KAAKG,aAAL,CAAmBH,GAAnB,CAAJ,EAA6B;AAC3B;AACD;AACD,+BAAU,KAAKD,KAAL,CAAWK,MAAX,GAAoB,CAA9B;AACA,WAAKL,KAAL,CAAWgB,GAAX;AACD;;AAED;;;;iCACmB;AACjB;AACA,+BAAU,KAAKhB,KAAL,CAAWK,MAAX,KAAsB,CAAhC,EAAmC,gDAAnC;AACD","file":"ResidualHeapRefCounter.js","sourcesContent":["/**\n * Copyright (c) 2017-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n */\n\n/* @flow */\n\nimport type { Logger } from \"./logger.js\";\nimport type { Modules } from \"./modules.js\";\nimport type { Realm } from \"../realm.js\";\nimport type { ObjectRefCount, AdditionalFunctionEffects } from \"./types.js\";\n\nimport invariant from \"../invariant.js\";\nimport { Value, EmptyValue, FunctionValue } from \"../values/index.js\";\nimport { ResidualHeapInspector } from \"./ResidualHeapInspector.js\";\nimport { ResidualHeapVisitor } from \"./ResidualHeapVisitor.js\";\n\n/**\n * Record residual heap object's incoming and outgoing reference counts.\n */\nexport class ResidualHeapRefCounter extends ResidualHeapVisitor {\n constructor(\n realm: Realm,\n logger: Logger,\n modules: Modules,\n additionalFunctionValuesAndEffects: Map<FunctionValue, AdditionalFunctionEffects>\n ) {\n super(realm, logger, modules, additionalFunctionValuesAndEffects);\n this._valueToEdgeRecord = new Map();\n this._path = [];\n }\n\n _valueToEdgeRecord: Map<Value, ObjectRefCount>;\n _path: Array<Value>; // Contains the path of nodes from root to current visiting node.\n\n getResult(): Map<Value, ObjectRefCount> {\n return this._valueToEdgeRecord;\n }\n\n _shouldIgnore(val: Value): boolean {\n return val instanceof EmptyValue || val.isIntrinsic() || ResidualHeapInspector.isLeaf(val);\n }\n\n preProcessValue(val: Value): boolean {\n if (this._shouldIgnore(val)) {\n return false;\n }\n\n if (this._path.length > 0) {\n this._updateParentOutgoingEdgeCount();\n }\n this._path.push(val);\n\n return this._updateValueIncomingEdgeCount(val);\n }\n\n _updateParentOutgoingEdgeCount() {\n const parent = this._path[this._path.length - 1];\n const edgeRecord = this._valueToEdgeRecord.get(parent);\n invariant(edgeRecord);\n ++edgeRecord.outGoing;\n }\n\n _updateValueIncomingEdgeCount(val: Value): boolean {\n let edgeRecord = this._valueToEdgeRecord.get(val);\n if (edgeRecord === undefined) {\n this._valueToEdgeRecord.set(val, {\n inComing: 1,\n outGoing: 0,\n });\n return true;\n } else {\n ++edgeRecord.inComing;\n return false; // visited node, skip its children.\n }\n }\n\n // Override.\n postProcessValue(val: Value) {\n if (this._shouldIgnore(val)) {\n return;\n }\n invariant(this._path.length > 0);\n this._path.pop();\n }\n\n // Override.\n visitRoots(): void {\n super.visitRoots();\n invariant(this._path.length === 0, \"Path should be balanced empty after traversal.\");\n }\n}\n"]}
|
||||
1924
build/node_modules/prepack/lib/serializer/ResidualHeapSerializer.js
generated
vendored
Normal file
1924
build/node_modules/prepack/lib/serializer/ResidualHeapSerializer.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
build/node_modules/prepack/lib/serializer/ResidualHeapSerializer.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualHeapSerializer.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
147
build/node_modules/prepack/lib/serializer/ResidualHeapValueIdentifiers.js
generated
vendored
Normal file
147
build/node_modules/prepack/lib/serializer/ResidualHeapValueIdentifiers.js
generated
vendored
Normal file
@@ -0,0 +1,147 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.ResidualHeapValueIdentifiers = undefined;
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
// This class maintains a map of values to babel identifiers.
|
||||
// This class can optionally track how often such value identifiers are referenced
|
||||
// when pass 1 is activated, which is usually followed by pass 2 in which
|
||||
// unneeded identifiers (those which were only ever referenced once) are
|
||||
// eliminated as the defining expression can be inlined.
|
||||
var ResidualHeapValueIdentifiers = exports.ResidualHeapValueIdentifiers = function () {
|
||||
function ResidualHeapValueIdentifiers(values, preludeGenerator) {
|
||||
_classCallCheck(this, ResidualHeapValueIdentifiers);
|
||||
|
||||
this.collectValToRefCountOnly = false;
|
||||
this._valueNameGenerator = preludeGenerator.createNameGenerator("_");
|
||||
this._populateIdentifierMap(values);
|
||||
}
|
||||
|
||||
_createClass(ResidualHeapValueIdentifiers, [{
|
||||
key: "initPass1",
|
||||
value: function initPass1() {
|
||||
this.collectValToRefCountOnly = true;
|
||||
this.valToRefCount = new Map();
|
||||
}
|
||||
}, {
|
||||
key: "initPass2",
|
||||
value: function initPass2() {
|
||||
this.collectValToRefCountOnly = false;
|
||||
}
|
||||
}, {
|
||||
key: "_populateIdentifierMap",
|
||||
value: function _populateIdentifierMap(values) {
|
||||
this.refs = new Map();
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = values[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var val = _step.value;
|
||||
|
||||
this._setIdentifier(val, this._createNewIdentifier(val));
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_createNewIdentifier",
|
||||
value: function _createNewIdentifier(val) {
|
||||
var name = this._valueNameGenerator.generate(val.__originalName || "");
|
||||
return t.identifier(name);
|
||||
}
|
||||
}, {
|
||||
key: "_setIdentifier",
|
||||
value: function _setIdentifier(val, id) {
|
||||
(0, _invariant2.default)(!this.refs.has(val));
|
||||
this.refs.set(val, id);
|
||||
}
|
||||
}, {
|
||||
key: "getIdentifier",
|
||||
value: function getIdentifier(val) {
|
||||
var id = this.refs.get(val);
|
||||
(0, _invariant2.default)(id !== undefined);
|
||||
return id;
|
||||
}
|
||||
}, {
|
||||
key: "deleteIdentifier",
|
||||
value: function deleteIdentifier(val) {
|
||||
(0, _invariant2.default)(this.refs.has(val));
|
||||
this.refs.delete(val);
|
||||
}
|
||||
}, {
|
||||
key: "getIdentifierAndIncrementReferenceCount",
|
||||
value: function getIdentifierAndIncrementReferenceCount(val) {
|
||||
this.incrementReferenceCount(val);
|
||||
var id = this.refs.get(val);
|
||||
(0, _invariant2.default)(id !== undefined, "Value Id cannot be null or undefined");
|
||||
return id;
|
||||
}
|
||||
}, {
|
||||
key: "incrementReferenceCount",
|
||||
value: function incrementReferenceCount(val) {
|
||||
if (this.collectValToRefCountOnly) {
|
||||
var valToRefCount = this.valToRefCount;
|
||||
(0, _invariant2.default)(valToRefCount !== undefined);
|
||||
var refCount = valToRefCount.get(val);
|
||||
if (refCount) {
|
||||
refCount++;
|
||||
} else {
|
||||
refCount = 1;
|
||||
}
|
||||
valToRefCount.set(val, refCount);
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "needsIdentifier",
|
||||
value: function needsIdentifier(val) {
|
||||
if (this.collectValToRefCountOnly || this.valToRefCount === undefined) return true;
|
||||
var refCount = this.valToRefCount.get(val);
|
||||
(0, _invariant2.default)(refCount !== undefined && refCount > 0);
|
||||
return refCount !== 1;
|
||||
}
|
||||
}]);
|
||||
|
||||
return ResidualHeapValueIdentifiers;
|
||||
}();
|
||||
//# sourceMappingURL=ResidualHeapValueIdentifiers.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/ResidualHeapValueIdentifiers.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualHeapValueIdentifiers.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1114
build/node_modules/prepack/lib/serializer/ResidualHeapVisitor.js
generated
vendored
Normal file
1114
build/node_modules/prepack/lib/serializer/ResidualHeapVisitor.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1
build/node_modules/prepack/lib/serializer/ResidualHeapVisitor.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualHeapVisitor.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
337
build/node_modules/prepack/lib/serializer/ResidualReactElements.js
generated
vendored
Normal file
337
build/node_modules/prepack/lib/serializer/ResidualReactElements.js
generated
vendored
Normal file
@@ -0,0 +1,337 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.ResidualReactElements = undefined;
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _ResidualHeapSerializer = require("./ResidualHeapSerializer.js");
|
||||
|
||||
var _hoisting = require("../react/hoisting.js");
|
||||
|
||||
var _index = require("../methods/index.js");
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
var _index2 = require("../values/index.js");
|
||||
|
||||
var _jsx = require("../react/jsx.js");
|
||||
|
||||
var _logger = require("./logger.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _errors = require("../errors");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
var ResidualReactElements = exports.ResidualReactElements = function () {
|
||||
function ResidualReactElements(realm, residualHeapSerializer) {
|
||||
_classCallCheck(this, ResidualReactElements);
|
||||
|
||||
this.realm = realm;
|
||||
this.residualHeapSerializer = residualHeapSerializer;
|
||||
this.logger = residualHeapSerializer.logger;
|
||||
this.reactOutput = realm.react.output || "create-element";
|
||||
this._lazilyHoistedNodes = undefined;
|
||||
}
|
||||
|
||||
_createClass(ResidualReactElements, [{
|
||||
key: "serializeReactElement",
|
||||
value: function serializeReactElement(val) {
|
||||
var typeValue = (0, _index.Get)(this.realm, val, "type");
|
||||
var keyValue = (0, _index.Get)(this.realm, val, "key");
|
||||
var refValue = (0, _index.Get)(this.realm, val, "ref");
|
||||
var propsValue = (0, _index.Get)(this.realm, val, "props");
|
||||
|
||||
(0, _invariant2.default)(typeValue !== null, "ReactElement type of null");
|
||||
|
||||
var attributes = [];
|
||||
var children = [];
|
||||
|
||||
if (keyValue !== null) {
|
||||
var keyExpr = this.residualHeapSerializer.serializeValue(keyValue);
|
||||
if (keyExpr.type !== "NullLiteral") {
|
||||
if (this.reactOutput === "jsx") {
|
||||
this._addSerializedValueToJSXAttriutes("key", keyExpr, attributes);
|
||||
} else if (this.reactOutput === "create-element") {
|
||||
this._addSerializedValueToObjectProperty("key", keyExpr, attributes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (refValue !== null) {
|
||||
var refExpr = this.residualHeapSerializer.serializeValue(refValue);
|
||||
if (refExpr.type !== "NullLiteral") {
|
||||
if (this.reactOutput === "jsx") {
|
||||
this._addSerializedValueToJSXAttriutes("ref", refExpr, attributes);
|
||||
} else if (this.reactOutput === "create-element") {
|
||||
this._addSerializedValueToObjectProperty("ref", refExpr, attributes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (propsValue instanceof _index2.ObjectValue) {
|
||||
// the propsValue is visited to get the properties, but we don't emit it as the object
|
||||
this.residualHeapSerializer.serializedValues.add(propsValue);
|
||||
// have to case propsValue to ObjectValue or Flow complains that propsValues can be null/undefined
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = propsValue.properties[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var _ref = _step.value;
|
||||
|
||||
var _ref2 = _slicedToArray(_ref, 2);
|
||||
|
||||
var key = _ref2[0];
|
||||
var propertyBinding = _ref2[1];
|
||||
|
||||
var desc = propertyBinding.descriptor;
|
||||
if (desc === undefined) continue; // deleted
|
||||
(0, _invariant2.default)(!(0, _index.IsAccessorDescriptor)(this.realm, desc), "expected descriptor to be a non-accessor property");
|
||||
|
||||
(0, _invariant2.default)(key !== "key" && key !== "ref", "\"" + key + "\" is a reserved prop name");
|
||||
|
||||
if (key === "children" && desc.value !== undefined) {
|
||||
var childrenValue = desc.value;
|
||||
if (childrenValue instanceof _index2.ArrayValue) {
|
||||
this.residualHeapSerializer.serializedValues.add(childrenValue);
|
||||
var childrenLength = (0, _index.Get)(this.realm, childrenValue, "length");
|
||||
var childrenLengthValue = 0;
|
||||
if (childrenLength instanceof _index2.NumberValue) {
|
||||
childrenLengthValue = childrenLength.value;
|
||||
for (var i = 0; i < childrenLengthValue; i++) {
|
||||
var child = (0, _index.Get)(this.realm, childrenValue, "" + i);
|
||||
if (child instanceof _index2.Value) {
|
||||
children.push(this._serializeReactElementChild(child));
|
||||
} else {
|
||||
this.logger.logError(val, "ReactElement \"props.children[" + i + "]\" failed to serialize due to a non-value");
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// otherwise it must be a value, as desc.value !== undefined.
|
||||
children.push(this._serializeReactElementChild(childrenValue));
|
||||
continue;
|
||||
}
|
||||
if (desc.value instanceof _index2.Value) {
|
||||
if (this.reactOutput === "jsx") {
|
||||
this._addSerializedValueToJSXAttriutes(key, this.residualHeapSerializer.serializeValue(desc.value), attributes);
|
||||
} else if (this.reactOutput === "create-element") {
|
||||
this._addSerializedValueToObjectProperty(key, this.residualHeapSerializer.serializeValue(desc.value), attributes);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var reactLibraryObject = this.realm.react.reactLibraryObject;
|
||||
var shouldHoist = this.residualHeapSerializer.currentFunctionBody !== this.residualHeapSerializer.mainBody && (0, _hoisting.canHoistReactElement)(this.realm, val);
|
||||
|
||||
var id = this.residualHeapSerializer.getSerializeObjectIdentifier(val);
|
||||
// this identifier is used as the deafult, but also passed to the hoisted factory function
|
||||
var originalCreateElementIdentifier = null;
|
||||
// this name is used when hoisting, and is passed into the factory function, rather than the original
|
||||
var hoistedCreateElementIdentifier = null;
|
||||
var reactElement = void 0;
|
||||
|
||||
if (this.reactOutput === "jsx") {
|
||||
reactElement = this._serializeReactElementToJSXElement(val, typeValue, attributes, children, reactLibraryObject);
|
||||
} else if (this.reactOutput === "create-element") {
|
||||
// if there is no React library, then we should throw and error, as it is needed for createElement output
|
||||
if (reactLibraryObject === undefined) {
|
||||
throw new _errors.FatalError("unable to serialize JSX to createElement due to React not being referenced in scope");
|
||||
}
|
||||
var createElement = (0, _index.Get)(this.realm, reactLibraryObject, "createElement");
|
||||
originalCreateElementIdentifier = this.residualHeapSerializer.serializeValue(createElement);
|
||||
if (shouldHoist) {
|
||||
// if we haven't created a _lazilyHoistedNodes before, then this is the first time
|
||||
// so we only create the hoisted identifier once
|
||||
if (this._lazilyHoistedNodes === undefined) {
|
||||
// create a new unique instance
|
||||
hoistedCreateElementIdentifier = t.identifier(this.residualHeapSerializer.intrinsicNameGenerator.generate());
|
||||
} else {
|
||||
hoistedCreateElementIdentifier = this._lazilyHoistedNodes.createElementIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
reactElement = this._serializeReactElementToCreateElement(val, typeValue, attributes, children, shouldHoist ? hoistedCreateElementIdentifier : originalCreateElementIdentifier);
|
||||
} else {
|
||||
(0, _invariant2.default)(false, "Unknown reactOutput specified");
|
||||
}
|
||||
// if we are hoisting this React element, put the assignment in the body
|
||||
// also ensure we are in an additional function
|
||||
if (shouldHoist) {
|
||||
// if the currentHoistedReactElements is not defined, we create it an emit the function call
|
||||
// this should only occur once per additional function
|
||||
if (this._lazilyHoistedNodes === undefined) {
|
||||
var funcId = t.identifier(this.residualHeapSerializer.functionNameGenerator.generate());
|
||||
this._lazilyHoistedNodes = {
|
||||
id: funcId,
|
||||
createElementIdentifier: hoistedCreateElementIdentifier,
|
||||
nodes: []
|
||||
};
|
||||
var statement = t.expressionStatement(t.logicalExpression("&&", t.binaryExpression("===", id, t.unaryExpression("void", t.numericLiteral(0), true)),
|
||||
// pass the createElementIdentifier if it's not null
|
||||
t.callExpression(funcId, originalCreateElementIdentifier ? [originalCreateElementIdentifier] : [])));
|
||||
this.residualHeapSerializer.emitter.emit(statement);
|
||||
}
|
||||
// we then push the reactElement and its id into our list of elements to process after
|
||||
// the current additional function has serialzied
|
||||
(0, _invariant2.default)(this._lazilyHoistedNodes !== undefined);
|
||||
(0, _invariant2.default)(Array.isArray(this._lazilyHoistedNodes.nodes));
|
||||
this._lazilyHoistedNodes.nodes.push({ id: id, astNode: reactElement });
|
||||
} else {
|
||||
var declar = t.variableDeclaration("var", [t.variableDeclarator(id, reactElement)]);
|
||||
this.residualHeapSerializer.emitter.emit(declar);
|
||||
}
|
||||
return reactElement;
|
||||
}
|
||||
}, {
|
||||
key: "_addSerializedValueToJSXAttriutes",
|
||||
value: function _addSerializedValueToJSXAttriutes(prop, expr, attributes) {
|
||||
attributes.push((0, _jsx.convertKeyValueToJSXAttribute)(prop, expr));
|
||||
}
|
||||
}, {
|
||||
key: "_addSerializedValueToObjectProperty",
|
||||
value: function _addSerializedValueToObjectProperty(prop, expr, attributes) {
|
||||
var key = void 0;
|
||||
|
||||
if (prop.includes("-")) {
|
||||
key = t.stringLiteral(prop);
|
||||
} else {
|
||||
key = t.identifier(prop);
|
||||
}
|
||||
attributes.push(t.objectProperty(key, expr));
|
||||
}
|
||||
}, {
|
||||
key: "_serializeReactElementToCreateElement",
|
||||
value: function _serializeReactElementToCreateElement(val, typeValue, attributes, children, createElementIdentifier) {
|
||||
var typeIdentifier = this.residualHeapSerializer.serializeValue(typeValue);
|
||||
var createElementArguments = [typeIdentifier];
|
||||
// check if we need to add attributes
|
||||
if (attributes.length !== 0) {
|
||||
// cast to any for createElementArguments as casting it to BabelNodeObjectProperty[] isn't working
|
||||
createElementArguments.push(t.objectExpression(attributes));
|
||||
}
|
||||
if (children.length !== 0) {
|
||||
if (attributes.length === 0) {
|
||||
createElementArguments.push(t.nullLiteral());
|
||||
}
|
||||
createElementArguments.push.apply(createElementArguments, _toConsumableArray(children));
|
||||
}
|
||||
// cast to any for createElementArguments as casting it to BabelNodeExpresion[] isn't working
|
||||
var createElementCall = t.callExpression(createElementIdentifier, createElementArguments);
|
||||
this._addBailOutMessageToBabelNode(val, createElementCall);
|
||||
return createElementCall;
|
||||
}
|
||||
}, {
|
||||
key: "_serializeReactElementToJSXElement",
|
||||
value: function _serializeReactElementToJSXElement(val, typeValue, attributes, children, reactLibraryObject) {
|
||||
if (reactLibraryObject !== undefined) {
|
||||
this.residualHeapSerializer.serializeValue(reactLibraryObject);
|
||||
}
|
||||
var identifier = (0, _jsx.convertExpressionToJSXIdentifier)(this.residualHeapSerializer.serializeValue(typeValue), true);
|
||||
var openingElement = t.jSXOpeningElement(identifier, attributes, children.length === 0);
|
||||
var closingElement = t.jSXClosingElement(identifier);
|
||||
|
||||
var jsxElement = t.jSXElement(openingElement, closingElement, children, children.length === 0);
|
||||
this._addBailOutMessageToBabelNode(val, jsxElement);
|
||||
return jsxElement;
|
||||
}
|
||||
}, {
|
||||
key: "_addBailOutMessageToBabelNode",
|
||||
value: function _addBailOutMessageToBabelNode(val, node) {
|
||||
// if there has been a bail-out, we create an inline BlockComment node before the JSX element
|
||||
if (val.$BailOutReason !== undefined) {
|
||||
// $BailOutReason contains an optional string of what to print out in the comment
|
||||
node.leadingComments = [{ type: "BlockComment", value: "" + val.$BailOutReason }];
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_serializeReactElementChild",
|
||||
value: function _serializeReactElementChild(child) {
|
||||
var expr = this.residualHeapSerializer.serializeValue(child);
|
||||
|
||||
if (this.reactOutput === "jsx") {
|
||||
if (t.isStringLiteral(expr) || t.isNumericLiteral(expr)) {
|
||||
return t.jSXText(expr.value + "");
|
||||
} else if (t.isJSXElement(expr)) {
|
||||
return expr;
|
||||
}
|
||||
return t.jSXExpressionContainer(expr);
|
||||
} else if (this.reactOutput === "create-element") {
|
||||
return expr;
|
||||
}
|
||||
(0, _invariant2.default)(false, "Unknown reactOutput specified");
|
||||
}
|
||||
}, {
|
||||
key: "serializeLazyHoistedNodes",
|
||||
value: function serializeLazyHoistedNodes() {
|
||||
var entries = [];
|
||||
if (this._lazilyHoistedNodes !== undefined) {
|
||||
var _lazilyHoistedNodes = this._lazilyHoistedNodes,
|
||||
id = _lazilyHoistedNodes.id,
|
||||
nodes = _lazilyHoistedNodes.nodes,
|
||||
createElementIdentifier = _lazilyHoistedNodes.createElementIdentifier;
|
||||
// create a function that initializes all the hoisted nodes
|
||||
|
||||
var func = t.functionExpression(null,
|
||||
// use createElementIdentifier if it's not null
|
||||
createElementIdentifier ? [createElementIdentifier] : [], t.blockStatement(nodes.map(function (node) {
|
||||
return t.expressionStatement(t.assignmentExpression("=", node.id, node.astNode));
|
||||
})));
|
||||
// push it to the mainBody of the module
|
||||
entries.push(t.variableDeclaration("var", [t.variableDeclarator(id, func)]));
|
||||
// output all the empty variable declarations that will hold the nodes lazily
|
||||
entries.push.apply(entries, _toConsumableArray(nodes.map(function (node) {
|
||||
return t.variableDeclaration("var", [t.variableDeclarator(node.id)]);
|
||||
})));
|
||||
// reset the _lazilyHoistedNodes so other additional functions work
|
||||
this._lazilyHoistedNodes = undefined;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
}]);
|
||||
|
||||
return ResidualReactElements;
|
||||
}();
|
||||
//# sourceMappingURL=ResidualReactElements.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/ResidualReactElements.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/ResidualReactElements.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
491
build/node_modules/prepack/lib/serializer/factorify.js
generated
vendored
Normal file
491
build/node_modules/prepack/lib/serializer/factorify.js
generated
vendored
Normal file
@@ -0,0 +1,491 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
exports.factorifyObjects = factorifyObjects;
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
var _generator = require("../utils/generator.js");
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function isLiteral(node) {
|
||||
switch (node.type) {
|
||||
case "NullLiteral":
|
||||
case "BooleanLiteral":
|
||||
case "StringLiteral":
|
||||
case "NumericLiteral":
|
||||
return true;
|
||||
case "UnaryExpression":
|
||||
return node.operator === "void" && isLiteral(node.argument);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isSameNode(left, right) {
|
||||
var type = left.type;
|
||||
|
||||
if (type !== right.type) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (type === "Identifier") {
|
||||
return left.name === right.name;
|
||||
}
|
||||
|
||||
if (type === "NullLiteral") {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type === "BooleanLiteral" || type === "StringLiteral" || type === "NumericLiteral") {
|
||||
return left.value === right.value;
|
||||
}
|
||||
|
||||
if (type === "UnaryExpression") {
|
||||
return left.operator === "void" && right.operator === "void" && isLiteral(left.argument) && isLiteral(right.argument);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function getObjectKeys(obj) {
|
||||
var keys = [];
|
||||
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = obj.properties[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var prop = _step.value;
|
||||
|
||||
if (prop.type !== "ObjectProperty") return false;
|
||||
|
||||
var key = prop.key;
|
||||
if (key.type === "StringLiteral") {
|
||||
keys.push(key.value);
|
||||
} else if (key.type === "Identifier") {
|
||||
if (prop.computed) return false;
|
||||
keys.push(key.name);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = keys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var key = _step2.value;
|
||||
|
||||
if (key.indexOf("|") >= 0) return false;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return keys.join("|");
|
||||
}
|
||||
|
||||
// This function looks for recurring initialization patterns in the code of the form
|
||||
// var x = { a: literal1, b: literal2 }
|
||||
// var y = { a: literal1, b: literal3 }
|
||||
// and transforms them into something like
|
||||
// function factory(b) { return { a: literal1, b } }
|
||||
// var x = factory(literal2);
|
||||
// var y = factory(literal3);
|
||||
// TODO #884: Right now, the visitor below only looks into top-level variable declaration
|
||||
// with a flat object literal initializer.
|
||||
// It should also look into conditional control flow, residual functions, and nested object literals.
|
||||
function factorifyObjects(body, factoryNameGenerator) {
|
||||
var signatures = Object.create(null);
|
||||
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = body[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var node = _step3.value;
|
||||
|
||||
switch (node.type) {
|
||||
case "VariableDeclaration":
|
||||
var _iteratorNormalCompletion10 = true;
|
||||
var _didIteratorError10 = false;
|
||||
var _iteratorError10 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator10 = node.declarations[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
|
||||
var _declar2 = _step10.value;
|
||||
var init = _declar2.init;
|
||||
|
||||
if (!init) continue;
|
||||
if (init.type !== "ObjectExpression") continue;
|
||||
|
||||
var _keys2 = getObjectKeys(init);
|
||||
if (!_keys2) continue;
|
||||
|
||||
var _initializerAstNodeName2 = "init";
|
||||
var _declars2 = signatures[_keys2] = signatures[_keys2] || [];
|
||||
_declars2.push({ declar: _declar2, initializerAstNodeName: _initializerAstNodeName2 });
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError10 = true;
|
||||
_iteratorError10 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion10 && _iterator10.return) {
|
||||
_iterator10.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError10) {
|
||||
throw _iteratorError10;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case "ExpressionStatement":
|
||||
var expr = node.expression;
|
||||
if (expr.type !== "AssignmentExpression") {
|
||||
break;
|
||||
}
|
||||
var right = expr.right;
|
||||
|
||||
if (right.type !== "ObjectExpression") {
|
||||
break;
|
||||
}
|
||||
|
||||
var _keys = getObjectKeys(right);
|
||||
if (!_keys) continue;
|
||||
|
||||
var _initializerAstNodeName = "right";
|
||||
var _declars = signatures[_keys] = signatures[_keys] || [];
|
||||
_declars.push({ declar: node.expression, initializerAstNodeName: _initializerAstNodeName });
|
||||
break;
|
||||
|
||||
default:
|
||||
// Continue to next node.
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var signatureKey in signatures) {
|
||||
var declars = signatures[signatureKey];
|
||||
if (declars.length < 5) continue;
|
||||
|
||||
var keys = signatureKey.split("|");
|
||||
|
||||
//
|
||||
var rootFactoryParams = [];
|
||||
var rootFactoryProps = [];
|
||||
for (var keyIndex = 0; keyIndex < keys.length; keyIndex++) {
|
||||
var key = keys[keyIndex];
|
||||
var id = t.identifier("__" + keyIndex);
|
||||
rootFactoryParams.push(id);
|
||||
var keyNode = t.isValidIdentifier(key) ? t.identifier(key) : t.stringLiteral(key);
|
||||
rootFactoryProps.push(t.objectProperty(keyNode, id));
|
||||
}
|
||||
|
||||
var rootFactoryId = t.identifier(factoryNameGenerator.generate("root"));
|
||||
var rootFactoryBody = t.blockStatement([t.returnStatement(t.objectExpression(rootFactoryProps))]);
|
||||
var rootFactory = t.functionDeclaration(rootFactoryId, rootFactoryParams, rootFactoryBody);
|
||||
body.unshift(rootFactory);
|
||||
|
||||
//
|
||||
var _iteratorNormalCompletion4 = true;
|
||||
var _didIteratorError4 = false;
|
||||
var _iteratorError4 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator4 = declars[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
|
||||
var _ref = _step4.value;
|
||||
var declar = _ref.declar,
|
||||
initializerAstNodeName = _ref.initializerAstNodeName;
|
||||
|
||||
var args = [];
|
||||
var _iteratorNormalCompletion6 = true;
|
||||
var _didIteratorError6 = false;
|
||||
var _iteratorError6 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator6 = declar[initializerAstNodeName].properties[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
|
||||
var prop = _step6.value;
|
||||
|
||||
args.push(prop.value);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError6 = true;
|
||||
_iteratorError6 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion6 && _iterator6.return) {
|
||||
_iterator6.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError6) {
|
||||
throw _iteratorError6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declar[initializerAstNodeName] = t.callExpression(rootFactoryId, args);
|
||||
}
|
||||
|
||||
//
|
||||
} catch (err) {
|
||||
_didIteratorError4 = true;
|
||||
_iteratorError4 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion4 && _iterator4.return) {
|
||||
_iterator4.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError4) {
|
||||
throw _iteratorError4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var seen = new Set();
|
||||
|
||||
var _loop = function _loop(_ref2) {
|
||||
var declar = _ref2.declar,
|
||||
initializerAstNodeName = _ref2.initializerAstNodeName;
|
||||
|
||||
if (seen.has(declar)) return "continue";
|
||||
|
||||
// build up a map containing the arguments that are shared
|
||||
var common = new Map();
|
||||
var mostSharedArgsLength = 0;
|
||||
var _iteratorNormalCompletion7 = true;
|
||||
var _didIteratorError7 = false;
|
||||
var _iteratorError7 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator7 = declars[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
|
||||
var _ref3 = _step7.value;
|
||||
var declar2 = _ref3.declar,
|
||||
initializerAstNodeName2 = _ref3.initializerAstNodeName;
|
||||
|
||||
if (seen.has(declar2)) continue;
|
||||
if (declar === declar2) continue;
|
||||
|
||||
var _sharedArgs = [];
|
||||
for (var _i = 0; _i < keys.length; _i++) {
|
||||
if (isSameNode(declar[initializerAstNodeName].arguments[_i], declar2[initializerAstNodeName2].arguments[_i])) {
|
||||
_sharedArgs.push(_i);
|
||||
}
|
||||
}
|
||||
if (!_sharedArgs.length) continue;
|
||||
|
||||
mostSharedArgsLength = Math.max(mostSharedArgsLength, _sharedArgs.length);
|
||||
common.set(declar2, _sharedArgs);
|
||||
}
|
||||
|
||||
// build up a mapping of the argument positions that are shared so we can pick the top one
|
||||
} catch (err) {
|
||||
_didIteratorError7 = true;
|
||||
_iteratorError7 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion7 && _iterator7.return) {
|
||||
_iterator7.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError7) {
|
||||
throw _iteratorError7;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var sharedPairs = Object.create(null);
|
||||
var _iteratorNormalCompletion8 = true;
|
||||
var _didIteratorError8 = false;
|
||||
var _iteratorError8 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator8 = common.entries()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
|
||||
var _ref4 = _step8.value;
|
||||
|
||||
var _ref5 = _slicedToArray(_ref4, 2);
|
||||
|
||||
var _declar = _ref5[0];
|
||||
var _args = _ref5[1];
|
||||
|
||||
if (_args.length === mostSharedArgsLength) {
|
||||
_args = _args.join(",");
|
||||
var _pair = sharedPairs[_args] = sharedPairs[_args] || [];
|
||||
_pair.push(_declar);
|
||||
}
|
||||
}
|
||||
|
||||
// get the highest pair
|
||||
} catch (err) {
|
||||
_didIteratorError8 = true;
|
||||
_iteratorError8 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion8 && _iterator8.return) {
|
||||
_iterator8.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError8) {
|
||||
throw _iteratorError8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var highestPairArgs = void 0;
|
||||
var highestPairCount = void 0;
|
||||
for (var pairArgs in sharedPairs) {
|
||||
var pair = sharedPairs[pairArgs];
|
||||
if (!highestPairArgs || pair.length > highestPairCount) {
|
||||
highestPairCount = pair.length;
|
||||
highestPairArgs = pairArgs;
|
||||
}
|
||||
}
|
||||
if (!highestPairArgs) return "continue";
|
||||
|
||||
//
|
||||
var declarsSub = sharedPairs[highestPairArgs].concat(declar);
|
||||
var removeArgs = highestPairArgs.split(",");
|
||||
|
||||
var subFactoryArgs = [];
|
||||
var subFactoryParams = [];
|
||||
var sharedArgs = declarsSub[0][initializerAstNodeName].arguments;
|
||||
for (var i = 0; i < sharedArgs.length; i++) {
|
||||
var arg = sharedArgs[i];
|
||||
if (removeArgs.indexOf(i + "") >= 0) {
|
||||
subFactoryArgs.push(arg);
|
||||
} else {
|
||||
var _id = t.identifier("__" + i);
|
||||
subFactoryArgs.push(_id);
|
||||
subFactoryParams.push(_id);
|
||||
}
|
||||
}
|
||||
|
||||
var subFactoryId = t.identifier(factoryNameGenerator.generate("sub"));
|
||||
var subFactoryBody = t.blockStatement([t.returnStatement(t.callExpression(rootFactoryId, subFactoryArgs))]);
|
||||
var subFactory = t.functionDeclaration(subFactoryId, subFactoryParams, subFactoryBody);
|
||||
body.unshift(subFactory);
|
||||
|
||||
var _iteratorNormalCompletion9 = true;
|
||||
var _didIteratorError9 = false;
|
||||
var _iteratorError9 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator9 = declarsSub[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
|
||||
var declarSub = _step9.value;
|
||||
|
||||
seen.add(declarSub);
|
||||
|
||||
var call = declarSub[initializerAstNodeName];
|
||||
call.callee = subFactoryId;
|
||||
call.arguments = call.arguments.filter(function (val, i) {
|
||||
return removeArgs.indexOf(i + "") < 0;
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError9 = true;
|
||||
_iteratorError9 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion9 && _iterator9.return) {
|
||||
_iterator9.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError9) {
|
||||
throw _iteratorError9;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var _iteratorNormalCompletion5 = true;
|
||||
var _didIteratorError5 = false;
|
||||
var _iteratorError5 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator5 = declars[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
|
||||
var _ref2 = _step5.value;
|
||||
|
||||
var _ret = _loop(_ref2);
|
||||
|
||||
if (_ret === "continue") continue;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError5 = true;
|
||||
_iteratorError5 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion5 && _iterator5.return) {
|
||||
_iterator5.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError5) {
|
||||
throw _iteratorError5;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=factorify.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/factorify.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/factorify.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
478
build/node_modules/prepack/lib/serializer/functions.js
generated
vendored
Normal file
478
build/node_modules/prepack/lib/serializer/functions.js
generated
vendored
Normal file
@@ -0,0 +1,478 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.Functions = undefined;
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _completions = require("../completions.js");
|
||||
|
||||
var _errors = require("../errors.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _errors2 = require("../utils/errors.js");
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _index2 = require("../methods/index.js");
|
||||
|
||||
var _modules = require("./modules.js");
|
||||
|
||||
var _babelTemplate = require("babel-template");
|
||||
|
||||
var _babelTemplate2 = _interopRequireDefault(_babelTemplate);
|
||||
|
||||
var _types = require("./types");
|
||||
|
||||
var _reconcilation = require("../react/reconcilation.js");
|
||||
|
||||
var _utils = require("../react/utils.js");
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
var Functions = exports.Functions = function () {
|
||||
function Functions(realm, functions, moduleTracer) {
|
||||
_classCallCheck(this, Functions);
|
||||
|
||||
this.realm = realm;
|
||||
this.functions = functions;
|
||||
this.moduleTracer = moduleTracer;
|
||||
this.writeEffects = new Map();
|
||||
this.functionExpressions = new Map();
|
||||
}
|
||||
// maps back from FunctionValue to the expression string
|
||||
|
||||
|
||||
_createClass(Functions, [{
|
||||
key: "_generateAdditionalFunctionCallsFromInput",
|
||||
value: function _generateAdditionalFunctionCallsFromInput() {
|
||||
var _this = this;
|
||||
|
||||
// lookup functions
|
||||
var calls = [];
|
||||
|
||||
var _loop = function _loop(fname) {
|
||||
var fun = void 0;
|
||||
var fnameAst = (0, _babelTemplate2.default)(fname)({}).expression;
|
||||
if (fnameAst) {
|
||||
try {
|
||||
var e = (0, _errors2.ignoreErrorsIn)(_this.realm, function () {
|
||||
return _this.realm.evaluateNodeForEffectsInGlobalEnv(fnameAst);
|
||||
});
|
||||
fun = e ? e[0] : undefined;
|
||||
} catch (ex) {
|
||||
if (!(ex instanceof _completions.ThrowCompletion)) throw ex;
|
||||
}
|
||||
}
|
||||
if (!(fun instanceof _index.FunctionValue)) {
|
||||
var error = new _errors.CompilerDiagnostic("Additional function " + fname + " not defined in the global environment", null, "PP1001", "FatalError");
|
||||
_this.realm.handleError(error);
|
||||
throw new _errors.FatalError();
|
||||
}
|
||||
_this.functionExpressions.set(fun, fname);
|
||||
var call = t.callExpression(fnameAst, []);
|
||||
calls.push([fun, call]);
|
||||
};
|
||||
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = (this.functions || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var fname = _step.value;
|
||||
|
||||
_loop(fname);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
// __reactComponentRoots
|
||||
|
||||
}, {
|
||||
key: "__generateAdditionalFunctions",
|
||||
value: function __generateAdditionalFunctions(globalKey) {
|
||||
var recordedAdditionalFunctions = new Map();
|
||||
var realm = this.realm;
|
||||
var globalRecordedAdditionalFunctionsMap = this.moduleTracer.modules.logger.tryQuery(function () {
|
||||
return (0, _index2.Get)(realm, realm.$GlobalObject, globalKey);
|
||||
}, realm.intrinsics.undefined, false);
|
||||
(0, _invariant2.default)(globalRecordedAdditionalFunctionsMap instanceof _index.ObjectValue);
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = globalRecordedAdditionalFunctionsMap.getOwnPropertyKeysArray()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var funcId = _step2.value;
|
||||
|
||||
var property = globalRecordedAdditionalFunctionsMap.properties.get(funcId);
|
||||
if (property) {
|
||||
var funcValue = property.descriptor && property.descriptor.value;
|
||||
if (!(funcValue instanceof _index.FunctionValue)) {
|
||||
(0, _invariant2.default)(funcValue instanceof _index.AbstractValue);
|
||||
realm.handleError(new _errors.CompilerDiagnostic("Additional Function Value " + funcId + " is an AbstractValue which is not allowed", undefined, "PP0001", "FatalError"));
|
||||
throw new _errors.FatalError("Additional Function values cannot be AbstractValues");
|
||||
}
|
||||
recordedAdditionalFunctions.set(funcValue, funcId);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return recordedAdditionalFunctions;
|
||||
}
|
||||
}, {
|
||||
key: "_createAdditionalEffects",
|
||||
value: function _createAdditionalEffects(effects) {
|
||||
return {
|
||||
effects: effects,
|
||||
transforms: []
|
||||
};
|
||||
}
|
||||
}, {
|
||||
key: "checkReactRootComponents",
|
||||
value: function checkReactRootComponents(statistics, react) {
|
||||
var recordedReactRootComponents = this.__generateAdditionalFunctions("__reactComponentRoots");
|
||||
|
||||
// Get write effects of the components
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = recordedReactRootComponents[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var _ref = _step3.value;
|
||||
|
||||
var _ref2 = _slicedToArray(_ref, 1);
|
||||
|
||||
var componentType = _ref2[0];
|
||||
|
||||
var simpleClassComponents = new Set();
|
||||
var reconciler = new _reconcilation.Reconciler(this.realm, this.moduleTracer, statistics, react, simpleClassComponents);
|
||||
(0, _invariant2.default)(componentType instanceof _index.ECMAScriptSourceFunctionValue, "only ECMAScriptSourceFunctionValue function values are supported as React root components");
|
||||
var effects = reconciler.render(componentType);
|
||||
var additionalFunctionEffects = this._createAdditionalEffects(effects);
|
||||
(0, _invariant2.default)(effects[0] instanceof _index.Value);
|
||||
if (simpleClassComponents.has(effects[0])) {
|
||||
// if the root component was a class and is now simple, we can convert it from a class
|
||||
// component to a functional component
|
||||
(0, _utils.convertSimpleClassComponentToFunctionalComponent)(this.realm, componentType, additionalFunctionEffects);
|
||||
this.writeEffects.set(componentType, additionalFunctionEffects);
|
||||
} else if ((0, _utils.valueIsClassComponent)(this.realm, componentType)) {
|
||||
var prototype = (0, _index2.Get)(this.realm, componentType, "prototype");
|
||||
(0, _invariant2.default)(prototype instanceof _index.ObjectValue);
|
||||
var renderMethod = (0, _index2.Get)(this.realm, prototype, "render");
|
||||
(0, _invariant2.default)(renderMethod instanceof _index.ECMAScriptSourceFunctionValue);
|
||||
this.writeEffects.set(renderMethod, additionalFunctionEffects);
|
||||
} else {
|
||||
this.writeEffects.set(componentType, additionalFunctionEffects);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_generateAdditionalFunctionCallsFromDirective",
|
||||
value: function _generateAdditionalFunctionCallsFromDirective() {
|
||||
var recordedAdditionalFunctions = this.__generateAdditionalFunctions("__additionalFunctions");
|
||||
|
||||
// The additional functions we registered at runtime are recorded at:
|
||||
// global.__additionalFunctions.id
|
||||
var calls = [];
|
||||
var _iteratorNormalCompletion4 = true;
|
||||
var _didIteratorError4 = false;
|
||||
var _iteratorError4 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator4 = recordedAdditionalFunctions[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
|
||||
var _ref3 = _step4.value;
|
||||
|
||||
var _ref4 = _slicedToArray(_ref3, 2);
|
||||
|
||||
var funcValue = _ref4[0];
|
||||
var funcId = _ref4[1];
|
||||
|
||||
// TODO #987: Make Additional Functions work with arguments
|
||||
calls.push([funcValue, t.callExpression(t.memberExpression(t.memberExpression(t.identifier("global"), t.identifier("__additionalFunctions")), t.identifier(funcId)), [])]);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError4 = true;
|
||||
_iteratorError4 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion4 && _iterator4.return) {
|
||||
_iterator4.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError4) {
|
||||
throw _iteratorError4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
}, {
|
||||
key: "checkThatFunctionsAreIndependent",
|
||||
value: function checkThatFunctionsAreIndependent() {
|
||||
var _this2 = this;
|
||||
|
||||
var calls = this._generateAdditionalFunctionCallsFromInput().concat(this._generateAdditionalFunctionCallsFromDirective());
|
||||
|
||||
// Get write effects of the functions
|
||||
|
||||
var _loop2 = function _loop2(funcValue, call) {
|
||||
// This may throw a FatalError if there is an unrecoverable error in the called function
|
||||
// When that happens we cannot prepack the bundle.
|
||||
// There may also be warnings reported for errors that happen inside imported modules that can be postponed.
|
||||
|
||||
var effects = _this2.realm.evaluatePure(function () {
|
||||
return _this2.realm.evaluateNodeForEffectsInGlobalEnv(call, _this2.moduleTracer, "additional function(" + funcValue.getName() + ")");
|
||||
});
|
||||
var additionalFunctionEffects = _this2._createAdditionalEffects(effects);
|
||||
_this2.writeEffects.set(funcValue, additionalFunctionEffects);
|
||||
};
|
||||
|
||||
var _iteratorNormalCompletion5 = true;
|
||||
var _didIteratorError5 = false;
|
||||
var _iteratorError5 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator5 = calls[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
|
||||
var _ref5 = _step5.value;
|
||||
|
||||
var _ref6 = _slicedToArray(_ref5, 2);
|
||||
|
||||
var funcValue = _ref6[0];
|
||||
var call = _ref6[1];
|
||||
|
||||
_loop2(funcValue, call);
|
||||
}
|
||||
|
||||
// check that functions are independent
|
||||
} catch (err) {
|
||||
_didIteratorError5 = true;
|
||||
_iteratorError5 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion5 && _iterator5.return) {
|
||||
_iterator5.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError5) {
|
||||
throw _iteratorError5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var conflicts = new Map();
|
||||
var _iteratorNormalCompletion6 = true;
|
||||
var _didIteratorError6 = false;
|
||||
var _iteratorError6 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator6 = calls[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
|
||||
var _ref7 = _step6.value;
|
||||
|
||||
var _ref8 = _slicedToArray(_ref7, 2);
|
||||
|
||||
var fun1 = _ref8[0];
|
||||
var call1 = _ref8[1];
|
||||
|
||||
// Also do argument validation here
|
||||
var funcLength = fun1.getLength();
|
||||
if (funcLength && funcLength > 0) {
|
||||
// TODO #987: Make Additional Functions work with arguments
|
||||
throw new _errors.FatalError("TODO: implement arguments to additional functions");
|
||||
}
|
||||
var additionalFunctionEffects = this.writeEffects.get(fun1);
|
||||
(0, _invariant2.default)(additionalFunctionEffects !== undefined);
|
||||
var e1 = additionalFunctionEffects.effects;
|
||||
(0, _invariant2.default)(e1 !== undefined);
|
||||
var fun1Name = this.functionExpressions.get(fun1) || fun1.intrinsicName || "unknown";
|
||||
if (e1[0] instanceof _completions.Completion) {
|
||||
var error = new _errors.CompilerDiagnostic("Additional function " + fun1Name + " may terminate abruptly", e1[0].location, "PP1002", "FatalError");
|
||||
this.realm.handleError(error);
|
||||
throw new _errors.FatalError();
|
||||
}
|
||||
var _iteratorNormalCompletion8 = true;
|
||||
var _didIteratorError8 = false;
|
||||
var _iteratorError8 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator8 = calls[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
|
||||
var _ref9 = _step8.value;
|
||||
|
||||
var _ref10 = _slicedToArray(_ref9, 2);
|
||||
|
||||
var call2 = _ref10[1];
|
||||
|
||||
if (call1 === call2) continue;
|
||||
this.reportWriteConflicts(fun1Name, conflicts, e1[3], call1, call2);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError8 = true;
|
||||
_iteratorError8 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion8 && _iterator8.return) {
|
||||
_iterator8.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError8) {
|
||||
throw _iteratorError8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError6 = true;
|
||||
_iteratorError6 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion6 && _iterator6.return) {
|
||||
_iterator6.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError6) {
|
||||
throw _iteratorError6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (conflicts.size > 0) {
|
||||
var _iteratorNormalCompletion7 = true;
|
||||
var _didIteratorError7 = false;
|
||||
var _iteratorError7 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator7 = conflicts.values()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
|
||||
var diagnostic = _step7.value;
|
||||
this.realm.handleError(diagnostic);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError7 = true;
|
||||
_iteratorError7 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion7 && _iterator7.return) {
|
||||
_iterator7.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError7) {
|
||||
throw _iteratorError7;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new _errors.FatalError();
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "getAdditionalFunctionValuesToEffects",
|
||||
value: function getAdditionalFunctionValuesToEffects() {
|
||||
return this.writeEffects;
|
||||
}
|
||||
}, {
|
||||
key: "reportWriteConflicts",
|
||||
value: function reportWriteConflicts(fname, conflicts, pbs, call1, call2) {
|
||||
var _this3 = this;
|
||||
|
||||
var reportConflict = function reportConflict(location) {
|
||||
var error = new _errors.CompilerDiagnostic("Property access conflicts with write in additional function " + fname, location, "PP1003", "FatalError");
|
||||
conflicts.set(location, error);
|
||||
};
|
||||
var writtenObjects = new Set();
|
||||
pbs.forEach(function (val, key, m) {
|
||||
writtenObjects.add(key.object);
|
||||
});
|
||||
var oldReportObjectGetOwnProperties = this.realm.reportObjectGetOwnProperties;
|
||||
this.realm.reportObjectGetOwnProperties = function (ob) {
|
||||
var location = _this3.realm.currentLocation;
|
||||
(0, _invariant2.default)(location);
|
||||
if (writtenObjects.has(ob) && !conflicts.has(location)) reportConflict(location);
|
||||
};
|
||||
var oldReportPropertyAccess = this.realm.reportPropertyAccess;
|
||||
this.realm.reportPropertyAccess = function (pb) {
|
||||
var location = _this3.realm.currentLocation;
|
||||
if (!location) return; // happens only when accessing an additional function property
|
||||
if (pbs.has(pb) && !conflicts.has(location)) reportConflict(location);
|
||||
};
|
||||
try {
|
||||
(0, _errors2.ignoreErrorsIn)(this.realm, function () {
|
||||
return _this3.realm.evaluateNodeForEffectsInGlobalEnv(call2, _this3.moduleTracer);
|
||||
});
|
||||
} finally {
|
||||
this.realm.reportPropertyAccess = oldReportPropertyAccess;
|
||||
this.realm.reportObjectGetOwnProperties = oldReportObjectGetOwnProperties;
|
||||
}
|
||||
}
|
||||
}]);
|
||||
|
||||
return Functions;
|
||||
}();
|
||||
//# sourceMappingURL=functions.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/functions.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/functions.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
17
build/node_modules/prepack/lib/serializer/index.js
generated
vendored
Normal file
17
build/node_modules/prepack/lib/serializer/index.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
var _serializer = require("./serializer.js");
|
||||
|
||||
exports.default = _serializer.Serializer; /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
//# sourceMappingURL=index.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/index.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/index.js.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/serializer/index.js"],"names":[],"mappings":";;;;;;AAWA;;0CAXA","file":"index.js","sourcesContent":["/**\n * Copyright (c) 2017-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n */\n\n/* @flow */\n\nimport { Serializer } from \"./serializer.js\";\nexport default Serializer;\n"]}
|
||||
161
build/node_modules/prepack/lib/serializer/logger.js
generated
vendored
Normal file
161
build/node_modules/prepack/lib/serializer/logger.js
generated
vendored
Normal file
@@ -0,0 +1,161 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.Logger = undefined;
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _errors = require("../errors.js");
|
||||
|
||||
var _index = require("../methods/index.js");
|
||||
|
||||
var _completions = require("../completions.js");
|
||||
|
||||
var _index2 = require("../values/index.js");
|
||||
|
||||
var _singletons = require("../singletons.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
var Logger = exports.Logger = function () {
|
||||
function Logger(realm, internalDebug) {
|
||||
_classCallCheck(this, Logger);
|
||||
|
||||
this.realm = realm;
|
||||
this._hasErrors = false;
|
||||
this.internalDebug = internalDebug;
|
||||
}
|
||||
|
||||
_createClass(Logger, [{
|
||||
key: "tryQuery",
|
||||
|
||||
|
||||
// Wraps a query that might potentially execute user code.
|
||||
value: function tryQuery(f, defaultValue, logFailures) {
|
||||
var _this = this;
|
||||
|
||||
var realm = this.realm;
|
||||
var context = new _realm.ExecutionContext();
|
||||
context.isStrict = realm.isStrict;
|
||||
var env = realm.$GlobalEnv;
|
||||
context.lexicalEnvironment = env;
|
||||
context.variableEnvironment = env;
|
||||
context.realm = realm;
|
||||
realm.pushContext(context);
|
||||
// We use partial evaluation so that we can throw away any state mutations
|
||||
var oldErrorHandler = realm.errorHandler;
|
||||
var _newErrorHandler = void 0;
|
||||
realm.errorHandler = _newErrorHandler = function newErrorHandler(d) {
|
||||
if (d.severity === "Information" || d.severity === "Warning") return "Recover";
|
||||
if (logFailures) {
|
||||
realm.errorHandler = oldErrorHandler;
|
||||
realm.handleError(d);
|
||||
realm.errorHandler = _newErrorHandler;
|
||||
}
|
||||
return "Fail";
|
||||
};
|
||||
try {
|
||||
var result = void 0;
|
||||
var effects = realm.evaluateForEffects(function () {
|
||||
try {
|
||||
result = f();
|
||||
} catch (e) {
|
||||
if (e instanceof _completions.Completion) {
|
||||
if (logFailures) _this.logCompletion(e);
|
||||
result = defaultValue;
|
||||
} else if (e instanceof _errors.FatalError) {
|
||||
result = defaultValue;
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return realm.intrinsics.undefined;
|
||||
});
|
||||
(0, _invariant2.default)(effects[0] === realm.intrinsics.undefined);
|
||||
return result;
|
||||
} finally {
|
||||
realm.errorHandler = oldErrorHandler;
|
||||
realm.popContext(context);
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "logCompletion",
|
||||
value: function logCompletion(res) {
|
||||
var realm = this.realm;
|
||||
var value = res.value;
|
||||
if (this.internalDebug) console.error("=== " + res.constructor.name + " ===");
|
||||
if (this.tryQuery(function () {
|
||||
return value instanceof _index2.ObjectValue && (0, _index.InstanceofOperator)(realm, value, realm.intrinsics.Error);
|
||||
}, false, false)) {
|
||||
var object = value;
|
||||
try {
|
||||
var err = new _errors.FatalError(this.tryQuery(function () {
|
||||
return _singletons.To.ToStringPartial(realm, (0, _index.Get)(realm, object, "message"));
|
||||
}, "(unknown message)", false));
|
||||
err.stack = this.tryQuery(function () {
|
||||
return _singletons.To.ToStringPartial(realm, (0, _index.Get)(realm, object, "stack"));
|
||||
}, "(unknown stack)", false);
|
||||
console.error(err.message);
|
||||
console.error(err.stack);
|
||||
if (this.internalDebug && res instanceof _completions.ThrowCompletion) console.error(res.nativeStack);
|
||||
} catch (err) {
|
||||
var message = object.properties.get("message");
|
||||
console.error(message && message.descriptor && message.descriptor.value instanceof _index2.StringValue ? message.descriptor.value.value : "(no message available)");
|
||||
console.error(err.stack);
|
||||
if (object.$ErrorData) {
|
||||
console.error(object.$ErrorData.contextStack);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
value = _singletons.To.ToStringPartial(realm, value);
|
||||
} catch (err) {
|
||||
value = err.message;
|
||||
}
|
||||
console.error(value);
|
||||
if (this.internalDebug && res instanceof _completions.ThrowCompletion) console.error(res.nativeStack);
|
||||
}
|
||||
this._hasErrors = true;
|
||||
}
|
||||
}, {
|
||||
key: "logError",
|
||||
value: function logError(value, message) {
|
||||
var loc = value.expressionLocation;
|
||||
if (loc) {
|
||||
var locString = loc.start.line + ":" + (loc.start.column + 1);
|
||||
if (loc.source) locString = loc.source + ":" + locString;
|
||||
message = message + "\nat: " + locString;
|
||||
} else if (value.intrinsicName) {
|
||||
message = message + "\nintrinsic name: " + value.intrinsicName;
|
||||
}
|
||||
|
||||
console.error(message);
|
||||
this._hasErrors = true;
|
||||
}
|
||||
}, {
|
||||
key: "hasErrors",
|
||||
value: function hasErrors() {
|
||||
return this._hasErrors;
|
||||
}
|
||||
}]);
|
||||
|
||||
return Logger;
|
||||
}();
|
||||
//# sourceMappingURL=logger.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/logger.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/logger.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
625
build/node_modules/prepack/lib/serializer/modules.js
generated
vendored
Normal file
625
build/node_modules/prepack/lib/serializer/modules.js
generated
vendored
Normal file
@@ -0,0 +1,625 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.Modules = exports.ModuleTracer = undefined;
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
|
||||
|
||||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
|
||||
|
||||
var _environment = require("../environment.js");
|
||||
|
||||
var _errors = require("../errors.js");
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _index = require("../methods/index.js");
|
||||
|
||||
var _completions = require("../completions.js");
|
||||
|
||||
var _singletons = require("../singletons.js");
|
||||
|
||||
var _index2 = require("../values/index.js");
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _logger = require("./logger.js");
|
||||
|
||||
var _types = require("./types.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
||||
|
||||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
function downgradeErrorsToWarnings(realm, f) {
|
||||
var savedHandler = realm.errorHandler;
|
||||
function handler(e) {
|
||||
e.severity = "Warning";
|
||||
realm.errorHandler = savedHandler;
|
||||
try {
|
||||
return realm.handleError(e);
|
||||
} finally {
|
||||
realm.errorHandler = handler;
|
||||
}
|
||||
}
|
||||
realm.errorHandler = handler;
|
||||
try {
|
||||
return f();
|
||||
} finally {
|
||||
realm.errorHandler = savedHandler;
|
||||
}
|
||||
}
|
||||
|
||||
var ModuleTracer = exports.ModuleTracer = function (_Tracer) {
|
||||
_inherits(ModuleTracer, _Tracer);
|
||||
|
||||
function ModuleTracer(modules, statistics, logModules) {
|
||||
_classCallCheck(this, ModuleTracer);
|
||||
|
||||
var _this = _possibleConstructorReturn(this, (ModuleTracer.__proto__ || Object.getPrototypeOf(ModuleTracer)).call(this));
|
||||
|
||||
_this.modules = modules;
|
||||
_this.evaluateForEffectsNesting = 0;
|
||||
_this.requireStack = [];
|
||||
_this.requireSequence = [];
|
||||
_this.logModules = logModules;
|
||||
_this.uninitializedModuleIdsRequiredInEvaluateForEffects = new Set();
|
||||
_this.statistics = statistics;
|
||||
return _this;
|
||||
}
|
||||
// We can't say that a module has been initialized if it was initialized in a
|
||||
// evaluate for effects context until we know the effects are applied.
|
||||
|
||||
|
||||
_createClass(ModuleTracer, [{
|
||||
key: "log",
|
||||
value: function log(message) {
|
||||
if (this.logModules) console.log("[modules] " + this.requireStack.map(function (_) {
|
||||
return " ";
|
||||
}).join("") + message);
|
||||
}
|
||||
}, {
|
||||
key: "beginEvaluateForEffects",
|
||||
value: function beginEvaluateForEffects(state) {
|
||||
if (state !== this) {
|
||||
this.log(">evaluate for effects");
|
||||
this.evaluateForEffectsNesting++;
|
||||
this.requireStack.push(undefined);
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "endEvaluateForEffects",
|
||||
value: function endEvaluateForEffects(state, effects) {
|
||||
if (state !== this) {
|
||||
var popped = this.requireStack.pop();
|
||||
(0, _invariant2.default)(popped === undefined);
|
||||
this.evaluateForEffectsNesting--;
|
||||
this.log("<evaluate for effects");
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "detourCall",
|
||||
value: function detourCall(F, thisArgument, argumentsList, newTarget, performCall) {
|
||||
var _this2 = this;
|
||||
|
||||
var realm = this.modules.realm;
|
||||
if (F === this.modules.getRequire() && !this.modules.disallowDelayingRequiresOverride && argumentsList.length === 1) {
|
||||
var moduleId = argumentsList[0];
|
||||
var moduleIdValue = void 0;
|
||||
if (moduleId instanceof _index2.NumberValue || moduleId instanceof _index2.StringValue) {
|
||||
moduleIdValue = moduleId.value;
|
||||
if (!this.modules.moduleIds.has(moduleIdValue) && this.modules.delayUnsupportedRequires) {
|
||||
this.modules.logger.logError(moduleId, "Module referenced by require call has not been defined.");
|
||||
}
|
||||
} else {
|
||||
if (this.modules.delayUnsupportedRequires) {
|
||||
this.modules.logger.logError(moduleId, "First argument to require function is not a number or string value.");
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!this.modules.delayUnsupportedRequires) {
|
||||
if ((this.requireStack.length === 0 || this.requireStack[this.requireStack.length - 1] !== moduleIdValue) && this.modules.moduleIds.has(moduleIdValue)) {
|
||||
this.requireStack.push(moduleIdValue);
|
||||
try {
|
||||
var value = performCall();
|
||||
this.modules.recordModuleInitialized(moduleIdValue, value);
|
||||
// Make this into a join point by suppressing the conditional exception.
|
||||
// TODO: delete this code and let the caller deal with the conditional exception.
|
||||
var completion = _singletons.Functions.incorporateSavedCompletion(realm, value);
|
||||
if (completion instanceof _completions.PossiblyNormalCompletion) {
|
||||
realm.stopEffectCapture(completion);
|
||||
var warning = new _errors.CompilerDiagnostic("Module import may fail with an exception", completion.location, "PP0018", "Warning");
|
||||
realm.handleError(warning);
|
||||
}
|
||||
return value;
|
||||
} finally {
|
||||
(0, _invariant2.default)(this.requireStack.pop() === moduleIdValue);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// If a require fails, recover from it and delay the factory call until runtime
|
||||
this.log(">require(" + moduleIdValue + ")");
|
||||
var isTopLevelRequire = this.requireStack.length === 0;
|
||||
if (this.evaluateForEffectsNesting > 0) {
|
||||
if (isTopLevelRequire) {
|
||||
var diagnostic = new _errors.CompilerDiagnostic("Non-deterministically conditional top-level require not currently supported", realm.currentLocation, "PP0017", "FatalError");
|
||||
realm.handleError(diagnostic);
|
||||
throw new _errors.FatalError();
|
||||
} else if (!this.modules.isModuleInitialized(moduleIdValue)) this.uninitializedModuleIdsRequiredInEvaluateForEffects.add(moduleIdValue);
|
||||
return undefined;
|
||||
} else {
|
||||
return downgradeErrorsToWarnings(realm, function () {
|
||||
var result = void 0;
|
||||
try {
|
||||
_this2.requireStack.push(moduleIdValue);
|
||||
var requireSequenceStart = _this2.requireSequence.length;
|
||||
_this2.requireSequence.push(moduleIdValue);
|
||||
var acceleratedModuleIds = void 0,
|
||||
effects = void 0;
|
||||
var previousNumDelayedModules = _this2.statistics.delayedModules;
|
||||
do {
|
||||
try {
|
||||
effects = realm.evaluateForEffects(function () {
|
||||
return performCall();
|
||||
}, _this2);
|
||||
} catch (e) {}
|
||||
|
||||
acceleratedModuleIds = [];
|
||||
if (isTopLevelRequire) {
|
||||
// We gathered all effects, but didn't apply them yet.
|
||||
// Let's check if there was any call to `require` in a
|
||||
// evaluate-for-effects context. If so, try to initialize
|
||||
// that module right now. Acceleration module initialization in this
|
||||
// way might not actually be desirable, but it works around
|
||||
// general prepack-limitations around joined abstract values involving
|
||||
// conditionals. Long term, Prepack needs to implement a notion of refinement
|
||||
// of conditional abstract values under the known path condition.
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = _this2.uninitializedModuleIdsRequiredInEvaluateForEffects[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var nestedModuleId = _step.value;
|
||||
|
||||
var nestedEffects = _this2.modules.tryInitializeModule(nestedModuleId, "accelerated initialization of conditional module " + nestedModuleId + " as it's required in an evaluate-for-effects context by module " + moduleIdValue);
|
||||
if (_this2.modules.accelerateUnsupportedRequires && nestedEffects !== undefined && nestedEffects[0] instanceof _index2.Value && _this2.modules.isModuleInitialized(nestedModuleId)) {
|
||||
acceleratedModuleIds.push(nestedModuleId);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_this2.uninitializedModuleIdsRequiredInEvaluateForEffects.clear();
|
||||
// Keep restarting for as long as we find additional modules to accelerate.
|
||||
if (acceleratedModuleIds.length > 0) {
|
||||
console.log("restarting require(" + moduleIdValue + ") after accelerating conditional require calls for " + acceleratedModuleIds.join());
|
||||
_this2.statistics.acceleratedModules += acceleratedModuleIds.length;
|
||||
}
|
||||
}
|
||||
} while (acceleratedModuleIds.length > 0);
|
||||
|
||||
if (effects === undefined || effects[0] instanceof _completions.AbruptCompletion) {
|
||||
console.log("delaying require(" + moduleIdValue + ")");
|
||||
_this2.statistics.delayedModules = previousNumDelayedModules + 1;
|
||||
// So we are about to emit a delayed require(...) call.
|
||||
// However, before we do that, let's try to require all modules that we
|
||||
// know this delayed require call will require.
|
||||
// This way, we ensure that those modules will be fully initialized
|
||||
// before the require call executes.
|
||||
// TODO #690: More needs to be done to make the delayUnsupportedRequires
|
||||
// feature completely safe. Open issues are:
|
||||
// 1) Side-effects on the heap of delayed factory functions are not discovered or rejected.
|
||||
// 2) While we do process an appropriate list of transitively required modules here,
|
||||
// it's likely just a subset / prefix of all transivitely required modules, as
|
||||
// more modules would have been required if the Introspection exception had not been thrown.
|
||||
// To be correct, those modules would have to be prepacked here as well.
|
||||
// TODO #798: Watch out for an upcoming change to the __d module declaration where the statically known
|
||||
// list of dependencies will be announced, so we'll no longer have to guess.
|
||||
var nestedModulesIds = new Set();
|
||||
for (var i = requireSequenceStart; i < _this2.requireSequence.length; i++) {
|
||||
var _nestedModuleId = _this2.requireSequence[i];
|
||||
if (nestedModulesIds.has(_nestedModuleId)) continue;
|
||||
nestedModulesIds.add(_nestedModuleId);
|
||||
_this2.modules.tryInitializeModule(_nestedModuleId, "initialization of module " + _nestedModuleId + " as it's required by module " + moduleIdValue);
|
||||
}
|
||||
|
||||
result = _index2.AbstractValue.createTemporalFromBuildFunction(realm, _index2.Value, [], function (_ref) {
|
||||
var _ref2 = _toArray(_ref);
|
||||
|
||||
return t.callExpression(t.identifier("require"), [t.valueToNode(moduleIdValue)]);
|
||||
});
|
||||
} else {
|
||||
result = effects[0];
|
||||
if (result instanceof _index2.Value) {
|
||||
realm.applyEffects(effects, "initialization of module " + moduleIdValue);
|
||||
_this2.modules.recordModuleInitialized(moduleIdValue, result);
|
||||
} else if (result instanceof _completions.PossiblyNormalCompletion) {
|
||||
var _warning = new _errors.CompilerDiagnostic("Module import may fail with an exception", result.location, "PP0018", "Warning");
|
||||
realm.handleError(_warning);
|
||||
result = result.value;
|
||||
realm.applyEffects(effects, "initialization of module " + moduleIdValue);
|
||||
_this2.modules.recordModuleInitialized(moduleIdValue, result);
|
||||
} else {
|
||||
(0, _invariant2.default)(false);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
var popped = _this2.requireStack.pop();
|
||||
(0, _invariant2.default)(popped === moduleIdValue);
|
||||
_this2.log("<require(" + moduleIdValue + ")");
|
||||
}
|
||||
(0, _invariant2.default)(result instanceof _index2.Value);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
} else if (F === this.modules.getDefine()) {
|
||||
if (this.evaluateForEffectsNesting !== 0) this.modules.logger.logError(F, "Defining a module in nested partial evaluation is not supported.");
|
||||
var factoryFunction = argumentsList[0];
|
||||
if (factoryFunction instanceof _index2.FunctionValue) this.modules.factoryFunctions.add(factoryFunction);else this.modules.logger.logError(factoryFunction, "First argument to define function is not a function value.");
|
||||
var _moduleId = argumentsList[1];
|
||||
if (_moduleId instanceof _index2.NumberValue || _moduleId instanceof _index2.StringValue) this.modules.moduleIds.add(_moduleId.value);else this.modules.logger.logError(_moduleId, "Second argument to define function is not a number or string value.");
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}]);
|
||||
|
||||
return ModuleTracer;
|
||||
}(_realm.Tracer);
|
||||
|
||||
var Modules = exports.Modules = function () {
|
||||
function Modules(realm, logger, statistics, logModules, delayUnsupportedRequires, accelerateUnsupportedRequires) {
|
||||
_classCallCheck(this, Modules);
|
||||
|
||||
this.realm = realm;
|
||||
this.logger = logger;
|
||||
this._require = realm.intrinsics.undefined;
|
||||
this._define = realm.intrinsics.undefined;
|
||||
this.factoryFunctions = new Set();
|
||||
this.moduleIds = new Set();
|
||||
this.initializedModules = new Map();
|
||||
realm.tracers.push(this.moduleTracer = new ModuleTracer(this, statistics, logModules));
|
||||
this.delayUnsupportedRequires = delayUnsupportedRequires;
|
||||
this.accelerateUnsupportedRequires = accelerateUnsupportedRequires;
|
||||
this.disallowDelayingRequiresOverride = false;
|
||||
}
|
||||
|
||||
_createClass(Modules, [{
|
||||
key: "resolveInitializedModules",
|
||||
value: function resolveInitializedModules() {
|
||||
this.initializedModules.clear();
|
||||
var globalInitializedModulesMap = this._getGlobalProperty("__initializedModules");
|
||||
(0, _invariant2.default)(globalInitializedModulesMap instanceof _index2.ObjectValue);
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = globalInitializedModulesMap.properties.keys()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var moduleId = _step2.value;
|
||||
|
||||
var property = globalInitializedModulesMap.properties.get(moduleId);
|
||||
(0, _invariant2.default)(property);
|
||||
var moduleValue = property.descriptor && property.descriptor.value;
|
||||
if (moduleValue instanceof _index2.Value) this.initializedModules.set(moduleId, moduleValue);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "_getGlobalProperty",
|
||||
value: function _getGlobalProperty(name) {
|
||||
if (this.active) return this.realm.intrinsics.undefined;
|
||||
this.active = true;
|
||||
try {
|
||||
var realm = this.realm;
|
||||
return this.logger.tryQuery(function () {
|
||||
return (0, _index.Get)(realm, realm.$GlobalObject, name);
|
||||
}, realm.intrinsics.undefined, false);
|
||||
} finally {
|
||||
this.active = false;
|
||||
}
|
||||
}
|
||||
}, {
|
||||
key: "getRequire",
|
||||
value: function getRequire() {
|
||||
if (!(this._require instanceof _index2.FunctionValue)) this._require = this._getGlobalProperty("require");
|
||||
return this._require;
|
||||
}
|
||||
}, {
|
||||
key: "getDefine",
|
||||
value: function getDefine() {
|
||||
if (!(this._define instanceof _index2.FunctionValue)) this._define = this._getGlobalProperty("__d");
|
||||
return this._define;
|
||||
}
|
||||
}, {
|
||||
key: "getIsRequire",
|
||||
value: function getIsRequire(formalParameters, functions) {
|
||||
var realm = this.realm;
|
||||
var logger = this.logger;
|
||||
var modules = this;
|
||||
return function (scope, node) {
|
||||
if (!t.isIdentifier(node.callee) || node.arguments.length !== 1 || !node.arguments[0]) return false;
|
||||
var argument = node.arguments[0];
|
||||
if (!t.isNumericLiteral(argument) && !t.isStringLiteral(argument)) return false;
|
||||
|
||||
(0, _invariant2.default)(node.callee);
|
||||
var innerName = node.callee.name;
|
||||
|
||||
var _loop = function _loop(f) {
|
||||
var scopedBinding = scope.getBinding(innerName);
|
||||
if (scopedBinding) {
|
||||
if (modules.factoryFunctions.has(f) && formalParameters[1] === scopedBinding.path.node) {
|
||||
(0, _invariant2.default)(scopedBinding.kind === "param");
|
||||
return "continue";
|
||||
}
|
||||
// The name binds to some local entity, but nothing we'd know what exactly it is
|
||||
return {
|
||||
v: false
|
||||
};
|
||||
}
|
||||
|
||||
var doesNotMatter = true;
|
||||
var reference = logger.tryQuery(function () {
|
||||
return _singletons.Environment.ResolveBinding(realm, innerName, doesNotMatter, f.$Environment);
|
||||
}, undefined, false);
|
||||
if (reference === undefined) {
|
||||
// We couldn't resolve as we came across some behavior that we cannot deal with abstractly
|
||||
return {
|
||||
v: false
|
||||
};
|
||||
}
|
||||
if (_singletons.Environment.IsUnresolvableReference(realm, reference)) return {
|
||||
v: false
|
||||
};
|
||||
var referencedBase = reference.base;
|
||||
var referencedName = reference.referencedName;
|
||||
if (typeof referencedName !== "string") return {
|
||||
v: false
|
||||
};
|
||||
var value = void 0;
|
||||
if (reference.base instanceof _environment.GlobalEnvironmentRecord) {
|
||||
value = logger.tryQuery(function () {
|
||||
return (0, _index.Get)(realm, realm.$GlobalObject, innerName);
|
||||
}, realm.intrinsics.undefined, false);
|
||||
} else {
|
||||
(0, _invariant2.default)(referencedBase instanceof _environment.DeclarativeEnvironmentRecord);
|
||||
var binding = referencedBase.bindings[referencedName];
|
||||
if (!binding.initialized) return {
|
||||
v: false
|
||||
};
|
||||
value = binding.value;
|
||||
}
|
||||
if (value !== modules.getRequire()) return {
|
||||
v: false
|
||||
};
|
||||
};
|
||||
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = functions[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var f = _step3.value;
|
||||
|
||||
var _ret = _loop(f);
|
||||
|
||||
switch (_ret) {
|
||||
case "continue":
|
||||
continue;
|
||||
|
||||
default:
|
||||
if ((typeof _ret === "undefined" ? "undefined" : _typeof(_ret)) === "object") return _ret.v;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
}
|
||||
}, {
|
||||
key: "recordModuleInitialized",
|
||||
value: function recordModuleInitialized(moduleId, value) {
|
||||
this.realm.assignToGlobal(t.memberExpression(t.memberExpression(t.identifier("global"), t.identifier("__initializedModules")), t.identifier("" + moduleId)), value);
|
||||
}
|
||||
}, {
|
||||
key: "tryInitializeModule",
|
||||
value: function tryInitializeModule(moduleId, message) {
|
||||
var _this3 = this;
|
||||
|
||||
var realm = this.realm;
|
||||
var previousDisallowDelayingRequiresOverride = this.disallowDelayingRequiresOverride;
|
||||
this.disallowDelayingRequiresOverride = true;
|
||||
return downgradeErrorsToWarnings(realm, function () {
|
||||
try {
|
||||
var _node = t.callExpression(t.identifier("require"), [t.valueToNode(moduleId)]);
|
||||
|
||||
var effects = realm.evaluateNodeForEffectsInGlobalEnv(_node);
|
||||
realm.applyEffects(effects, message);
|
||||
return effects;
|
||||
} catch (err) {
|
||||
if (err instanceof _errors.FatalError) return undefined;else throw err;
|
||||
} finally {
|
||||
_this3.disallowDelayingRequiresOverride = previousDisallowDelayingRequiresOverride;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, {
|
||||
key: "initializeMoreModules",
|
||||
value: function initializeMoreModules() {
|
||||
// partially evaluate all factory methods by calling require
|
||||
var count = 0;
|
||||
var _iteratorNormalCompletion4 = true;
|
||||
var _didIteratorError4 = false;
|
||||
var _iteratorError4 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator4 = this.moduleIds[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
|
||||
var moduleId = _step4.value;
|
||||
|
||||
if (this.initializedModules.has(moduleId)) continue;
|
||||
var effects = this.tryInitializeModule(moduleId, "Speculative initialization of module " + moduleId);
|
||||
if (effects === undefined) continue;
|
||||
var result = effects[0];
|
||||
if (!(result instanceof _index2.Value)) continue; // module might throw
|
||||
count++;
|
||||
this.initializedModules.set(moduleId, result);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError4 = true;
|
||||
_iteratorError4 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion4 && _iterator4.return) {
|
||||
_iterator4.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError4) {
|
||||
throw _iteratorError4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (count > 0) console.log("=== speculatively initialized " + count + " additional modules");
|
||||
}
|
||||
}, {
|
||||
key: "isModuleInitialized",
|
||||
value: function isModuleInitialized(moduleId) {
|
||||
var realm = this.realm;
|
||||
var oldReadOnly = realm.setReadOnly(true);
|
||||
var oldDisallowDelayingRequiresOverride = this.disallowDelayingRequiresOverride;
|
||||
this.disallowDelayingRequiresOverride = true;
|
||||
try {
|
||||
var _node2 = t.callExpression(t.identifier("require"), [t.valueToNode(moduleId)]);
|
||||
|
||||
var _realm$evaluateNodeFo = realm.evaluateNodeForEffectsInGlobalEnv(_node2),
|
||||
_realm$evaluateNodeFo2 = _slicedToArray(_realm$evaluateNodeFo, 5),
|
||||
compl = _realm$evaluateNodeFo2[0],
|
||||
generator = _realm$evaluateNodeFo2[1],
|
||||
bindings = _realm$evaluateNodeFo2[2],
|
||||
properties = _realm$evaluateNodeFo2[3],
|
||||
createdObjects = _realm$evaluateNodeFo2[4];
|
||||
// for lint unused
|
||||
|
||||
|
||||
(0, _invariant2.default)(bindings);
|
||||
|
||||
if (compl instanceof _completions.AbruptCompletion) return undefined;
|
||||
(0, _invariant2.default)(compl instanceof _index2.Value);
|
||||
|
||||
if (!generator.empty() || compl instanceof _index2.ObjectValue && createdObjects.has(compl)) return undefined;
|
||||
// Check for escaping property assignments, if none escape, we got an existing object
|
||||
var escapes = false;
|
||||
var _iteratorNormalCompletion5 = true;
|
||||
var _didIteratorError5 = false;
|
||||
var _iteratorError5 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator5 = properties[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
|
||||
var _ref3 = _step5.value;
|
||||
|
||||
var _ref4 = _slicedToArray(_ref3, 1);
|
||||
|
||||
var binding = _ref4[0];
|
||||
|
||||
var object = binding.object;
|
||||
(0, _invariant2.default)(object instanceof _index2.ObjectValue);
|
||||
if (!createdObjects.has(object)) escapes = true;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError5 = true;
|
||||
_iteratorError5 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion5 && _iterator5.return) {
|
||||
_iterator5.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError5) {
|
||||
throw _iteratorError5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (escapes) return undefined;
|
||||
|
||||
return compl;
|
||||
} catch (err) {
|
||||
if (err instanceof _errors.FatalError) return undefined;
|
||||
throw err;
|
||||
} finally {
|
||||
realm.setReadOnly(oldReadOnly);
|
||||
this.disallowDelayingRequiresOverride = oldDisallowDelayingRequiresOverride;
|
||||
}
|
||||
}
|
||||
}]);
|
||||
|
||||
return Modules;
|
||||
}();
|
||||
//# sourceMappingURL=modules.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/modules.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/modules.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
225
build/node_modules/prepack/lib/serializer/serializer.js
generated
vendored
Normal file
225
build/node_modules/prepack/lib/serializer/serializer.js
generated
vendored
Normal file
@@ -0,0 +1,225 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.Serializer = undefined;
|
||||
|
||||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _errors = require("../errors.js");
|
||||
|
||||
var _completions = require("../completions.js");
|
||||
|
||||
var _generator = require("../utils/generator.js");
|
||||
|
||||
var _babelGenerator = require("babel-generator");
|
||||
|
||||
var _babelGenerator2 = _interopRequireDefault(_babelGenerator);
|
||||
|
||||
var _traverseFast = require("../utils/traverse-fast.js");
|
||||
|
||||
var _traverseFast2 = _interopRequireDefault(_traverseFast);
|
||||
|
||||
var _utils = require("../flow/utils.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _types = require("./types.js");
|
||||
|
||||
var _functions = require("./functions.js");
|
||||
|
||||
var _logger = require("./logger.js");
|
||||
|
||||
var _modules = require("./modules.js");
|
||||
|
||||
var _LoggingTracer = require("./LoggingTracer.js");
|
||||
|
||||
var _ResidualHeapVisitor = require("./ResidualHeapVisitor.js");
|
||||
|
||||
var _ResidualHeapSerializer = require("./ResidualHeapSerializer.js");
|
||||
|
||||
var _ResidualHeapValueIdentifiers = require("./ResidualHeapValueIdentifiers.js");
|
||||
|
||||
var _LazyObjectsSerializer = require("./LazyObjectsSerializer.js");
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
var _ResidualHeapRefCounter = require("./ResidualHeapRefCounter");
|
||||
|
||||
var _ResidualHeapGraphGenerator = require("./ResidualHeapGraphGenerator");
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
var Serializer = exports.Serializer = function () {
|
||||
function Serializer(realm) {
|
||||
var serializerOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
|
||||
_classCallCheck(this, Serializer);
|
||||
|
||||
(0, _invariant2.default)(realm.useAbstractInterpretation);
|
||||
// Start tracking mutations
|
||||
realm.generator = new _generator.Generator(realm, "main");
|
||||
|
||||
this.realm = realm;
|
||||
this.logger = new _logger.Logger(this.realm, !!serializerOptions.internalDebug);
|
||||
this.statistics = new _types.SerializerStatistics();
|
||||
this.modules = new _modules.Modules(this.realm, this.logger, this.statistics, !!serializerOptions.logModules, !!serializerOptions.delayUnsupportedRequires, !!serializerOptions.accelerateUnsupportedRequires);
|
||||
this.functions = new _functions.Functions(this.realm, serializerOptions.additionalFunctions, this.modules.moduleTracer);
|
||||
if (serializerOptions.trace) this.realm.tracers.push(new _LoggingTracer.LoggingTracer(this.realm));
|
||||
|
||||
this.options = serializerOptions;
|
||||
this.react = {
|
||||
usedReactElementKeys: new Set()
|
||||
};
|
||||
}
|
||||
|
||||
_createClass(Serializer, [{
|
||||
key: "_execute",
|
||||
value: function _execute(sources) {
|
||||
var sourceMaps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
|
||||
|
||||
var realm = this.realm;
|
||||
|
||||
var _realm$$GlobalEnv$exe = realm.$GlobalEnv.executeSources(sources, "script", function (ast) {
|
||||
var realmPreludeGenerator = realm.preludeGenerator;
|
||||
(0, _invariant2.default)(realmPreludeGenerator);
|
||||
var forbiddenNames = realmPreludeGenerator.nameGenerator.forbiddenNames;
|
||||
(0, _traverseFast2.default)(ast, function (node) {
|
||||
if (!t.isIdentifier(node)) return false;
|
||||
|
||||
forbiddenNames.add(node.name);
|
||||
return true;
|
||||
});
|
||||
}),
|
||||
_realm$$GlobalEnv$exe2 = _slicedToArray(_realm$$GlobalEnv$exe, 2),
|
||||
res = _realm$$GlobalEnv$exe2[0],
|
||||
code = _realm$$GlobalEnv$exe2[1];
|
||||
|
||||
if (res instanceof _completions.AbruptCompletion) {
|
||||
var context = new _realm.ExecutionContext();
|
||||
realm.pushContext(context);
|
||||
try {
|
||||
this.logger.logCompletion(res);
|
||||
} finally {
|
||||
realm.popContext(context);
|
||||
}
|
||||
var diagnostic = new _errors.CompilerDiagnostic("Global code may end abruptly", res.location, "PP0016", "FatalError");
|
||||
realm.handleError(diagnostic);
|
||||
throw new _errors.FatalError();
|
||||
}
|
||||
return code;
|
||||
}
|
||||
}, {
|
||||
key: "init",
|
||||
value: function init(sources) {
|
||||
var sourceMaps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
|
||||
|
||||
// Phase 1: Let's interpret.
|
||||
var timingStats = this.options.profile ? new _types.TimingStatistics() : undefined;
|
||||
if (timingStats !== undefined) {
|
||||
timingStats.totalTime = Date.now();
|
||||
timingStats.globalCodeTime = Date.now();
|
||||
}
|
||||
var code = this._execute(sources);
|
||||
if (timingStats !== undefined) timingStats.globalCodeTime = Date.now() - timingStats.globalCodeTime;
|
||||
if (this.logger.hasErrors()) return undefined;
|
||||
this.modules.resolveInitializedModules();
|
||||
this.functions.checkThatFunctionsAreIndependent();
|
||||
var reactStatistics = null;
|
||||
if (this.realm.react.enabled) {
|
||||
reactStatistics = new _types.ReactStatistics();
|
||||
this.functions.checkReactRootComponents(reactStatistics, this.react);
|
||||
}
|
||||
|
||||
if (this.options.initializeMoreModules) {
|
||||
if (timingStats !== undefined) timingStats.initializeMoreModulesTime = Date.now();
|
||||
this.modules.initializeMoreModules();
|
||||
if (this.logger.hasErrors()) return undefined;
|
||||
if (timingStats !== undefined) timingStats.initializeMoreModulesTime = Date.now() - timingStats.initializeMoreModulesTime;
|
||||
}
|
||||
|
||||
var additionalFunctionValuesAndEffects = this.functions.getAdditionalFunctionValuesToEffects();
|
||||
//Deep traversal of the heap to identify the necessary scope of residual functions
|
||||
if (timingStats !== undefined) timingStats.deepTraversalTime = Date.now();
|
||||
var residualHeapVisitor = new _ResidualHeapVisitor.ResidualHeapVisitor(this.realm, this.logger, this.modules, additionalFunctionValuesAndEffects);
|
||||
residualHeapVisitor.visitRoots();
|
||||
if (this.logger.hasErrors()) return undefined;
|
||||
if (timingStats !== undefined) timingStats.deepTraversalTime = Date.now() - timingStats.deepTraversalTime;
|
||||
|
||||
var realmPreludeGenerator = this.realm.preludeGenerator;
|
||||
(0, _invariant2.default)(realmPreludeGenerator);
|
||||
var residualHeapValueIdentifiers = new _ResidualHeapValueIdentifiers.ResidualHeapValueIdentifiers(residualHeapVisitor.values.keys(), realmPreludeGenerator);
|
||||
|
||||
var heapGraph = void 0;
|
||||
if (this.options.heapGraphFormat) {
|
||||
var heapRefCounter = new _ResidualHeapRefCounter.ResidualHeapRefCounter(this.realm, this.logger, this.modules, additionalFunctionValuesAndEffects);
|
||||
heapRefCounter.visitRoots();
|
||||
|
||||
var heapGraphGenerator = new _ResidualHeapGraphGenerator.ResidualHeapGraphGenerator(this.realm, this.logger, this.modules, additionalFunctionValuesAndEffects, residualHeapValueIdentifiers, heapRefCounter.getResult());
|
||||
heapGraphGenerator.visitRoots();
|
||||
(0, _invariant2.default)(this.options.heapGraphFormat);
|
||||
heapGraph = heapGraphGenerator.generateResult(this.options.heapGraphFormat);
|
||||
}
|
||||
|
||||
// Phase 2: Let's serialize the heap and generate code.
|
||||
// Serialize for the first time in order to gather reference counts
|
||||
|
||||
if (this.options.inlineExpressions) {
|
||||
if (timingStats !== undefined) timingStats.referenceCountsTime = Date.now();
|
||||
residualHeapValueIdentifiers.initPass1();
|
||||
new _ResidualHeapSerializer.ResidualHeapSerializer(this.realm, this.logger, this.modules, residualHeapValueIdentifiers, residualHeapVisitor.inspector, residualHeapVisitor.values, residualHeapVisitor.functionInstances, residualHeapVisitor.functionInfos, this.options, residualHeapVisitor.referencedDeclaredValues, additionalFunctionValuesAndEffects, residualHeapVisitor.additionalFunctionValueInfos, residualHeapVisitor.declarativeEnvironmentRecordsBindings, this.statistics, this.react).serialize();
|
||||
if (this.logger.hasErrors()) return undefined;
|
||||
if (timingStats !== undefined) timingStats.referenceCountsTime = Date.now() - timingStats.referenceCountsTime;
|
||||
residualHeapValueIdentifiers.initPass2();
|
||||
}
|
||||
|
||||
// Serialize for a second time, using reference counts to minimize number of generated identifiers
|
||||
if (timingStats !== undefined) timingStats.serializePassTime = Date.now();
|
||||
var TargetSerializer = this.options.lazyObjectsRuntime != null ? _LazyObjectsSerializer.LazyObjectsSerializer : _ResidualHeapSerializer.ResidualHeapSerializer;
|
||||
var residualHeapSerializer = new TargetSerializer(this.realm, this.logger, this.modules, residualHeapValueIdentifiers, residualHeapVisitor.inspector, residualHeapVisitor.values, residualHeapVisitor.functionInstances, residualHeapVisitor.functionInfos, this.options, residualHeapVisitor.referencedDeclaredValues, additionalFunctionValuesAndEffects, residualHeapVisitor.additionalFunctionValueInfos, residualHeapVisitor.declarativeEnvironmentRecordsBindings, this.statistics, this.react);
|
||||
|
||||
var ast = residualHeapSerializer.serialize();
|
||||
if (this.realm.react.enabled && this.realm.react.flowRequired) {
|
||||
(0, _utils.stripFlowTypeAnnotations)(ast);
|
||||
}
|
||||
var generated = (0, _babelGenerator2.default)(ast, { sourceMaps: sourceMaps }, code);
|
||||
if (timingStats !== undefined) {
|
||||
timingStats.serializePassTime = Date.now() - timingStats.serializePassTime;
|
||||
timingStats.totalTime = Date.now() - timingStats.totalTime;
|
||||
}
|
||||
(0, _invariant2.default)(!this.logger.hasErrors());
|
||||
if (this.options.logStatistics) residualHeapSerializer.statistics.log();
|
||||
return {
|
||||
code: generated.code,
|
||||
map: generated.map,
|
||||
reactStatistics: reactStatistics,
|
||||
statistics: residualHeapSerializer.statistics,
|
||||
timingStats: timingStats,
|
||||
heapGraph: heapGraph
|
||||
};
|
||||
}
|
||||
}]);
|
||||
|
||||
return Serializer;
|
||||
}();
|
||||
//# sourceMappingURL=serializer.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/serializer.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/serializer.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
111
build/node_modules/prepack/lib/serializer/types.js
generated
vendored
Normal file
111
build/node_modules/prepack/lib/serializer/types.js
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.SerializerStatistics = exports.ReactStatistics = exports.TimingStatistics = exports.BodyReference = undefined;
|
||||
|
||||
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
exports.AreSameResidualBinding = AreSameResidualBinding;
|
||||
|
||||
var _environment = require("../environment.js");
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _abstract = require("../methods/abstract.js");
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
||||
|
||||
// TODO: add type for additional functions.
|
||||
function AreSameResidualBinding(realm, x, y) {
|
||||
if (x.serializedValue === y.serializedValue) return true;
|
||||
if (x.value && x.value === y.value) return true;
|
||||
if (x.value instanceof _index.ConcreteValue && y.value instanceof _index.ConcreteValue) {
|
||||
return (0, _abstract.SameValue)(realm, x.value, y.value);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
var BodyReference = exports.BodyReference = function () {
|
||||
function BodyReference(body, index) {
|
||||
_classCallCheck(this, BodyReference);
|
||||
|
||||
(0, _invariant2.default)(index >= 0);
|
||||
this.body = body;
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
_createClass(BodyReference, [{
|
||||
key: "isNotEarlierThan",
|
||||
value: function isNotEarlierThan(other) {
|
||||
return this.body === other.body && this.index >= other.index;
|
||||
}
|
||||
}]);
|
||||
|
||||
return BodyReference;
|
||||
}();
|
||||
|
||||
var TimingStatistics = exports.TimingStatistics = function TimingStatistics() {
|
||||
_classCallCheck(this, TimingStatistics);
|
||||
|
||||
this.totalTime = 0;
|
||||
this.globalCodeTime = 0;
|
||||
this.initializeMoreModulesTime = 0;
|
||||
this.deepTraversalTime = 0;
|
||||
this.referenceCountsTime = 0;
|
||||
this.serializePassTime = 0;
|
||||
};
|
||||
|
||||
var ReactStatistics = exports.ReactStatistics = function ReactStatistics() {
|
||||
_classCallCheck(this, ReactStatistics);
|
||||
|
||||
this.optimizedTrees = 0;
|
||||
this.inlinedComponents = 0;
|
||||
};
|
||||
|
||||
var SerializerStatistics = exports.SerializerStatistics = function () {
|
||||
function SerializerStatistics() {
|
||||
_classCallCheck(this, SerializerStatistics);
|
||||
|
||||
this.objects = 0;
|
||||
this.objectProperties = 0;
|
||||
this.functions = 0;
|
||||
this.functionClones = 0;
|
||||
this.referentialized = 0;
|
||||
this.valueIds = 0;
|
||||
this.valuesInlined = 0;
|
||||
this.delayedValues = 0;
|
||||
this.acceleratedModules = 0;
|
||||
this.delayedModules = 0;
|
||||
}
|
||||
|
||||
_createClass(SerializerStatistics, [{
|
||||
key: "log",
|
||||
value: function log() {
|
||||
console.log("=== serialization statistics");
|
||||
console.log(this.objects + " objects with " + this.objectProperties + " properties");
|
||||
console.log(this.functions + " functions plus " + this.functionClones + " clones due to captured variables; " + this.referentialized + " captured mutable variables");
|
||||
console.log(this.valueIds + " eager and " + this.delayedValues + " delayed value ids generated, and " + this.valuesInlined + " values inlined");
|
||||
console.log(this.acceleratedModules + " accelerated and " + this.delayedModules + " delayed modules.");
|
||||
}
|
||||
}]);
|
||||
|
||||
return SerializerStatistics;
|
||||
}();
|
||||
//# sourceMappingURL=types.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/types.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/types.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
113
build/node_modules/prepack/lib/serializer/utils.js
generated
vendored
Normal file
113
build/node_modules/prepack/lib/serializer/utils.js
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.getSuggestedArrayLiteralLength = getSuggestedArrayLiteralLength;
|
||||
exports.commonAncestorOf = commonAncestorOf;
|
||||
exports.getOrDefault = getOrDefault;
|
||||
|
||||
var _invariant = require("../invariant.js");
|
||||
|
||||
var _invariant2 = _interopRequireDefault(_invariant);
|
||||
|
||||
var _index = require("../methods/index.js");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Get index property list length by searching array properties list for the max index key value plus 1.
|
||||
*/
|
||||
/**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
function getSuggestedArrayLiteralLength(realm, val) {
|
||||
(0, _invariant2.default)((0, _index.IsArray)(realm, val));
|
||||
|
||||
var length = 0;
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = val.properties.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var key = _step.value;
|
||||
|
||||
if ((0, _index.IsArrayIndex)(realm, key) && Number(key) >= length) {
|
||||
length = Number(key) + 1;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
function commonAncestorOf(node1, node2) {
|
||||
if (node1 === node2) return node1;
|
||||
// First get the path length to the root node for both nodes while also checking if
|
||||
// either node is the parent of the other.
|
||||
var n1 = node1,
|
||||
n2 = node2,
|
||||
count1 = 0,
|
||||
count2 = 0;
|
||||
while (true) {
|
||||
var p1 = n1 && n1.getParent();
|
||||
var p2 = n2 && n2.getParent();
|
||||
if (p1 === node2) return node2;
|
||||
if (p2 === node1) return node1;
|
||||
if (p1) count1++;
|
||||
if (p2) count2++;
|
||||
if (!p1 && !p2) break;
|
||||
n1 = p1;
|
||||
n2 = p2;
|
||||
}
|
||||
// Now shorten the longest path to the same length as the shorter path
|
||||
n1 = node1;
|
||||
while (count1 > count2) {
|
||||
(0, _invariant2.default)(n1 !== undefined);
|
||||
n1 = n1.getParent();
|
||||
count1--;
|
||||
}
|
||||
n2 = node2;
|
||||
while (count1 < count2) {
|
||||
(0, _invariant2.default)(n2 !== undefined);
|
||||
n2 = n2.getParent();
|
||||
count2--;
|
||||
}
|
||||
// Now run up both paths in tandem, stopping at the first common entry
|
||||
while (n1 !== n2) {
|
||||
(0, _invariant2.default)(n1 !== undefined);
|
||||
n1 = n1.getParent();
|
||||
(0, _invariant2.default)(n2 !== undefined);
|
||||
n2 = n2.getParent();
|
||||
}
|
||||
return n1;
|
||||
}
|
||||
|
||||
// Gets map[key] with default value provided by defaultFn
|
||||
function getOrDefault(map, key, defaultFn) {
|
||||
var value = map.get(key);
|
||||
if (value === undefined) map.set(key, value = defaultFn());
|
||||
(0, _invariant2.default)(value !== undefined);
|
||||
return value;
|
||||
}
|
||||
//# sourceMappingURL=utils.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/utils.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/utils.js.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/serializer/utils.js"],"names":["getSuggestedArrayLiteralLength","commonAncestorOf","getOrDefault","realm","val","length","properties","keys","key","Number","node1","node2","n1","n2","count1","count2","p1","getParent","p2","undefined","map","defaultFn","value","get","set"],"mappings":";;;;;QAoBgBA,8B,GAAAA,8B;QAcAC,gB,GAAAA,gB;QA2CAC,Y,GAAAA,Y;;AA/DhB;;;;AACA;;;;AAEA;;;AAjBA;;;;;;;;;AAoBO,SAASF,8BAAT,CAAwCG,KAAxC,EAAsDC,GAAtD,EAAgF;AACrF,2BAAU,oBAAQD,KAAR,EAAeC,GAAf,CAAV;;AAEA,MAAIC,SAAS,CAAb;AAHqF;AAAA;AAAA;;AAAA;AAIrF,yBAAkBD,IAAIE,UAAJ,CAAeC,IAAf,EAAlB,8HAAyC;AAAA,UAA9BC,GAA8B;;AACvC,UAAI,yBAAaL,KAAb,EAAoBK,GAApB,KAA4BC,OAAOD,GAAP,KAAeH,MAA/C,EAAuD;AACrDA,iBAASI,OAAOD,GAAP,IAAc,CAAvB;AACD;AACF;AARoF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AASrF,SAAOH,MAAP;AACD;;AAIM,SAASJ,gBAAT,CAAwCS,KAAxC,EAAyDC,KAAzD,EAAoF;AACzF,MAAID,UAAUC,KAAd,EAAqB,OAAOD,KAAP;AACrB;AACA;AACA,MAAIE,KAAKF,KAAT;AAAA,MACEG,KAAKF,KADP;AAAA,MAEEG,SAAS,CAFX;AAAA,MAGEC,SAAS,CAHX;AAIA,SAAO,IAAP,EAAa;AACX,QAAIC,KAAKJ,MAAMA,GAAGK,SAAH,EAAf;AACA,QAAIC,KAAKL,MAAMA,GAAGI,SAAH,EAAf;AACA,QAAID,OAAOL,KAAX,EAAkB,OAAOA,KAAP;AAClB,QAAIO,OAAOR,KAAX,EAAkB,OAAOA,KAAP;AAClB,QAAIM,EAAJ,EAAQF;AACR,QAAII,EAAJ,EAAQH;AACR,QAAI,CAACC,EAAD,IAAO,CAACE,EAAZ,EAAgB;AAChBN,SAAKI,EAAL;AACAH,SAAKK,EAAL;AACD;AACD;AACAN,OAAKF,KAAL;AACA,SAAOI,SAASC,MAAhB,EAAwB;AACtB,6BAAUH,OAAOO,SAAjB;AACAP,SAAKA,GAAGK,SAAH,EAAL;AACAH;AACD;AACDD,OAAKF,KAAL;AACA,SAAOG,SAASC,MAAhB,EAAwB;AACtB,6BAAUF,OAAOM,SAAjB;AACAN,SAAKA,GAAGI,SAAH,EAAL;AACAF;AACD;AACD;AACA,SAAOH,OAAOC,EAAd,EAAkB;AAChB,6BAAUD,OAAOO,SAAjB;AACAP,SAAKA,GAAGK,SAAH,EAAL;AACA,6BAAUJ,OAAOM,SAAjB;AACAN,SAAKA,GAAGI,SAAH,EAAL;AACD;AACD,SAAOL,EAAP;AACD;;AAED;AACO,SAASV,YAAT,CAA4BkB,GAA5B,EAA4CZ,GAA5C,EAAoDa,SAApD,EAA2E;AAChF,MAAIC,QAAQF,IAAIG,GAAJ,CAAQf,GAAR,CAAZ;AACA,MAAIc,UAAUH,SAAd,EAAyBC,IAAII,GAAJ,CAAQhB,GAAR,EAAcc,QAAQD,WAAtB;AACzB,2BAAUC,UAAUH,SAApB;AACA,SAAOG,KAAP;AACD","file":"utils.js","sourcesContent":["/**\n * Copyright (c) 2017-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n */\n\n/* @flow */\n\nimport type { ObjectValue } from \"../values/index.js\";\nimport type { Realm } from \"../realm.js\";\n\nimport invariant from \"../invariant.js\";\nimport { IsArray, IsArrayIndex } from \"../methods/index.js\";\n\n/**\n * Get index property list length by searching array properties list for the max index key value plus 1.\n */\nexport function getSuggestedArrayLiteralLength(realm: Realm, val: ObjectValue): number {\n invariant(IsArray(realm, val));\n\n let length = 0;\n for (const key of val.properties.keys()) {\n if (IsArrayIndex(realm, key) && Number(key) >= length) {\n length = Number(key) + 1;\n }\n }\n return length;\n}\n\ninterface HasParent { getParent(): void | HasParent }\n\nexport function commonAncestorOf<T: HasParent>(node1: void | T, node2: void | T): void | T {\n if (node1 === node2) return node1;\n // First get the path length to the root node for both nodes while also checking if\n // either node is the parent of the other.\n let n1 = node1,\n n2 = node2,\n count1 = 0,\n count2 = 0;\n while (true) {\n let p1 = n1 && n1.getParent();\n let p2 = n2 && n2.getParent();\n if (p1 === node2) return node2;\n if (p2 === node1) return node1;\n if (p1) count1++;\n if (p2) count2++;\n if (!p1 && !p2) break;\n n1 = p1;\n n2 = p2;\n }\n // Now shorten the longest path to the same length as the shorter path\n n1 = node1;\n while (count1 > count2) {\n invariant(n1 !== undefined);\n n1 = n1.getParent();\n count1--;\n }\n n2 = node2;\n while (count1 < count2) {\n invariant(n2 !== undefined);\n n2 = n2.getParent();\n count2--;\n }\n // Now run up both paths in tandem, stopping at the first common entry\n while (n1 !== n2) {\n invariant(n1 !== undefined);\n n1 = n1.getParent();\n invariant(n2 !== undefined);\n n2 = n2.getParent();\n }\n return n1;\n}\n\n// Gets map[key] with default value provided by defaultFn\nexport function getOrDefault<K, V>(map: Map<K, V>, key: K, defaultFn: () => V): V {\n let value = map.get(key);\n if (value === undefined) map.set(key, (value = defaultFn()));\n invariant(value !== undefined);\n return value;\n}\n"]}
|
||||
239
build/node_modules/prepack/lib/serializer/visitors.js
generated
vendored
Normal file
239
build/node_modules/prepack/lib/serializer/visitors.js
generated
vendored
Normal file
@@ -0,0 +1,239 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.ClosureRefVisitor = exports.ClosureRefReplacer = undefined;
|
||||
|
||||
var _realm = require("../realm.js");
|
||||
|
||||
var _index = require("../values/index.js");
|
||||
|
||||
var _babelTypes = require("babel-types");
|
||||
|
||||
var t = _interopRequireWildcard(_babelTypes);
|
||||
|
||||
var _jsx = require("../react/jsx");
|
||||
|
||||
var _internalizer = require("../utils/internalizer.js");
|
||||
|
||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
|
||||
|
||||
function markVisited(node, data) {
|
||||
node._renamedOnce = data;
|
||||
} /**
|
||||
* Copyright (c) 2017-present, Facebook, Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This source code is licensed under the BSD-style license found in the
|
||||
* LICENSE file in the root directory of this source tree. An additional grant
|
||||
* of patent rights can be found in the PATENTS file in the same directory.
|
||||
*/
|
||||
|
||||
function shouldVisit(node, data) {
|
||||
return node._renamedOnce !== data;
|
||||
}
|
||||
|
||||
// replaceWith causes the node to be re-analyzed, so to prevent double replacement
|
||||
// we add this property on the node to mark it such that it does not get replaced
|
||||
// again on this pass
|
||||
// TODO: Make this work when replacing with arbitrary BabelNodeExpressions. Currently
|
||||
// if the node that we're substituting contains identifiers as children,
|
||||
// they will be visited again and possibly transformed.
|
||||
// If necessary we could implement this by following node.parentPath and checking
|
||||
// if any parent nodes are marked visited, but that seem unnecessary right now.let closureRefReplacer = {
|
||||
function replaceName(path, residualFunctionBinding, name, data) {
|
||||
if (path.scope.hasBinding(name, /*noGlobals*/true)) return;
|
||||
|
||||
if (residualFunctionBinding && shouldVisit(path.node, data)) {
|
||||
markVisited(residualFunctionBinding.serializedValue, data);
|
||||
var serializedValue = residualFunctionBinding.serializedValue;
|
||||
|
||||
if (path.node.type === "JSXIdentifier" || path.node.type === "JSXMemberIdentifier") {
|
||||
path.replaceWith((0, _jsx.convertExpressionToJSXIdentifier)(serializedValue, true));
|
||||
} else {
|
||||
path.replaceWith(serializedValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getLiteralTruthiness(node) {
|
||||
// In the return value, 'known' is true only if this is a literal of known truthiness and with no side effects; if 'known' is true, 'value' is its truthiness.
|
||||
if (t.isBooleanLiteral(node) || t.isNumericLiteral(node) || t.isStringLiteral(node)) {
|
||||
return { known: true, value: !!node.value };
|
||||
}
|
||||
if (t.isFunctionExpression(node) || t.isArrowFunctionExpression(node) || t.isRegExpLiteral(node) || t.isClassExpression(node) && node.superClass === null && node.body.body.length === 0 || t.isObjectExpression(node) && node.properties.length === 0 || t.isArrayExpression(node) && node.elements.length === 0) {
|
||||
return { known: true, value: true };
|
||||
}
|
||||
if (t.isNullLiteral(node)) {
|
||||
return { known: true, value: false };
|
||||
}
|
||||
return { known: false };
|
||||
}
|
||||
|
||||
function canShareFunctionBody(duplicateFunctionInfo) {
|
||||
// Only share function when:
|
||||
// 1. it does not access any free variables.
|
||||
// 2. it does not use "this".
|
||||
var _duplicateFunctionInf = duplicateFunctionInfo.functionInfo,
|
||||
unbound = _duplicateFunctionInf.unbound,
|
||||
modified = _duplicateFunctionInf.modified,
|
||||
usesThis = _duplicateFunctionInf.usesThis;
|
||||
|
||||
return unbound.size === 0 && modified.size === 0 && !usesThis;
|
||||
}
|
||||
|
||||
var ClosureRefReplacer = exports.ClosureRefReplacer = {
|
||||
ReferencedIdentifier: function ReferencedIdentifier(path, state) {
|
||||
if (ignorePath(path)) return;
|
||||
|
||||
var residualFunctionBindings = state.residualFunctionBindings;
|
||||
var name = path.node.name;
|
||||
var residualFunctionBinding = residualFunctionBindings.get(name);
|
||||
if (residualFunctionBinding) replaceName(path, residualFunctionBinding, name, residualFunctionBindings);
|
||||
},
|
||||
CallExpression: function CallExpression(path, state) {
|
||||
// Here we apply the require optimization by replacing require calls with their
|
||||
// corresponding initialized modules.
|
||||
var requireReturns = state.requireReturns;
|
||||
if (!state.isRequire || !state.isRequire(path.scope, path.node)) return;
|
||||
state.requireStatistics.count++;
|
||||
if (state.modified.has(path.node.callee.name)) return;
|
||||
|
||||
var moduleId = "" + path.node.arguments[0].value;
|
||||
var new_node = requireReturns.get(moduleId);
|
||||
if (new_node !== undefined) {
|
||||
markVisited(new_node, state.residualFunctionBindings);
|
||||
path.replaceWith(new_node);
|
||||
state.requireStatistics.replaced++;
|
||||
}
|
||||
},
|
||||
"AssignmentExpression|UpdateExpression": function AssignmentExpressionUpdateExpression(path, state) {
|
||||
var residualFunctionBindings = state.residualFunctionBindings;
|
||||
var ids = path.getBindingIdentifierPaths();
|
||||
for (var name in ids) {
|
||||
var residualFunctionBinding = residualFunctionBindings.get(name);
|
||||
if (residualFunctionBinding) {
|
||||
var nestedPath = ids[name];
|
||||
replaceName(nestedPath, residualFunctionBinding, name, residualFunctionBindings);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
// TODO: handle FunctionDeclaration.
|
||||
// Replace "function () {}" ==> "factory_id.bind(null)".
|
||||
FunctionExpression: function FunctionExpression(path, state) {
|
||||
if (t.isProgram(path.parentPath.parentPath.node)) {
|
||||
// Our goal is replacing duplicate nested function so skip root residual function itself.
|
||||
// This assumes the root function is wrapped with: t.file(t.program([t.expressionStatement(rootFunction).
|
||||
return;
|
||||
}
|
||||
|
||||
var functionExpression = path.node;
|
||||
var functionTag = functionExpression.body.uniqueOrderedTag;
|
||||
if (!functionTag) {
|
||||
// Un-interpreted nested function.
|
||||
return;
|
||||
}
|
||||
var duplicateFunctionInfo = state.factoryFunctionInfos.get(functionTag);
|
||||
if (duplicateFunctionInfo && canShareFunctionBody(duplicateFunctionInfo)) {
|
||||
var factoryId = duplicateFunctionInfo.factoryId;
|
||||
|
||||
path.replaceWith(t.callExpression(t.memberExpression(factoryId, t.identifier("bind")), [_internalizer.nullExpression]));
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
// A few very simple dead code elimination helpers. Eventually these should be subsumed by the partial evaluators.
|
||||
IfStatement: {
|
||||
exit: function exit(path, state) {
|
||||
var node = path.node;
|
||||
var testTruthiness = getLiteralTruthiness(node.test);
|
||||
if (testTruthiness.known) {
|
||||
if (testTruthiness.value) {
|
||||
// Strictly speaking this is not safe: Annex B.3.4 allows FunctionDeclarations as the body of IfStatements in sloppy mode,
|
||||
// which have weird hoisting behavior: `console.log(typeof f); if (true) function f(){} console.log(typeof f)` will print 'undefined', 'function', but
|
||||
// `console.log(typeof f); function f(){} console.log(typeof f)` will print 'function', 'function'.
|
||||
// However, Babylon can't parse these, so it doesn't come up.
|
||||
path.replaceWith(node.consequent);
|
||||
} else {
|
||||
if (node.alternate !== null) {
|
||||
path.replaceWith(node.alternate);
|
||||
} else {
|
||||
path.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
ConditionalExpression: {
|
||||
exit: function exit(path, state) {
|
||||
var node = path.node;
|
||||
var testTruthiness = getLiteralTruthiness(node.test);
|
||||
if (testTruthiness.known) {
|
||||
path.replaceWith(testTruthiness.value ? node.consequent : node.alternate);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
LogicalExpression: {
|
||||
exit: function exit(path, state) {
|
||||
var node = path.node;
|
||||
var leftTruthiness = getLiteralTruthiness(node.left);
|
||||
if (node.operator === "&&" && leftTruthiness.known) {
|
||||
path.replaceWith(leftTruthiness.value ? node.right : node.left);
|
||||
} else if (node.operator === "||" && leftTruthiness.known) {
|
||||
path.replaceWith(leftTruthiness.value ? node.left : node.right);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
WhileStatement: {
|
||||
exit: function exit(path, state) {
|
||||
var node = path.node;
|
||||
var testTruthiness = getLiteralTruthiness(node.test);
|
||||
if (testTruthiness.known && !testTruthiness.value) {
|
||||
path.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function visitName(path, state, name, modified) {
|
||||
// Is the name bound to some local identifier? If so, we don't need to do anything
|
||||
if (path.scope.hasBinding(name, /*noGlobals*/true)) return;
|
||||
|
||||
// Otherwise, let's record that there's an unbound identifier
|
||||
state.functionInfo.unbound.add(name);
|
||||
if (modified) state.functionInfo.modified.add(name);
|
||||
}
|
||||
|
||||
function ignorePath(path) {
|
||||
var parent = path.parent;
|
||||
return t.isLabeledStatement(parent) || t.isBreakStatement(parent) || t.isContinueStatement(parent);
|
||||
}
|
||||
|
||||
// TODO #886: doesn't check that `arguments` and `this` is in top function
|
||||
var ClosureRefVisitor = exports.ClosureRefVisitor = {
|
||||
ReferencedIdentifier: function ReferencedIdentifier(path, state) {
|
||||
if (ignorePath(path)) return;
|
||||
|
||||
var innerName = path.node.name;
|
||||
if (innerName === "arguments") {
|
||||
state.functionInfo.usesArguments = true;
|
||||
return;
|
||||
}
|
||||
visitName(path, state, innerName, false);
|
||||
},
|
||||
ThisExpression: function ThisExpression(path, state) {
|
||||
state.functionInfo.usesThis = true;
|
||||
},
|
||||
"AssignmentExpression|UpdateExpression": function AssignmentExpressionUpdateExpression(path, state) {
|
||||
for (var name in path.getBindingIdentifiers()) {
|
||||
visitName(path, state, name, true);
|
||||
}
|
||||
}
|
||||
};
|
||||
//# sourceMappingURL=visitors.js.map
|
||||
1
build/node_modules/prepack/lib/serializer/visitors.js.map
generated
vendored
Normal file
1
build/node_modules/prepack/lib/serializer/visitors.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user