Source: EBNFP/Seq.js

"use strict";

/** @fileOverview Implements `class page.EBNFP.Seq extends page.EBNF.Seq`.
  * @author Axel T. Schreiner <ats@cs.rit.edu>
  * @version 1.5.0
  */

/** Creates a new representation of a sequence with optional precedence for EBNFP.
  * @class Represents a sequence with optional precedence for EBNFP.
  * @extends page.EBNF.Seq
  * @private
  *
  * @example
  * alt: a b %prec 'x' | c %prec 'y';
  * 
  * @param {epNode[]} _nodes sequence, at least two, or with precedence.
  * @param {page.BNF.T} [_prec] terminal providing the precedence.
  *
  * @property {epNode[]} nodes descendants, at least two, or with precedence.
  * @property {page.BNF.T} [prec.t] terminal providing the precedence.
  * @property {page.BNF.NT} nt corresponding non-terminal for BNF.
  * @property {boolean} empty true if no input can be accepted.
  * @property {Map} first terminals at front, maps ord to {@link page.BNF.T}.
  * @property {Map} follow terminals following, maps ord to {@link page.BNF.T}.
  */
page.EBNFP.Seq = function (_nodes, _prec) {
  page.EBNF.Seq.call(this, _nodes);
  this.prec = _prec;
};

page.subclass(page.EBNFP.Seq, 'page.EBNFP.Seq', page.EBNF.Seq);

/** Displays a sequence in EBNF notation with precedence, if any.
  * @override
  * @variation EBNFP
  * @returns {string}.
  */
page.EBNFP.Seq.prototype.toString = function () {
  return page.EBNF.Seq.prototype.toString.call(this) + (this.prec ? ' %prec ' + this.prec : '');
};

/** Called once by {@link page.EBNFP#init} to recursively translate into BNF.
  *
  *     a %prec b
  *
  * is translated to
  *
  *     $#: a %prec b;
  *
  * @private
  * @override
  * @variation EBNFP
  *
  * @param {page.EBNFP} _grammar object to which the construct belongs.
  * @param {page.EBNF.NT} [_nt] left-hand side, if known; avoids the need for a fresh non-terminal.
  *
  * @returns  {page.BNF.NT} non-terminal representing the translated construct.
  */
page.EBNFP.Seq.prototype.toBNF = function (_grammar, _nt) {
  _grammar.assert('__WHERE__', !this.nt);
  _grammar.assert('__WHERE__', this.nodes.length > 1 || this.prec);

  var result = this.nt = _nt ? _nt : _grammar.bnf.nt('$');    // $#
  var at = _grammar.bnf.rules.length;                         // placeholder
  _grammar.bnf.rules.push(null);
  
  _grammar.bnf.rules[at] = _grammar.bnf.rule(result, this.nodes.map(function (node) {
    return node instanceof page.BNF.T ? node : node.toBNF(_grammar);
  }), this.prec);    
  return result;
};