///|
/// Adds an item to a collection object.
pub type ItemAdder = (@nodes.XamlObject, @nodes.XamlValue) -> Unit raise

///|
/// Adds a keyed entry to a dictionary object.
pub type EntryAdder = (@nodes.XamlObject, @nodes.XamlValue, @nodes.XamlValue) -> Unit raise

///|
/// Evaluates a markup extension object to the value that it stands for, with the services of the
/// load (design D14).
pub type ValueProvider = (@nodes.XamlObject, ServiceContext) -> @nodes.XamlValue raise

///|
/// A registered XAML type. Its member table includes the members that it inherits.
///
/// A generic type as registered is open: its name carries `type_parameter` references as type
/// arguments, as do the types of its members. `SchemaContext::resolve_type` gives the closed type for
/// type arguments, with the arguments substituted into its name, base type and member types.
pub struct XamlType {
  /// The identity of the type: its name in its preferred namespace (design D11).
  name : @nodes.XamlTypeName
  /// Every namespace URI that names the type, the preferred one first: its XAML namespace URIs in
  /// System.Xaml's preference order, then its CLR-style namespace URI, if any.
  namespaces : ReadOnlyArray[String]
  /// The CLR-style namespace name `N` that the type registers, if any.
  clr_namespace : String?
  /// The scope of the CLR-style namespace, the analogue of an assembly.
  scope : String?
  /// The names of the type parameters of a generic type, in order; empty for other types.
  type_parameters : ReadOnlyArray[String]
  base_type : @nodes.XamlTypeName?
  /// The member that takes element content, declared or inherited.
  content_property : String?
  /// The item type of a collection, or the value type of a dictionary's entries: `x:Object` unless
  /// registered, and `None` for other types.
  item_type : @nodes.XamlTypeName?
  /// The key type of a dictionary: `x:Object` unless registered, and `None` for other types.
  key_type : @nodes.XamlTypeName?
  priv members : Map[String, XamlMember]
  priv member_order : ReadOnlyArray[String]
  /// The members of base types that a nearer member of the name hides, as objects of this type have them.
  priv hidden_members : ReadOnlyArray[XamlMember]
  /// The attached properties that the type and its bases define, nearest first.
  priv attached : Map[String, XamlMember]
  /// The attached events that the type and its bases define, nearest first.
  priv attached_events : Map[String, XamlMember]
  /// The static fields of the type and its bases, nearest first.
  priv static_fields : Map[String, XamlStaticMember]
  /// The static properties of the type and its bases, nearest first.
  priv static_properties : Map[String, XamlStaticMember]
  /// The enumeration registration of an enumeration type.
  enumeration : XamlEnumeration?
  /// The constructors and factory methods, in registration order, with closed parameter types.
  priv constructors : ReadOnlyArray[XamlConstructor]
  priv type_converter : TypeConverter?
  priv value_serializer : ValueSerializer?
  priv parse_function : ParseFunction?
  priv add_item : ItemAdder?
  priv add_entry : EntryAdder?
  priv item_enumerator : ItemEnumerator?
  priv entry_enumerator : EntryEnumerator?
  priv instance_descriptor : InstanceDescriber?
  priv attached_store : AttachedMemberStore?
  priv provide_value : ValueProvider?
  /// The id of the key that wraps objects of the type, its own or its nearest base type's.
  priv object_key : Int32?
  priv begin_init : InitializationCallback?
  priv end_init : InitializationCallback?
  /// The aliased directives and their members, declared or inherited and not cleared.
  priv aliases : ReadOnlyArray[(AliasedDirective, String)]
  priv whitespace_significant : Bool
  priv trim_whitespace : Bool
  priv usable_during_initialization : Bool
  priv name_scope : NameScopeSource?
  priv is_abstract : Bool
  priv declared_dependency_owner : @dependency.OwnerType?
  priv dependency_owner : @dependency.OwnerType?
  priv dependency_link : DependencyLink?
  priv any_value_converter : AnyValueConverter?
}

///|
/// A declared or inherited member, not an attached member: the property found nearest first, and only
/// when there is none the event found the same way.
pub fn XamlType::find_member(self : XamlType, name : String) -> XamlMember? {
  self.members.get(name)
}

///|
/// The member `target`, which a type or one of its base types resolved, as objects of this type have
/// it: its operations take handles of this type, also when a nearer member of the name hides it. `None`
/// when this type does not have the member. An attached member is the same one on every object.
pub fn XamlType::own_member(
  self : XamlType,
  target : XamlMember,
) -> XamlMember? {
  guard target.kind is (Property | Event) else { return Some(target) }
  let is_target = (candidate : XamlMember) => {
    candidate.name == target.name &&
    candidate.kind == target.kind &&
    candidate.declaring_type == target.declaring_type
  }
  match self.members.get(target.name) {
    Some(nearest) if is_target(nearest) => Some(nearest)
    _ => self.hidden_members.iter().find_first(is_target)
  }
}

///|
/// The declared and inherited members, base type members first.
pub fn XamlType::members(self : XamlType) -> Iter[XamlMember] {
  self.member_order.iter().filter_map(name => self.members.get(name))
}

///|
/// The attached member `name` that this type or a base type defines: the attached property found
/// nearest first, and only when there is none the attached event found the same way (design D3,
/// 2F21). An inherited attached member keeps its declaring type (F13).
pub fn XamlType::attached_member(self : XamlType, name : String) -> XamlMember? {
  match self.attached.get(name) {
    Some(property) => Some(property)
    None => self.attached_events.get(name)
  }
}

///|
pub fn XamlType::content_member(self : XamlType) -> XamlMember? {
  match self.content_property {
    Some(name) => self.members.get(name)
    None => None
  }
}

///|
/// The type converter of the type: its own, else its nearest base type's other than `x:Object`'s,
/// else the enumeration converter of an enumeration, else a built-in one, as System.Xaml
/// `XamlType.LookupTypeConverter` finds it (design D19).
pub fn XamlType::type_converter(self : XamlType) -> TypeConverter? {
  self.type_converter
}

///|
/// The value serializer of the type: its own, else its base types' nearest first, else the built-in
/// one of the exact type (design D19).
pub fn XamlType::value_serializer(self : XamlType) -> ValueSerializer? {
  self.value_serializer
}

///|
/// The parse function that the type registers, which reads text before the type converter.
pub fn XamlType::parse_function(self : XamlType) -> ParseFunction? {
  self.parse_function
}

///|
pub fn XamlType::item_adder(self : XamlType) -> ItemAdder? {
  self.add_item
}

///|
pub fn XamlType::entry_adder(self : XamlType) -> EntryAdder? {
  self.add_entry
}

///|
pub fn XamlType::value_provider(self : XamlType) -> ValueProvider? {
  self.provide_value
}

///|
pub fn XamlType::is_collection(self : XamlType) -> Bool {
  self.add_item is Some(_)
}

///|
pub fn XamlType::is_dictionary(self : XamlType) -> Bool {
  self.add_entry is Some(_)
}

///|
pub fn XamlType::is_markup_extension(self : XamlType) -> Bool {
  self.provide_value is Some(_)
}

///|
priv struct MemberDefinition {
  name : String
  kind : XamlMemberKind
  value_type : @nodes.XamlTypeName?
  nullable : Bool
  setter : MemberSetter?
  getter : MemberGetter?
  save_reader : SaveReader?
  type_converter : TypeConverter?
  value_serializer : ValueSerializer?
  bracket_pairs : Array[(Char, Char)]
  default_value : @nodes.XamlValue?
  should_serialize : ShouldSerialize?
  visibility : SerializationVisibility
  depends_on : Array[String]
  constructor_argument : String?
  event_adder : EventAdder?
  paired : Bool
  routed_event : @events.RoutedEventInfo?
  dependency : DependencyMember?
}

///|
/// A type registration that a `SchemaContextBuilder` turns into a `XamlType`.
///
/// The methods add to the definition and return it, so registrations chain.
pub struct XamlTypeDefinition {
  priv name : @nodes.XamlTypeName
  /// The XAML namespace URIs, in registration order; `name` uses the first.
  priv namespaces : Array[String]
  /// The scope and CLR-style namespace name.
  priv mut clr : (String, String)?
  priv type_parameters : ReadOnlyArray[String]
  priv mut base_type : @nodes.XamlTypeName?
  priv mut content_property : Designation[String]
  priv aliases : Array[(AliasedDirective, Designation[String])]
  priv mut whitespace_significant : Bool
  priv mut trim_whitespace : Bool
  priv mut usable_during_initialization : Bool?
  priv mut name_scope : (NameScopeLookup, NameScopeRegister)?
  /// A member of the type, or the attached member of the owner type.
  priv mut name_scope_property : (String, @nodes.XamlTypeName?)?
  /// The short name of a built-in markup extension, such as `Type` for `TypeExtension`, which names
  /// the same type (F15).
  priv mut short_name : String?
  priv mut is_abstract : Bool
  priv members : Array[MemberDefinition]
  priv statics : Array[StaticDefinition]
  priv constructors : Array[ConstructorDefinition]
  /// The converter for the identity of the type.
  priv type_converter : ((@nodes.XamlTypeName) -> TypeConverter)?
  priv mut value_serializer : ValueSerializer?
  /// A value serializer of the exact type only, not inherited: the built-in ones.
  priv mut exact_serializer : ValueSerializer?
  priv mut parse_function : ParseFunction?
  /// The backing type, named values and flags marker of an enumeration.
  priv mut enumeration : (EnumBacking, Array[(String, Int64)], Bool)?
  priv mut add_item : ItemAdder?
  priv mut add_entry : EntryAdder?
  priv mut item_type : @nodes.XamlTypeName?
  priv mut key_type : @nodes.XamlTypeName?
  priv mut entry_item_type : @nodes.XamlTypeName?
  priv mut item_enumerator : ItemEnumerator?
  priv mut entry_enumerator : EntryEnumerator?
  priv mut instance_descriptor : InstanceDescriber?
  priv mut attached_store : AttachedMemberStore?
  priv mut provide_value : ValueProvider?
  priv mut object_key : Int32?
  priv base_views : Array[BaseView]
  priv mut begin_init : InitializationCallback?
  priv mut end_init : InitializationCallback?
  /// More than one is a conflict.
  priv dependency_owners : Array[(@dependency.OwnerType, DependencyLink?)]
  priv mut any_value_converter : AnyValueConverter?
}

///|
/// A type registration. `type_parameters` names the type parameters of a generic type, in order;
/// member and base types refer to them with `type_parameter`. Types are keyed by namespace, name and
/// the number of type parameters, so `Tuple` with one and with two parameters are different types.
pub fn XamlTypeDefinition::new(
  namespace_uri : String,
  name : String,
  type_parameters~ : Array[String] = [],
  base_type? : @nodes.XamlTypeName,
  content_property? : String,
  type_converter? : TypeConverter,
) -> XamlTypeDefinition {
  {
    name: @nodes.XamlTypeName::new(
      namespace_uri,
      name,
      type_arguments=type_parameters.map(type_parameter),
    ),
    namespaces: [namespace_uri],
    clr: None,
    type_parameters: ReadOnlyArray::from_array(type_parameters),
    base_type,
    content_property: match content_property {
      Some(name) => Set(name)
      None => Inherit
    },
    aliases: [],
    whitespace_significant: false,
    trim_whitespace: false,
    usable_during_initialization: None,
    name_scope: None,
    name_scope_property: None,
    short_name: None,
    is_abstract: false,
    members: [],
    statics: [],
    constructors: [],
    type_converter: type_converter.map(converter => _ => converter),
    value_serializer: None,
    exact_serializer: None,
    parse_function: None,
    enumeration: None,
    add_item: None,
    add_entry: None,
    item_type: None,
    key_type: None,
    entry_item_type: None,
    item_enumerator: None,
    entry_enumerator: None,
    instance_descriptor: None,
    attached_store: None,
    provide_value: None,
    object_key: None,
    base_views: [],
    begin_init: None,
    end_init: None,
    dependency_owners: [],
    any_value_converter: None,
  }
}

///|
/// A type registered only under the CLR-style namespace clr_namespace of scope, whose URI
/// clr-namespace:N;assembly=S is then its preferred namespace (design D11, 2F27).
pub fn XamlTypeDefinition::new_clr(
  scope : String,
  clr_namespace : String,
  name : String,
  type_parameters~ : Array[String] = [],
  base_type? : @nodes.XamlTypeName,
  content_property? : String,
  type_converter? : TypeConverter,
) -> XamlTypeDefinition {
  let definition = XamlTypeDefinition::new(
    clr_namespace_uri(clr_namespace, scope),
    name,
    type_parameters~,
    base_type?,
    content_property?,
    type_converter?,
  )
  definition.namespaces.clear()
  definition.clr = Some((scope, clr_namespace))
  definition
}

///|
/// Register the type under another XAML namespace URI as well, as several .NET
/// XmlnsDefinitionAttributes map URIs to one CLR namespace. The type keeps one identity.
pub fn XamlTypeDefinition::add_namespace(
  self : XamlTypeDefinition,
  namespace_uri : String,
) -> XamlTypeDefinition {
  self.namespaces.push(namespace_uri)
  self
}

///|
/// Register the CLR-style namespace name clr_namespace in scope for the type. Its URI
/// clr-namespace:N;assembly=S is the type's last secondary namespace.
pub fn XamlTypeDefinition::clr_namespace(
  self : XamlTypeDefinition,
  scope : String,
  clr_namespace : String,
) -> XamlTypeDefinition {
  self.clr = Some((scope, clr_namespace))
  self
}

///|
pub fn XamlTypeDefinition::type_name(
  self : XamlTypeDefinition,
) -> @nodes.XamlTypeName {
  self.name
}

///|
/// Whether `char` can be in a bracket pair, as System.Xaml `SpecialBracketCharacters.IsValidBracketCharacter` decides
/// for its UTF-16 units.
fn is_bracket(char : Char) -> Bool {
  char.is_bmp() &&
  !char.is_whitespace() &&
  !"=,'\"{}\\".contains_char(char) &&
  // Letters and digits can be in a name after its first character.
  (char == '_' || !@nodes.is_object_name("a\{char}"))
}

///|
/// Add a member that the type declares. `nullable` makes its value type nullable: text converts
/// with the value type's converter and null is a value of it. `type_converter` and
/// `value_serializer` take precedence over those of the value type. `bracket_pairs` are the
/// opening and closing characters inside which markup extension text for the member is not split,
/// as System.Xaml `MarkupExtensionBracketCharactersAttribute` (F41). The two differ, and neither is a letter, a
/// digit, white space, beyond U+FFFF or one of `=`, `,`, `'`, `"`, `{`, `}` and `\`.
///
/// For saving (design D20, D21): `save_reader` reads the value that saving compares and writes,
/// beside the getter that loading uses, and needs the getter; `default_value` is the value that
/// saving leaves out, as .NET `DefaultValueAttribute`, converted at `build()` when it is not
/// assignable, and for a value type that is a type parameter in each derived type that closes it and
/// can convert it; `should_serialize` decides otherwise, as a `ShouldSerialize` method; `visibility` is
/// .NET `DesignerSerializationVisibility`; `depends_on` names the members written before this one,
/// as `DependsOnAttribute`, ignoring names that are not members; `constructor_argument` names the
/// constructor parameter that receives the value, as `ConstructorArgumentAttribute`.
pub fn XamlTypeDefinition::add_member(
  self : XamlTypeDefinition,
  name : String,
  value_type? : @nodes.XamlTypeName,
  nullable~ : Bool = false,
  setter? : MemberSetter,
  getter? : MemberGetter,
  save_reader? : SaveReader,
  type_converter? : TypeConverter,
  value_serializer? : ValueSerializer,
  bracket_pairs~ : ArrayView[(Char, Char)] = [],
  default_value? : @nodes.XamlValue,
  should_serialize? : ShouldSerialize,
  visibility~ : SerializationVisibility = Visible,
  depends_on~ : ArrayView[String] = [],
  constructor_argument? : String,
) -> XamlTypeDefinition {
  self.members.push({
    name,
    kind: Property,
    value_type,
    nullable,
    setter,
    getter,
    save_reader,
    type_converter,
    value_serializer,
    bracket_pairs: bracket_pairs.to_owned(),
    default_value,
    should_serialize,
    visibility,
    depends_on: depends_on.to_owned(),
    constructor_argument,
    event_adder: None,
    paired: false,
    routed_event: None,
    dependency: None,
  })
  self
}

///|
/// Add an attached member that the type defines for other objects, such as `Grid.Row`. The options
/// are those of `add_member`.
pub fn XamlTypeDefinition::add_attached_member(
  self : XamlTypeDefinition,
  name : String,
  value_type? : @nodes.XamlTypeName,
  nullable~ : Bool = false,
  setter? : MemberSetter,
  getter? : MemberGetter,
  save_reader? : SaveReader,
  type_converter? : TypeConverter,
  value_serializer? : ValueSerializer,
  bracket_pairs~ : ArrayView[(Char, Char)] = [],
  default_value? : @nodes.XamlValue,
  should_serialize? : ShouldSerialize,
  visibility~ : SerializationVisibility = Visible,
) -> XamlTypeDefinition {
  self.members.push({
    name,
    kind: Attached,
    value_type,
    nullable,
    setter,
    getter,
    save_reader,
    type_converter,
    value_serializer,
    bracket_pairs: bracket_pairs.to_owned(),
    default_value,
    should_serialize,
    visibility,
    depends_on: [],
    constructor_argument: None,
    event_adder: None,
    paired: false,
    routed_event: None,
    dependency: None,
  })
  self
}

///|
/// Register the value serializer of the type, which derived types inherit.
pub fn XamlTypeDefinition::value_serializer(
  self : XamlTypeDefinition,
  serializer : ValueSerializer,
) -> XamlTypeDefinition {
  self.value_serializer = Some(serializer)
  self
}

///|
/// Register a function that reads values of the type from text before its type converter, as
/// Avalonia uses a static `Parse(string)` method (design D19). It is not inherited.
pub fn XamlTypeDefinition::parse_function(
  self : XamlTypeDefinition,
  parse : ParseFunction,
) -> XamlTypeDefinition {
  self.parse_function = Some(parse)
  self
}

///|
/// Make the type an enumeration with the backing type `backing` and the named `values`, in order.
/// A value of an `UInt64` enumeration above the `Int64` range is given as its two's complement, such
/// as `-1` for 2^64 - 1. Without its own converter the type converts with the enumeration
/// converter.
pub fn XamlTypeDefinition::enumeration(
  self : XamlTypeDefinition,
  backing : EnumBacking,
  values : ArrayView[(String, Int64)],
  flags~ : Bool = false,
) -> XamlTypeDefinition {
  self.enumeration = Some((backing, values.to_owned(), flags))
  self
}

///|
pub fn XamlTypeDefinition::base_type(
  self : XamlTypeDefinition,
  base_type : @nodes.XamlTypeName,
) -> XamlTypeDefinition {
  self.base_type = Some(base_type)
  self
}

///|
pub fn XamlTypeDefinition::content_property(
  self : XamlTypeDefinition,
  name : String,
) -> XamlTypeDefinition {
  self.content_property = Set(name)
  self
}

///|
/// Make the type a collection whose items `add` adds. `item_type` is the type of its items,
/// `x:Object` unless given, as System.Xaml `XamlType.ItemType`.
pub fn XamlTypeDefinition::collection(
  self : XamlTypeDefinition,
  add : ItemAdder,
  item_type? : @nodes.XamlTypeName,
) -> XamlTypeDefinition {
  self.add_item = Some(add)
  self.item_type = item_type
  self
}

///|
/// Make the type a dictionary whose keyed entries `add` adds. `key_type` and `item_type` are the
/// types of its keys and values, `x:Object` unless given, as System.Xaml `XamlType.KeyType` and
/// `ItemType`.
pub fn XamlTypeDefinition::dictionary(
  self : XamlTypeDefinition,
  add : EntryAdder,
  key_type? : @nodes.XamlTypeName,
  item_type? : @nodes.XamlTypeName,
) -> XamlTypeDefinition {
  self.add_entry = Some(add)
  self.key_type = key_type
  self.entry_item_type = item_type
  self
}

///|
/// Make the type a markup extension. Its constructors are its positional signatures, selected by
/// argument count only (design D13).
pub fn XamlTypeDefinition::markup_extension(
  self : XamlTypeDefinition,
  provide_value : ValueProvider,
) -> XamlTypeDefinition {
  self.provide_value = Some(provide_value)
  self
}