// Moved from apps/selfhost-compiler/boxes/parser/scan/parser_common_utils_box.hako
// ParserCommonUtilsBox — shared utility functions for parser boxes
// Responsibility: Provide common string/character operations used across parser components
// Notes: Pure utility functions; no state, no dependencies
using lang.compiler.parser.scan.parser_string_utils_box as ParserStringUtilsBox

static box ParserCommonUtilsBox {
  // ===== 数値・文字列変換 =====

  i2s(v) { return "" + v }

  // ===== 文字判定 =====

  is_alpha(ch) {
    return (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z") || ch == "_"
  }

  is_digit(ch) {
    return ch >= "0" && ch <= "9"
  }

  // ===== 文字列検索・操作 =====

  dq() { return "\"" }

  starts_with(src, i, pat) {
    local n = src.length()
    local m = pat.length()
    if i + m > n { return 0 }
    local k = 0
    loop(k < m) {
      if src.substring(i + k, i + k + 1) != pat.substring(k, k + 1) { return 0 }
      k = k + 1
    }
    return 1
  }

  index_of(src, i, pat) {
    local n = src.length()
    local m = pat.length()
    if m == 0 { return i }
    local j = i
    loop(j + m <= n) {
      if me.starts_with(src, j, pat) { return j }
      j = j + 1
    }
    return -1
  }

  trim(s) {
    // Phase 71-SSA: Direct implementation to avoid ValueId mapping issue in static box delegation
    if s == null { return "" }
    local str = "" + s
    local n = str.length()

    // Leading whitespace: use static method to avoid SSA undef
    local b = ParserStringUtilsBox.skip_ws(str, 0)
    if b >= n { return "" }

    // Trailing whitespace: walk backwards until a non-space is found.
    local e = n
    loop(e > b) {
      local ch = str.substring(e - 1, e)
      if ch == " " || ch == "\t" || ch == "\n" || ch == "\r" || ch == ";" { e = e - 1 } else { break }
    }

    if e > b { return str.substring(b, e) }
    return ""
  }

  esc_json(s) {
    local out = ""
    local i = 0
    local n = s.length()
    loop(i < n) {
      local ch = s.substring(i, i+1)
      if ch == "\\" { out = out + "\\\\" }
      else { if ch == "\"" { out = out + "\\\"" }
      else { out = out + ch } }
      i = i + 1
    }
    return out
  }
}
