///|
/// Maximum allowed regex pattern length in Unicode scalar values.
const MAX_PATTERN_CHARS : Int32 = 4096

///|
/// Maximum number of NFA states permitted for a compiled regex.
const MAX_NFA_STATES : Int32 = 4096

///|
/// Maximum explicit repetition count allowed in `{m}`, `{m,}`, or `{m,n}`.
const MAX_REPEAT_COUNT : Int32 = 1000

///|
/// Maximum group nesting depth permitted during regex parsing.
const MAX_GROUP_DEPTH : Int32 = 64

///|
/// Maximum compilation work units (guards against nested zero-width repeats).
const MAX_COMPILE_OPS : Int32 = 16384

///|
#derive(Eq, Debug)
priv enum ShorthandKind {
  Digit
  NotDigit
  Word
  NotWord
  Space
  NotSpace
}

///|
#derive(Eq, Debug)
priv struct CompiledClass {
  negated : Bool
  case_insensitive : Bool
  ranges : Array[(Int32, Int32)]
}

///|
priv enum ClassItem {
  Single(Char)
  Range(Char, Char)
  Shorthand(ShorthandKind)
  RangeSet(Array[(Int32, Int32)], Bool)
}

///|
#derive(Eq, Debug)
priv enum Matcher {
  Literal(Char, Bool)
  AnyChar(Bool)
  Shorthand(ShorthandKind)
  CharClass(Int32)
}

///|
#derive(Eq, Debug)
priv enum AnchorKind {
  BeginText
  EndText
  BeginLine
  EndLine
  WordBoundary
  NotWordBoundary
}

///|
#derive(Eq, Debug)
priv enum NfaState {
  Match(Matcher, Int32)
  Assert(AnchorKind, Int32)
  Split(Int32, Int32)
  Accept
}

///|
priv struct Flags {
  mut case_insensitive : Bool
  mut multiline : Bool
  mut dotall : Bool
}

///|
fn Flags::default() -> Flags {
  { case_insensitive: false, multiline: false, dotall: false, }
}

///|
fn Flags::copy(self : Flags) -> Flags {
  {
    case_insensitive: self.case_insensitive,
    multiline: self.multiline,
    dotall: self.dotall,
  }
}

///|
priv enum Ast {
  Empty
  AtomMatch(Matcher)
  AtomClass(CompiledClass)
  AtomAssert(AnchorKind)
  Concat(Array[Ast])
  Alt(Array[Ast])
  Repeat(Ast, Int32, Int32?, Bool)
}

///|
priv enum PieceResult {
  Node(Ast)
  FlagOnly
}

///|
priv enum ClassAtom {
  Char(Char)
  Shorthand(ShorthandKind)
  RangeSet(Array[(Int32, Int32)], Bool)
}

///|
/// A compiled ReDoS-safe Thompson NFA regular expression.
///
/// Matching executes in linear `O(states * chars)` time with zero backtracking.
#derive(Eq, Debug)
pub struct CompiledRegex {
  priv pattern : String
  priv start : Int32
  priv states : Array[NfaState]
  priv classes : Array[CompiledClass]
}

///|
/// Returns the original pattern string used to compile this regex.
pub fn CompiledRegex::pattern(self : CompiledRegex) -> String {
  self.pattern
}

///|
fn is_ascii_digit(ch : Char) -> Bool {
  ch >= '0' && ch <= '9'
}

///|
fn is_ascii_word(ch : Char) -> Bool {
  (ch >= '0' && ch <= '9') ||
  (ch >= 'a' && ch <= 'z') ||
  (ch >= 'A' && ch <= 'Z') ||
  ch == '_'
}

///|
fn is_ascii_space(ch : Char) -> Bool {
  ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\u{0c}'
}

///|
fn is_ascii_punct(ch : Char) -> Bool {
  let code = ch.to_int()
  (code >= 0x21 && code <= 0x2F) ||
  (code >= 0x3A && code <= 0x40) ||
  (code >= 0x5B && code <= 0x60) ||
  (code >= 0x7B && code <= 0x7E)
}

///|
fn posix_class_ranges(name : String) -> Array[(Int32, Int32)]? {
  match name {
    "alnum" => Some([(0x30, 0x39), (0x41, 0x5A), (0x61, 0x7A)])
    "alpha" => Some([(0x41, 0x5A), (0x61, 0x7A)])
    "ascii" => Some([(0x00, 0x7F)])
    "blank" => Some([(0x09, 0x09), (0x20, 0x20)])
    "cntrl" => Some([(0x00, 0x1F), (0x7F, 0x7F)])
    "digit" => Some([(0x30, 0x39)])
    "graph" => Some([(0x21, 0x7E)])
    "lower" => Some([(0x61, 0x7A)])
    "print" => Some([(0x20, 0x7E)])
    "punct" => Some([(0x21, 0x2F), (0x3A, 0x40), (0x5B, 0x60), (0x7B, 0x7E)])
    "space" => Some([(0x09, 0x0D), (0x20, 0x20)])
    "upper" => Some([(0x41, 0x5A)])
    "word" => Some([(0x30, 0x39), (0x41, 0x5A), (0x5F, 0x5F), (0x61, 0x7A)])
    "xdigit" => Some([(0x30, 0x39), (0x41, 0x46), (0x61, 0x66)])
    _ => None
  }
}

///|
fn hex_value(ch : Char) -> Int32? {
  if ch >= '0' && ch <= '9' {
    Some(ch.to_int() - '0'.to_int())
  } else if ch >= 'a' && ch <= 'f' {
    Some(ch.to_int() - 'a'.to_int() + 10)
  } else if ch >= 'A' && ch <= 'F' {
    Some(ch.to_int() - 'A'.to_int() + 10)
  } else {
    None
  }
}

///|
fn shorthand_matches(kind : ShorthandKind, ch : Char) -> Bool {
  match kind {
    Digit => is_ascii_digit(ch)
    NotDigit => !is_ascii_digit(ch)
    Word => is_ascii_word(ch)
    NotWord => !is_ascii_word(ch)
    Space => is_ascii_space(ch)
    NotSpace => !is_ascii_space(ch)
  }
}

///|
fn normalize_ranges(raw : Array[(Int32, Int32)]) -> Array[(Int32, Int32)] {
  if raw.is_empty() {
    return []
  }
  let sorted = raw.copy()
  sorted.sort_by(fn(a, b) { if a.0 != b.0 { a.0 - b.0 } else { a.1 - b.1 } })
  let merged : Array[(Int32, Int32)] = []
  let mut cur_lo = sorted[0].0
  let mut cur_hi = sorted[0].1
  for i in 1.. cur_hi {
        cur_hi = hi
      }
    } else {
      merged.push((cur_lo, cur_hi))
      cur_lo = lo
      cur_hi = hi
    }
  }
  merged.push((cur_lo, cur_hi))
  merged
}

///|
fn complement_ranges(ranges : Array[(Int32, Int32)]) -> Array[(Int32, Int32)] {
  let norm = normalize_ranges(ranges)
  let out : Array[(Int32, Int32)] = []
  let mut cur = 0
  for pair in norm {
    let (lo, hi) = pair
    if cur < lo {
      out.push((cur, lo - 1))
    }
    if hi >= 0x10FFFF {
      return out
    }
    cur = hi + 1
  }
  if cur <= 0x10FFFF {
    out.push((cur, 0x10FFFF))
  }
  out
}

///|
/// Binary searches `unicode_fold_ranges` for the smallest index whose `end`
/// is `>= target` (or `unicode_fold_ranges.length()` if none).
fn find_first_fold_entry(target : Int32) -> Int32 {
  let mut lo = 0
  let mut hi = unicode_fold_ranges.length()
  while lo < hi {
    let mid = lo + (hi - lo) / 2
    if unicode_fold_ranges[mid].1 < target {
      lo = mid + 1
    } else {
      hi = mid
    }
  }
  lo
}

///|
fn shorthand_positive_ranges(
  kind : ShorthandKind,
) -> (Array[(Int32, Int32)], Bool) {
  match kind {
    Digit => ([(0x30, 0x39)], false)
    NotDigit => ([(0x30, 0x39)], true)
    Word => ([(0x30, 0x39), (0x41, 0x5A), (0x5F, 0x5F), (0x61, 0x7A)], false)
    NotWord => ([(0x30, 0x39), (0x41, 0x5A), (0x5F, 0x5F), (0x61, 0x7A)], true)
    Space => ([(0x09, 0x0A), (0x0C, 0x0D), (0x20, 0x20)], false)
    NotSpace => ([(0x09, 0x0A), (0x0C, 0x0D), (0x20, 0x20)], true)
  }
}

///|
fn ranges_contain(ranges : Array[(Int32, Int32)], code : Int32) -> Bool {
  let mut lo = 0
  let mut hi = ranges.length()
  while lo < hi {
    let mid = lo + (hi - lo) / 2
    let (rlo, rhi) = ranges[mid]
    if code < rlo {
      hi = mid
    } else if code > rhi {
      lo = mid + 1
    } else {
      return true
    }
  }
  false
}

///|
fn CompiledClass::matches(self : CompiledClass, ch : Char) -> Bool {
  let key = if self.case_insensitive {
    unicode_fold_code(ch.to_int())
  } else {
    ch.to_int()
  }
  let matched = ranges_contain(self.ranges, key)
  if self.negated {
    !matched
  } else {
    matched
  }
}

///|
fn Matcher::matches(
  self : Matcher,
  ch : Char,
  classes : Array[CompiledClass],
  class_cache_gen : Array[Int32],
  class_cache_val : Array[Bool],
  gen : Int32,
) -> Bool {
  match self {
    Literal(target, case_insensitive) =>
      if case_insensitive {
        unicode_fold_code(ch.to_int()) == unicode_fold_code(target.to_int())
      } else {
        ch == target
      }
    AnyChar(dotall) => dotall || ch != '\n'
    Shorthand(kind) => shorthand_matches(kind, ch)
    CharClass(cid) => {
      if class_cache_gen[cid] != gen {
        class_cache_gen[cid] = gen
        class_cache_val[cid] = classes[cid].matches(ch)
      }
      class_cache_val[cid]
    }
  }
}

///|
fn is_word_at(chars : Array[Char], idx : Int32) -> Bool {
  if idx < 0 || idx >= chars.length() {
    false
  } else {
    is_ascii_word(chars[idx])
  }
}

///|
fn AnchorKind::matches(
  self : AnchorKind,
  chars : Array[Char],
  pos : Int32,
) -> Bool {
  let len = chars.length()
  match self {
    BeginText => pos == 0
    EndText => pos == len
    BeginLine => pos == 0 || chars[pos - 1] == '\n'
    EndLine => pos == len || chars[pos] == '\n'
    WordBoundary => is_word_at(chars, pos - 1) != is_word_at(chars, pos)
    NotWordBoundary => is_word_at(chars, pos - 1) == is_word_at(chars, pos)
  }
}

///|
priv struct Parser {
  chars : Array[Char]
  mut index : Int32
  mut flags : Flags
  mut depth : Int32
  mut compile_ops : Int32
  budget : EvalBudget?
  mut limit_err : LimitError?
}

///|
fn Parser::new(chars : Array[Char], budget? : EvalBudget) -> Parser {
  {
    chars,
    index: 0,
    flags: Flags::default(),
    depth: 0,
    compile_ops: 0,
    budget,
    limit_err: None,
  }
}

///|
fn Parser::consume_compile_ops(
  self : Parser,
  count : Int32,
) -> Result[Unit, String] {
  if count <= 0 {
    return Ok(())
  }
  match self.limit_err {
    Some(e) => return Err(e.message())
    None => ()
  }
  for _ in 0..
        match b.consume_step() {
          Ok(_) => ()
          Err(e) => {
            self.limit_err = Some(e)
            return Err(e.message())
          }
        }
      None => ()
    }
    self.compile_ops += 1
    if self.compile_ops > MAX_COMPILE_OPS {
      return Err("regex too complex: exceeds compilation budget")
    }
  }
  Ok(())
}

///|
/// Appends the image of `[lo, hi]` under `unicode_fold_code` into `out`,
/// advancing `cursor` monotonically across `unicode_fold_ranges` in O(active)
/// time while charging emitted ranges against compile limits and `EvalBudget`.
fn Parser::fold_range_with_cursor(
  self : Parser,
  lo : Int32,
  hi : Int32,
  cursor : Ref[Int32],
  out : Array[(Int32, Int32)],
) -> Result[Unit, String] {
  let n_fold = unicode_fold_ranges.length()
  let mut idx = cursor.val
  while idx < n_fold && unicode_fold_ranges[idx].1 < lo {
    idx += 1
  }
  let mut cur = lo
  while cur <= hi && idx < n_fold {
    let (start, end, step, delta) = unicode_fold_ranges[idx]
    if start > hi {
      break
    }
    if cur < start {
      match self.consume_compile_ops(1) {
        Ok(_) => ()
        Err(e) => return Err(e)
      }
      out.push((cur, start - 1))
      cur = start
    }
    let seg_hi = if hi < end { hi } else { end }
    if step == 1 {
      match self.consume_compile_ops(1) {
        Ok(_) => ()
        Err(e) => return Err(e)
      }
      out.push((cur + delta, seg_hi + delta))
    } else {
      let span = seg_hi - cur + 1
      match self.consume_compile_ops(span) {
        Ok(_) => ()
        Err(e) => return Err(e)
      }
      for c in cur..<=seg_hi {
        let f = if (c - start) % step == 0 { c + delta } else { c }
        out.push((f, f))
      }
    }
    cur = seg_hi + 1
    if end <= hi {
      idx += 1
    }
  }
  if cur <= hi {
    match self.consume_compile_ops(1) {
      Ok(_) => ()
      Err(e) => return Err(e)
    }
    out.push((cur, hi))
  }
  cursor.val = idx
  Ok(())
}

///|
/// Appends the image of an isolated range `[lo, hi]` under `unicode_fold_code`
/// into `out` via binary search into `unicode_fold_ranges`.
fn Parser::fold_range_into(
  self : Parser,
  lo : Int32,
  hi : Int32,
  out : Array[(Int32, Int32)],
) -> Result[Unit, String] {
  let cursor : Ref[Int32] = { val: find_first_fold_entry(lo), }
  self.fold_range_with_cursor(lo, hi, cursor, out)
}

///|
/// Folds a range set using an O(N + active_entries) two-pointer merge against
/// `unicode_fold_ranges`.
fn Parser::fold_ranges(
  self : Parser,
  ranges : Array[(Int32, Int32)],
) -> Result[Array[(Int32, Int32)], String] {
  if ranges.is_empty() {
    return Ok([])
  }
  match self.consume_compile_ops(ranges.length()) {
    Ok(_) => ()
    Err(e) => return Err(e)
  }
  let norm = normalize_ranges(ranges)
  let folded : Array[(Int32, Int32)] = []
  let cursor : Ref[Int32] = { val: find_first_fold_entry(norm[0].0), }
  for r in norm {
    match self.fold_range_with_cursor(r.0, r.1, cursor, folded) {
      Ok(_) => ()
      Err(e) => return Err(e)
    }
  }
  Ok(normalize_ranges(folded))
}

///|
/// Compiles a positive or negated range set item, preserving RE2 `(?i)\P{...}`
/// semantics (`complement(fold(pos))`).
fn Parser::compile_range_set_item(
  self : Parser,
  pos : Array[(Int32, Int32)],
  is_neg : Bool,
  case_insensitive : Bool,
) -> Result[Array[(Int32, Int32)], String] {
  if case_insensitive {
    let folded = match self.fold_ranges(pos) {
      Ok(rs) => rs
      Err(e) => return Err(e)
    }
    if is_neg {
      match self.consume_compile_ops(folded.length()) {
        Ok(_) => ()
        Err(e) => return Err(e)
      }
      Ok(complement_ranges(folded))
    } else {
      Ok(folded)
    }
  } else if is_neg {
    match self.consume_compile_ops(pos.length()) {
      Ok(_) => ()
      Err(e) => return Err(e)
    }
    Ok(complement_ranges(pos))
  } else {
    Ok(pos)
  }
}

///|
fn Parser::compile_char_class(
  self : Parser,
  negated : Bool,
  items : Array[ClassItem],
  case_insensitive : Bool,
) -> Result[CompiledClass, String] {
  let compiled : Array[(Int32, Int32)] = []
  for item in items {
    match item {
      Single(c) => {
        match self.consume_compile_ops(1) {
          Ok(_) => ()
          Err(e) => return Err(e)
        }
        let code = c.to_int()
        if case_insensitive {
          let f = unicode_fold_code(code)
          compiled.push((f, f))
        } else {
          compiled.push((code, code))
        }
      }
      Range(lo, hi) =>
        if case_insensitive {
          match self.fold_range_into(lo.to_int(), hi.to_int(), compiled) {
            Ok(_) => ()
            Err(e) => return Err(e)
          }
        } else {
          match self.consume_compile_ops(1) {
            Ok(_) => ()
            Err(e) => return Err(e)
          }
          compiled.push((lo.to_int(), hi.to_int()))
        }
      Shorthand(kind) => {
        let (pos, is_neg) = shorthand_positive_ranges(kind)
        let expanded = match
          self.compile_range_set_item(pos, is_neg, case_insensitive) {
          Ok(rs) => rs
          Err(e) => return Err(e)
        }
        match self.consume_compile_ops(expanded.length()) {
          Ok(_) => ()
          Err(e) => return Err(e)
        }
        for r in expanded {
          compiled.push(r)
        }
      }
      RangeSet(pos, is_neg) => {
        let expanded = match
          self.compile_range_set_item(pos, is_neg, case_insensitive) {
          Ok(rs) => rs
          Err(e) => return Err(e)
        }
        match self.consume_compile_ops(expanded.length()) {
          Ok(_) => ()
          Err(e) => return Err(e)
        }
        for r in expanded {
          compiled.push(r)
        }
      }
    }
  }
  Ok({ negated, case_insensitive, ranges: normalize_ranges(compiled), })
}

///|
fn Parser::peek(self : Parser) -> Char? {
  if self.limit_err is Some(_) {
    return None
  }
  if self.index < self.chars.length() {
    Some(self.chars[self.index])
  } else {
    None
  }
}

///|
fn Parser::peek_at(self : Parser, delta : Int32) -> Char? {
  if self.limit_err is Some(_) {
    return None
  }
  let target = self.index + delta
  if target >= 0 && target < self.chars.length() {
    Some(self.chars[target])
  } else {
    None
  }
}

///|
fn Parser::advance(self : Parser) -> Char? {
  if self.limit_err is Some(_) {
    return None
  }
  match self.budget {
    Some(b) =>
      match b.consume_step() {
        Ok(_) => ()
        Err(e) => {
          self.limit_err = Some(e)
          return None
        }
      }
    None => ()
  }
  if self.index < self.chars.length() {
    let ch = self.chars[self.index]
    self.index += 1
    Some(ch)
  } else {
    None
  }
}

///|
fn Parser::parse_hex_fixed(
  self : Parser,
  count : Int32,
) -> Result[Char, String] {
  let mut code = 0
  for _ in 0..
        match hex_value(ch) {
          Some(d) => code = (code << 4) | d
          None => return Err("invalid hex escape sequence in regex")
        }
      None => return Err("truncated hex escape sequence in regex")
    }
  }
  match code.to_char() {
    Some(ch) => Ok(ch)
    None => Err("invalid Unicode codepoint in regex escape")
  }
}

///|
fn Parser::parse_hex_braced(self : Parser) -> Result[Char, String] {
  let mut code = 0
  let mut digits = 0
  let mut overflow = false
  while true {
    match self.advance() {
      None => return Err("unclosed braced hex escape in regex")
      Some('}') => {
        if digits == 0 {
          return Err("empty braced hex escape in regex")
        }
        if overflow {
          return Err("Unicode codepoint out of range in regex escape")
        }
        match code.to_char() {
          Some(ch) => return Ok(ch)
          None => return Err("invalid Unicode codepoint in regex escape")
        }
      }
      Some(ch) =>
        match hex_value(ch) {
          Some(d) => {
            digits += 1
            if code > 0x10FFFF {
              overflow = true
            } else {
              code = (code << 4) | d
              if code > 0x10FFFF {
                overflow = true
              }
            }
          }
          None => return Err("invalid hex digit in braced regex escape")
        }
    }
  }
  Err("unclosed braced hex escape in regex")
}

///|
fn Parser::parse_unicode_property(
  self : Parser,
  is_upper_p : Bool,
) -> Result[(Array[(Int32, Int32)], Bool), String] {
  let prefix = if is_upper_p { "P" } else { "p" }
  let (raw_name, prop_name, inner_neg) = match self.peek() {
    None => return Err("truncated Unicode property escape in regex")
    Some('{') => {
      ignore(self.advance())
      let inner_neg = if self.peek() == Some('^') {
        ignore(self.advance())
        true
      } else {
        false
      }
      let buf = StringBuilder()
      let mut closed = false
      while true {
        match self.advance() {
          None => break
          Some('}') => {
            closed = true
            break
          }
          Some(ch) => buf.write_char(ch)
        }
      }
      if !closed {
        return Err("unclosed Unicode property escape in regex")
      }
      let s = buf.to_string()
      if s.is_empty() {
        return Err("empty Unicode property escape in regex")
      }
      let raw = if inner_neg { "^" + s } else { s }
      (raw, s, inner_neg)
    }
    Some(ch) =>
      if (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') {
        ignore(self.advance())
        let s = ch.to_string()
        (s, s, false)
      } else {
        return Err(
          "invalid Unicode property escape '\\" +
          prefix +
          ch.to_string() +
          "' in regex",
        )
      }
  }
  let is_neg = if inner_neg { !is_upper_p } else { is_upper_p }
  match unicode_property_ranges(prop_name) {
    Some(ranges) => Ok((ranges, is_neg))
    None =>
      Err(
        "unsupported Unicode property '\\" +
        prefix +
        "{" +
        raw_name +
        "}' in regex",
      )
  }
}

///|
fn Parser::parse_posix_class(
  self : Parser,
) -> Result[(Array[(Int32, Int32)], Bool), String] {
  // Opening "[: " has been peeked: consume '[' and ':'.
  ignore(self.advance())
  ignore(self.advance())
  let negated = if self.peek() == Some('^') {
    ignore(self.advance())
    true
  } else {
    false
  }
  let buf = StringBuilder()
  while true {
    match self.peek() {
      None => return Err("unclosed POSIX character class in regex")
      Some(':') if self.peek_at(1) == Some(']') => {
        ignore(self.advance())
        ignore(self.advance())
        break
      }
      Some(']') => return Err("unclosed POSIX character class in regex")
      Some(ch) => {
        ignore(self.advance())
        buf.write_char(ch)
      }
    }
  }
  let name = buf.to_string()
  match posix_class_ranges(name) {
    Some(ranges) => Ok((ranges, negated))
    None =>
      Err(
        "unknown POSIX character class '[:" +
        (if negated { "^" } else { "" }) +
        name +
        ":]' in regex",
      )
  }
}

///|
fn Parser::parse_escape_char_or_shorthand(
  self : Parser,
  in_class : Bool,
) -> Result[ClassAtom, String] {
  match self.advance() {
    None => Err("trailing backslash in regex")
    Some('d') => Ok(Shorthand(Digit))
    Some('D') => Ok(Shorthand(NotDigit))
    Some('w') => Ok(Shorthand(Word))
    Some('W') => Ok(Shorthand(NotWord))
    Some('s') => Ok(Shorthand(Space))
    Some('S') => Ok(Shorthand(NotSpace))
    Some('p') =>
      match self.parse_unicode_property(false) {
        Ok((rs, is_neg)) => Ok(RangeSet(rs, is_neg))
        Err(e) => Err(e)
      }
    Some('P') =>
      match self.parse_unicode_property(true) {
        Ok((rs, is_neg)) => Ok(RangeSet(rs, is_neg))
        Err(e) => Err(e)
      }
    Some('n') => Ok(Char('\n'))
    Some('r') => Ok(Char('\r'))
    Some('t') => Ok(Char('\t'))
    Some('f') => Ok(Char('\u{0c}'))
    Some('v') => Ok(Char('\u{0b}'))
    Some('a') => Ok(Char('\u{07}'))
    Some('x') =>
      if self.peek() == Some('{') {
        ignore(self.advance())
        match self.parse_hex_braced() {
          Ok(ch) => Ok(Char(ch))
          Err(e) => Err(e)
        }
      } else {
        match self.parse_hex_fixed(2) {
          Ok(ch) => Ok(Char(ch))
          Err(e) => Err(e)
        }
      }
    Some('u') =>
      if self.peek() == Some('{') {
        ignore(self.advance())
        match self.parse_hex_braced() {
          Ok(ch) => Ok(Char(ch))
          Err(e) => Err(e)
        }
      } else {
        match self.parse_hex_fixed(4) {
          Ok(ch) => Ok(Char(ch))
          Err(e) => Err(e)
        }
      }
    Some(ch) =>
      if is_ascii_punct(ch) {
        Ok(Char(ch))
      } else if in_class {
        Err(
          "invalid escape sequence '\\" +
          ch.to_string() +
          "' in character class",
        )
      } else {
        Err("invalid escape sequence '\\" + ch.to_string() + "' in regex")
      }
  }
}

///|
fn Parser::parse_escape_atom(self : Parser) -> Result[Ast, String] {
  match self.peek() {
    None => Err("trailing backslash in regex")
    Some('A') => {
      ignore(self.advance())
      Ok(AtomAssert(BeginText))
    }
    Some('z') => {
      ignore(self.advance())
      Ok(AtomAssert(EndText))
    }
    Some('b') => {
      ignore(self.advance())
      Ok(AtomAssert(WordBoundary))
    }
    Some('B') => {
      ignore(self.advance())
      Ok(AtomAssert(NotWordBoundary))
    }
    Some('p') | Some('P') => {
      let is_upper = self.advance() == Some('P')
      match self.parse_unicode_property(is_upper) {
        Ok((rs, is_neg)) =>
          match
            self.compile_char_class(
              is_neg,
              [RangeSet(rs, false)],
              self.flags.case_insensitive,
            ) {
            Ok(cls) => Ok(AtomClass(cls))
            Err(e) => Err(e)
          }
        Err(e) => Err(e)
      }
    }
    _ =>
      match self.parse_escape_char_or_shorthand(false) {
        Ok(Char(ch)) => Ok(AtomMatch(Literal(ch, self.flags.case_insensitive)))
        Ok(Shorthand(kind)) =>
          if self.flags.case_insensitive {
            match self.compile_char_class(false, [Shorthand(kind)], true) {
              Ok(cls) => Ok(AtomClass(cls))
              Err(e) => Err(e)
            }
          } else {
            Ok(AtomMatch(Shorthand(kind)))
          }
        Ok(RangeSet(rs, is_neg)) =>
          match
            self.compile_char_class(
              false,
              [RangeSet(rs, is_neg)],
              self.flags.case_insensitive,
            ) {
            Ok(cls) => Ok(AtomClass(cls))
            Err(e) => Err(e)
          }
        Err(e) => Err(e)
      }
  }
}

///|
fn Parser::parse_class_atom(self : Parser) -> Result[ClassAtom, String] {
  match self.peek() {
    None => Err("unclosed character class in regex")
    Some('[') if self.peek_at(1) == Some(':') =>
      match self.parse_posix_class() {
        Ok((rs, neg)) => Ok(RangeSet(rs, neg))
        Err(e) => Err(e)
      }
    Some('\\') => {
      ignore(self.advance())
      self.parse_escape_char_or_shorthand(true)
    }
    Some(_) =>
      match self.advance() {
        Some(ch) => Ok(Char(ch))
        None => Err("unclosed character class in regex")
      }
  }
}

///|
fn Parser::parse_char_class(self : Parser) -> Result[Ast, String] {
  // Opening '[' has already been consumed.
  let negated = if self.peek() == Some('^') {
    ignore(self.advance())
    true
  } else {
    false
  }
  let items : Array[ClassItem] = []
  let mut first = true
  while true {
    match self.peek() {
      None => return Err("unclosed character class in regex")
      Some(']') if !first => {
        ignore(self.advance())
        match
          self.compile_char_class(negated, items, self.flags.case_insensitive) {
          Ok(cls) => return Ok(AtomClass(cls))
          Err(e) => return Err(e)
        }
      }
      _ => {
        let atom = match self.parse_class_atom() {
          Ok(a) => a
          Err(e) => return Err(e)
        }
        first = false
        match atom {
          Char(lo) =>
            if self.peek() == Some('-') &&
              self.peek_at(1) != Some(']') &&
              self.peek_at(1) != None {
              ignore(self.advance()) // consume '-'
              let end_atom = match self.parse_class_atom() {
                Ok(a) => a
                Err(e) => return Err(e)
              }
              match end_atom {
                Char(hi) => {
                  if lo.to_int() > hi.to_int() {
                    return Err(
                      "invalid character class range '" +
                      lo.to_string() +
                      "-" +
                      hi.to_string() +
                      "' in regex",
                    )
                  }
                  items.push(Range(lo, hi))
                }
                Shorthand(_) | RangeSet(_, _) =>
                  return Err(
                    "invalid character class range: shorthand class cannot be range endpoint",
                  )
              }
            } else {
              items.push(Single(lo))
            }
          Shorthand(kind) => items.push(Shorthand(kind))
          RangeSet(rs, neg) => items.push(RangeSet(rs, neg))
        }
      }
    }
  }
  Err("unclosed character class in regex")
}

///|
fn Parser::parse_uint_bounded(self : Parser) -> (Int32, Bool) {
  let mut val = 0
  let mut overflow = false
  while true {
    match self.peek() {
      Some(ch) if is_ascii_digit(ch) => {
        ignore(self.advance())
        let d = ch.to_int() - '0'.to_int()
        if val > MAX_REPEAT_COUNT {
          overflow = true
        } else {
          val = val * 10 + d
          if val > MAX_REPEAT_COUNT {
            overflow = true
          }
        }
      }
      _ => break
    }
  }
  (val, overflow)
}

///|
/// Attempts to parse `{m}`, `{m,}`, or `{m,n}` at the current `{`.
/// Returns:
/// - `Ok(Some((min, max)))` if a valid counted quantifier was parsed.
/// - `Ok(None)` if `{` does not form quantifier syntax (caller treats `{` as literal).
/// - `Err(msg)` if `{m,n}` syntax was recognized but violates bounds or `min > max`.
fn Parser::try_parse_counted_quantifier(
  self : Parser,
) -> Result[(Int32, Int32?)?, String] {
  if self.peek() != Some('{') {
    return Ok(None)
  }
  let saved = self.index
  ignore(self.advance()) // consume '{'
  match self.peek() {
    Some(ch) if is_ascii_digit(ch) => ()
    _ => {
      self.index = saved
      return Ok(None)
    }
  }
  let (min_val, min_overflow) = self.parse_uint_bounded()
  match self.peek() {
    Some('}') => {
      ignore(self.advance())
      if min_overflow {
        return Err(
          "regex too complex: repeat count exceeds limit (" +
          MAX_REPEAT_COUNT.to_string() +
          ")",
        )
      }
      Ok(Some((min_val, Some(min_val))))
    }
    Some(',') => {
      ignore(self.advance())
      match self.peek() {
        Some('}') => {
          ignore(self.advance())
          if min_overflow {
            return Err(
              "regex too complex: repeat count exceeds limit (" +
              MAX_REPEAT_COUNT.to_string() +
              ")",
            )
          }
          Ok(Some((min_val, None)))
        }
        Some(ch) if is_ascii_digit(ch) => {
          let (max_val, max_overflow) = self.parse_uint_bounded()
          if self.peek() == Some('}') {
            ignore(self.advance())
            if min_overflow || max_overflow {
              return Err(
                "regex too complex: repeat count exceeds limit (" +
                MAX_REPEAT_COUNT.to_string() +
                ")",
              )
            }
            if max_val < min_val {
              return Err(
                "invalid quantifier range {" +
                min_val.to_string() +
                "," +
                max_val.to_string() +
                "} in regex",
              )
            }
            Ok(Some((min_val, Some(max_val))))
          } else {
            self.index = saved
            Ok(None)
          }
        }
        _ => {
          self.index = saved
          Ok(None)
        }
      }
    }
    _ => {
      self.index = saved
      Ok(None)
    }
  }
}

///|
fn Parser::parse_group(self : Parser) -> Result[PieceResult, String] {
  // Opening '(' has already been consumed.
  if self.depth >= MAX_GROUP_DEPTH {
    return Err(
      "regex too complex: exceeds maximum group nesting depth (" +
      MAX_GROUP_DEPTH.to_string() +
      ")",
    )
  }
  if self.peek() == Some('?') {
    ignore(self.advance()) // consume '?'
    match self.peek() {
      None => return Err("unclosed group in regex")
      Some(':') => {
        ignore(self.advance())
        let saved_flags = self.flags.copy()
        self.depth += 1
        let body = self.parse_alt()
        self.depth -= 1
        self.flags = saved_flags
        match body {
          Err(e) => return Err(e)
          Ok(ast) => {
            if self.peek() != Some(')') {
              return Err("unclosed group in regex")
            }
            ignore(self.advance())
            return Ok(Node(ast))
          }
        }
      }
      _ => {
        let new_flags = self.flags.copy()
        let mut negating = false
        let mut saw_flag = false
        let mut saw_flag_after_minus = false
        while true {
          match self.peek() {
            None => return Err("unclosed flag group in regex")
            Some(')') => {
              if !saw_flag || (negating && !saw_flag_after_minus) {
                return Err("invalid empty flag specification in regex")
              }
              ignore(self.advance())
              self.flags = new_flags
              return Ok(FlagOnly)
            }
            Some(':') => {
              if !saw_flag || (negating && !saw_flag_after_minus) {
                return Err("invalid empty flag specification in regex")
              }
              ignore(self.advance())
              let saved_flags = self.flags.copy()
              self.flags = new_flags
              self.depth += 1
              let body = self.parse_alt()
              self.depth -= 1
              self.flags = saved_flags
              match body {
                Err(e) => return Err(e)
                Ok(ast) => {
                  if self.peek() != Some(')') {
                    return Err("unclosed group in regex")
                  }
                  ignore(self.advance())
                  return Ok(Node(ast))
                }
              }
            }
            Some('-') => {
              if negating {
                return Err("duplicate '-' in regex flag specification")
              }
              ignore(self.advance())
              negating = true
            }
            Some('i') => {
              ignore(self.advance())
              new_flags.case_insensitive = !negating
              saw_flag = true
              if negating {
                saw_flag_after_minus = true
              }
            }
            Some('m') => {
              ignore(self.advance())
              new_flags.multiline = !negating
              saw_flag = true
              if negating {
                saw_flag_after_minus = true
              }
            }
            Some('s') => {
              ignore(self.advance())
              new_flags.dotall = !negating
              saw_flag = true
              if negating {
                saw_flag_after_minus = true
              }
            }
            Some(ch) =>
              return Err("invalid regex flag '" + ch.to_string() + "'")
          }
        }
        return Err("unclosed flag group in regex")
      }
    }
  } else {
    let saved_flags = self.flags.copy()
    self.depth += 1
    let body = self.parse_alt()
    self.depth -= 1
    self.flags = saved_flags
    match body {
      Err(e) => Err(e)
      Ok(ast) => {
        if self.peek() != Some(')') {
          return Err("unclosed group in regex")
        }
        ignore(self.advance())
        Ok(Node(ast))
      }
    }
  }
}

///|
fn Parser::parse_piece(self : Parser) -> Result[PieceResult, String] {
  let atom : Ast = match self.peek() {
    None => return Err("unexpected end of regex")
    Some('(') => {
      ignore(self.advance())
      match self.parse_group() {
        Ok(FlagOnly) => return Ok(FlagOnly)
        Ok(Node(ast)) => ast
        Err(e) => return Err(e)
      }
    }
    Some('[') => {
      ignore(self.advance())
      match self.parse_char_class() {
        Ok(ast) => ast
        Err(e) => return Err(e)
      }
    }
    Some('.') => {
      ignore(self.advance())
      AtomMatch(AnyChar(self.flags.dotall))
    }
    Some('^') => {
      ignore(self.advance())
      if self.flags.multiline {
        AtomAssert(BeginLine)
      } else {
        AtomAssert(BeginText)
      }
    }
    Some('$') => {
      ignore(self.advance())
      if self.flags.multiline {
        AtomAssert(EndLine)
      } else {
        AtomAssert(EndText)
      }
    }
    Some('\\') => {
      ignore(self.advance())
      match self.parse_escape_atom() {
        Ok(ast) => ast
        Err(e) => return Err(e)
      }
    }
    Some(ch) if ch == '*' || ch == '+' || ch == '?' =>
      return Err("missing argument to quantifier '" + ch.to_string() + "'")
    Some('{') =>
      match self.try_parse_counted_quantifier() {
        Ok(Some(_)) => return Err("missing argument to counted quantifier")
        Err(e) => return Err(e)
        Ok(None) => {
          ignore(self.advance())
          AtomMatch(Literal('{', self.flags.case_insensitive))
        }
      }
    Some(ch) => {
      ignore(self.advance())
      AtomMatch(Literal(ch, self.flags.case_insensitive))
    }
  }
  // Parse at most one optional quantifier (with optional lazy '?').
  match self.peek() {
    Some('*') => {
      ignore(self.advance())
      let greedy = if self.peek() == Some('?') {
        ignore(self.advance())
        false
      } else {
        true
      }
      Ok(Node(Repeat(atom, 0, None, greedy)))
    }
    Some('+') => {
      ignore(self.advance())
      let greedy = if self.peek() == Some('?') {
        ignore(self.advance())
        false
      } else {
        true
      }
      Ok(Node(Repeat(atom, 1, None, greedy)))
    }
    Some('?') => {
      ignore(self.advance())
      let greedy = if self.peek() == Some('?') {
        ignore(self.advance())
        false
      } else {
        true
      }
      Ok(Node(Repeat(atom, 0, Some(1), greedy)))
    }
    Some('{') =>
      match self.try_parse_counted_quantifier() {
        Ok(Some((min_val, max_val))) => {
          let greedy = if self.peek() == Some('?') {
            ignore(self.advance())
            false
          } else {
            true
          }
          Ok(Node(Repeat(atom, min_val, max_val, greedy)))
        }
        Ok(None) => Ok(Node(atom))
        Err(e) => Err(e)
      }
    _ => Ok(Node(atom))
  }
}

///|
fn Parser::parse_concat(self : Parser) -> Result[Ast, String] {
  let parts : Array[Ast] = []
  while true {
    match self.peek() {
      None | Some('|') | Some(')') => break
      _ =>
        match self.parse_piece() {
          Ok(FlagOnly) => ()
          Ok(Node(node)) => parts.push(node)
          Err(e) => return Err(e)
        }
    }
  }
  if parts.is_empty() {
    Ok(Empty)
  } else if parts.length() == 1 {
    Ok(parts[0])
  } else {
    Ok(Concat(parts))
  }
}

///|
fn Parser::parse_alt(self : Parser) -> Result[Ast, String] {
  let first = match self.parse_concat() {
    Ok(node) => node
    Err(e) => return Err(e)
  }
  if self.peek() != Some('|') {
    return Ok(first)
  }
  let branches : Array[Ast] = [first]
  while self.peek() == Some('|') {
    ignore(self.advance())
    match self.parse_concat() {
      Ok(node) => branches.push(node)
      Err(e) => return Err(e)
    }
  }
  Ok(Alt(branches))
}

///|
priv struct Compiler {
  states : Array[NfaState]
  class_pool : Array[CompiledClass]
  mut ops : Int32
  budget : EvalBudget?
  mut limit_err : LimitError?
}

///|
fn Compiler::new(budget? : EvalBudget, initial_ops~ : Int32 = 0) -> Compiler {
  {
    states: [Accept],
    class_pool: [],
    ops: initial_ops,
    budget,
    limit_err: None,
  }
}

///|
fn Compiler::intern_class(self : Compiler, cls : CompiledClass) -> Int32 {
  for i in 0.. Result[Unit, String] {
  match self.budget {
    Some(b) =>
      match b.consume_step() {
        Ok(_) => ()
        Err(e) => {
          self.limit_err = Some(e)
          return Err(e.message())
        }
      }
    None => ()
  }
  self.ops += 1
  if self.ops > MAX_COMPILE_OPS {
    Err("regex too complex: exceeds compilation budget")
  } else {
    Ok(())
  }
}

///|
fn Compiler::emit(self : Compiler, state : NfaState) -> Result[Int32, String] {
  if self.states.length() >= MAX_NFA_STATES {
    return Err(
      "regex too complex: exceeds state limit (" +
      MAX_NFA_STATES.to_string() +
      ")",
    )
  }
  let id = self.states.length()
  self.states.push(state)
  Ok(id)
}

///|
fn Compiler::compile_plus(
  self : Compiler,
  inner : Ast,
  next : Int32,
  greedy : Bool,
) -> Result[Int32, String] {
  let split_id = match self.emit(Accept) {
    Ok(id) => id
    Err(e) => return Err(e)
  }
  let body = match self.compile(inner, split_id) {
    Ok(id) => id
    Err(e) => return Err(e)
  }
  self.states[split_id] = if greedy {
    Split(body, next)
  } else {
    Split(next, body)
  }
  Ok(body)
}

///|
fn ast_can_match_empty(node : Ast) -> Bool {
  match node {
    Empty | AtomAssert(_) => true
    AtomMatch(_) | AtomClass(_) => false
    Concat(parts) => {
      for part in parts {
        if !ast_can_match_empty(part) {
          return false
        }
      }
      true
    }
    Alt(branches) => {
      for branch in branches {
        if ast_can_match_empty(branch) {
          return true
        }
      }
      false
    }
    Repeat(inner, min_val, _, _) => min_val == 0 || ast_can_match_empty(inner)
  }
}

///|
fn Compiler::compile(
  self : Compiler,
  node : Ast,
  next : Int32,
) -> Result[Int32, String] {
  match self.consume_op() {
    Ok(_) => ()
    Err(e) => return Err(e)
  }
  match node {
    Empty => Ok(next)
    AtomMatch(matcher) => self.emit(Match(matcher, next))
    AtomClass(cls) => {
      let cid = self.intern_class(cls)
      self.emit(Match(CharClass(cid), next))
    }
    AtomAssert(anchor) => self.emit(Assert(anchor, next))
    Concat(parts) => {
      let mut cur = next
      let mut i = parts.length() - 1
      while i >= 0 {
        cur = match self.compile(parts[i], cur) {
          Ok(id) => id
          Err(e) => return Err(e)
        }
        i -= 1
      }
      Ok(cur)
    }
    Alt(branches) => {
      if branches.is_empty() {
        return Ok(next)
      }
      let mut cur = match self.compile(branches[branches.length() - 1], next) {
        Ok(id) => id
        Err(e) => return Err(e)
      }
      let mut i = branches.length() - 2
      while i >= 0 {
        let lhs = match self.compile(branches[i], next) {
          Ok(id) => id
          Err(e) => return Err(e)
        }
        cur = match self.emit(Split(lhs, cur)) {
          Ok(id) => id
          Err(e) => return Err(e)
        }
        i -= 1
      }
      Ok(cur)
    }
    Repeat(inner, min_val, max_opt, greedy) =>
      match max_opt {
        None =>
          if min_val == 0 {
            if ast_can_match_empty(inner) {
              let plus_entry = match self.compile_plus(inner, next, greedy) {
                Ok(id) => id
                Err(e) => return Err(e)
              }
              let entry_split = if greedy {
                Split(plus_entry, next)
              } else {
                Split(next, plus_entry)
              }
              self.emit(entry_split)
            } else {
              let split_id = match self.emit(Accept) {
                Ok(id) => id
                Err(e) => return Err(e)
              }
              let body = match self.compile(inner, split_id) {
                Ok(id) => id
                Err(e) => return Err(e)
              }
              self.states[split_id] = if greedy {
                Split(body, next)
              } else {
                Split(next, body)
              }
              Ok(split_id)
            }
          } else {
            let mut cur = match self.compile_plus(inner, next, greedy) {
              Ok(id) => id
              Err(e) => return Err(e)
            }
            for _ in 0..<(min_val - 1) {
              match self.consume_op() {
                Ok(_) => ()
                Err(e) => return Err(e)
              }
              cur = match self.compile(inner, cur) {
                Ok(id) => id
                Err(e) => return Err(e)
              }
            }
            Ok(cur)
          }
        Some(max_val) => {
          let mut cur = next
          let opt_count = max_val - min_val
          for _ in 0.. ()
              Err(e) => return Err(e)
            }
            let copy = match self.compile(inner, cur) {
              Ok(id) => id
              Err(e) => return Err(e)
            }
            let split_state = if greedy {
              Split(copy, next)
            } else {
              Split(next, copy)
            }
            cur = match self.emit(split_state) {
              Ok(id) => id
              Err(e) => return Err(e)
            }
          }
          for _ in 0.. ()
              Err(e) => return Err(e)
            }
            cur = match self.compile(inner, cur) {
              Ok(id) => id
              Err(e) => return Err(e)
            }
          }
          Ok(cur)
        }
      }
  }
}

///|
/// Compiles a regular expression pattern into a linear-time Thompson NFA.
///
/// Rejects invalid syntax and patterns that exceed bounded compilation limits.
pub fn compile_regex(pattern : String) -> Result[CompiledRegex, String] {
  let chars : Array[Char] = []
  for ch in pattern {
    if chars.length() >= MAX_PATTERN_CHARS {
      return Err(
        "regex too complex: pattern length exceeds limit (" +
        MAX_PATTERN_CHARS.to_string() +
        ")",
      )
    }
    chars.push(ch)
  }
  let parser = Parser::new(chars)
  let ast = match parser.parse_alt() {
    Ok(a) => a
    Err(e) => return Err(e)
  }
  if parser.peek() != None {
    return Err("unmatched ')' in regex")
  }
  let compiler = Compiler::new(initial_ops=parser.compile_ops)
  let start = match compiler.compile(ast, 0) {
    Ok(id) => id
    Err(e) => return Err(e)
  }
  Ok({ pattern, start, states: compiler.states, classes: compiler.class_pool, })
}

///|
fn add_epsilon_closure(
  states : Array[NfaState],
  chars : Array[Char],
  pos : Int32,
  initial : Int32,
  out : Array[Int32],
  visited : Array[Int32],
  gen : Int32,
  stack : Array[Int32],
) -> Bool {
  stack.clear()
  stack.push(initial)
  while true {
    match stack.pop() {
      None => break
      Some(s) => {
        if visited[s] == gen {
          continue
        }
        visited[s] = gen
        match states[s] {
          Accept => return true
          Match(_, _) => out.push(s)
          Assert(anchor, next) =>
            if anchor.matches(chars, pos) {
              stack.push(next)
            }
          Split(out1, out2) => {
            stack.push(out2)
            stack.push(out1)
          }
        }
      }
    }
  }
  false
}

///|
/// Returns `true` if `input` matches this compiled regular expression
/// (unanchored RE2 / CUE `=~` substring semantics by default).
pub fn CompiledRegex::is_match(self : CompiledRegex, input : String) -> Bool {
  let chars = input.to_array()
  let n_states = self.states.length()
  let n_classes = self.classes.length()
  let visited = Array::make(n_states, 0)
  let class_cache_gen = Array::make(n_classes, 0)
  let class_cache_val = Array::make(n_classes, false)
  let stack : Array[Int32] = []
  let mut curr : Array[Int32] = []
  let mut next : Array[Int32] = []
  let mut gen = 1
  if add_epsilon_closure(
      self.states,
      chars,
      0,
      self.start,
      curr,
      visited,
      gen,
      stack,
    ) {
    return true
  }
  for pos in 0..
          if matcher.matches(
              ch,
              self.classes,
              class_cache_gen,
              class_cache_val,
              gen,
            ) {
            if add_epsilon_closure(
                self.states,
                chars,
                pos + 1,
                target,
                next,
                visited,
                gen,
                stack,
              ) {
              return true
            }
          }
        _ => ()
      }
    }
    if add_epsilon_closure(
        self.states,
        chars,
        pos + 1,
        self.start,
        next,
        visited,
        gen,
        stack,
      ) {
      return true
    }
    let tmp = curr
    curr = next
    next = tmp
  }
  false
}

///|
fn add_find_epsilon_closure(
  states : Array[NfaState],
  chars : Array[Char],
  pos : Int32,
  initial : Int32,
  start_pos : Int32,
  out_states : Array[Int32],
  out_starts : Array[Int32],
  visited : Array[Int32],
  gen : Int32,
  stack : Array[Int32],
) -> Bool {
  stack.clear()
  stack.push(initial)
  while true {
    match stack.pop() {
      None => break
      Some(s) => {
        if visited[s] == gen {
          continue
        }
        visited[s] = gen
        match states[s] {
          Accept => return true
          Match(_, _) => {
            out_states.push(s)
            out_starts.push(start_pos)
          }
          Assert(anchor, next) =>
            if anchor.matches(chars, pos) {
              stack.push(next)
            }
          Split(out1, out2) => {
            stack.push(out2)
            stack.push(out1)
          }
        }
      }
    }
  }
  false
}

///|
/// Finds the leftmost-first RE2 match of this compiled regex in `input`,
/// executing in linear `O(states * chars)` time with zero backtracking.
///
/// Explicitly distinguishes `None` (no match) from `Some("")` (empty match).
pub fn CompiledRegex::find(self : CompiledRegex, input : String) -> String? {
  let chars = input.to_array()
  let n_states = self.states.length()
  let n_classes = self.classes.length()
  let visited = Array::make(n_states, 0)
  let class_cache_gen = Array::make(n_classes, 0)
  let class_cache_val = Array::make(n_classes, false)
  let stack : Array[Int32] = []
  let mut curr_states : Array[Int32] = []
  let mut curr_starts : Array[Int32] = []
  let mut next_states : Array[Int32] = []
  let mut next_starts : Array[Int32] = []
  let mut best_match : (Int32, Int32)? = None
  let mut gen = 1
  if add_find_epsilon_closure(
      self.states,
      chars,
      0,
      self.start,
      0,
      curr_states,
      curr_starts,
      visited,
      gen,
      stack,
    ) {
    best_match = Some((0, 0))
  }
  for pos in 0..
          if matcher.matches(
              ch,
              self.classes,
              class_cache_gen,
              class_cache_val,
              gen,
            ) {
            if add_find_epsilon_closure(
                self.states,
                chars,
                pos + 1,
                target,
                sp,
                next_states,
                next_starts,
                visited,
                gen,
                stack,
              ) {
              best_match = Some((sp, pos + 1))
              break
            }
          }
        _ => ()
      }
    }
    if best_match is None {
      if add_find_epsilon_closure(
          self.states,
          chars,
          pos + 1,
          self.start,
          pos + 1,
          next_states,
          next_starts,
          visited,
          gen,
          stack,
        ) {
        best_match = Some((pos + 1, pos + 1))
      }
    }
    let tmp_s = curr_states
    curr_states = next_states
    next_states = tmp_s
    let tmp_p = curr_starts
    curr_starts = next_starts
    next_starts = tmp_p
  }
  match best_match {
    None => None
    Some((start_idx, end_idx)) => {
      let buf = StringBuilder()
      for i in start_idx.. Result[Bool, String] {
  match compile_regex(pattern) {
    Ok(re) => Ok(re.is_match(input))
    Err(e) => Err(e)
  }
}

///|
/// Compiles `pattern` and finds the leftmost-first match in `input`.
pub fn regex_find(pattern : String, input : String) -> Result[String?, String] {
  match compile_regex(pattern) {
    Ok(re) => Ok(re.find(input))
    Err(e) => Err(e)
  }
}

///|
fn scan_chars_with_budget(
  s : String,
  max_chars : Int32?,
  budget : EvalBudget,
) -> Result[Array[Char], CueError] {
  let out : Array[Char] = []
  for ch in s {
    match budget.consume_step() {
      Ok(_) => ()
      Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
    }
    match max_chars {
      Some(limit) =>
        if out.length() >= limit {
          return Err(
            CueError::new(
              RegexConflict,
              "regex pattern exceeds maximum length of \{limit} characters",
            ),
          )
        }
      None => ()
    }
    out.push(ch)
  }
  Ok(out)
}

///|
/// Compiles a regular expression pattern into a linear-time Thompson NFA while
/// accounting parsing and compilation steps against `budget`.
pub fn compile_regex_with_budget(
  pattern : String,
  budget : EvalBudget,
) -> Result[CompiledRegex, CueError] {
  match budget.consume_step() {
    Ok(_) => ()
    Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
  }
  let chars = match
    scan_chars_with_budget(pattern, Some(MAX_PATTERN_CHARS), budget) {
    Ok(cs) => cs
    Err(e) => return Err(e)
  }
  let parser = Parser::new(chars, budget~)
  let ast_res = parser.parse_alt()
  match parser.limit_err {
    Some(e) => return Err(CueError::new(ResourceLimit, e.message()))
    None => ()
  }
  let ast = match ast_res {
    Ok(a) => a
    Err(e) => return Err(CueError::new(RegexConflict, e))
  }
  if parser.peek() != None {
    return Err(CueError::new(RegexConflict, "unmatched ')' in regex"))
  }
  let compiler = Compiler::new(budget~, initial_ops=parser.compile_ops)
  let start_res = compiler.compile(ast, 0)
  match compiler.limit_err {
    Some(e) => return Err(CueError::new(ResourceLimit, e.message()))
    None => ()
  }
  let start = match start_res {
    Ok(id) => id
    Err(e) => return Err(CueError::new(RegexConflict, e))
  }
  Ok({ pattern, start, states: compiler.states, classes: compiler.class_pool, })
}

///|
fn add_epsilon_closure_with_budget(
  states : Array[NfaState],
  chars : Array[Char],
  pos : Int32,
  initial : Int32,
  out : Array[Int32],
  visited : Array[Int32],
  gen : Int32,
  stack : Array[Int32],
  budget : EvalBudget,
) -> Result[Bool, CueError] {
  stack.clear()
  stack.push(initial)
  while true {
    match stack.pop() {
      None => break
      Some(s) => {
        match budget.consume_step() {
          Ok(_) => ()
          Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
        }
        if visited[s] == gen {
          continue
        }
        visited[s] = gen
        match states[s] {
          Accept => return Ok(true)
          Match(_, _) => out.push(s)
          Assert(anchor, next) =>
            if anchor.matches(chars, pos) {
              stack.push(next)
            }
          Split(out1, out2) => {
            stack.push(out2)
            stack.push(out1)
          }
        }
      }
    }
  }
  Ok(false)
}

///|
/// Returns `true` if `input` matches this compiled regular expression while
/// charging NFA execution steps against `budget`.
pub fn CompiledRegex::is_match_with_budget(
  self : CompiledRegex,
  input : String,
  budget : EvalBudget,
) -> Result[Bool, CueError] {
  match budget.consume_step() {
    Ok(_) => ()
    Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
  }
  let chars = match scan_chars_with_budget(input, None, budget) {
    Ok(cs) => cs
    Err(e) => return Err(e)
  }
  let n_states = self.states.length()
  let n_classes = self.classes.length()
  let visited = Array::make(n_states, 0)
  let class_cache_gen = Array::make(n_classes, 0)
  let class_cache_val = Array::make(n_classes, false)
  let stack : Array[Int32] = []
  let mut curr : Array[Int32] = []
  let mut next : Array[Int32] = []
  let mut gen = 1
  match
    add_epsilon_closure_with_budget(
      self.states,
      chars,
      0,
      self.start,
      curr,
      visited,
      gen,
      stack,
      budget,
    ) {
    Ok(true) => return Ok(true)
    Ok(false) => ()
    Err(e) => return Err(e)
  }
  for pos in 0.. ()
      Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
    }
    let ch = chars[pos]
    gen += 1
    if gen == 0x7FFFFFFF {
      for i in 0.. ()
        Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
      }
      match self.states[s] {
        Match(matcher, target) =>
          if matcher.matches(
              ch,
              self.classes,
              class_cache_gen,
              class_cache_val,
              gen,
            ) {
            match
              add_epsilon_closure_with_budget(
                self.states,
                chars,
                pos + 1,
                target,
                next,
                visited,
                gen,
                stack,
                budget,
              ) {
              Ok(true) => return Ok(true)
              Ok(false) => ()
              Err(e) => return Err(e)
            }
          }
        _ => ()
      }
    }
    match
      add_epsilon_closure_with_budget(
        self.states,
        chars,
        pos + 1,
        self.start,
        next,
        visited,
        gen,
        stack,
        budget,
      ) {
      Ok(true) => return Ok(true)
      Ok(false) => ()
      Err(e) => return Err(e)
    }
    let tmp = curr
    curr = next
    next = tmp
  }
  Ok(false)
}

///|
fn add_find_epsilon_closure_with_budget(
  states : Array[NfaState],
  chars : Array[Char],
  pos : Int32,
  initial : Int32,
  start_pos : Int32,
  out_states : Array[Int32],
  out_starts : Array[Int32],
  visited : Array[Int32],
  gen : Int32,
  stack : Array[Int32],
  budget : EvalBudget,
) -> Result[Bool, CueError] {
  stack.clear()
  stack.push(initial)
  while true {
    match stack.pop() {
      None => break
      Some(s) => {
        match budget.consume_step() {
          Ok(_) => ()
          Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
        }
        if visited[s] == gen {
          continue
        }
        visited[s] = gen
        match states[s] {
          Accept => return Ok(true)
          Match(_, _) => {
            out_states.push(s)
            out_starts.push(start_pos)
          }
          Assert(anchor, next) =>
            if anchor.matches(chars, pos) {
              stack.push(next)
            }
          Split(out1, out2) => {
            stack.push(out2)
            stack.push(out1)
          }
        }
      }
    }
  }
  Ok(false)
}

///|
/// Finds the leftmost-first RE2 match of this compiled regex in `input` while
/// charging NFA steps and output UTF-8 byte length against `budget`.
pub fn CompiledRegex::find_with_budget(
  self : CompiledRegex,
  input : String,
  budget : EvalBudget,
) -> Result[String?, CueError] {
  match budget.consume_step() {
    Ok(_) => ()
    Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
  }
  let chars = match scan_chars_with_budget(input, None, budget) {
    Ok(cs) => cs
    Err(e) => return Err(e)
  }
  let n_states = self.states.length()
  let n_classes = self.classes.length()
  let visited = Array::make(n_states, 0)
  let class_cache_gen = Array::make(n_classes, 0)
  let class_cache_val = Array::make(n_classes, false)
  let stack : Array[Int32] = []
  let mut curr_states : Array[Int32] = []
  let mut curr_starts : Array[Int32] = []
  let mut next_states : Array[Int32] = []
  let mut next_starts : Array[Int32] = []
  let mut best_match : (Int32, Int32)? = None
  let mut gen = 1
  match
    add_find_epsilon_closure_with_budget(
      self.states,
      chars,
      0,
      self.start,
      0,
      curr_states,
      curr_starts,
      visited,
      gen,
      stack,
      budget,
    ) {
    Ok(true) => best_match = Some((0, 0))
    Ok(false) => ()
    Err(e) => return Err(e)
  }
  for pos in 0.. ()
      Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
    }
    let ch = chars[pos]
    gen += 1
    if gen == 0x7FFFFFFF {
      for i in 0.. ()
        Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
      }
      let s = curr_states[i]
      let sp = curr_starts[i]
      match self.states[s] {
        Match(matcher, target) =>
          if matcher.matches(
              ch,
              self.classes,
              class_cache_gen,
              class_cache_val,
              gen,
            ) {
            match
              add_find_epsilon_closure_with_budget(
                self.states,
                chars,
                pos + 1,
                target,
                sp,
                next_states,
                next_starts,
                visited,
                gen,
                stack,
                budget,
              ) {
              Ok(true) => {
                best_match = Some((sp, pos + 1))
                break
              }
              Ok(false) => ()
              Err(e) => return Err(e)
            }
          }
        _ => ()
      }
    }
    if best_match is None {
      match
        add_find_epsilon_closure_with_budget(
          self.states,
          chars,
          pos + 1,
          self.start,
          pos + 1,
          next_states,
          next_starts,
          visited,
          gen,
          stack,
          budget,
        ) {
        Ok(true) => best_match = Some((pos + 1, pos + 1))
        Ok(false) => ()
        Err(e) => return Err(e)
      }
    }
    let tmp_s = curr_states
    curr_states = next_states
    next_states = tmp_s
    let tmp_p = curr_starts
    curr_starts = next_starts
    next_starts = tmp_p
  }
  match best_match {
    None => Ok(None)
    Some((start_idx, end_idx)) => {
      let mut utf8_len = 0
      for i in start_idx.. ()
        Err(e) => return Err(CueError::new(ResourceLimit, e.message()))
      }
      let buf = StringBuilder()
      for i in start_idx.. Result[Bool, CueError] {
  match compile_regex_with_budget(pattern, budget) {
    Ok(re) => re.is_match_with_budget(input, budget)
    Err(e) => Err(e)
  }
}

///|
/// Compiles `pattern` and finds the leftmost-first match in `input`, enforcing
/// `budget`.
pub fn regex_find_with_budget(
  pattern : String,
  input : String,
  budget : EvalBudget,
) -> Result[String?, CueError] {
  match compile_regex_with_budget(pattern, budget) {
    Ok(re) => re.find_with_budget(input, budget)
    Err(e) => Err(e)
  }
}

///|
/// Normalized conjunction of CUE regex match (`=~`) and non-match (`!~`)
/// constraints.
///
/// Both `positive` and `negative` are stored in sorted, deduplicated order so
/// structural equality satisfies lattice commutativity, associativity, and
/// idempotence.
#derive(Eq, Debug)
pub(all) struct RegexConstraints {
  positive : Array[String]
  negative : Array[String]
}

///|
/// Returns an empty `RegexConstraints` with no match or non-match restrictions.
pub fn RegexConstraints::empty() -> RegexConstraints {
  { positive: [], negative: [], }
}

///|
/// Returns `true` if there are no positive or negative regex constraints.
pub fn RegexConstraints::is_empty(self : RegexConstraints) -> Bool {
  self.positive.is_empty() && self.negative.is_empty()
}

///|
/// Creates a `RegexConstraints` requiring `=~ pattern`, validating that
/// `pattern` compiles.
pub fn RegexConstraints::from_match(
  pattern : String,
) -> Result[RegexConstraints, String] {
  match compile_regex(pattern) {
    Ok(_) => Ok({ positive: [pattern], negative: [], })
    Err(e) => Err(e)
  }
}

///|
/// Creates a `RegexConstraints` requiring `!~ pattern`, validating that
/// `pattern` compiles.
pub fn RegexConstraints::from_not_match(
  pattern : String,
) -> Result[RegexConstraints, String] {
  match compile_regex(pattern) {
    Ok(_) => Ok({ positive: [], negative: [pattern], })
    Err(e) => Err(e)
  }
}

///|
fn merge_sorted_unique(a : Array[String], b : Array[String]) -> Array[String] {
  let combined : Array[String] = []
  for item in a {
    combined.push(item)
  }
  for item in b {
    combined.push(item)
  }
  combined.sort()
  let out : Array[String] = []
  for item in combined {
    if out.is_empty() || out[out.length() - 1] != item {
      out.push(item)
    }
  }
  out
}

///|
fn find_first_common(a : Array[String], b : Array[String]) -> String? {
  let mut i = 0
  let mut j = 0
  while i < a.length() && j < b.length() {
    let cmp = a[i].compare(b[j])
    if cmp == 0 {
      return Some(a[i])
    } else if cmp < 0 {
      i += 1
    } else {
      j += 1
    }
  }
  None
}

///|
fn format_cue_string(text : String) -> String {
  let zero : @syntax.Position = { offset: 0, line: 0, column: 0, }
  let span : @syntax.Span = { start: zero, end: zero, }
  @syntax.format_expr(@syntax.Expr::String(text, span))
}

///|
/// Unifies two `RegexConstraints` by merging their normalized positive and
/// negative pattern sets, failing if any exact pattern appears in both.
pub fn RegexConstraints::unify(
  self : RegexConstraints,
  other : RegexConstraints,
) -> Result[RegexConstraints, String] {
  let positive = merge_sorted_unique(self.positive, other.positive)
  let negative = merge_sorted_unique(self.negative, other.negative)
  match find_first_common(positive, negative) {
    Some(conflict) =>
      Err(
        "conflicting regex constraints: =~" +
        format_cue_string(conflict) +
        " & !~" +
        format_cue_string(conflict),
      )
    None => Ok({ positive, negative, })
  }
}

///|
/// Checks that `input` matches every `positive` pattern and does not match any
/// `negative` pattern.
pub fn RegexConstraints::matches(
  self : RegexConstraints,
  input : String,
) -> Result[Unit, String] {
  for pat in self.positive {
    match compile_regex(pat) {
      Err(e) => return Err("invalid regex " + format_cue_string(pat) + ": " + e)
      Ok(re) =>
        if !re.is_match(input) {
          return Err(
            "string " +
            format_cue_string(input) +
            " does not match =~" +
            format_cue_string(pat),
          )
        }
    }
  }
  for pat in self.negative {
    match compile_regex(pat) {
      Err(e) => return Err("invalid regex " + format_cue_string(pat) + ": " + e)
      Ok(re) =>
        if re.is_match(input) {
          return Err(
            "string " +
            format_cue_string(input) +
            " matches forbidden !~" +
            format_cue_string(pat),
          )
        }
    }
  }
  Ok(())
}

///|
/// Formats these regex constraints in canonical CUE syntax, e.g.
/// `=~"^a" & !~"bad"`. Returns `""` when empty.
pub fn RegexConstraints::format(self : RegexConstraints) -> String {
  let buf = StringBuilder()
  let mut first = true
  for pat in self.positive {
    if !first {
      buf.write_string(" & ")
    }
    first = false
    buf.write_string("=~")
    buf.write_string(format_cue_string(pat))
  }
  for pat in self.negative {
    if !first {
      buf.write_string(" & ")
    }
    first = false
    buf.write_string("!~")
    buf.write_string(format_cue_string(pat))
  }
  buf.to_string()
}