"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.LazyObjectsSerializer = undefined;

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("../utils/logger.js");

var _modules = require("../utils/modules.js");

var _ResidualHeapInspector = require("./ResidualHeapInspector.js");

var _ResidualHeapValueIdentifiers = require("./ResidualHeapValueIdentifiers.js");

var _ResidualHeapSerializer = require("./ResidualHeapSerializer.js");

var _utils = require("./utils.js");

var _generator = require("../utils/generator.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; } }

/**
 * 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.
 */

const 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...
 */
class LazyObjectsSerializer extends _ResidualHeapSerializer.ResidualHeapSerializer {
  constructor(realm, logger, modules, residualHeapValueIdentifiers, residualHeapInspector, residualValues, residualFunctionInstances, residualClassMethodInstances, residualFunctionInfos, options, referencedDeclaredValues, additionalFunctionValuesAndEffects, additionalFunctionValueInfos, declarativeEnvironmentRecordsBindings, statistics, react, referentializer, generatorParents) {
    super(realm, logger, modules, residualHeapValueIdentifiers, residualHeapInspector, residualValues, residualFunctionInstances, residualClassMethodInstances, residualFunctionInfos, options, referencedDeclaredValues, additionalFunctionValuesAndEffects, additionalFunctionValueInfos, declarativeEnvironmentRecordsBindings, statistics, react, referentializer, generatorParents);
    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");
  }
  // 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.


  _getValueLazyId(obj) {
    return (0, _utils.getOrDefault)(this._valueLazyIds, obj, () => this._lazyObjectIdSeed++);
  }

  // TODO: change to use _getTarget() to get the lazy objects initializer body.
  _serializeLazyObjectInitializer(obj) {
    const initializerBody = {
      type: LAZY_OBJECTS_SERIALIZER_BODY_TYPE,
      parentBody: undefined,
      entries: [],
      done: false
    };
    let oldBody = this.emitter.beginEmitting(LAZY_OBJECTS_SERIALIZER_BODY_TYPE, initializerBody);
    this._emitObjectProperties(obj);
    this.emitter.endEmitting(LAZY_OBJECTS_SERIALIZER_BODY_TYPE, oldBody);
    return initializerBody;
  }

  _serializeLazyObjectInitializerSwitchCase(obj, initializer) {
    // TODO: only serialize this switch case if the initializer(property assignment) is not empty.
    const caseBody = initializer.entries.concat(t.breakStatement());
    const lazyId = this._getValueLazyId(obj);
    return t.switchCase(t.numericLiteral(lazyId), caseBody);
  }

  _serializeInitializationCallback() {
    const body = [];

    const switchCases = [];
    for (const [obj, initializer] of this._lazyObjectInitializers) {
      switchCases.push(this._serializeLazyObjectInitializerSwitchCase(obj, initializer));
    }
    // Default case.
    switchCases.push(t.switchCase(null, [t.throwStatement(t.newExpression(t.identifier("Error"), [t.stringLiteral("Unknown lazy id")]))]));

    const selector = t.identifier("id");
    body.push(t.switchStatement(selector, switchCases));

    const params = [this._callbackLazyObjectParam, selector];
    const initializerCallbackFunction = t.functionExpression(null, params, t.blockStatement(body));
    // TODO: use NameGenerator.
    return t.variableDeclaration("var", [t.variableDeclarator(this._initializationCallbackName, initializerCallbackFunction)]);
  }

  _serializeRegisterInitializationCallback() {
    return t.expressionStatement(t.callExpression(t.memberExpression(this._lazyObjectJSRuntimeName, t.identifier("setLazyObjectInitializer")), [this._initializationCallbackName]));
  }

  _serializeCreateLazyObject(obj) {
    const 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.
   */
  _isEmittingIntoLazyObjectInitializerBody(obj) {
    const 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.
  getSerializeObjectIdentifier(val) {
    return val instanceof _index.ObjectValue && this._isEmittingIntoLazyObjectInitializerBody(val) ? this._callbackLazyObjectParam : super.getSerializeObjectIdentifier(val);
  }

  // Override default serializer with lazy mode.
  serializeValueRawObject(obj, skipPrototype) {
    if (obj.temporalAlias !== undefined) return super.serializeValueRawObject(obj, skipPrototype);
    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.
  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());
    }
  }
}
exports.LazyObjectsSerializer = LazyObjectsSerializer;
//# sourceMappingURL=LazyObjectsSerializer.js.map