'use strict';

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

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 _baseParserGenerator = require('../base-parser-generator');

var _baseParserGenerator2 = _interopRequireDefault(_baseParserGenerator);

var _llParsingTable = require('./ll-parsing-table');

var _llParsingTable2 = _interopRequireDefault(_llParsingTable);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

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; } /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                * The MIT License (MIT)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                * Copyright (c) 2015-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */

/**
 * Template for LL(1) parser.
 */
var LL_PARSER_TEMPLATE = _fs2.default.readFileSync(__dirname + '/../templates/ll.template.js', 'utf-8');

/**
 * LL parser generator. Creates a parser module for a given grammar, and
 * saves it to the `outputFile`.
 */

var LLParserGeneratorDefault = function (_BaseParserGenerator) {
  _inherits(LLParserGeneratorDefault, _BaseParserGenerator);

  /**
   * Instance constructor.
   */
  function LLParserGeneratorDefault(_ref) {
    var _this;

    var grammar = _ref.grammar,
        outputFile = _ref.outputFile,
        _ref$options = _ref.options,
        options = _ref$options === undefined ? {} : _ref$options;

    _classCallCheck(this, LLParserGeneratorDefault);

    if (!grammar.getMode().isLL()) {
      throw new Error('LL parser generator: LL(1) grammar is expected.');
    }
    (_this = _possibleConstructorReturn(this, (LLParserGeneratorDefault.__proto__ || Object.getPrototypeOf(LLParserGeneratorDefault)).call(this, { grammar: grammar, outputFile: outputFile, options: options })), _this).setTable(new _llParsingTable2.default({ grammar: grammar })).setTemplate(LL_PARSER_TEMPLATE);
    return _this;
  }

  /**
   * Generates parser data.
   */


  _createClass(LLParserGeneratorDefault, [{
    key: 'generateParserData',
    value: function generateParserData() {
      _get(LLParserGeneratorDefault.prototype.__proto__ || Object.getPrototypeOf(LLParserGeneratorDefault.prototype), 'generateParserData', this).call(this);
      this._generateStartSymbol();
    }

    /**
     * Format of the production is:
     * [RHS.reverse().map(index)]
     * The RHS is reversed to push onto the stack at derivation.
     * LL parser doesn't implement yet semantic action.
     */

  }, {
    key: 'generateRawProductionsData',
    value: function generateRawProductionsData() {
      var _this2 = this;

      var productionsData = this.getGrammar().getProductions().map(function (production) {
        // RHS for derivation.
        var reversedRHS = [];
        if (!production.isEpsilon()) {
          reversedRHS = production.getRHS().map(function (symbol) {
            return _this2.getEncodedSymbol(symbol.getSymbol()).toString();
          }).reverse();
        }
        return [reversedRHS];
      });

      // For 1-based index production.
      productionsData.unshift([-1]);
      return productionsData;
    }
  }, {
    key: 'generateProductionsData',
    value: function generateProductionsData() {
      return this.generateRawProductionsData().map(function (data) {
        return JSON.stringify(data);
      });
    }

    /**
     * Actual parsing table.
     */

  }, {
    key: 'generateParseTableData',
    value: function generateParseTableData() {
      var originalTable = this._table.get();
      var table = {};

      for (var nonTerminal in originalTable) {
        var row = {};
        var originalRow = originalTable[nonTerminal];

        for (var symbol in originalRow) {
          var entry = originalRow[symbol];
          row[this.getEncodedSymbol(symbol)] = entry;
        }

        table[this.getEncodedNonTerminal(nonTerminal)] = row;
      }

      return table;
    }
  }, {
    key: '_generateStartSymbol',
    value: function _generateStartSymbol() {
      var startSymbol = this.getEncodedNonTerminal(this.getGrammar().getStartSymbol());
      this.writeData('START', '\'' + startSymbol + '\'');
    }
  }]);

  return LLParserGeneratorDefault;
}(_baseParserGenerator2.default);

exports.default = LLParserGeneratorDefault;