///|
/// Evaluate whether an expression can match the empty string given current nullable rules.
fn expr_is_nullable(expr : Expr, nullable : Map[String, Bool]) -> Bool {
  match expr {
    Literal(codes) => codes.length() == 0
    CharClass(_, _) | AnyChar => false
    RuleRef(name) => nullable.get(name).unwrap_or(false)
    Seq(items) => {
      for item in items {
        if !expr_is_nullable(item, nullable) {
          return false
        }
      }
      true
    }
    Alt(branches) => {
      for b in branches {
        if expr_is_nullable(b, nullable) {
          return true
        }
      }
      false
    }
    Repeat(inner, min_v, _) => min_v == 0 || expr_is_nullable(inner, nullable)
  }
}

///|
/// Compute the fixed-point set of rules that can match the empty string.
pub fn Grammar::nullable_rules(self : Grammar) -> Map[String, Bool] {
  let nullable : Map[String, Bool] = Map([])
  let mut changed = true
  while changed {
    changed = false
    for rule in self.rules {
      if !nullable.get(rule.name).unwrap_or(false) {
        if expr_is_nullable(rule.expr, nullable) {
          nullable[rule.name] = true
          changed = true
        }
      }
    }
  }
  nullable
}

///|
fn push_unique(arr : Array[String], val : String) -> Unit {
  for x in arr {
    if x == val {
      return
    }
  }
  arr.push(val)
}

///|
/// Collect all rule references appearing anywhere inside an expression.
fn collect_all_refs(expr : Expr, out : Array[String]) -> Unit {
  match expr {
    RuleRef(name) => push_unique(out, name)
    Seq(items) =>
      for item in items {
        collect_all_refs(item, out)
      }
    Alt(branches) =>
      for b in branches {
        collect_all_refs(b, out)
      }
    Repeat(inner, _, _) => collect_all_refs(inner, out)
    Literal(_) | CharClass(_, _) | AnyChar => ()
  }
}

///|
/// Return direct rule-to-rule dependency adjacency map.
pub fn Grammar::rule_dependencies(self : Grammar) -> Map[String, Array[String]] {
  let deps : Map[String, Array[String]] = Map([])
  for rule in self.rules {
    let refs = match deps.get(rule.name) {
      Some(existing) => existing
      None => {
        let a : Array[String] = []
        deps[rule.name] = a
        a
      }
    }
    collect_all_refs(rule.expr, refs)
  }
  deps
}

///|
/// Collect rules that can appear at the left-most (zero-consumed) position of `expr`.
fn collect_left_refs(
  expr : Expr,
  nullable : Map[String, Bool],
  out : Array[String],
) -> Unit {
  match expr {
    RuleRef(name) => push_unique(out, name)
    Seq(items) =>
      for item in items {
        collect_left_refs(item, nullable, out)
        if !expr_is_nullable(item, nullable) {
          break
        }
      }
    Alt(branches) =>
      for b in branches {
        collect_left_refs(b, nullable, out)
      }
    Repeat(inner, _, max_v) =>
      match max_v {
        Some(0) => ()
        _ => collect_left_refs(inner, nullable, out)
      }
    Literal(_) | CharClass(_, _) | AnyChar => ()
  }
}

///|
/// Collect rules that can be derived from `expr` while consuming zero input overall.
fn collect_zero_cost_refs(
  expr : Expr,
  nullable : Map[String, Bool],
  out : Array[String],
) -> Unit {
  match expr {
    RuleRef(name) => push_unique(out, name)
    Seq(items) =>
      // A reference in a sequence participates in an empty cycle only if all
      // sibling items can derive empty.
      for i = 0; i < items.length(); i = i + 1 {
        let mut others_nullable = true
        for j = 0; j < items.length(); j = j + 1 {
          if j != i && !expr_is_nullable(items[j], nullable) {
            others_nullable = false
            break
          }
        }
        if others_nullable {
          collect_zero_cost_refs(items[i], nullable, out)
        }
      }
    Alt(branches) =>
      for b in branches {
        collect_zero_cost_refs(b, nullable, out)
      }
    Repeat(inner, _, max_v) =>
      match max_v {
        Some(0) => ()
        _ => collect_zero_cost_refs(inner, nullable, out)
      }
    Literal(_) | CharClass(_, _) | AnyChar => ()
  }
}

///|
fn can_reach(
  start : String,
  target : String,
  graph : Map[String, Array[String]],
) -> Bool {
  let visited : Map[String, Bool] = Map([])
  let queue : Array[String] = []
  match graph.get(start) {
    Some(neighbors) =>
      for n in neighbors {
        if n == target {
          return true
        }
        if !visited.contains(n) {
          visited[n] = true
          queue.push(n)
        }
      }
    None => return false
  }
  let mut head = 0
  while head < queue.length() {
    let cur = queue[head]
    head += 1
    match graph.get(cur) {
      Some(neighbors) =>
        for n in neighbors {
          if n == target {
            return true
          }
          if !visited.contains(n) {
            visited[n] = true
            queue.push(n)
          }
        }
      None => ()
    }
  }
  false
}

///|
/// Detect rules participating in direct or indirect left recursion.
pub fn Grammar::find_left_recursion(self : Grammar) -> Array[String] {
  let nullable = self.nullable_rules()
  let left_graph : Map[String, Array[String]] = Map([])
  for rule in self.rules {
    let refs : Array[String] = []
    collect_left_refs(rule.expr, nullable, refs)
    left_graph[rule.name] = refs
  }
  let cyclic : Array[String] = []
  for rule in self.rules {
    if can_reach(rule.name, rule.name, left_graph) {
      push_unique(cyclic, rule.name)
    }
  }
  cyclic
}

///|
/// Detect rules that can cyclically derive themselves while consuming zero characters.
pub fn Grammar::find_empty_cycles(self : Grammar) -> Array[String] {
  let nullable = self.nullable_rules()
  let empty_graph : Map[String, Array[String]] = Map([])
  for rule in self.rules {
    let refs : Array[String] = []
    collect_zero_cost_refs(rule.expr, nullable, refs)
    empty_graph[rule.name] = refs
  }
  let cyclic : Array[String] = []
  for rule in self.rules {
    if can_reach(rule.name, rule.name, empty_graph) {
      push_unique(cyclic, rule.name)
    }
  }
  cyclic
}