// Scoped unique-name allocation (implements spec.mbt).

///|
/// Allocates unique identifiers within one scope (a file's types, a struct's
/// fields, a function's parameters). Create one per scope; names reserved in
/// one scope do not affect other scopes.
pub struct Namer {
  priv taken : Map[String, Unit]
}

///|
pub fn Namer::new() -> Namer {
  { taken: Map([]), }
}

///|
/// True if `name` has been reserved or allocated in this scope.
pub fn Namer::is_taken(self : Namer, name : String) -> Bool {
  self.taken.contains(name)
}

///|
/// Reserve `name` so `unique` / `unique_type` will never return it.
pub fn Namer::reserve(self : Namer, name : String) -> Unit {
  self.taken[name] = ()
}

///|
/// Reserve MoonBit's un-declarable built-in and `core/builtin` prelude type
/// names (`Error`, `Self`, `Unit`, `Option`, `Result`, `Array`, `Map`, `Json`,
/// primitive numeric/string/byte types, views, `FixedArray`, etc.) so
/// generated `struct` / `enum` / `type` declarations never trigger compiler
/// error [4003] or shadow prelude types inside a package.
pub fn Namer::reserve_builtin_types(self : Namer) -> Unit {
  let builtins = [
    "Error", "Self", "Unit", "Bool", "Byte", "Char", "Int", "Int16", "Int32", "Int64",
    "UInt", "UInt16", "UInt32", "UInt64", "Float", "Double", "String", "Bytes", "FixedArray",
    "Option", "Result", "Array", "Map", "Json", "StringView", "BytesView", "ArrayView",
    "Iter", "Iter2", "Ref", "BigInt", "StringBuilder", "UninitializedArray", "FuncRef",
  ]
  for b in builtins {
    self.taken[b] = ()
  }
}

///|
fn Namer::allocate(self : Namer, base : String) -> String {
  let mut candidate = base
  let mut n : Int32 = 2
  while self.taken.contains(candidate) {
    candidate = base + n.to_string()
    n += 1
  }
  self.taken[candidate] = ()
  candidate
}

///|
/// Allocate a unique MoonBit value identifier based on `base` (guaranteed
/// `LIDENT` starting with `[a-z_]` and keyword-escaped): returns `base` itself
/// when free, otherwise `base2`, `base3`, ... The returned name is reserved.
///
/// `base` is defensively sanitized, keyword-escaped and made valid first, so
/// raw spec input (`""`, `"a b"`, `"type"`, `"2xx"`, `"Foo"`) cannot produce
/// an invalid value identifier. Use `unique_type` for `UIDENT` type/variant names.
pub fn Namer::unique(self : Namer, base : String) -> String {
  let clean = ensure_valid_ident(escape_keyword(sanitize(base)))
  self.allocate(clean)
}

///|
/// Allocate a unique MoonBit type/variant identifier (guaranteed `UIDENT`,
/// starting with `[A-Z]` and keyword-escaped). Note: runs `sanitize` (not
/// `to_pascal`), so callers wanting PascalCase should pass `ident_pascal(raw)`.
pub fn Namer::unique_type(self : Namer, base : String) -> String {
  let clean = escape_keyword(ensure_valid_type_ident(sanitize(base)))
  self.allocate(clean)
}