"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) /* istanbul ignore next */  if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    /* istanbul ignore next */  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var parser_public_1 = require("../parser_public");
var gast_public_1 = require("./gast_public");
var utils_1 = require("../../utils/utils");
function resolveGrammar(topLevels) {
    var refResolver = new GastRefResolverVisitor(topLevels);
    refResolver.resolveRefs();
    return refResolver.errors;
}
exports.resolveGrammar = resolveGrammar;
var GastRefResolverVisitor = (function (_super) {
    __extends(GastRefResolverVisitor, _super);
    function GastRefResolverVisitor(nameToTopRule) {
        _super.call(this);
        this.nameToTopRule = nameToTopRule;
        this.errors = [];
    }
    GastRefResolverVisitor.prototype.resolveRefs = function () {
        var _this = this;
        utils_1.forEach(this.nameToTopRule.values(), function (prod) {
            _this.currTopLevel = prod;
            prod.accept(_this);
        });
    };
    GastRefResolverVisitor.prototype.visitNonTerminal = function (node) {
        var ref = this.nameToTopRule.get(node.nonTerminalName);
        if (!ref) {
            var msg = "Invalid grammar, reference to a rule which is not defined: ->" + node.nonTerminalName + "<-\n" +
                "inside top level rule: ->" + this.currTopLevel.name + "<-";
            this.errors.push({
                message: msg,
                type: parser_public_1.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,
                ruleName: this.currTopLevel.name,
                unresolvedRefName: node.nonTerminalName
            });
        }
        else {
            node.referencedRule = ref;
        }
    };
    return GastRefResolverVisitor;
}(gast_public_1.gast.GAstVisitor));
exports.GastRefResolverVisitor = GastRefResolverVisitor;
