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

var _baseParserGenerator2 = _interopRequireDefault(_baseParserGenerator);

var _canonicalCollection = require('./canonical-collection');

var _canonicalCollection2 = _interopRequireDefault(_canonicalCollection);

var _lrParsingTable = require('./lr-parsing-table');

var _lrParsingTable2 = _interopRequireDefault(_lrParsingTable);

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

/**
 * Generic JS template for all LR parsers.
 */
var LR_PARSER_TEMPLATE = _fs2.default.readFileSync(__dirname + '/../templates/lr.template.js', 'utf-8');

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

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

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

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

    _classCallCheck(this, LRParserGeneratorDefault);

    if (!grammar.getMode().isLR()) {
      throw new Error('LR parser generator: LR grammar is expected.');
    }

    var table = new _lrParsingTable2.default({
      canonicalCollection: new _canonicalCollection2.default({ grammar: grammar }),
      grammar: grammar,
      resolveConflicts: options.resolveConflicts
    });

    (_this = _possibleConstructorReturn(this, (LRParserGeneratorDefault.__proto__ || Object.getPrototypeOf(LRParserGeneratorDefault)).call(this, { grammar: grammar, outputFile: outputFile, options: options })), _this).setTable(table).setTemplate(LR_PARSER_TEMPLATE);
    return _this;
  }

  /**
   * Default format in the [ ] array notation.
   */


  _createClass(LRParserGeneratorDefault, [{
    key: 'generateProductionsData',
    value: function generateProductionsData() {
      return this.generateRawProductionsData().map(function (data) {
        return '[' + data + ']';
      });
    }

    /**
     * Format of the production is:
     * [Non-terminal index, RHS.length, semanticAction]
     */

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

      return this.getGrammar().getProductions().map(function (production) {
        var LHS = production.getLHS().getSymbol().replace(/'/g, "\\'");
        var RHSLength = production.isEpsilon() ? 0 : production.getRHS().length;
        var semanticAction = _this2.buildSemanticAction(production);

        var result = [_this2.getEncodedNonTerminal(LHS), RHSLength];

        if (semanticAction) {
          result.push(semanticAction);
        }

        return result;
      });
    }

    /**
     * Actual parsing table.
     */

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

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

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

        table[state] = row;
      }

      return table;
    }
  }]);

  return LRParserGeneratorDefault;
}(_baseParserGenerator2.default);

exports.default = LRParserGeneratorDefault;