///|
/// A registration problem that `SchemaContextBuilder::build` reports.
#derive(Eq, Debug)
pub(all) enum SchemaConflict {
  /// Two types use the same namespace URI, name and generic arity.
  DuplicateType(namespace_uri~ : String, name~ : String, arity~ : Int32)
  /// Two types use the same scope, CLR-style namespace, name and generic arity.
  DuplicateClrType(
    scope~ : String,
    clr_namespace~ : String,
    name~ : String,
    arity~ : Int32,
  )
  /// A CLR-style namespace registration with an empty scope or namespace name.
  InvalidClrNamespace(name~ : String, scope~ : String, clr_namespace~ : String)
  /// A type registered under the empty namespace URI.
  EmptyNamespaceUri(name~ : String)
  /// A preferred prefix that is empty, not an NCName, `xml` or `xmlns`, or registered for the empty
  /// namespace URI.
  InvalidPrefix(prefix~ : String, namespace_uri~ : String)
  /// A subsumption with an empty namespace URI.
  InvalidSubsumption(newer~ : String, older~ : String)
  /// One older namespace subsumed by more than one newer namespace (System.Xaml
  /// `DuplicateXmlnsCompat`).
  DuplicateSubsumption(older~ : String, newer~ : ReadOnlyArray[String])
  /// Subsumptions that form a cycle, its namespaces in ordinal order (System.Xaml
  /// `XmlnsCompatCycle`).
  SubsumptionCycle(ReadOnlyArray[String])
  /// A type whose preferred namespace subsumption maps to a namespace where its name is another
  /// type, so documents could not name it (design D11).
  PreferredNamespaceConflict(
    name~ : String,
    preferred~ : String,
    mapped~ : String,
  )
  /// A member or base type of a generic type refers to a type parameter that the type does not
  /// declare.
  UnknownTypeParameter(@nodes.XamlTypeName, String)
  /// A type registers two members of one name space with the same name: two instance or static
  /// members, or two attached members (design D3, 2F8).
  DuplicateMember(@nodes.XamlTypeName, String)
  /// A static member registered with neither or both of a value and a getter.
  InvalidStaticMember(@nodes.XamlTypeName, String)
  /// A member that registers a save reader and no getter, which saving needs to decide whether
  /// to write it (design D21).
  SaveReaderWithoutGetter(@nodes.XamlTypeName, String)
  /// A member with a bracket pair that System.Xaml rejects (`SpecialBracketCharacters`).
  InvalidBracketPair(
    @nodes.XamlTypeName,
    String,
    opening~ : Char,
    closing~ : Char,
  )
  /// A type that registers an item or entry enumerator without an add operation of its own or of a
  /// base type.
  EnumeratorWithoutAdd(@nodes.XamlTypeName)
  /// A type with its own object key inherits an operation registered with a base type's key, and
  /// no chain of base views leads from its key to that key (design D8). `operation` is the member
  /// or the callback: `add`, `items`, `entries`, `instance descriptor`, `attached member store`,
  /// `provide value`, `begin init`, `end init`, `name scope`, `dependency link` or `AnyValue converter`.
  MissingBaseView(
    @nodes.XamlTypeName,
    base~ : @nodes.XamlTypeName,
    operation~ : String,
  )
  /// A type that names more than one owner type.
  DuplicateDependencyOwner(@nodes.XamlTypeName)
  /// A member that is a dependency property, on a type whose objects have no dependency object.
  MemberWithoutDependencyObject(@nodes.XamlTypeName, String)
  /// An attached member that is a dependency property, on a type that names no owner type itself.
  AttachedMemberWithoutOwner(@nodes.XamlTypeName, String)
  /// A member whose dependency property is not in the registry of the owner type of its type.
  PropertyRegistryMismatch(
    @nodes.XamlTypeName,
    String,
    property~ : @dependency.RegistryId,
    owner~ : @dependency.RegistryId,
  )
  /// A default value that does not convert to the member's value type, with the input and the
  /// converter's message.
  InvalidDefaultValue(
    @nodes.XamlTypeName,
    String,
    input~ : String,
    message~ : String,
  )
  /// Two directives use the same namespace URI and name.
  DuplicateDirective(namespace_uri~ : String, name~ : String)
  /// A base type that is not registered.
  UnknownBaseType(@nodes.XamlTypeName, base~ : @nodes.XamlTypeName)
  /// A base type chain that returns to the type.
  BaseTypeCycle(@nodes.XamlTypeName)
  /// A content property, alias, name-scope property or positional parameter that names no member
  /// of the type.
  UnknownMember(@nodes.XamlTypeName, String)
  /// A name-scope property that names no attached member of its owner type or the owner's bases.
  UnknownAttachedMember(
    @nodes.XamlTypeName,
    String,
    owner~ : @nodes.XamlTypeName,
  )
  /// A markup extension that is usable during initialization, which System.Xaml rejects as
  /// `UsableDuringInitializationOnME`.
  UsableDuringInitializationOnMarkupExtension(@nodes.XamlTypeName)
  /// A named value of an enumeration outside the range of its backing type.
  InvalidEnumValue(@nodes.XamlTypeName, String)
  /// Two constructors, or two factory methods of one name, with the same parameter types.
  DuplicateConstructor(
    @nodes.XamlTypeName,
    factory_method~ : String?,
    parameter_types~ : ReadOnlyArray[@nodes.XamlTypeName],
  )
  /// A markup extension with two constructors of one count, which positional arguments cannot tell
  /// apart (System.Xaml `MarkupExtensionWithDuplicateArity`).
  DuplicatePositionalArity(@nodes.XamlTypeName, Int32)
}

///|
pub fn SchemaConflict::message(self : SchemaConflict) -> String {
  match self {
    DuplicateType(namespace_uri~, name~, arity~) =>
      "type {\{namespace_uri}}\{name} with \{arity} type parameter(s) is registered more than once"
    DuplicateClrType(scope~, clr_namespace~, name~, arity~) =>
      "type \{clr_namespace}.\{name} with \{arity} type parameter(s) is registered more than once in the scope \{scope}"
    InvalidClrNamespace(name~, scope~, clr_namespace~) =>
      "type \{name} registers the CLR-style namespace \"\{clr_namespace}\" in the scope \"\{scope}\"; both must be non-empty"
    EmptyNamespaceUri(name~) =>
      "type \{name} is registered under the empty namespace URI"
    InvalidPrefix(prefix~, namespace_uri~) =>
      "the preferred prefix \"\{prefix}\" of the namespace \"\{namespace_uri}\" is not valid: a prefix is a non-empty NCName other than xml and xmlns, for a non-empty namespace URI"
    InvalidSubsumption(newer~, older~) =>
      "the namespace \"\{newer}\" cannot subsume \"\{older}\": both URIs must be non-empty"
    DuplicateSubsumption(older~, newer~) =>
      "the namespace \"\{older}\" is subsumed by more than one namespace: \{quoted_list(newer)}"
    SubsumptionCycle(namespaces) =>
      "the subsumptions of the namespaces \{quoted_list(namespaces)} form a cycle"
    PreferredNamespaceConflict(name~, preferred~, mapped~) =>
      "type \{name} is preferred in the namespace \"\{preferred}\", which subsumption maps to \"\{mapped}\", where \{name} is another type"
    UnknownTypeParameter(t, parameter) =>
      "type \{qualified(t)} refers to the type parameter \{parameter}, which it does not declare"
    MissingBaseView(t, base~, operation~) =>
      "type \{qualified(t)} has its own object key and inherits \{operation} from \{qualified(base)}, whose key no base view of it reaches"
    DuplicateDependencyOwner(t) =>
      "type \{qualified(t)} names more than one dependency owner type"
    MemberWithoutDependencyObject(t, m) =>
      "member \{m} of type \{qualified(t)} is a dependency property, and objects of the type have no dependency object"
    AttachedMemberWithoutOwner(t, m) =>
      "attached member \{t.name}.\{m} of type \{qualified(t)} is a dependency property, and the type names no dependency owner type"
    PropertyRegistryMismatch(t, m, property~, owner~) =>
      "member \{m} of type \{qualified(t)} is a dependency property of \{property}, and the owner type of the type is in \{owner}"
    SaveReaderWithoutGetter(t, m) =>
      "member \{m} of type \{qualified(t)} registers a save reader without a getter"
    InvalidBracketPair(t, m, opening~, closing~) =>
      "member \{m} of type \{qualified(t)} cannot have the bracket pair \{opening} and \{closing}, which have to be two different characters up to U+FFFF, no letters, digits or white space, and none of = , ' \" { } \\"
    EnumeratorWithoutAdd(t) =>
      "type \{qualified(t)} registers an enumerator without an add operation"
    InvalidDefaultValue(t, m, input~, message~) =>
      "the default value \{input} of member \{m} of type \{qualified(t)} does not convert: \{message}"
    InvalidStaticMember(t, m) =>
      "type \{qualified(t)} registers the static member \{m} without exactly one of a value and a getter"
    DuplicateMember(t, m) =>
      "type \{qualified(t)} registers member \{m} more than once"
    DuplicateDirective(namespace_uri~, name~) =>
      "directive {\{namespace_uri}}\{name} is registered more than once"
    UnknownBaseType(t, base~) =>
      "type \{qualified(t)} names base type \{qualified(base)}, which is not registered"
    BaseTypeCycle(t) => "the base types of \{qualified(t)} form a cycle"
    UnknownMember(t, m) =>
      "type \{qualified(t)} names member \{m}, which it does not declare or inherit"
    UnknownAttachedMember(t, m, owner~) =>
      "type \{qualified(t)} names the attached member \{m} of \{qualified(owner)}, which it does not define or inherit"
    UsableDuringInitializationOnMarkupExtension(t) =>
      "markup extension \{qualified(t)} is usable during initialization, which a markup extension cannot be"
    DuplicateConstructor(t, factory_method~, parameter_types~) => {
      let what = match factory_method {
        Some(name) => "the factory method \{name}"
        None => "a constructor"
      }
      let types = parameter_types.iter().map(qualified).collect().join(", ")
      "type \{qualified(t)} registers \{what} with the parameter types (\{types}) more than once"
    }
    DuplicatePositionalArity(t, count) =>
      "markup extension \{qualified(t)} registers more than one constructor of \{count} argument(s), which positional arguments cannot tell apart"
    InvalidEnumValue(t, value) =>
      "the value \{value} of the enumeration \{qualified(t)} is outside the range of its backing type"
  }
}

///|
/// `{namespace}Name`, with type arguments in the same form, as messages show type names.
fn qualified(name : @nodes.XamlTypeName) -> String {
  name.to_string()
}

///|
fn quoted_list(items : ReadOnlyArray[String]) -> String {
  items.iter().map(item => "\"\{item}\"").collect().join(", ")
}

///|
/// The registrations do not form a valid schema context.
#derive(Eq, Debug)
pub(all) suberror SchemaError {
  Conflicts(ReadOnlyArray[SchemaConflict])
}

///|
pub fn SchemaError::message(self : SchemaError) -> String {
  let Conflicts(conflicts) = self
  let parts = conflicts.iter().map(c => c.message()).collect()
  "invalid schema registrations: \{parts.join("; ")}"
}

///|
/// Collects type, directive, preferred prefix and namespace subsumption registrations and builds an
/// immutable `SchemaContext` (design D3, D11).
pub struct SchemaContextBuilder {
  priv types : Array[XamlTypeDefinition]
  priv directives : Array[XamlMember]
  priv prefixes : Array[(String, String)]
  priv subsumptions : Array[(String, String)]
}

///|
pub fn SchemaContextBuilder::new() -> SchemaContextBuilder {
  { types: [], directives: [], prefixes: [], subsumptions: [], }
}

///|
pub fn SchemaContextBuilder::add_type(
  self : SchemaContextBuilder,
  definition : XamlTypeDefinition,
) -> SchemaContextBuilder {
  self.types.push(definition)
  self
}

///|
/// Add a custom directive of a namespace other than the XAML language namespaces and the XML
/// namespace, whose directives are built in (design D8). With `item_type` it is a collection
/// directive. `build()` fails with `DuplicateDirective` for a directive of those namespaces or a
/// second directive of one namespace and name.
pub fn SchemaContextBuilder::add_directive(
  self : SchemaContextBuilder,
  namespace_uri : String,
  name : String,
  value_type? : @nodes.XamlTypeName,
  item_type? : @nodes.XamlTypeName,
  allowed_locations~ : AllowedLocations = anywhere,
) -> SchemaContextBuilder {
  self.directives.push(
    XamlMember::directive(
      language_alias(namespace_uri),
      name,
      value_type?,
      item_type?,
      allowed_locations~,
    ),
  )
  self
}

///|
/// Register `prefix` as a preferred prefix of `namespace_uri`, as .NET `XmlnsPrefixAttribute` does.
/// Of several preferred prefixes of one URI the shortest, then the ordinal least, is chosen (F30).
pub fn SchemaContextBuilder::add_preferred_prefix(
  self : SchemaContextBuilder,
  namespace_uri : String,
  prefix : String,
) -> SchemaContextBuilder {
  self.prefixes.push((namespace_uri, prefix))
  self
}

///|
/// Register that the namespace `newer` subsumes the namespace `older`, as .NET
/// `XmlnsCompatibleWithAttribute(older, newer)` does: a document that uses `older` is read as if it
/// used `newer` (design D17).
pub fn SchemaContextBuilder::add_namespace_subsumption(
  self : SchemaContextBuilder,
  newer~ : String,
  older~ : String,
) -> SchemaContextBuilder {
  self.subsumptions.push((newer, older))
  self
}

///|
/// An immutable set of registered XAML types and directives.
///
/// Every context contains the XAML language namespace with its built-in types and directives,
/// reachable under the 2006 and 2009 URIs. Each type has one identity, its name in its preferred
/// namespace; every namespace that names it finds the same `XamlType` (design D11).
pub struct SchemaContext {
  /// The types by identity.
  priv types : Map[TypeKey, XamlType]
  /// The identity of each registered (namespace, name, arity), for every namespace of each type.
  priv index : Map[TypeKey, TypeKey]
  /// The generic arities registered for each namespace and name, for arity mismatch errors.
  priv arities : Map[(String, String), Array[Int32]]
  priv directives : Map[(String, String), XamlMember]
  /// The preferred prefix of each namespace that has one.
  priv prefixes : Map[String, String]
  /// The newer namespace of each subsumed one.
  priv newer : Map[String, String]
  /// The namespaces that the context resolves.
  priv known : Map[String, Unit]
  /// The scopes that register each (CLR-style namespace, name, arity), in registration order.
  priv clr_scopes : Map[TypeKey, Array[String]]
  priv dependency_types : DependencyTypes
}

///|
/// One definition of a base chain, with the map from its type parameters to their arguments in
/// terms of the most derived type of the chain.
priv struct ChainLink {
  record : TypeRecord
  arguments : Map[String, @nodes.XamlTypeName]
}

///|
/// A type definition with its identity and namespaces.
priv struct TypeRecord {
  definition : XamlTypeDefinition
  identity : @nodes.XamlTypeName
  namespaces : Array[String]
}

///|
/// The namespaces of `definition` in preference order: its XAML namespace URIs sorted by
/// `preferences`, with the 2009 XAML language URI after the 2006 one, then its CLR-style URI.
/// It reports an empty URI or CLR-style registration and gives `None`.
fn definition_namespaces(
  definition : XamlTypeDefinition,
  preferences : NamespacePreferences,
  conflicts : Array[SchemaConflict],
) -> Array[String]? {
  let name = definition.name.name
  let xaml : Array[String] = []
  for uri in definition.namespaces {
    if uri.is_empty() {
      conflicts.push(EmptyNamespaceUri(name~))
      return None
    }
    let uri = language_alias(uri)
    if !xaml.contains(uri) {
      xaml.push(uri)
    }
  }
  if xaml.contains(@nodes.xaml_language_namespace) &&
    !xaml.contains(xaml_language_namespace_2009) {
    xaml.push(xaml_language_namespace_2009)
  }
  // Insertion sort: types register few namespaces.
  for i in 1.. 0 && preferences.compare(xaml[j], xaml[j - 1]) < 0 {
      xaml.swap(j, j - 1)
      j -= 1
    }
  }
  if definition.clr is Some((scope, clr_namespace)) {
    if scope.is_empty() || clr_namespace.is_empty() {
      conflicts.push(InvalidClrNamespace(name~, scope~, clr_namespace~))
      return None
    }
    xaml.push(clr_namespace_uri(clr_namespace, scope))
  }
  Some(xaml)
}

///|
/// The preferred prefixes and subsumptions, checked as `build()` requires.
fn SchemaContextBuilder::namespace_preferences(
  self : SchemaContextBuilder,
  conflicts : Array[SchemaConflict],
) -> NamespacePreferences {
  let prefixes : Map[String, String] = Map([
    (@nodes.xaml_language_namespace, "x"),
    (xaml_language_namespace_2009, "x"),
  ])
  for entry in self.prefixes {
    let (namespace_uri, prefix) = entry
    if namespace_uri.is_empty() ||
      !@nodes.is_ncname(prefix) ||
      prefix is ("xml" | "xmlns") {
      conflicts.push(InvalidPrefix(prefix~, namespace_uri~))
      continue
    }
    prefixes[namespace_uri] = choose_prefix(prefixes.get(namespace_uri), prefix)
  }
  let candidates : Map[String, Array[String]] = Map([])
  for entry in self.subsumptions {
    let (newer, older) = entry
    if newer.is_empty() || older.is_empty() {
      conflicts.push(InvalidSubsumption(newer~, older~))
      continue
    }
    match candidates.get(older) {
      Some(list) => if !list.contains(newer) { list.push(newer) }
      None => candidates[older] = [newer]
    }
  }
  let newer : Map[String, String] = Map([])
  for older, list in candidates {
    if list.length() > 1 {
      conflicts.push(
        DuplicateSubsumption(older~, newer=ReadOnlyArray::from_array(list)),
      )
    } else {
      newer[older] = list[0]
    }
  }
  // Each cycle once, its namespaces in ordinal order.
  let cycles : Array[Array[String]] = []
  for start, _ in newer {
    let path = [start]
    let mut current = start
    while newer.get(current) is Some(next) {
      if next == start {
        path.sort_by((a, b) => a.lexical_compare(b))
        if !cycles.contains(path) {
          cycles.push(path)
          conflicts.push(SubsumptionCycle(ReadOnlyArray::from_array(path)))
        }
        break
      }
      if path.contains(next) {
        // A cycle that does not pass through `start`; it is reported from its own namespaces.
        break
      }
      path.push(next)
      current = next
    }
  }
  let subsumed_count : Map[String, Int32] = Map([])
  for _, target in newer {
    subsumed_count[target] = subsumed_count.get(target).unwrap_or(0) + 1
  }
  { prefixes, newer, subsumed_count, }
}

///|
/// The namespace that a document's `namespace_uri` is read as, given the subsumptions `newer` and
/// whether a namespace resolves (`TryGetCompatibleXamlNamespace`, design D17): a namespace without a
/// newer one is itself when it resolves; otherwise its newer namespace must resolve, and the chain is
/// followed while each further replacement resolves. An understood namespace is always itself. `None`
/// means the namespace is not supported.
fn compatible_in(
  newer : Map[String, String],
  known : (String) -> Bool,
  namespace_uri : String,
  is_understood~ : (String) -> Bool = _ => false,
) -> String? {
  if is_understood(namespace_uri) {
    return Some(namespace_uri)
  }
  match newer.get(namespace_uri) {
    None => if known(namespace_uri) { Some(namespace_uri) } else { None }
    Some(first) => {
      if !known(first) {
        return None
      }
      let mut current = first
      let mut steps = 0
      while !is_understood(current) &&
            newer.get(current) is Some(next) &&
            known(next) &&
            steps <= newer.length() {
        current = next
        steps += 1
      }
      Some(current)
    }
  }
}

///|
/// Build the context, or raise `SchemaError` with every conflict in registration order.
pub fn SchemaContextBuilder::build(
  self : SchemaContextBuilder,
) -> SchemaContext raise SchemaError {
  let conflicts : Array[SchemaConflict] = []
  let preferences = self.namespace_preferences(conflicts)
  // Identities and the namespace index.
  let records : Map[TypeKey, TypeRecord] = Map([])
  let order : Array[TypeKey] = []
  let index : Map[TypeKey, TypeKey] = Map([])
  let arities : Map[(String, String), Array[Int32]] = Map([])
  let clr_scopes : Map[TypeKey, Array[String]] = Map([])
  let dependency_types = DependencyTypes::new(index)
  let all_definitions = builtin_types(dependency_types)
  all_definitions.append(self.types)
  for definition in all_definitions {
    guard definition_namespaces(definition, preferences, conflicts)
      is Some(namespaces) else {
      continue
    }
    let name = definition.name.name
    let arity = definition.type_parameters.length()
    let clr_uri = definition.clr.map(c => clr_namespace_uri(c.1, c.0))
    // A built-in markup extension also answers to its short name (F15).
    let names = [name]
    if definition.short_name is Some(short) {
      names.push(short)
    }
    let collision = namespaces
      .iter()
      .filter(uri => names.iter().any(n => index.contains((uri, n, arity))))
      .head()
    if collision is Some(uri) {
      match (definition.clr, clr_uri) {
        (Some((scope, clr_namespace)), Some(clr)) if clr == uri =>
          conflicts.push(
            DuplicateClrType(scope~, clr_namespace~, name~, arity~),
          )
        _ => conflicts.push(DuplicateType(namespace_uri=uri, name~, arity~))
      }
      continue
    }
    let identity = @nodes.XamlTypeName::new(
      namespaces[0],
      name,
      type_arguments=definition.name.type_arguments[:],
    )
    let key = definition_key(identity)
    for uri in namespaces {
      for n in names {
        index[(uri, n, arity)] = key
        match arities.get((uri, n)) {
          Some(list) => list.push(arity)
          None => arities[(uri, n)] = [arity]
        }
      }
    }
    if definition.clr is Some((scope, clr_namespace)) {
      match clr_scopes.get((clr_namespace, name, arity)) {
        Some(list) => list.push(scope)
        None => clr_scopes[(clr_namespace, name, arity)] = [scope]
      }
    }
    records[key] = { definition, identity, namespaces, }
    order.push(key)
  }
  let canonical = (name : @nodes.XamlTypeName) => canonical_in(index, name)
  // A type other than `x:Object` that omits its base type derives from `x:Object`, as System.Xaml
  // `XamlType.LookupBaseType` gives `Object` (2F11).
  let base_of = (record : TypeRecord) => {
    match record.definition.base_type {
      Some(base) => Some(base)
      None =>
        if definition_key(record.identity) == definition_key(object_type) {
          None
        } else {
          Some(object_type)
        }
    }
  }
  for key in order {
    let record = records[key]
    let definition = record.definition
    let name = record.identity
    // Instance and static members share one name space and attached members another, as
    // System.Xaml `TypeReflector` keeps separate non-attachable and attachable caches (2F8).
    let instance_names : Map[String, Unit] = Map([])
    let attachable_names : Map[String, Unit] = Map([])
    let claim = (space : Map[String, Unit], member_name : String) => {
      if space.contains(member_name) {
        conflicts.push(DuplicateMember(name, member_name))
      }
      space[member_name] = ()
    }
    for entry in definition.members {
      match entry.kind {
        Attached | AttachedEvent => claim(attachable_names, entry.name)
        Property | Event | Directive => claim(instance_names, entry.name)
      }
      if entry.save_reader is Some(_) && entry.getter is None {
        conflicts.push(SaveReaderWithoutGetter(name, entry.name))
      }
      for pair in entry.bracket_pairs {
        let (opening, closing) = pair
        if opening == closing || !is_bracket(opening) || !is_bracket(closing) {
          conflicts.push(
            InvalidBracketPair(name, entry.name, opening~, closing~),
          )
        }
      }
    }
    for entry in definition.statics {
      claim(instance_names, entry.name)
      if entry.get is None {
        conflicts.push(InvalidStaticMember(name, entry.name))
      }
    }
    if definition.enumeration is Some((_, values, _)) {
      for entry in values {
        claim(instance_names, entry.0)
      }
    }
    let referenced = definition.base_type.iter().to_array()
    for entry in definition.members {
      if entry.value_type is Some(value_type) {
        referenced.push(value_type)
      }
    }
    for c in definition.constructors {
      for parameter in c.parameters {
        referenced.push(parameter.type_name)
      }
    }
    for entry in definition.statics {
      if entry.value_type is Some(value_type) {
        referenced.push(value_type)
      }
    }
    for
      t in [
        definition.item_type,
        definition.key_type,
        definition.entry_item_type,
      ] {
      if t is Some(t) {
        referenced.push(t)
      }
    }
    let unknown : Array[String] = []
    for type_name in referenced {
      for parameter in unknown_parameters(type_name, definition.type_parameters) {
        if !unknown.contains(parameter) {
          unknown.push(parameter)
          conflicts.push(UnknownTypeParameter(name, parameter))
        }
      }
    }
  }
  // Each type with its base chain, most derived first. A type with a broken chain gets none.
  let chains : Map[TypeKey, Array[ChainLink]] = Map([])
  for key in order {
    let name = records[key].identity
    let chain = [ChainLink::{ record: records[key], arguments: Map([]), }]
    let mut broken = false
    while chain.last() is Some(last) && base_of(last.record) is Some(base) {
      let base = substitute(canonical(base), last.arguments)
      let base_key = index.get(definition_key(base))
      if base_key == Some(key) ||
        chain
        .iter()
        .any(link => Some(definition_key(link.record.identity)) == base_key) {
        conflicts.push(BaseTypeCycle(name))
        broken = true
        break
      }
      guard base_key.bind(k => records.get(k)) is Some(base_record) else {
        if chain.length() == 1 {
          conflicts.push(UnknownBaseType(name, base~))
        }
        broken = true
        break
      }
      chain.push({
        record: base_record,
        arguments: parameter_map(base_record.definition.type_parameters, base),
      })
    }
    if !broken {
      chains[key] = chain
    }
  }
  let types : Map[TypeKey, XamlType] = Map([])
  // The types whose name-scope property is an attached member: the type, the member, its owner and
  // whether the type declares it.
  let scope_properties : Array[(TypeKey, String, @nodes.XamlTypeName, Bool)] = []
  for key in order {
    guard chains.get(key) is Some(chain) else { continue }
    let record = chain[0].record
    let definition = record.definition
    let name = record.identity
    let members : Map[String, XamlMember] = Map([])
    let member_order : Array[String] = []
    let attached : Map[String, XamlMember] = Map([])
    let attached_events : Map[String, XamlMember] = Map([])
    // The chain link that declares each instance member.
    let member_links : Map[String, Int32] = Map([])
    // The members that a nearer one of the name replaces, with their chain links.
    let hidden : Array[(XamlMember, Int32)] = []
    for i = chain.length() - 1; i >= 0; i = i - 1 {
      let declaring = chain[i].record
      let arguments = chain[i].arguments
      for entry in declaring.definition.members {
        let registered = XamlMember::{
          name: entry.name,
          kind: entry.kind,
          declaring_type: Some(substitute(declaring.identity, arguments)),
          namespace_uri: declaring.identity.namespace_uri,
          value_type: entry.value_type.map(t => {
            substitute(canonical(t), arguments)
          }),
          nullable: entry.nullable,
          setter: entry.setter,
          getter: entry.getter,
          type_converter: entry.type_converter,
          value_serializer: entry.value_serializer,
          bracket_pairs: ReadOnlyArray::from_array(entry.bracket_pairs),
          default_value: entry.default_value,
          visibility: entry.visibility,
          depends_on: ReadOnlyArray::from_array(entry.depends_on),
          constructor_argument: entry.constructor_argument,
          dependency_property: None,
          routed_event: entry.routed_event,
          allowed_locations: anywhere,
          item_type: None,
          save_reader: entry.save_reader,
          should_serialize: entry.should_serialize,
          event_adder: entry.event_adder,
          paired_registration: entry.paired,
          is_paired: false,
        }
        let registered = match entry.dependency {
          Some(dependency) =>
            registered.with_dependency(dependency, dependency_types)
          None => registered
        }
        match entry.kind {
          // Attached members are inherited with their declaring type (F13).
          Attached => attached[entry.name] = registered
          AttachedEvent => attached_events[entry.name] = registered
          // A property anywhere in the hierarchy is found before any event (System.Xaml
          // `XamlType.LookupMember`), so an event never replaces a base property.
          Event if members.get(entry.name) is Some({ kind: Property, .. }) => ()
          _ => {
            match (members.get(entry.name), member_links.get(entry.name)) {
              (Some(previous), Some(link)) => hidden.push((previous, link))
              _ => member_order.push(entry.name)
            }
            members[entry.name] = registered
            member_links[entry.name] = i
          }
        }
      }
    }
    // Converters, value serializers, collection and dictionary adders and markup extension behavior
    // are inherited from the nearest base type that registers them. Factories, parse functions and
    // enumerations are not: they belong to the exact type.
    let inherited = chain.map(link => link.record.definition)
    // Content property and aliases: inherited, set or cleared (F18). A designation that names no
    // member is reported only on the type that declares it, not on each derived type.
    let content_property = designated(inherited, d => d.content_property).map(found => {
      found.0
    })
    if definition.content_property is Set(content) && !members.contains(content) {
      conflicts.push(UnknownMember(name, content))
    }
    let aliases : Array[(AliasedDirective, String)] = []
    for directive in [Name, Key, Uid, Lang] {
      let pick = (d : XamlTypeDefinition) => {
        let mut found = Inherit
        for entry in d.aliases {
          if entry.0 == directive {
            found = entry.1
          }
        }
        found
      }
      match designated(inherited, pick) {
        Some((member_name, index)) =>
          if members.contains(member_name) {
            aliases.push((directive, member_name))
          } else if index == 0 {
            conflicts.push(UnknownMember(name, member_name))
          }
        None => ()
      }
    }
    let usable_during_initialization = inherited
      .iter()
      .filter_map(d => d.usable_during_initialization)
      .head()
      .unwrap_or(false)
    let enumeration = match definition.enumeration {
      Some((backing, values, flags)) => {
        for entry in values {
          if !backing.contains(entry.1) {
            conflicts.push(InvalidEnumValue(name, entry.0))
          }
        }
        Some(XamlEnumeration::{
          backing,
          flags,
          values: ReadOnlyArray::from_array(
            values.map(entry => (entry.0, entry.1.reinterpret_as_uint64())),
          ),
        })
      }
      None => None
    }
    // The type's own converter, else the nearest base type's other than `x:Object`'s, else the
    // enumeration converter (System.Xaml `XamlType.LookupTypeConverter`).
    let type_converter = chain
      .iter()
      .filter(link => {
        physical_equal(link.record, record) ||
        definition_key(link.record.identity) != definition_key(object_type)
      })
      .filter_map(link => {
        link.record.definition.type_converter.map(f => f(link.record.identity))
      })
      .head()
    let type_converter = match type_converter {
      Some(converter) => Some(converter)
      None => enumeration.map(e => enumeration_converter(name, e))
    }
    // Static members of the type and its bases, nearest first; an enumeration's values are its
    // static fields.
    let static_fields : Map[String, XamlStaticMember] = Map([])
    let static_properties : Map[String, XamlStaticMember] = Map([])
    for i = chain.length() - 1; i >= 0; i = i - 1 {
      let declaring = chain[i].record
      let arguments = chain[i].arguments
      for entry in declaring.definition.statics {
        guard entry.get is Some(get) else { continue }
        let registered = XamlStaticMember::{
          name: entry.name,
          kind: entry.kind,
          declaring_type: substitute(declaring.identity, arguments),
          value_type: entry.value_type.map(t => {
            substitute(canonical(t), arguments)
          }),
          get,
        }
        match entry.kind {
          Field => static_fields[entry.name] = registered
          Property => static_properties[entry.name] = registered
        }
      }
    }
    if enumeration is Some(e) {
      for entry in e.values {
        let value = enum_value({ type_name: name, bits: entry.1, })
        static_fields[entry.0] = {
          name: entry.0,
          kind: Field,
          declaring_type: name,
          value_type: Some(name),
          get: () => value,
        }
      }
    }
    let value_serializer = match
      inherited.iter().filter_map(d => d.value_serializer).head() {
      Some(serializer) => Some(serializer)
      None => definition.exact_serializer
    }
    let extension = inherited
      .iter()
      .filter(d => d.provide_value is Some(_))
      .head()
    // Collection and dictionary behavior, with the item and key types, comes from the nearest type
    // that registers the add operation; enumerators are inherited separately (2F65).
    let collection = inherited.iter().filter(d => d.add_item is Some(_)).head()
    let dictionary = inherited.iter().filter(d => d.add_entry is Some(_)).head()
    let link_of = (d : XamlTypeDefinition) => {
      inherited.search_by(other => physical_equal(other, d)).unwrap_or(0)
    }
    // An item or key type that `d` registers, with the type arguments that this type gives to `d`.
    let contents_type = (
      d : XamlTypeDefinition,
      registered : @nodes.XamlTypeName?,
    ) => {
      match registered {
        Some(t) => substitute(canonical(t), chain[link_of(d)].arguments)
        None => object_type
      }
    }
    let item_type = match (dictionary, collection) {
      (Some(d), _) => Some(contents_type(d, d.entry_item_type))
      (None, Some(c)) => Some(contents_type(c, c.item_type))
      (None, None) => None
    }
    if (definition.item_enumerator is Some(_) && collection is None) ||
      (definition.entry_enumerator is Some(_) && dictionary is None) {
      conflicts.push(EnumeratorWithoutAdd(name))
    }
    // Dependencies on names that are not members are ignored.
    for member_name, entry in members {
      if entry.depends_on.iter().any(d => !members.contains(d)) {
        members[member_name] = {
          ..entry,
          depends_on: ReadOnlyArray::from_array(
            entry.depends_on.iter().filter(d => members.contains(d)).collect(),
          ),
        }
      }
    }
    // Inherited operations registered with a base type's key run through the base views (design
    // D8). Only a type that registers its own key reports a missing view; types that share its key
    // inherit the problem.
    let keys = effective_keys(inherited)
    let adapter = (index : Int32, operation : String) => {
      match reach(inherited, keys, index) {
        Same => None
        Via(adapt) => Some(adapt)
        Unreachable => {
          if definition.object_key is Some(_) {
            conflicts.push(
              MissingBaseView(
                name,
                base=chain[index].record.identity,
                operation~,
              ),
            )
          }
          None
        }
      }
    }
    let adapted_members : Array[XamlMember] = []
    for member_name in member_order {
      guard members.get(member_name) is Some(m) &&
        member_links.get(member_name) is Some(index) &&
        index > 0 &&
        m.has_instance_operations() else {
        continue
      }
      if adapter(index, member_name) is Some(adapt) {
        adapted_members.push(m.through(adapt))
      }
    }
    for m in adapted_members {
      members[m.name] = m
    }
    // A hidden member that no base view reaches is no member of the type; nothing is reported, because
    // only a document that names the base type uses it.
    let hidden_members = hidden.filter_map(entry => {
      let (m, index) = entry
      if !m.has_instance_operations() {
        return Some(m)
      }
      match reach(inherited, keys, index) {
        Same => Some(m)
        Via(adapt) => Some(m.through(adapt))
        Unreachable => None
      }
    })
    mark_pairs(members, attached_events)
    let add_item = match collection {
      Some(d) =>
        match (d.add_item, adapter(link_of(d), "add")) {
          (Some(add), Some(adapt)) =>
            Some((target, item) => add(adapt(target), item))
          (add, _) => add
        }
      None => None
    }
    let add_entry = match dictionary {
      Some(d) =>
        match (d.add_entry, adapter(link_of(d), "add")) {
          (Some(add), Some(adapt)) =>
            Some((target, key, item) => add(adapt(target), key, item))
          (add, _) => add
        }
      None => None
    }
    let item_enumerator = match nearest(inherited, d => d.item_enumerator) {
      Some((f, index)) =>
        match adapter(index, "items") {
          Some(adapt) => Some(target => f(adapt(target)))
          None => Some(f)
        }
      None => None
    }
    let entry_enumerator = match nearest(inherited, d => d.entry_enumerator) {
      Some((f, index)) =>
        match adapter(index, "entries") {
          Some(adapt) => Some(target => f(adapt(target)))
          None => Some(f)
        }
      None => None
    }
    let instance_descriptor = match
      nearest(inherited, d => d.instance_descriptor) {
      Some((f, index)) =>
        match adapter(index, "instance descriptor") {
          Some(adapt) => Some(target => f(adapt(target)))
          None => Some(f)
        }
      None => None
    }
    let attached_store = match nearest(inherited, d => d.attached_store) {
      Some((f, index)) =>
        match adapter(index, "attached member store") {
          Some(adapt) => Some(target => f(adapt(target)))
          None => Some(f)
        }
      None => None
    }
    let provide_value = match extension {
      Some(d) =>
        match (d.provide_value, adapter(link_of(d), "provide value")) {
          (Some(f), Some(adapt)) =>
            Some((target, services) => f(adapt(target), services))
          (f, _) => f
        }
      None => None
    }
    let callback = (
      pick : (XamlTypeDefinition) -> InitializationCallback?,
      operation : String,
    ) => {
      match nearest(inherited, pick) {
        Some((f, index)) =>
          match adapter(index, operation) {
            Some(adapt) => Some(target => f(adapt(target)))
            None => Some(f)
          }
        None => None
      }
    }
    let dependency_link = match
      nearest(inherited, d => d.dependency_owners.get(0).bind(o => o.1)) {
      Some((link, index)) => {
        let link = match adapter(index, "dependency link") {
          Some(adapt) => target => link(adapt(target))
          None => link
        }
        dependency_types.links[key] = link
        Some(link)
      }
      None => None
    }
    let attached_store = match dependency_link {
      Some(_) => {
        let direct = Set::from_iter(
          members.values().filter_map(m => m.dependency_property),
        )
        Some(target => {
          dependency_types.attached_values(target, direct, attached_store)
        })
      }
      None => attached_store
    }
    let owner_of = (d : XamlTypeDefinition) => {
      d.dependency_owners.get(0).map(o => o.0)
    }
    let declared_dependency_owner = owner_of(definition)
    if declared_dependency_owner is Some(owner) &&
      !dependency_types.owners.contains(owner) {
      dependency_types.owners[owner] = name
    }
    if definition.dependency_owners.length() > 1 {
      conflicts.push(DuplicateDependencyOwner(name))
    }
    let dependency_owner = nearest(inherited, owner_of).map(found => found.0)
    for entry in definition.members {
      guard entry.dependency is Some({ property, .. }) else { continue }
      let owner = if entry.kind is Attached {
        if declared_dependency_owner is None {
          conflicts.push(AttachedMemberWithoutOwner(name, entry.name))
        }
        declared_dependency_owner
      } else {
        if dependency_link is None {
          conflicts.push(MemberWithoutDependencyObject(name, entry.name))
        }
        dependency_owner
      }
      if owner is Some(owner) && owner.registry_id() != property.registry_id() {
        conflicts.push(
          PropertyRegistryMismatch(
            name,
            entry.name,
            property=property.registry_id(),
            owner=owner.registry_id(),
          ),
        )
      }
    }
    let any_value_converter = if key == definition_key(object_type) {
      Some(value => dependency_types.any_value(value))
    } else {
      match nearest(inherited, d => d.any_value_converter) {
        Some((convert, index)) => {
          let convert = match adapter(index, "AnyValue converter") {
            Some(adapt) =>
              (value : @nodes.XamlValue) => {
                match value {
                  Object(target) => convert(Object(adapt(target)))
                  _ => convert(value)
                }
              }
            None => convert
          }
          dependency_types.converters[key] = convert
          Some(convert)
        }
        None => None
      }
    }
    let begin_init = callback(d => d.begin_init, "begin init")
    let end_init = callback(d => d.end_init, "end init")
    // True on a markup extension is a conflict (System.Xaml `UsableDuringInitializationOnME`),
    // reported once, on the type where the flag and the extension behavior first meet.
    if usable_during_initialization && extension is Some(_) {
      let base_reported = chain.length() > 1 &&
        inherited[1:].iter().any(d => d.provide_value is Some(_)) &&
        inherited[1:]
        .iter()
        .filter_map(d => d.usable_during_initialization)
        .head() ==
        Some(true)
      if !base_reported {
        conflicts.push(UsableDuringInitializationOnMarkupExtension(name))
      }
    }
    let property_scope : NameScopeSource? = match
      nearest(inherited, d => d.name_scope_property) {
      Some(((member_name, None), index)) =>
        if members.contains(member_name) {
          Some(Member(member_name))
        } else {
          if index == 0 {
            conflicts.push(UnknownMember(name, member_name))
          }
          None
        }
      Some(((member_name, Some(owner)), index)) => {
        scope_properties.push((key, member_name, canonical(owner), index == 0))
        None
      }
      None => None
    }
    let name_scope : NameScopeSource? = match
      nearest(inherited, d => d.name_scope) {
      Some(((lookup, register), index)) =>
        match adapter(index, "name scope") {
          Some(adapt) =>
            Some(
              Operations((target, name) => lookup(adapt(target), name), (
                target,
                name,
                value,
              ) => register(adapt(target), name, value)),
            )
          None => Some(Operations(lookup, register))
        }
      None => property_scope
    }
    types[key] = {
      name,
      namespaces: ReadOnlyArray::from_array(record.namespaces),
      clr_namespace: definition.clr.map(c => c.1),
      scope: definition.clr.map(c => c.0),
      type_parameters: definition.type_parameters,
      base_type: base_of(record).map(canonical),
      content_property,
      members,
      member_order: ReadOnlyArray::from_array(member_order),
      hidden_members: ReadOnlyArray::from_array(hidden_members),
      attached,
      attached_events,
      static_fields,
      static_properties,
      enumeration,
      constructors: check_constructors(
        name,
        definition,
        extension is Some(_),
        canonical,
        conflicts,
      ),
      type_converter,
      value_serializer,
      parse_function: definition.parse_function,
      add_item,
      add_entry,
      item_type,
      key_type: dictionary.map(d => contents_type(d, d.key_type)),
      item_enumerator,
      entry_enumerator,
      instance_descriptor,
      attached_store,
      provide_value,
      object_key: keys[0],
      begin_init,
      end_init,
      aliases: ReadOnlyArray::from_array(aliases),
      whitespace_significant: inherited
      .iter()
      .any(d => d.whitespace_significant),
      trim_whitespace: inherited.iter().any(d => d.trim_whitespace),
      usable_during_initialization,
      name_scope,
      is_abstract: definition.is_abstract,
      declared_dependency_owner,
      dependency_owner,
      dependency_link,
      any_value_converter,
    }
  }
  dependency_types.add_attached_members(order.map(key => records[key]), types)
  // Attached name-scope properties, once every owner type is built.
  for entry in scope_properties {
    let (key, member_name, owner, declared) = entry
    guard types.get(key) is Some(t) else { continue }
    match
      index
      .get(definition_key(owner))
      .bind(k => types.get(k))
      .bind(o => o.attached.get(member_name)) {
      Some(m) =>
        if t.name_scope is None {
          types[key] = { ..t, name_scope: Some(Attached(m)), }
        }
      None =>
        if declared {
          conflicts.push(UnknownAttachedMember(t.name, member_name, owner~))
        }
    }
  }
  let directives : Map[(String, String), XamlMember] = Map([])
  for directive in builtin_directives() {
    directives[(directive.namespace_uri, directive.name)] = directive
  }
  for directive in self.directives {
    let key = (directive.namespace_uri, directive.name)
    if directives.contains(key) ||
      directive.namespace_uri == @nodes.xaml_language_namespace ||
      directive.namespace_uri == xml_namespace {
      conflicts.push(
        DuplicateDirective(
          namespace_uri=directive.namespace_uri,
          name=directive.name,
        ),
      )
      continue
    }
    directives[key] = directive
  }
  let known : Map[String, Unit] = Map([
    (@nodes.xaml_language_namespace, ()),
    (xaml_language_namespace_2009, ()),
  ])
  for entry, _ in index {
    known[entry.0] = ()
  }
  for entry, _ in directives {
    known[entry.0] = ()
  }
  // A type's preferred namespace must still name it after subsumption (design D11).
  for key in order {
    let identity = records[key].identity
    let preferred = identity.namespace_uri
    let mapped = compatible_in(
      preferences.newer,
      uri => known.contains(uri),
      preferred,
    )
    if mapped is Some(mapped) &&
      mapped != preferred &&
      index.get((mapped, identity.name, identity.arity())) is Some(other) &&
      other != key {
      conflicts.push(
        PreferredNamespaceConflict(name=identity.name, preferred~, mapped~),
      )
    }
  }
  if !conflicts.is_empty() {
    raise Conflicts(ReadOnlyArray::from_array(conflicts))
  }
  let context = {
    types,
    index,
    arities,
    directives,
    prefixes: preferences.prefixes,
    newer: preferences.newer,
    known,
    clr_scopes,
    dependency_types,
  }
  context.convert_defaults(order)
  context
}

///|
/// Convert the default values that are not assignable to their members' value types, with a
/// schema-only service context, in every type that has the member (design D3). A default that does not
/// convert is a conflict on the type that declares the member. The type parameters of a generic type have
/// no conversion, so a derived type converts its defaults, and keeps one that does not convert.
fn SchemaContext::convert_defaults(
  self : SchemaContext,
  order : Array[TypeKey],
) -> Unit raise SchemaError {
  let conflicts : Array[SchemaConflict] = []
  // By the declaring type and the name, and whether the member is attached.
  let results : Map[(@nodes.XamlTypeName, String, Bool), @nodes.XamlValue] = Map([],
  )
  let services = ServiceContext::new(self)
  for key in order {
    guard self.types.get(key) is Some(t) else { continue }
    let converted = (m : XamlMember) => {
      guard m is { default_value: Some(value), declaring_type: Some(owner), .. } &&
        self.needs_conversion(m, value) else {
        return m
      }
      let id = (owner, m.name, m.kind is Attached)
      let result = match results.get(id) {
        Some(result) => result
        None =>
          self.convert_member_value(m, value, context=services) catch {
            ConversionFailed(input~, message~, ..) => {
              if owner == t.name {
                conflicts.push(
                  InvalidDefaultValue(owner, m.name, input~, message~),
                )
              }
              return m
            }
          }
      }
      results[id] = result
      { ..m, default_value: Some(result), }
    }
    for members in [t.members, t.attached] {
      for name, m in members {
        members[name] = converted(m)
      }
    }
    self.types[key] = {
      ..t,
      hidden_members: t.hidden_members.map(converted),
      name_scope: match t.name_scope {
        Some(Attached(m)) => Some(Attached(converted(m)))
        other => other
      },
    }
  }
  if !conflicts.is_empty() {
    raise Conflicts(ReadOnlyArray::from_array(conflicts))
  }
}

///|
/// Whether a default value must be converted: it is not null and not assignable to the member's
/// value type.
fn SchemaContext::needs_conversion(
  self : SchemaContext,
  target : XamlMember,
  value : @nodes.XamlValue,
) -> Bool {
  guard target.value_type is Some(value_type) else { return false }
  if value is Null ||
    value_type == object_type ||
    unknown_parameters(value_type, []).length() > 0 {
    return false
  }
  match value_type_name(value) {
    Some(source) => !self.is_assignable(source, value_type)
    None => true
  }
}

///|
/// `name` with every registered node named by its identity: its preferred namespace, and for the
/// short name of a built-in markup extension such as `x:Type` its full name.
fn canonical_in(
  index : Map[TypeKey, TypeKey],
  name : @nodes.XamlTypeName,
) -> @nodes.XamlTypeName {
  rebuild(name, _ => None, n => {
    match index.get((language_alias(n.namespace_uri), n.name, n.arity())) {
      Some(key) => (key.0, key.1)
      None => (n.namespace_uri, n.name)
    }
  })
}

///|
/// The identity key of the type registered as (`namespace_uri`, `name`, `arity`).
fn SchemaContext::identity_key(
  self : SchemaContext,
  namespace_uri : String,
  name : String,
  arity : Int32,
) -> TypeKey? {
  self.index.get((language_alias(namespace_uri), name, arity))
}

///|
/// The type that `name` names, closed over its type arguments, or `None` when `resolve_type` fails.
pub fn SchemaContext::get_type(
  self : SchemaContext,
  name : @nodes.XamlTypeName,
) -> XamlType? {
  if name.arity() == 0 {
    return self
      .identity_key(name.namespace_uri, name.name, 0)
      .bind(key => self.types.get(key))
  }
  try self.resolve_type(name) catch {
    _ => None
  } noraise {
    t => Some(t)
  }
}

///|
/// The type that `name` names, under any of its namespaces. For a generic type every type
/// argument, at any depth, must resolve with its arity, and the result is the closed type with the
/// arguments, named by their identities, substituted into its base and member types.
pub fn SchemaContext::resolve_type(
  self : SchemaContext,
  name : @nodes.XamlTypeName,
) -> XamlType raise TypeResolutionError {
  let pending = [name]
  while pending.pop() is Some(current) {
    if self.identity_key(current.namespace_uri, current.name, current.arity())
      is None {
      match
        self.arities.get((language_alias(current.namespace_uri), current.name)) {
        Some(expected) =>
          raise ArityMismatch(
            name=current,
            expected=ReadOnlyArray::from_array(expected),
            given=current.arity(),
          )
        None => raise UnknownType(current)
      }
    }
    for argument in current.type_arguments {
      pending.push(argument)
    }
  }
  let canonical = canonical_in(self.index, name)
  guard self.types.get(definition_key(canonical)) is Some(t) else {
    raise UnknownType(name)
  }
  if name.arity() == 0 {
    t
  } else {
    t.close(canonical)
  }
}

///|
/// The type registered as `name` with `arity` type parameters under the namespace URI
/// `namespace_uri`, any of the type's namespaces. A generic type is returned open, with its type
/// parameters. CLR-style URIs are matched as registered; `lookup_type_in` also resolves `using:`
/// URIs and applies a local scope.
pub fn SchemaContext::lookup_type(
  self : SchemaContext,
  namespace_uri : String,
  name : String,
  arity~ : Int32 = 0,
) -> XamlType? {
  self.identity_key(namespace_uri, name, arity).bind(key => self.types.get(key))
}

///|
/// The type registered as `name` with `arity` type parameters in the namespace a document names
/// with `namespace_uri` (design D11, 2F27, 2F28): `clr-namespace:N;assembly=S` in scope `S`,
/// `clr-namespace:N` in `local_scope` when one is given, and `using:N` in every scope that
/// registers `N`. It raises `MalformedClrNamespace` for a malformed CLR-style URI and
/// `AmbiguousType` when several scopes register the type of a `using:` URI.
pub fn SchemaContext::lookup_type_in(
  self : SchemaContext,
  namespace_uri : String,
  name : String,
  arity~ : Int32 = 0,
  local_scope? : String,
) -> XamlType? raise NamespaceError {
  match clr_reference(namespace_uri) {
    NotClr => self.lookup_type(namespace_uri, name, arity~)
    ClrNamespace(clr_namespace~, scope~) =>
      match (scope, local_scope) {
        (Some(scope), _) | (None, Some(scope)) =>
          self.lookup_type(
            clr_namespace_uri(clr_namespace, scope),
            name,
            arity~,
          )
        (None, None) => None
      }
    Using(clr_namespace) =>
      match self.clr_scopes.get((clr_namespace, name, arity)) {
        None => None
        Some([scope]) =>
          self.lookup_type(
            clr_namespace_uri(clr_namespace, scope),
            name,
            arity~,
          )
        Some(scopes) =>
          raise AmbiguousType(
            name~,
            namespace_uri~,
            scopes=ReadOnlyArray::from_array(scopes),
          )
      }
  }
}

///|
/// The type that a document names in braces as `name` with `arity` type arguments, such as
/// `NullExtension` for `{x:Null}`: the type `nameExtension`, else the type `name`, each found as
/// `lookup_type_in` finds it. The type is a markup extension or any other type, because System.Xaml
/// `MeScanner.ResolveTypeName` does not filter by kind (design D13, 3F-OD5).
pub fn SchemaContext::lookup_type_in_braces(
  self : SchemaContext,
  namespace_uri : String,
  name : String,
  arity~ : Int32 = 0,
  local_scope? : String,
) -> XamlType? raise NamespaceError {
  let suffixed = self.lookup_type_in(
    namespace_uri,
    name + "Extension",
    arity~,
    local_scope?,
  )
  if suffixed is Some(_) {
    suffixed
  } else {
    self.lookup_type_in(namespace_uri, name, arity~, local_scope?)
  }
}

///|
/// The types registered under the namespace URI `namespace_uri`, any of their namespaces, in
/// registration order.
pub fn SchemaContext::types_in(
  self : SchemaContext,
  namespace_uri : String,
) -> Array[XamlType] {
  let uri = language_alias(namespace_uri)
  self.types.values().filter(t => t.namespaces.contains(uri)).collect()
}

///|
/// The directive `name` of the XAML namespace `namespace_uri`.
pub fn SchemaContext::directive(
  self : SchemaContext,
  namespace_uri : String,
  name : String,
) -> XamlMember? {
  self.directives.get((language_alias(namespace_uri), name))
}

///|
/// The preferred prefix of `namespace_uri`: `x` for both XAML language URIs, else the shortest,
/// then the ordinal least, of its registered preferred prefixes.
pub fn SchemaContext::preferred_prefix(
  self : SchemaContext,
  namespace_uri : String,
) -> String? {
  self.prefixes.get(namespace_uri)
}

///|
/// Whether the context resolves `namespace_uri`: a namespace of a registered type or directive,
/// either XAML language URI, or `using:N` for a registered CLR-style namespace `N`.
pub fn SchemaContext::is_known_namespace(
  self : SchemaContext,
  namespace_uri : String,
) -> Bool {
  if self.known.contains(namespace_uri) {
    return true
  }
  let reference = clr_reference(namespace_uri) catch { _ => return false }
  match reference {
    Using(clr_namespace) =>
      self.clr_scopes.keys().any(key => key.0 == clr_namespace)
    _ => false
  }
}

///|
/// The namespace that a document's `namespace_uri` is read as after subsumption, as System.Xaml
/// `XamlSchemaContext.TryGetCompatibleXamlNamespace` gives it (design D17): itself when nothing
/// subsumes it and it resolves; else its newer namespace, which must resolve, followed further while
/// each replacement resolves. `None` means the namespace is not supported: an unresolved
/// replacement is not retried with the original URI.
///
/// `clr-namespace:N` and `clr-namespace:N;assembly=` are in the scope `local_scope`, in which every
/// CLR-style namespace resolves, as each one of a loaded assembly does in System.Xaml. A namespace for
/// which `is_understood` gives true is itself, whatever is registered.
pub fn SchemaContext::compatible_namespace(
  self : SchemaContext,
  namespace_uri : String,
  local_scope? : String,
  is_understood? : (String) -> Bool,
) -> String? {
  let is_in_local_scope = (uri : String) => {
    local_scope is Some(scope) &&
    (clr_reference(uri) catch { _ => NotClr })
    is ClrNamespace(scope=Some(found), ..) &&
    found == scope
  }
  compatible_in(
    self.newer,
    uri => self.is_known_namespace(uri) || is_in_local_scope(uri),
    normalize_clr_namespace(namespace_uri, local_scope?) catch {
      _ => namespace_uri
    },
    is_understood?,
  )
}

///|
/// The attached member `name` that the type `owner` or one of its bases defines, nearest first.
pub fn SchemaContext::attached_member(
  self : SchemaContext,
  owner : @nodes.XamlTypeName,
  name : String,
) -> XamlMember? {
  match self.get_type(owner) {
    Some(t) => t.attached_member(name)
    None => None
  }
}

///|
/// Resolve a dotted name such as `Grid.Row`, written in the XAML namespace `namespace_uri`, to the
/// attached member `Row` of the type `Grid` of that namespace, the context-free attachable lookup
/// (design D3, 2F15, 2F21): an attached property of `Grid` or its bases, nearest first, and only when
/// there is none an attached event found the same way. It never returns an instance member or an
/// instance event, and the name must have exactly one `.`.
pub fn SchemaContext::resolve_attached_member(
  self : SchemaContext,
  namespace_uri : String,
  dotted_name : String,
) -> XamlMember? {
  guard dotted_name.find(".") is Some(dot) &&
    dotted_name.rev_find(".") == Some(dot) else {
    return None
  }
  let owner = dotted_name[:dot].to_owned()
  let local_name = dotted_name[dot + 1:].to_owned()
  if owner.is_empty() || local_name.is_empty() {
    return None
  }
  self.attached_member(
    @nodes.XamlTypeName::new(namespace_uri, owner),
    local_name,
  )
}

///|
/// Whether a value of type `type_name` can be used where `target` is expected: the types are equal
/// or `target` is a base type of `type_name`. Names in any of a type's namespaces are the same type.
pub fn SchemaContext::is_assignable(
  self : SchemaContext,
  type_name : @nodes.XamlTypeName,
  target : @nodes.XamlTypeName,
) -> Bool {
  let target = canonical_in(self.index, target)
  let mut current = Some(canonical_in(self.index, type_name))
  // A built context has no base type cycles, so the walk ends.
  while current is Some(name) {
    if name == target {
      return true
    }
    current = match self.types.get(definition_key(name)) {
      Some(t) =>
        t.base_type.map(base => {
          substitute(base, parameter_map(t.type_parameters, name))
        })
      None => None
    }
  }
  false
}

///|
/// The constructors of `definition` with canonical parameter types, reporting two constructors, or
/// two factory methods of one name, with the same parameter types, and on a markup extension two
/// positional constructors of one count (design D13, D16).
fn check_constructors(
  name : @nodes.XamlTypeName,
  definition : XamlTypeDefinition,
  is_extension : Bool,
  canonical : (@nodes.XamlTypeName) -> @nodes.XamlTypeName,
  conflicts : Array[SchemaConflict],
) -> ReadOnlyArray[XamlConstructor] {
  let constructors : Array[XamlConstructor] = []
  for c in definition.constructors {
    let parameters = c.parameters.map(p => {
      ..p,
      type_name: canonical(p.type_name),
    })
    let types = parameters.map(p => p.type_name)
    let duplicate = constructors
      .iter()
      .any(other => {
        other.factory_method == c.factory_method &&
        other.parameter_types().iter().collect() == types
      })
    if duplicate {
      conflicts.push(
        DuplicateConstructor(
          name,
          factory_method=c.factory_method,
          parameter_types=ReadOnlyArray::from_array(types),
        ),
      )
    } else if is_extension &&
      c.factory_method is None &&
      c.positional &&
      constructors
      .iter()
      .any(other => {
        other.factory_method is None &&
        other.positional &&
        other.arity() == parameters.length()
      }) {
      conflicts.push(DuplicatePositionalArity(name, parameters.length()))
    }
    constructors.push({
      factory_method: c.factory_method,
      parameters: ReadOnlyArray::from_array(parameters),
      invoke: (c.invoke)(name),
      positional: c.positional,
    })
  }
  ReadOnlyArray::from_array(constructors)
}