///|
/// The XAML language namespace of [MS-XAML-2017], conventionally bound to the prefix `x`.
pub let xaml_language_namespace : String = "http://schemas.microsoft.com/winfx/2006/xaml"

///|
/// The name of a XAML type: a XAML namespace URI, a local name and the type arguments of a closed
/// generic type, each itself a type name (design D11). A non-generic name has no type arguments.
///
/// Equality, comparison, hashing, text and debug output walk the type arguments with explicit work
/// stacks, so deeply nested names cannot overflow a target's stack (design D8, 2F18).
pub(all) struct XamlTypeName {
  namespace_uri : String
  name : String
  type_arguments : ReadOnlyArray[XamlTypeName]
}

///|
pub fn XamlTypeName::new(
  namespace_uri : String,
  name : String,
  type_arguments~ : ArrayView[XamlTypeName] = [],
) -> XamlTypeName {
  {
    namespace_uri,
    name,
    type_arguments: ReadOnlyArray::from_array(type_arguments),
  }
}

///|
/// The number of type arguments: the generic arity that the name looks a type up by.
pub fn XamlTypeName::arity(self : XamlTypeName) -> Int32 {
  self.type_arguments.length()
}

///|
pub impl Eq for XamlTypeName with fn equal(self, other) {
  let pending = [(self, other)]
  while pending.pop() is Some((a, b)) {
    if physical_equal(a, b) {
      continue
    }
    if a.namespace_uri != b.namespace_uri ||
      a.name != b.name ||
      a.type_arguments.length() != b.type_arguments.length() {
      return false
    }
    for i, argument in a.type_arguments {
      pending.push((argument, b.type_arguments[i]))
    }
  }
  true
}

///|
priv enum CompareStep {
  Names(XamlTypeName, XamlTypeName)
  Counts(Int32, Int32)
}

///|
/// Namespace URI, then local name, then the type arguments in order, a missing argument first.
pub impl Compare for XamlTypeName with fn compare(self, other) {
  let pending = [CompareStep::Names(self, other)]
  while pending.pop() is Some(step) {
    match step {
      Counts(a, b) => {
        let order = a.compare(b)
        if order != 0 {
          return order
        }
      }
      Names(a, b) => {
        if physical_equal(a, b) {
          continue
        }
        let order = a.namespace_uri.compare(b.namespace_uri)
        if order != 0 {
          return order
        }
        let order = a.name.compare(b.name)
        if order != 0 {
          return order
        }
        let shared = if a.arity() < b.arity() { a.arity() } else { b.arity() }
        pending.push(Counts(a.arity(), b.arity()))
        for i = shared - 1; i >= 0; i = i - 1 {
          pending.push(Names(a.type_arguments[i], b.type_arguments[i]))
        }
      }
    }
  }
  0
}

///|
/// The expanded form `{namespace}Name({namespace}Arg)` as one flat literal.
pub impl Debug for XamlTypeName with fn to_repr(self) {
  @debug.Repr::literal("\{self}")
}

///|
pub impl Hash for XamlTypeName with fn hash_combine(self, hasher) {
  // Pre-order with argument counts, so different trees feed different sequences.
  let pending = [self]
  while pending.pop() is Some(name) {
    hasher.combine_string(name.namespace_uri)
    hasher.combine_string(name.name)
    hasher.combine_int(name.type_arguments.length())
    for i = name.type_arguments.length() - 1; i >= 0; i = i - 1 {
      pending.push(name.type_arguments[i])
    }
  }
}

///|
/// The name of a XAML member in a start member node.
///
/// - `Member` is a member of the object; `owner` is the type that declares it, such as `Control`
///   for `Content` on a `Button`.
/// - `Attached` is an attached member that `owner` defines, such as `Grid.Row`, set on another object.
/// - `Directive` is a member of a XAML namespace that no type declares, such as `x:Name`.
/// - `UnknownDirective` names a directive with no schema entry, as System.Xaml's `new
///   XamlDirective(ns, name)`: a reader gives it for a directive written where its directive does
///   not allow it, and it never resolves to the registered directive of that name (design D8, 3F5).
#derive(Eq, Hash, Compare, Debug)
pub(all) enum XamlMemberName {
  Member(owner~ : XamlTypeName, name~ : String)
  Attached(owner~ : XamlTypeName, name~ : String)
  Directive(namespace_uri~ : String, name~ : String)
  UnknownDirective(namespace_uri~ : String, name~ : String)
}

///|
/// The local name of a member, without its owner or namespace.
pub fn XamlMemberName::name(self : XamlMemberName) -> String {
  match self {
    Member(name~, ..)
    | Attached(name~, ..)
    | Directive(name~, ..)
    | UnknownDirective(name~, ..) => name
  }
}

///|
/// One node of a XAML node stream. Node values are immutable.
///
/// A well-formed stream has one root object. Namespace declarations come immediately before the
/// start object that they apply to, at the start of the stream or inside a member, never before a
/// get object or directly inside an object. An object holds start member and end member pairs; a
/// member holds values, objects and get objects.
///
/// The payloads (design D8, 2F19): `NamespaceDeclaration` carries the prefix, `""` for the default
/// namespace, and the namespace URI; `StartObject` a `XamlTypeName`; `StartMember` a
/// `XamlMemberName`; `Value` a `XamlValue`. Nodes carry names, not schema entries, and no source
/// positions, so streams compare equal across a round trip.
#derive(Eq, Debug)
pub(all) enum XamlNode {
  /// Binds `prefix` to `namespace_uri` for the object that follows. The default namespace has the
  /// prefix `""`.
  NamespaceDeclaration(prefix~ : String, namespace_uri~ : String)
  /// Starts a new object of a XAML type.
  StartObject(XamlTypeName)
  /// Starts the existing value of the enclosing member, such as a read-only collection.
  GetObject
  /// Ends the current start object or get object.
  EndObject
  /// Starts a member of the current object.
  StartMember(XamlMemberName)
  /// Ends the current member.
  EndMember
  /// A value of the current member.
  Value(XamlValue)
}

///|
/// The node kinds, for code that dispatches on the kind alone.
#derive(Eq, Hash, Debug)
pub(all) enum XamlNodeKind {
  NamespaceDeclaration
  StartObject
  GetObject
  EndObject
  StartMember
  EndMember
  Value
}

///|
/// The node for people, such as `start member {urn:ui}Button.Content`. Type names and values are
/// written with explicit work stacks, so a deeply nested node cannot overflow a target's stack.
pub fn XamlNode::describe(self : XamlNode) -> String {
  match self {
    NamespaceDeclaration(prefix~, namespace_uri~) =>
      "namespace declaration \"\{prefix}\" = \"\{namespace_uri}\""
    StartObject(type_name) => "start object \{type_name}"
    GetObject => "get object"
    EndObject => "end object"
    StartMember(Member(owner~, name~)) => "start member \{owner}.\{name}"
    StartMember(Attached(owner~, name~)) =>
      "start member \{owner}.\{name} (attached)"
    StartMember(Directive(namespace_uri~, name~)) =>
      "start member {\{namespace_uri}}\{name} (directive)"
    StartMember(UnknownDirective(namespace_uri~, name~)) =>
      "start member {\{namespace_uri}}\{name} (unknown directive)"
    EndMember => "end member"
    Value(value) => "value \{value.debug_text()}"
  }
}

///|
pub fn XamlNode::kind(self : XamlNode) -> XamlNodeKind {
  match self {
    NamespaceDeclaration(..) => NamespaceDeclaration
    StartObject(_) => StartObject
    GetObject => GetObject
    EndObject => EndObject
    StartMember(_) => StartMember
    EndMember => EndMember
    Value(_) => Value
  }
}