///|
/// A parameter of a constructor or factory method: its name, its type and whether null is a value of
/// it beyond the types that accept null anyway (design D16).
#derive(Eq, Debug)
pub(all) struct XamlParameter {
  name : String
  type_name : @nodes.XamlTypeName
  nullable : Bool
}

///|
pub fn XamlParameter::new(
  name : String,
  type_name : @nodes.XamlTypeName,
  nullable~ : Bool = false,
) -> XamlParameter {
  { name, type_name, nullable, }
}

///|
/// Creates an object from the type arguments of the type being constructed, empty for a type that
/// is not generic, and the arguments, one for each parameter in order. A factory method may return
/// an object of another type, or null; the object writer checks the result.
pub type ConstructorFunction = (
  ReadOnlyArray[@nodes.XamlTypeName],
  ReadOnlyArray[@nodes.XamlValue],
) -> @nodes.XamlValue raise

///|
/// A registered constructor or named factory method with its ordered parameters (design D13, D16).
/// Constructors and factory methods are not inherited.
pub struct XamlConstructor {
  /// The name of the factory method, or `None` for a constructor.
  factory_method : String?
  parameters : ReadOnlyArray[XamlParameter]
  priv invoke : ConstructorFunction
  /// Whether the constructor is a positional signature of a markup extension.
  priv positional : Bool
}

///|
pub fn XamlConstructor::arity(self : XamlConstructor) -> Int32 {
  self.parameters.length()
}

///|
/// Run the constructor with the type arguments of the closed type and the arguments.
pub fn XamlConstructor::invoke(
  self : XamlConstructor,
  type_arguments : ArrayView[@nodes.XamlTypeName],
  arguments : ArrayView[@nodes.XamlValue],
) -> @nodes.XamlValue raise {
  (self.invoke)(
    ReadOnlyArray::from_array(type_arguments),
    ReadOnlyArray::from_array(arguments),
  )
}

///|
/// The parameter types, in order.
pub fn XamlConstructor::parameter_types(
  self : XamlConstructor,
) -> ReadOnlyArray[@nodes.XamlTypeName] {
  ReadOnlyArray::from_array(
    self.parameters.iter().map(p => p.type_name).collect(),
  )
}

///|
priv struct ConstructorDefinition {
  factory_method : String?
  parameters : Array[XamlParameter]
  /// The function for the identity of the type.
  invoke : (@nodes.XamlTypeName) -> ConstructorFunction
  positional : Bool
}

///|
/// Register a constructor with the ordered `parameters`. A zero-parameter constructor is the default
/// constructor. Two constructors with the same parameter types are a build conflict, and so, on a
/// markup extension, are two of one count, because positional arguments select by count only.
pub fn XamlTypeDefinition::add_constructor(
  self : XamlTypeDefinition,
  parameters : ArrayView[XamlParameter],
  invoke : ConstructorFunction,
) -> XamlTypeDefinition {
  self.constructors.push({
    factory_method: None,
    parameters: parameters.to_owned(),
    invoke: _ => invoke,
    positional: true,
  })
  self
}

///|
/// Register the factory method `name` with the ordered `parameters`, which `x:FactoryMethod` names.
/// It may take no arguments. Two factory methods of one name with the same parameter types are a
/// build conflict.
pub fn XamlTypeDefinition::add_factory_method(
  self : XamlTypeDefinition,
  name : String,
  parameters : ArrayView[XamlParameter],
  invoke : ConstructorFunction,
) -> XamlTypeDefinition {
  self.constructors.push({
    factory_method: Some(name),
    parameters: parameters.to_owned(),
    invoke: _ => invoke,
    positional: false,
  })
  self
}

///|
/// A constructor that is not a positional signature, as the string constructor of `x:TypeExtension`
/// beside its fixed type-value signature.
fn XamlTypeDefinition::add_non_positional_constructor(
  self : XamlTypeDefinition,
  parameters : ArrayView[XamlParameter],
  invoke : ConstructorFunction,
) -> XamlTypeDefinition {
  self.constructors.push({
    factory_method: None,
    parameters: parameters.to_owned(),
    invoke: _ => invoke,
    positional: false,
  })
  self
}

///|
/// The constructors of the type, in registration order; factory methods are not included.
pub fn XamlType::constructors(self : XamlType) -> Array[XamlConstructor] {
  self.constructors.iter().filter(c => c.factory_method is None).collect()
}

///|
/// The constructors that take `arity` arguments, in registration order.
pub fn XamlType::constructors_of_arity(
  self : XamlType,
  arity : Int32,
) -> Array[XamlConstructor] {
  self.constructors().filter(c => c.arity() == arity)
}

///|
/// The zero-parameter constructor that default construction uses.
pub fn XamlType::default_constructor(self : XamlType) -> XamlConstructor? {
  self.constructors_of_arity(0).iter().head()
}

///|
/// The factory methods named `name`, in registration order.
pub fn XamlType::factory_methods(
  self : XamlType,
  name : String,
) -> Array[XamlConstructor] {
  self.constructors.iter().filter(c => c.factory_method == Some(name)).collect()
}

///|
/// The positional signature of a markup extension for `count` arguments: its constructor of that
/// count, as System.Xaml keys positional parameters by count only (Owner, 2F-OD1). The one-argument
/// signature of `x:TypeExtension` takes a type value.
pub fn XamlType::positional_signature(
  self : XamlType,
  count : Int32,
) -> XamlConstructor? {
  self.constructors
  .iter()
  .filter(c => c.factory_method is None && c.positional && c.arity() == count)
  .head()
}

///|
/// The constructor with the most parameters, the last registered on a tie, as System.Xaml
/// `XamlParserContext.InitLongestConstructor` picks it for the bracket pairs of positional text.
pub fn XamlType::longest_constructor(self : XamlType) -> XamlConstructor? {
  let mut longest : XamlConstructor? = None
  for c in self.constructors() {
    match longest {
      Some(l) if l.arity() > c.arity() => ()
      _ => longest = Some(c)
    }
  }
  longest
}

///|
/// A selected constructor or factory method with the arguments to pass it, widened to the parameter
/// types.
pub struct ConstructorMatch {
  selected : XamlConstructor
  arguments : ReadOnlyArray[@nodes.XamlValue]
}

///|
/// Why `x:Arguments` selects no constructor or factory method.
#derive(Eq, Debug)
pub(all) suberror ArgumentsError {
  /// No candidate of the argument count accepts the arguments. An argument type is `None` for null.
  NoMatchingConstructor(
    type_name~ : @nodes.XamlTypeName,
    factory_method~ : String?,
    argument_types~ : ReadOnlyArray[@nodes.XamlTypeName?],
  )
  /// Several candidates accept the arguments and none is more specific than the others.
  AmbiguousConstructor(
    type_name~ : @nodes.XamlTypeName,
    factory_method~ : String?,
    candidates~ : ReadOnlyArray[ReadOnlyArray[@nodes.XamlTypeName]],
  )
  /// An instance descriptor gave a factory method that its type does not register, or a constructor
  /// of a type without constructors.
  InvalidDescriptor(
    type_name~ : @nodes.XamlTypeName,
    factory_method~ : (@nodes.XamlTypeName, String)?,
  )
  /// No constructor, or factory method of that name, has as many parameters as an instance
  /// descriptor gave arguments.
  WrongDescriptorArgumentCount(
    type_name~ : @nodes.XamlTypeName,
    factory_method~ : (@nodes.XamlTypeName, String)?,
    count~ : Int32,
  )
  /// An instance descriptor gave an argument that is no value of the parameter type; `argument_type`
  /// is `None` for null and for a list.
  WrongDescriptorArgumentType(
    type_name~ : @nodes.XamlTypeName,
    factory_method~ : (@nodes.XamlTypeName, String)?,
    argument_type~ : @nodes.XamlTypeName?,
    parameter_type~ : @nodes.XamlTypeName,
  )
  /// A constructor or factory method gave null, or a value of a type that is not assignable to the
  /// type being constructed; `result_type` is `None` for null.
  InvalidResult(
    type_name~ : @nodes.XamlTypeName,
    factory_method~ : String?,
    result_type~ : @nodes.XamlTypeName?,
  )
}

///|
pub fn ArgumentsError::message(self : ArgumentsError) -> String {
  let target = (type_name : @nodes.XamlTypeName, factory : String?) => {
    match factory {
      Some(name) => "factory method \{name} of \{type_name}"
      None => "constructor of \{type_name}"
    }
  }
  let list = (types : ReadOnlyArray[@nodes.XamlTypeName]) => {
    "(" + types.iter().map(t => t.to_string()).collect().join(", ") + ")"
  }
  let described = (factory : (@nodes.XamlTypeName, String)?) => {
    match factory {
      Some((owner, name)) => " (the factory method \{name} of \{owner})"
      None => ""
    }
  }
  match self {
    NoMatchingConstructor(type_name~, factory_method~, argument_types~) => {
      let types = argument_types
        .iter()
        .map(t => t.map(t => t.to_string()).unwrap_or("null"))
        .collect()
        .join(", ")
      let count = argument_types.length()
      "x:Arguments of \{type_name}: no \{target(type_name, factory_method)} takes \{count} argument(s) of the types (\{types})"
    }
    AmbiguousConstructor(type_name~, factory_method~, candidates~) => {
      let lists = candidates.iter().map(list).collect().join(" and ")
      "x:Arguments of \{type_name}: the arguments match more than one \{target(type_name, factory_method)}: \{lists}"
    }
    InvalidDescriptor(type_name~, factory_method~) =>
      "the instance descriptor of \{type_name} gave no valid constructor or method\{described(factory_method)}"
    WrongDescriptorArgumentCount(type_name~, factory_method~, count~) =>
      "the instance descriptor of \{type_name} gave the wrong number of arguments: \{count}\{described(factory_method)}"
    WrongDescriptorArgumentType(
      type_name~,
      factory_method~,
      argument_type~,
      parameter_type~,
    ) => {
      let argument = argument_type.map(t => t.to_string()).unwrap_or("null")
      "the instance descriptor of \{type_name} gave an argument of the type \{argument} for a parameter of the type \{parameter_type}\{described(factory_method)}"
    }
    InvalidResult(type_name~, factory_method~, result_type~) => {
      let result = match result_type {
        Some(t) => "a value of \{t}"
        None => "null"
      }
      "the \{target(type_name, factory_method)} gave \{result}, which is not a \{type_name}"
    }
  }
}

///|
/// The built-in value types, which do not accept null unless a parameter is nullable.
fn is_value_type(name : @nodes.XamlTypeName) -> Bool {
  name.namespace_uri == @nodes.xaml_language_namespace &&
  name.arity() == 0 &&
  name.name
  is ("Boolean"
  | "Byte"
  | "Int16"
  | "Int32"
  | "Int64"
  | "Single"
  | "Double"
  | "Char"
  | "Decimal"
  | "TimeSpan")
}

///|
/// Whether null is a value of the type `name`: of every type but the built-in value types and
/// enumerations.
fn SchemaContext::takes_null(
  self : SchemaContext,
  name : @nodes.XamlTypeName,
) -> Bool {
  let name = canonical_in(self.index, name)
  !is_value_type(name) &&
  !(self.get_type(name) is Some({ enumeration: Some(_), .. }))
}

///|
/// Whether `value` as it is, without conversion and widening, is a value for a place of the type
/// `target`, such as a member or a collection item: an instance of the type, or null when the type or the
/// place takes null.
pub fn SchemaContext::accepts(
  self : SchemaContext,
  target : @nodes.XamlTypeName,
  value : @nodes.XamlValue,
  nullable~ : Bool = false,
) -> Bool {
  match value {
    Null => nullable || self.takes_null(target)
    _ => self.is_instance_of(value, target)
  }
}

///|
/// The primitive widenings of the CLR binder (`DefaultBinder.CanChangePrimitive`) between the XAML
/// language primitives: whether a value of `from` widens to `to`.
fn widens(from : @nodes.XamlTypeName, to : @nodes.XamlTypeName) -> Bool {
  let ns = @nodes.xaml_language_namespace
  if from.namespace_uri != ns ||
    to.namespace_uri != ns ||
    from.arity() != 0 ||
    to.arity() != 0 {
    return false
  }
  match (from.name, to.name) {
    ("Byte", "Char" | "Int16" | "Int32" | "Int64" | "Single" | "Double") => true
    ("Char", "Int32" | "Int64" | "Single" | "Double") => true
    ("Int16", "Int32" | "Int64" | "Single" | "Double") => true
    ("Int32", "Int64" | "Single" | "Double") => true
    ("Int64", "Single" | "Double") => true
    ("Single", "Double") => true
    _ => false
  }
}

///|
/// `value` widened to the primitive type `to`.
fn widen(
  value : @nodes.XamlValue,
  to : @nodes.XamlTypeName,
) -> @nodes.XamlValue {
  let wide : Double? = match value {
    Byte(b) => Some(b.to_int().to_double())
    Char(u) => Some(u.to_int().to_double())
    Int16(i) => Some(i.to_int().to_double())
    Int(i) => Some(i.to_double())
    Int64(i) => Some(i.to_double())
    Single(f) => Some(f.to_double())
    _ => None
  }
  match (to.name, value) {
    ("Char", Byte(b)) => Char(b.to_int().to_uint16())
    ("Int16", Byte(b)) => Int16(Int16::from_int(b.to_int()))
    ("Int32", Byte(b)) => Int(b.to_int())
    ("Int32", Char(u)) => Int(u.to_int())
    ("Int32", Int16(i)) => Int(i.to_int())
    ("Int64", Byte(b)) => Int64(b.to_int().to_int64())
    ("Int64", Char(u)) => Int64(u.to_int64())
    ("Int64", Int16(i)) => Int64(i.to_int().to_int64())
    ("Int64", Int(i)) => Int64(i.to_int64())
    // A `Double` in between would round twice.
    ("Single", Int64(i)) => Single(Float::from_int64(i))
    ("Single", _) if wide is Some(d) => Single(Float::from_double(d))
    ("Double", _) if wide is Some(d) => Double(d)
    _ => value
  }
}

///|
/// Whether `argument` fits `parameter`: `Some(false)` as it is, `Some(true)` after primitive
/// widening, `None` not at all.
fn SchemaContext::fit(
  self : SchemaContext,
  parameter : XamlParameter,
  argument : @nodes.XamlValue,
) -> Bool? {
  let target = canonical_in(self.index, parameter.type_name)
  match argument {
    Null =>
      if parameter.nullable || self.takes_null(target) {
        Some(false)
      } else {
        None
      }
    List(_) => if target == object_type { Some(false) } else { None }
    _ => {
      guard value_type_name(argument) is Some(source) else { return None }
      let source = canonical_in(self.index, source)
      if source == target ||
        target == object_type ||
        self.is_assignable(source, target) {
        Some(false)
      } else if widens(source, target) {
        Some(true)
      } else {
        None
      }
    }
  }
}

///|
/// Which of two parameter types is more specific for an argument of type `argument`, as
/// `DefaultBinder.FindMostSpecificType` decides: 1 for the first, 2 for the second, 0 for neither.
fn SchemaContext::more_specific_type(
  self : SchemaContext,
  first : @nodes.XamlTypeName,
  second : @nodes.XamlTypeName,
  argument : @nodes.XamlTypeName?,
) -> Int32 {
  let first = canonical_in(self.index, first)
  let second = canonical_in(self.index, second)
  if first == second {
    return 0
  }
  if argument is Some(a) {
    let a = canonical_in(self.index, a)
    if a == first {
      return 1
    }
    if a == second {
      return 2
    }
  }
  let first_to_second = second == object_type ||
    self.is_assignable(first, second) ||
    widens(first, second)
  let second_to_first = first == object_type ||
    self.is_assignable(second, first) ||
    widens(second, first)
  if first_to_second && !second_to_first {
    1
  } else if second_to_first && !first_to_second {
    2
  } else {
    0
  }
}

///|
/// Which of two candidates is more specific, as `DefaultBinder.FindMostSpecificMethod` compares
/// parameter lists: 1, 2 or 0 for a tie.
fn SchemaContext::more_specific(
  self : SchemaContext,
  first : XamlConstructor,
  second : XamlConstructor,
  arguments : ArrayView[@nodes.XamlValue],
) -> Int32 {
  let mut first_better = false
  let mut second_better = false
  for i, argument in arguments {
    match
      self.more_specific_type(
        first.parameters[i].type_name,
        second.parameters[i].type_name,
        value_type_name(argument),
      ) {
      1 => first_better = true
      2 => second_better = true
      _ => ()
    }
  }
  if first_better == second_better {
    0
  } else if first_better {
    1
  } else {
    2
  }
}

///|
/// The index of the most specific of the `applicable` candidates, at least one, or the ambiguity error. Each is compared only with
/// the best one before it, so among candidates that do not compare the order can decide, as in `DefaultBinder.BindToMethod`.
fn SchemaContext::most_specific(
  self : SchemaContext,
  target : XamlType,
  applicable : Array[XamlConstructor],
  arguments : ArrayView[@nodes.XamlValue],
  factory_method : String?,
) -> Int32 raise ArgumentsError {
  let mut best = 0
  let mut ambiguous = false
  for i in 1.. ambiguous = true
      2 => {
        best = i
        ambiguous = false
      }
      _ => ()
    }
  }
  if ambiguous {
    raise AmbiguousConstructor(
      type_name=target.name,
      factory_method~,
      candidates=ReadOnlyArray::from_array(
        applicable.map(c => c.parameter_types()),
      ),
    )
  }
  best
}

///|
/// Select the constructor, or with `factory_method` the factory method of that name, of `target`
/// for `x:Arguments`, by the CLR binder rules this release supports (design D16, 2F13): each
/// argument of the exact parameter type, of a more specific assignable type or of a primitive type
/// that widens to it, and null for a parameter that accepts null; among several matches the most
/// specific, and a tie an ambiguity error. Parameter arrays are not supported.
pub fn SchemaContext::select_constructor(
  self : SchemaContext,
  target : XamlType,
  arguments : ArrayView[@nodes.XamlValue],
  factory_method? : String,
) -> ConstructorMatch raise ArgumentsError {
  let candidates = match factory_method {
    Some(name) => target.factory_methods(name)
    None => target.constructors()
  }
  let applicable : Array[(XamlConstructor, Array[Bool])] = []
  for c in candidates {
    if c.arity() != arguments.length() {
      continue
    }
    let fits = []
    for i, parameter in c.parameters {
      match self.fit(parameter, arguments[i]) {
        Some(fit) => fits.push(fit)
        None => break
      }
    }
    if fits.length() == arguments.length() {
      applicable.push((c, fits))
    }
  }
  if applicable.is_empty() {
    raise NoMatchingConstructor(
      type_name=target.name,
      factory_method~,
      argument_types=ReadOnlyArray::from_array(
        arguments.iter().map(value_type_name).collect(),
      ),
    )
  }
  let best = self.most_specific(
    target,
    applicable.map(entry => entry.0),
    arguments,
    factory_method,
  )
  let (selected, fits) = applicable[best]
  let values = []
  for i, argument in arguments {
    values.push(
      if fits[i] {
        widen(argument, selected.parameters[i].type_name)
      } else {
        argument
      },
    )
  }
  { selected, arguments: ReadOnlyArray::from_array(values), }
}

///|
/// Check what `selected` gave for `target`: null, or a value whose type is not assignable to
/// `target`, is an error naming the type, the factory method and the result's type (design D16).
pub fn SchemaContext::check_result(
  self : SchemaContext,
  target : XamlType,
  selected : XamlConstructor,
  result : @nodes.XamlValue,
) -> Unit raise ArgumentsError {
  let result_type = value_type_name(result)
  let fits = match result_type {
    Some(t) => target.name == object_type || self.is_assignable(t, target.name)
    None => false
  }
  if !fits {
    raise InvalidResult(
      type_name=target.name,
      factory_method=selected.factory_method,
      result_type~,
    )
  }
}