"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const errors = require("./lib-utils-errors.cjs");
const ast = require("./lib-languages-generated-ast.cjs");
const syntaxTree = require("./lib-syntax-tree.cjs");
const astUtils = require("./lib-utils-ast-utils.cjs");
const cstUtils = require("./lib-utils-cst-utils.cjs");
const regexpUtils = require("./lib-utils-regexp-utils.cjs");
function getEntryRule(grammar) {
  return grammar.rules.find((e) => ast.isParserRule(e) && e.entry);
}
function getHiddenRules(grammar) {
  return grammar.rules.filter((e) => ast.isTerminalRule(e) && e.hidden);
}
function getAllReachableRules(grammar, allTerminals) {
  const ruleNames = /* @__PURE__ */ new Set();
  const entryRule = getEntryRule(grammar);
  if (!entryRule) {
    return new Set(grammar.rules);
  }
  const topMostRules = [entryRule].concat(getHiddenRules(grammar));
  for (const rule of topMostRules) {
    ruleDfs(rule, ruleNames, allTerminals);
  }
  const rules = /* @__PURE__ */ new Set();
  for (const rule of grammar.rules) {
    if (ruleNames.has(rule.name) || ast.isTerminalRule(rule) && rule.hidden) {
      rules.add(rule);
    }
  }
  return rules;
}
function ruleDfs(rule, visitedSet, allTerminals) {
  visitedSet.add(rule.name);
  astUtils.streamAllContents(rule).forEach((node) => {
    if (ast.isRuleCall(node) || allTerminals) {
      const refRule = node.rule.ref;
      if (refRule && !visitedSet.has(refRule.name)) {
        ruleDfs(refRule, visitedSet, allTerminals);
      }
    }
  });
}
function getCrossReferenceTerminal(crossRef) {
  if (crossRef.terminal) {
    return crossRef.terminal;
  } else if (crossRef.type.ref) {
    const nameAssigment = findNameAssignment(crossRef.type.ref);
    return nameAssigment === null || nameAssigment === void 0 ? void 0 : nameAssigment.terminal;
  }
  return void 0;
}
function isCommentTerminal(terminalRule) {
  return terminalRule.hidden && !regexpUtils.isWhitespace(terminalRegex(terminalRule));
}
function findNodesForProperty(node, property) {
  if (!node || !property) {
    return [];
  }
  return findNodesForPropertyInternal(node, property, node.astNode, true);
}
function findNodeForProperty(node, property, index) {
  if (!node || !property) {
    return void 0;
  }
  const nodes = findNodesForPropertyInternal(node, property, node.astNode, true);
  if (nodes.length === 0) {
    return void 0;
  }
  if (index !== void 0) {
    index = Math.max(0, Math.min(index, nodes.length - 1));
  } else {
    index = 0;
  }
  return nodes[index];
}
function findNodesForPropertyInternal(node, property, element, first) {
  if (!first) {
    const nodeFeature = astUtils.getContainerOfType(node.grammarSource, ast.isAssignment);
    if (nodeFeature && nodeFeature.feature === property) {
      return [node];
    }
  }
  if (syntaxTree.isCompositeCstNode(node) && node.astNode === element) {
    return node.content.flatMap((e) => findNodesForPropertyInternal(e, property, element, false));
  }
  return [];
}
function findNodeForKeyword(node, keyword, index) {
  if (!node) {
    return void 0;
  }
  const nodes = findNodesForKeywordInternal(node, keyword, node === null || node === void 0 ? void 0 : node.astNode);
  if (nodes.length === 0) {
    return void 0;
  }
  if (index !== void 0) {
    index = Math.max(0, Math.min(index, nodes.length - 1));
  } else {
    index = 0;
  }
  return nodes[index];
}
function findNodesForKeywordInternal(node, keyword, element) {
  if (node.astNode !== element) {
    return [];
  }
  if (ast.isKeyword(node.grammarSource) && node.grammarSource.value === keyword) {
    return [node];
  }
  const treeIterator = cstUtils.streamCst(node).iterator();
  let result;
  const keywordNodes = [];
  do {
    result = treeIterator.next();
    if (!result.done) {
      const childNode = result.value;
      if (childNode.astNode === element) {
        if (ast.isKeyword(childNode.grammarSource) && childNode.grammarSource.value === keyword) {
          keywordNodes.push(childNode);
        }
      } else {
        treeIterator.prune();
      }
    }
  } while (!result.done);
  return keywordNodes;
}
function findAssignment(cstNode) {
  var _a;
  const astNode = cstNode.astNode;
  while (astNode === ((_a = cstNode.container) === null || _a === void 0 ? void 0 : _a.astNode)) {
    const assignment = astUtils.getContainerOfType(cstNode.grammarSource, ast.isAssignment);
    if (assignment) {
      return assignment;
    }
    cstNode = cstNode.container;
  }
  return void 0;
}
function findNameAssignment(type) {
  let startNode = type;
  if (ast.isInferredType(startNode)) {
    if (ast.isAction(startNode.$container)) {
      startNode = startNode.$container.$container;
    } else if (ast.isParserRule(startNode.$container)) {
      startNode = startNode.$container;
    } else {
      errors.assertUnreachable(startNode.$container);
    }
  }
  return findNameAssignmentInternal(type, startNode, /* @__PURE__ */ new Map());
}
function findNameAssignmentInternal(type, startNode, cache) {
  var _a;
  function go(node, refType) {
    let childAssignment = void 0;
    const parentAssignment = astUtils.getContainerOfType(node, ast.isAssignment);
    if (!parentAssignment) {
      childAssignment = findNameAssignmentInternal(refType, refType, cache);
    }
    cache.set(type, childAssignment);
    return childAssignment;
  }
  if (cache.has(type)) {
    return cache.get(type);
  }
  cache.set(type, void 0);
  for (const node of astUtils.streamAllContents(startNode)) {
    if (ast.isAssignment(node) && node.feature.toLowerCase() === "name") {
      cache.set(type, node);
      return node;
    } else if (ast.isRuleCall(node) && ast.isParserRule(node.rule.ref)) {
      return go(node, node.rule.ref);
    } else if (ast.isSimpleType(node) && ((_a = node.typeRef) === null || _a === void 0 ? void 0 : _a.ref)) {
      return go(node, node.typeRef.ref);
    }
  }
  return void 0;
}
function isDataTypeRule(rule) {
  return isDataTypeRuleInternal(rule, /* @__PURE__ */ new Set());
}
function isDataTypeRuleInternal(rule, visited) {
  if (visited.has(rule)) {
    return true;
  } else {
    visited.add(rule);
  }
  for (const node of astUtils.streamAllContents(rule)) {
    if (ast.isRuleCall(node)) {
      if (!node.rule.ref) {
        return false;
      }
      if (ast.isParserRule(node.rule.ref) && !isDataTypeRuleInternal(node.rule.ref, visited)) {
        return false;
      }
    } else if (ast.isAssignment(node)) {
      return false;
    } else if (ast.isAction(node)) {
      return false;
    }
  }
  return Boolean(rule.definition);
}
function getExplicitRuleType(rule) {
  if (rule.inferredType) {
    return rule.inferredType.name;
  } else if (rule.dataType) {
    return rule.dataType;
  } else if (rule.returnType) {
    const refType = rule.returnType.ref;
    if (refType) {
      if (ast.isParserRule(refType)) {
        return refType.name;
      } else if (ast.isInterface(refType) || ast.isType(refType)) {
        return refType.name;
      }
    }
  }
  return void 0;
}
function getTypeName(type) {
  var _a;
  if (ast.isParserRule(type)) {
    return isDataTypeRule(type) ? type.name : (_a = getExplicitRuleType(type)) !== null && _a !== void 0 ? _a : type.name;
  } else if (ast.isInterface(type) || ast.isType(type) || ast.isReturnType(type)) {
    return type.name;
  } else if (ast.isAction(type)) {
    const actionType = getActionType(type);
    if (actionType) {
      return actionType;
    }
  } else if (ast.isInferredType(type)) {
    return type.name;
  }
  throw new Error("Cannot get name of Unknown Type");
}
function getActionType(action) {
  var _a;
  if (action.inferredType) {
    return action.inferredType.name;
  } else if ((_a = action.type) === null || _a === void 0 ? void 0 : _a.ref) {
    return getTypeName(action.type.ref);
  }
  return void 0;
}
function getRuleType(rule) {
  var _a, _b, _c;
  if (ast.isTerminalRule(rule)) {
    return (_b = (_a = rule.type) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : "string";
  } else {
    return (_c = getExplicitRuleType(rule)) !== null && _c !== void 0 ? _c : rule.name;
  }
}
function terminalRegex(terminalRule) {
  const flags = {
    s: false,
    i: false,
    u: false
  };
  const source = abstractElementToRegex(terminalRule.definition, flags);
  const flagText = Object.entries(flags).filter(([, value]) => value).map(([name]) => name).join("");
  return new RegExp(source, flagText);
}
const WILDCARD = /[\s\S]/.source;
function abstractElementToRegex(element, flags) {
  if (ast.isTerminalAlternatives(element)) {
    return terminalAlternativesToRegex(element);
  } else if (ast.isTerminalGroup(element)) {
    return terminalGroupToRegex(element);
  } else if (ast.isCharacterRange(element)) {
    return characterRangeToRegex(element);
  } else if (ast.isTerminalRuleCall(element)) {
    const rule = element.rule.ref;
    if (!rule) {
      throw new Error("Missing rule reference.");
    }
    return withCardinality(abstractElementToRegex(rule.definition), {
      cardinality: element.cardinality,
      lookahead: element.lookahead
    });
  } else if (ast.isNegatedToken(element)) {
    return negateTokenToRegex(element);
  } else if (ast.isUntilToken(element)) {
    return untilTokenToRegex(element);
  } else if (ast.isRegexToken(element)) {
    const lastSlash = element.regex.lastIndexOf("/");
    const source = element.regex.substring(1, lastSlash);
    const regexFlags = element.regex.substring(lastSlash + 1);
    if (flags) {
      flags.i = regexFlags.includes("i");
      flags.s = regexFlags.includes("s");
      flags.u = regexFlags.includes("u");
    }
    return withCardinality(source, {
      cardinality: element.cardinality,
      lookahead: element.lookahead,
      wrap: false
    });
  } else if (ast.isWildcard(element)) {
    return withCardinality(WILDCARD, {
      cardinality: element.cardinality,
      lookahead: element.lookahead
    });
  } else {
    throw new Error(`Invalid terminal element: ${element === null || element === void 0 ? void 0 : element.$type}`);
  }
}
function terminalAlternativesToRegex(alternatives) {
  return withCardinality(alternatives.elements.map((e) => abstractElementToRegex(e)).join("|"), {
    cardinality: alternatives.cardinality,
    lookahead: alternatives.lookahead
  });
}
function terminalGroupToRegex(group) {
  return withCardinality(group.elements.map((e) => abstractElementToRegex(e)).join(""), {
    cardinality: group.cardinality,
    lookahead: group.lookahead
  });
}
function untilTokenToRegex(until) {
  return withCardinality(`${WILDCARD}*?${abstractElementToRegex(until.terminal)}`, {
    cardinality: until.cardinality,
    lookahead: until.lookahead
  });
}
function negateTokenToRegex(negate) {
  return withCardinality(`(?!${abstractElementToRegex(negate.terminal)})${WILDCARD}*?`, {
    cardinality: negate.cardinality,
    lookahead: negate.lookahead
  });
}
function characterRangeToRegex(range) {
  if (range.right) {
    return withCardinality(`[${keywordToRegex(range.left)}-${keywordToRegex(range.right)}]`, {
      cardinality: range.cardinality,
      lookahead: range.lookahead,
      wrap: false
    });
  }
  return withCardinality(keywordToRegex(range.left), {
    cardinality: range.cardinality,
    lookahead: range.lookahead,
    wrap: false
  });
}
function keywordToRegex(keyword) {
  return regexpUtils.escapeRegExp(keyword.value);
}
function withCardinality(regex, options) {
  var _a;
  if (options.wrap !== false || options.lookahead) {
    regex = `(${(_a = options.lookahead) !== null && _a !== void 0 ? _a : ""}${regex})`;
  }
  if (options.cardinality) {
    return `${regex}${options.cardinality}`;
  }
  return regex;
}
exports.findAssignment = findAssignment;
exports.findNameAssignment = findNameAssignment;
exports.findNodeForKeyword = findNodeForKeyword;
exports.findNodeForProperty = findNodeForProperty;
exports.findNodesForKeywordInternal = findNodesForKeywordInternal;
exports.findNodesForProperty = findNodesForProperty;
exports.getActionType = getActionType;
exports.getAllReachableRules = getAllReachableRules;
exports.getCrossReferenceTerminal = getCrossReferenceTerminal;
exports.getEntryRule = getEntryRule;
exports.getExplicitRuleType = getExplicitRuleType;
exports.getHiddenRules = getHiddenRules;
exports.getRuleType = getRuleType;
exports.getTypeName = getTypeName;
exports.isCommentTerminal = isCommentTerminal;
exports.isDataTypeRule = isDataTypeRule;
exports.terminalRegex = terminalRegex;
//# sourceMappingURL=lib-utils-grammar-utils.cjs.map
