///|
/// Why a type name cannot be parsed from text or formatted as text.
#derive(Eq, Debug)
pub(all) suberror TypeNameError {
  /// `text` is not a type name: `offset` is the UTF-16 offset where the syntax fails.
  MalformedTypeName(text~ : String, offset~ : Int32, message~ : String)
  /// The prefix resolver does not know `prefix` (`""` for the default namespace).
  UnknownTypeNamePrefix(text~ : String, prefix~ : String)
  /// `text` has a CLR array-rank suffix such as `[]`, which is not supported (design D11, F23).
  ArrayTypeName(text~ : String)
  /// The prefix lookup has no prefix for `namespace_uri`.
  NoPrefixForNamespace(namespace_uri~ : String)
}

///|
/// A description of the error for people.
pub fn TypeNameError::message(self : TypeNameError) -> String {
  match self {
    MalformedTypeName(text~, offset~, message~) =>
      "malformed type name \"\{text}\" at offset \{offset}: \{message}"
    UnknownTypeNamePrefix(text~, prefix~) =>
      if prefix.is_empty() {
        "type name \"\{text}\" has no default namespace in scope"
      } else {
        "type name \"\{text}\" uses the unknown prefix \"\{prefix}\""
      }
    ArrayTypeName(text~) =>
      "type name \"\{text}\" is an array type; array types are not supported"
    NoPrefixForNamespace(namespace_uri~) =>
      "no prefix is in scope for the namespace \"\{namespace_uri}\""
  }
}

///|
priv enum TextPart {
  Name(XamlTypeName)
  Literal(String)
}

///|
/// The text form `prefix:Name(Arg1, Arg2)`, as System.Xaml `XamlTypeName.ToString` gives it with a
/// prefix lookup. `prefix_of` gives the prefix of a namespace URI; the prefix `""` writes no
/// `prefix:`. It raises `NoPrefixForNamespace` for a namespace that has no prefix.
pub fn XamlTypeName::to_text(
  self : XamlTypeName,
  prefix_of : (String) -> String?,
) -> String raise TypeNameError {
  self.format(namespace_uri => {
    guard prefix_of(namespace_uri) is Some(prefix) else {
      raise NoPrefixForNamespace(namespace_uri~)
    }
    if prefix.is_empty() {
      ""
    } else {
      prefix + ":"
    }
  })
}

///|
/// The expanded form `{namespace}Name({namespace}Arg)`, which needs no prefixes, for messages.
pub impl Show for XamlTypeName with fn output(self, logger) {
  logger.write_string(self.format(namespace_uri => "{\{namespace_uri}}"))
}

///|
pub extend XamlTypeName with Show::{to_string}

///|
/// The name with `qualifier` giving the text before each local name, arguments in parentheses.
fn XamlTypeName::format(
  self : XamlTypeName,
  qualifier : (String) -> String raise?,
) -> String raise? {
  let buffer = StringBuilder()
  let pending = [TextPart::Name(self)]
  while pending.pop() is Some(part) {
    match part {
      Literal(text) => buffer.write_string(text)
      Name(name) => {
        buffer.write_string(qualifier(name.namespace_uri))
        buffer.write_string(name.name)
        let count = name.type_arguments.length()
        if count > 0 {
          buffer.write_char('(')
          pending.push(Literal(")"))
          for i = count - 1; i >= 0; i = i - 1 {
            pending.push(Name(name.type_arguments[i]))
            if i > 0 {
              pending.push(Literal(", "))
            }
          }
        }
      }
    }
  }
  buffer.to_string()
}

///|
/// Parse one type name in the text form `prefix:Name(Arg1, Arg2)`. `namespace_of` resolves a prefix,
/// `""` for an unprefixed name, to its namespace URI. White space around names, parentheses and
/// commas is allowed.
pub fn XamlTypeName::parse(
  text : String,
  namespace_of : (String) -> String?,
) -> XamlTypeName raise TypeNameError {
  let names = parse_type_names(text, namespace_of, list=false)
  names[0]
}

///|
/// Parse a comma-separated list of one or more type names, as `x:TypeArguments` holds.
pub fn XamlTypeName::parse_list(
  text : String,
  namespace_of : (String) -> String?,
) -> Array[XamlTypeName] raise TypeNameError {
  parse_type_names(text, namespace_of, list=true)
}

///|
/// A generic type name whose type arguments are still being parsed.
priv struct OpenName {
  namespace_uri : String
  name : String
  arguments : Array[XamlTypeName]
}

///|
fn parse_type_names(
  text : String,
  namespace_of : (String) -> String?,
  list~ : Bool,
) -> Array[XamlTypeName] raise TypeNameError {
  let open_names : Array[OpenName] = []
  let names : Array[XamlTypeName] = []
  let length = text.length()
  let mut position = 0
  let skip_space = () => {
    while position < length && is_space(text.at(position)) {
      position += 1
    }
  }
  let malformed = (message : String) => {
    MalformedTypeName(text~, offset=position, message~)
  }
  while true {
    // A qualified name: `prefix:Name` or `Name`.
    skip_space()
    let first = scan_ncname(text, position)
    if first == position {
      raise malformed("expected a type name")
    }
    let mut prefix = ""
    let mut local_name = text.exact_view(start=position, end=first)
    position = first
    if position < length && text.at(position) == ':' {
      let second = scan_ncname(text, position + 1)
      if second == position + 1 {
        position += 1
        raise malformed("expected a name after the prefix")
      }
      prefix = local_name.to_owned()
      local_name = text.exact_view(start=position + 1, end=second)
      position = second
    }
    guard namespace_of(prefix) is Some(namespace_uri) else {
      raise UnknownTypeNamePrefix(text~, prefix~)
    }
    skip_space()
    if position < length && text.at(position) == '(' {
      position += 1
      open_names.push({
        namespace_uri,
        name: local_name.to_owned(),
        arguments: [],
      })
      continue
    }
    let mut done = XamlTypeName::new(namespace_uri, local_name.to_owned())
    // Close the names that `done` completes, then look for the next name.
    let mut expect_name = false
    while !expect_name {
      skip_space()
      if position < length && text.at(position) == '[' {
        raise ArrayTypeName(text~)
      }
      match open_names.last() {
        Some(open) => {
          open.arguments.push(done)
          if position >= length {
            raise malformed("expected \",\" or \")\"")
          }
          match text.at(position) {
            ',' => {
              position += 1
              expect_name = true
            }
            ')' => {
              position += 1
              open_names.pop() |> ignore
              done = XamlTypeName::new(
                open.namespace_uri,
                open.name,
                type_arguments=open.arguments,
              )
            }
            _ => raise malformed("expected \",\" or \")\"")
          }
        }
        None => {
          names.push(done)
          if position >= length {
            return names
          }
          if list && text.at(position) == ',' {
            position += 1
            expect_name = true
          } else {
            raise malformed("unexpected text after the type name")
          }
        }
      }
    }
  }
  names
}

///|
/// Whether `text` is an NCName: an XML name without `:`, such as a namespace prefix.
pub fn is_ncname(text : String) -> Bool {
  !text.is_empty() && scan_ncname(text, 0) == text.length()
}

///|
fn is_space(unit : UInt16) -> Bool {
  unit is (' ' | '\t' | '\r' | '\n')
}

///|
/// The offset after the NCName (XML 1.0 `Name` without `:`) that starts at `start`, or `start` when
/// none does.
fn scan_ncname(text : String, start : Int32) -> Int32 {
  let length = text.length()
  let mut position = start
  while position < length {
    let unit = text.at(position)
    let (code_point, width) = if unit.is_leading_surrogate() &&
      position + 1 < length &&
      text.at(position + 1).is_trailing_surrogate() {
      let trailing = text.at(position + 1).to_int()
      (0x10000 + ((unit.to_int() - 0xD800) << 10) + (trailing - 0xDC00), 2)
    } else {
      (unit.to_int(), 1)
    }
    let accepted = if position == start {
      is_name_start(code_point)
    } else {
      is_name_start(code_point) || is_name_continue(code_point)
    }
    if !accepted {
      break
    }
    position += width
  }
  position
}

///|
/// XML 1.0 `NameStartChar` without `:`.
fn is_name_start(c : Int32) -> Bool {
  (c >= 'A' && c <= 'Z') ||
  (c >= 'a' && c <= 'z') ||
  c == '_' ||
  (c >= 0xC0 && c <= 0xD6) ||
  (c >= 0xD8 && c <= 0xF6) ||
  (c >= 0xF8 && c <= 0x2FF) ||
  (c >= 0x370 && c <= 0x37D) ||
  (c >= 0x37F && c <= 0x1FFF) ||
  (c >= 0x200C && c <= 0x200D) ||
  (c >= 0x2070 && c <= 0x218F) ||
  (c >= 0x2C00 && c <= 0x2FEF) ||
  (c >= 0x3001 && c <= 0xD7FF) ||
  (c >= 0xF900 && c <= 0xFDCF) ||
  (c >= 0xFDF0 && c <= 0xFFFD) ||
  (c >= 0x10000 && c <= 0xEFFFF)
}

///|
/// The characters of XML 1.0 `NameChar` that `NameStartChar` lacks.
fn is_name_continue(c : Int32) -> Bool {
  c == '-' ||
  c == '.' ||
  (c >= '0' && c <= '9') ||
  c == 0xB7 ||
  (c >= 0x300 && c <= 0x36F) ||
  (c >= 0x203F && c <= 0x2040)
}