Files
asciidisco.com/build/node_modules/prepack/lib/serializer/LazyObjectsSerializer.js
2023-08-01 13:49:46 +02:00

230 lines
15 KiB
JavaScript

"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