"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const toFastProperties = require("../@chevrotain/utils/lib-src-to-fast-properties.cjs");
const follow = require("./lib-src-parse-grammar-follow.cjs");
const tokens_public = require("./lib-src-scan-tokens_public.cjs");
const errors_public = require("./lib-src-parse-errors_public.cjs");
const gast_resolver_public = require("./lib-src-parse-grammar-gast-gast_resolver_public.cjs");
const recoverable = require("./lib-src-parse-parser-traits-recoverable.cjs");
const looksahead = require("./lib-src-parse-parser-traits-looksahead.cjs");
const tree_builder = require("./lib-src-parse-parser-traits-tree_builder.cjs");
const lexer_adapter = require("./lib-src-parse-parser-traits-lexer_adapter.cjs");
const recognizer_api = require("./lib-src-parse-parser-traits-recognizer_api.cjs");
const recognizer_engine = require("./lib-src-parse-parser-traits-recognizer_engine.cjs");
const error_handler = require("./lib-src-parse-parser-traits-error_handler.cjs");
const context_assist = require("./lib-src-parse-parser-traits-context_assist.cjs");
const gast_recorder = require("./lib-src-parse-parser-traits-gast_recorder.cjs");
const perf_tracer = require("./lib-src-parse-parser-traits-perf_tracer.cjs");
const apply_mixins = require("./lib-src-parse-parser-utils-apply_mixins.cjs");
const checks = require("./lib-src-parse-grammar-checks.cjs");
const clone = require("../lodash-es/clone.cjs");
const forEach = require("../lodash-es/forEach.cjs");
const values = require("../lodash-es/values.cjs");
const isEmpty = require("../lodash-es/isEmpty.cjs");
const map = require("../lodash-es/map.cjs");
const has = require("../lodash-es/has.cjs");
const END_OF_FILE = tokens_public.createTokenInstance(tokens_public.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN);
Object.freeze(END_OF_FILE);
const DEFAULT_PARSER_CONFIG = Object.freeze({
  recoveryEnabled: false,
  maxLookahead: 3,
  dynamicTokensEnabled: false,
  outputCst: true,
  errorMessageProvider: errors_public.defaultParserErrorProvider,
  nodeLocationTracking: "none",
  traceInitPerf: false,
  skipValidations: false
});
const DEFAULT_RULE_CONFIG = Object.freeze({
  recoveryValueFunc: () => void 0,
  resyncEnabled: true
});
exports.ParserDefinitionErrorType = void 0;
(function(ParserDefinitionErrorType) {
  ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME";
  ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME";
  ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE";
  ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS";
  ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF";
  ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION";
  ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT";
  ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS";
  ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE";
  ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME";
  ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 10] = "NO_NON_EMPTY_LOOKAHEAD";
  ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 11] = "AMBIGUOUS_PREFIX_ALTS";
  ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 12] = "TOO_MANY_ALTS";
  ParserDefinitionErrorType[ParserDefinitionErrorType["CUSTOM_LOOKAHEAD_VALIDATION"] = 13] = "CUSTOM_LOOKAHEAD_VALIDATION";
})(exports.ParserDefinitionErrorType || (exports.ParserDefinitionErrorType = {}));
function EMPTY_ALT(value = void 0) {
  return function() {
    return value;
  };
}
class Parser {
  /**
   *  @deprecated use the **instance** method with the same name instead
   */
  static performSelfAnalysis(parserInstance) {
    throw Error("The **static** `performSelfAnalysis` method has been deprecated.	\nUse the **instance** method with the same name instead.");
  }
  performSelfAnalysis() {
    this.TRACE_INIT("performSelfAnalysis", () => {
      let defErrorsMsgs;
      this.selfAnalysisDone = true;
      const className = this.className;
      this.TRACE_INIT("toFastProps", () => {
        toFastProperties.toFastProperties(this);
      });
      this.TRACE_INIT("Grammar Recording", () => {
        try {
          this.enableRecording();
          forEach.default(this.definedRulesNames, (currRuleName) => {
            const wrappedRule = this[currRuleName];
            const originalGrammarAction = wrappedRule["originalGrammarAction"];
            let recordedRuleGast;
            this.TRACE_INIT(`${currRuleName} Rule`, () => {
              recordedRuleGast = this.topLevelRuleRecord(currRuleName, originalGrammarAction);
            });
            this.gastProductionsCache[currRuleName] = recordedRuleGast;
          });
        } finally {
          this.disableRecording();
        }
      });
      let resolverErrors = [];
      this.TRACE_INIT("Grammar Resolving", () => {
        resolverErrors = gast_resolver_public.resolveGrammar({
          rules: values.default(this.gastProductionsCache)
        });
        this.definitionErrors = this.definitionErrors.concat(resolverErrors);
      });
      this.TRACE_INIT("Grammar Validations", () => {
        if (isEmpty.default(resolverErrors) && this.skipValidations === false) {
          const validationErrors = gast_resolver_public.validateGrammar({
            rules: values.default(this.gastProductionsCache),
            tokenTypes: values.default(this.tokensMap),
            errMsgProvider: errors_public.defaultGrammarValidatorErrorProvider,
            grammarName: className
          });
          const lookaheadValidationErrors = checks.validateLookahead({
            lookaheadStrategy: this.lookaheadStrategy,
            rules: values.default(this.gastProductionsCache),
            tokenTypes: values.default(this.tokensMap),
            grammarName: className
          });
          this.definitionErrors = this.definitionErrors.concat(validationErrors, lookaheadValidationErrors);
        }
      });
      if (isEmpty.default(this.definitionErrors)) {
        if (this.recoveryEnabled) {
          this.TRACE_INIT("computeAllProdsFollows", () => {
            const allFollows = follow.computeAllProdsFollows(values.default(this.gastProductionsCache));
            this.resyncFollows = allFollows;
          });
        }
        this.TRACE_INIT("ComputeLookaheadFunctions", () => {
          var _a, _b;
          (_b = (_a = this.lookaheadStrategy).initialize) === null || _b === void 0 ? void 0 : _b.call(_a, {
            rules: values.default(this.gastProductionsCache)
          });
          this.preComputeLookaheadFunctions(values.default(this.gastProductionsCache));
        });
      }
      if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING && !isEmpty.default(this.definitionErrors)) {
        defErrorsMsgs = map.default(this.definitionErrors, (defError) => defError.message);
        throw new Error(`Parser Definition Errors detected:
 ${defErrorsMsgs.join("\n-------------------------------\n")}`);
      }
    });
  }
  constructor(tokenVocabulary, config) {
    this.definitionErrors = [];
    this.selfAnalysisDone = false;
    const that = this;
    that.initErrorHandler(config);
    that.initLexerAdapter();
    that.initLooksAhead(config);
    that.initRecognizerEngine(tokenVocabulary, config);
    that.initRecoverable(config);
    that.initTreeBuilder(config);
    that.initContentAssist();
    that.initGastRecorder(config);
    that.initPerformanceTracer(config);
    if (has.default(config, "ignoredIssues")) {
      throw new Error("The <ignoredIssues> IParserConfig property has been deprecated.\n	Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.\n	See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n	For further details.");
    }
    this.skipValidations = has.default(config, "skipValidations") ? config.skipValidations : DEFAULT_PARSER_CONFIG.skipValidations;
  }
}
Parser.DEFER_DEFINITION_ERRORS_HANDLING = false;
apply_mixins.applyMixins(Parser, [
  recoverable.Recoverable,
  looksahead.LooksAhead,
  tree_builder.TreeBuilder,
  lexer_adapter.LexerAdapter,
  recognizer_engine.RecognizerEngine,
  recognizer_api.RecognizerApi,
  error_handler.ErrorHandler,
  context_assist.ContentAssist,
  gast_recorder.GastRecorder,
  perf_tracer.PerformanceTracer
]);
class EmbeddedActionsParser extends Parser {
  constructor(tokenVocabulary, config = DEFAULT_PARSER_CONFIG) {
    const configClone = clone.default(config);
    configClone.outputCst = false;
    super(tokenVocabulary, configClone);
  }
}
exports.DEFAULT_PARSER_CONFIG = DEFAULT_PARSER_CONFIG;
exports.DEFAULT_RULE_CONFIG = DEFAULT_RULE_CONFIG;
exports.EMPTY_ALT = EMPTY_ALT;
exports.END_OF_FILE = END_OF_FILE;
exports.EmbeddedActionsParser = EmbeddedActionsParser;
exports.Parser = Parser;
//# sourceMappingURL=lib-src-parse-parser-parser.cjs.map
