// References by name, and the objects that wait for them (design D15, D16 and D25).
//
// An object is unfinished while it waits for a reference, or for an unfinished object in its members or items.
// Its queued adds and its end callback run when it waits for nothing, also after its end node. Objects point to
// those that wait for them and never back, so there is no cycle of references among the frames.

///|
/// What a markup extension or converter gives for names that have no complete object yet. It says nothing about the
/// place, so that one that is kept does no harm in another place.
priv struct Token {
  names : ReadOnlyArray[String]
  /// Whether the object with the only name is the value. Else the extension or converter runs again.
  is_direct : Bool
}

///|
let token_key : @nodes.ObjectKey[Token] = @nodes.ObjectKey::new()

///|
let token_type : @nodes.XamlTypeName = @nodes.XamlTypeName::new(
  "urn:moonrockz:xaml", "Token",
)

///|
/// An extension or a converter with everything that it needs to run again.
type Producer = () -> @nodes.XamlValue raise @nodes.XamlWriteError

///|
/// What stands in the writer for a value that waits for names.
priv struct Fixup {
  names : ReadOnlyArray[String]
  /// The index of the scope where the search starts.
  scope : Int32
  /// What gives the value then. Without it the object with the only name is the value.
  producer : Producer?
  /// The object that is the value, when it comes from its initialization text.
  object : ObjectFrame?
}

///|
let fixup_key : @nodes.ObjectKey[Fixup] = @nodes.ObjectKey::new()

///|
fn Fixup::value(self : Fixup) -> @nodes.XamlValue {
  Object(fixup_key.wrap(token_type, self))
}

///|
fn fixup_of(value : @nodes.XamlValue) -> Fixup? {
  match value {
    Object(handle) => fixup_key.unwrap(handle)
    _ => None
  }
}

///|
/// The value that `producer` gives in the scope with the index `scope`, or a fix-up when it gives a token.
fn produced(
  scope : Int32,
  producer : Producer,
) -> @nodes.XamlValue raise @nodes.XamlWriteError {
  let value = producer()
  guard value is Object(handle) &&
    token_key.unwrap(handle) is Some({ names, is_direct, }) else {
    return value
  }
  let producer = if is_direct { None } else { Some(producer) }
  Fixup::{ names, scope, producer, object: None, }.value()
}

///|
/// Where a value goes that can come late.
priv enum Place {
  /// A member, with the site of its start and whether its value names the object.
  Member(@schema.XamlMember, Site, Naming)
  Item(PendingAdd)
  Key(ItemKey)
  Result
}

///|
/// A fix-up in the place of its value.
priv struct Reference {
  mut fixup : Fixup
  /// How many of its names have no complete object yet.
  mut missing : Int32
  site : Site
  /// The object that has the place, and that waits for the value.
  holder : ObjectFrame
  place : Place
  mut is_done : Bool
  /// The unfinished object that the end of the load found.
  mut target : ObjectFrame?
}

///|
priv enum Work {
  /// An object has ended: its value goes to its place, and the objects that wait for it go on.
  Ended(ObjectFrame)
  /// The object that the reference can wait for, by this name, is complete.
  Resolve(Reference, String, ObjectFrame)
}

///|
/// A value that has a name.
priv struct Named {
  value : @nodes.XamlValue
  /// The object, unless it was made before the load.
  owner : ObjectFrame?
  is_complete : Bool
}

///|
/// The value of `name` in the first scope that has it, from the one with the index `index` outward.
fn NameTable::find_name(
  self : NameTable,
  index : Int32,
  name : String,
) -> Named? raise {
  let mut next = Some(index)
  // Without a scope the load is over.
  while next is Some(index) && self.scopes.get(index) is Some(scope) {
    if self.operations(index).find(name) is Some(value) {
      // The scope of a supplied root can have it before the load.
      let owner = match scope.names.get(name) {
        None if self.root
          is Some({ instance: Some(Object(instance)), .. } as root) &&
          !instance.is_value() &&
          value == Object(instance) => Some(root)
        owner => owner
      }
      let is_complete = match owner {
        Some(owner) =>
          if self.is_ending {
            owner.is_complete
          } else {
            !owner.is_open && owner.pending == 0
          }
        None => !self.is_under_construction(value)
      }
      return Some({ value, owner, is_complete, })
    }
    next = scope.parent
  }
  None
}

///|
fn NameTable::is_under_construction(
  self : NameTable,
  value : @nodes.XamlValue,
) -> Bool {
  value is Object(handle) &&
  !handle.is_value() &&
  self.objects
  .iter()
  .any(object => object.instance is Some(Object(open)) && open == handle)
}

///|
/// The names of the scope with the index `scope`, as an extension or converter sees them. Until the document
/// ends only complete objects are found (System.Xaml `ObjectWriterContext.ResolveName`). An object whose only missing
/// value is the one that the producer gives is complete (`XamlObjectWriter.IsFullyInitialized`).
fn NameTable::resolver(self : NameTable, scope : Int32) -> @schema.NameResolver {
  @schema.NameResolver::new(
    resolve=name => {
      match self.find_name(scope, name) {
        Some({ value, is_complete, owner, }) if is_complete || self.is_ending => {
          if self.is_ending && owner is Some(owner) {
            self.found.push(owner)
          }
          Some({ value, fully_initialized: is_complete, })
        }
        _ => None
      }
    },
    fixup_token=(names, can_assign_directly) => {
      if self.is_ending {
        return None
      }
      guard !can_assign_directly || names.length() == 1 else {
        raise @schema.ValueError(
          "a token that is assigned directly takes one name, not \{names.length()}",
        )
      }
      Some(
        token_key.wrap(token_type, { names, is_direct: can_assign_directly, }),
      )
    },
  )
}

///|
/// Give `value` to `place` of `holder`, or let `holder` wait for it when it is a fix-up.
fn XamlObjectWriter::put(
  self : XamlObjectWriter,
  holder : ObjectFrame,
  place : Place,
  value : @nodes.XamlValue,
  site : Site,
) -> Unit raise @nodes.XamlWriteError {
  if fixup_of(value) is Some(fixup) {
    if self.table.is_ending {
      raise site.error("names are not resolved: \{fixup.names.join(", ")}")
    }
    // The result has no object that waits for it.
    if !(place is Result) {
      holder.pending += 1
    }
    let reference = {
      fixup,
      missing: fixup.names.length(),
      site,
      holder,
      place,
      is_done: false,
      target: None,
    }
    self.references.push(reference)
    self.wait_for(reference)
    return
  }
  match place {
    Member(definition, member_site, naming) => {
      self.set_member(holder, definition, member_site, value, site)
      if naming is Converted {
        self.register_name(holder, value, site)
      }
    }
    Item(add) => add.value = value
    Key(key) => {
      key.value = Some(value)
      key.is_pending = false
    }
    Result => self.result = Some(value)
  }
}

///|
/// Keep `reference` with each of its names, in the innermost scope that can still get the name. An object that is
/// complete completes no second time, so such a name waits for the end of the load, as in System.Xaml. So does the result,
/// because a token is no result.
fn XamlObjectWriter::wait_for(
  self : XamlObjectWriter,
  reference : Reference,
) -> Unit {
  if reference.place is Result {
    return
  }
  for name in reference.fixup.names {
    let mut scope = self.table.scopes[reference.fixup.scope]
    while scope.is_closed &&
          !scope.names.contains(name) &&
          scope.parent is Some(parent) {
      scope = self.table.scopes[parent]
    }
    scope.waiting.get_or_init(name, () => []).push(reference)
  }
}

///|
/// Give `reference`, which waits no more, its value: `named`, the object with its only name, or what its producer gives
/// now. Another token of the producer waits in the same place.
fn XamlObjectWriter::settle(
  self : XamlObjectWriter,
  reference : Reference,
  named : @nodes.XamlValue,
) -> @nodes.XamlValue raise @nodes.XamlWriteError {
  let { holder, place, site, fixup: { scope, producer, object, .. }, .. } = reference
  let (value, place) = match (producer, place) {
    (Some(producer), _) => (produced(scope, producer), place)
    // System.Xaml `ProcessNameFixup_Simple` sets the member only.
    (None, Member(definition, member_site, _)) =>
      (named, Member(definition, member_site, No))
    (None, _) => (named, place)
  }
  if !self.table.is_ending {
    if fixup_of(value) is Some(again) {
      reference.fixup = { ..again, object, }
      reference.missing = again.names.length()
      holder.pending += 1
      self.wait_for(reference)
      return value
    }
    reference.is_done = true
  }
  let made = if producer is Some(_) { object } else { None }
  if made is Some(object) {
    self.create_late(object, value)
  }
  self.put(holder, place, value, site)
  if made is Some(object) {
    self.complete(object)
  }
  value
}

///|
/// `object` waits for `child`.
fn ObjectFrame::wait_for(self : ObjectFrame, child : ObjectFrame) -> Unit {
  self.pending += 1
  child.waiters.push(self)
}

///|
/// Raise when `target` uses `value`, which `object` gives if there is one, at once and it is not complete: forward
/// references are for members, items and keys only (System.Xaml `ForwardRefDirectives` and
/// `TransitiveForwardRefDirectives`).
fn XamlObjectWriter::check_is_complete(
  self : XamlObjectWriter,
  parent : ObjectFrame,
  target : MemberFrame,
  value : @nodes.XamlValue,
  site : Site,
  object? : ObjectFrame,
) -> Unit raise @nodes.XamlWriteError {
  let is_used_at_once = match target.role {
    Arguments
    | PositionalParameters
    | FactoryMethod
    | Initialization
    | Name
    | Base => true
    _ => false
  }
  if fixup_of(value) is Some(fixup) {
    let is_directive = target.role is Property(_) &&
      target.site.node is StartMember(Directive(_))
    if is_used_at_once || is_directive {
      raise target.incomplete(parent, fixup.names[:], site)
    }
  } else if is_used_at_once && object is Some(object) && object.pending > 0 {
    raise self.incomplete_content(parent, target, object)
  }
}

///|
/// The error of `object`, which waits and which `target` uses at once. It is about the first reference in it.
fn XamlObjectWriter::incomplete_content(
  self : XamlObjectWriter,
  parent : ObjectFrame,
  target : MemberFrame,
  object : ObjectFrame,
) -> @nodes.XamlWriteError {
  // A reference of an object before this one can have come since its start.
  let open = self.references[object.first_reference:]
    .iter()
    .filter(reference => {
      !reference.is_done && reference.site.index > object.start.index
    })
    .collect()
  let names = []
  for reference in open {
    for name in reference.fixup.names {
      if !names.contains(name) {
        names.push(name)
      }
    }
  }
  target.incomplete(
    parent,
    names,
    open.get(0).map(reference => reference.site).unwrap_or(object.start),
  )
}

///|
fn MemberFrame::incomplete(
  self : MemberFrame,
  parent : ObjectFrame,
  names : ArrayView[String],
  site : Site,
) -> @nodes.XamlWriteError {
  let what = match (self.role, self.site.node) {
    (PositionalParameters, _) => "a positional parameter"
    (_, StartMember(Directive(namespace_uri~, name~))) if namespace_uri ==
      @nodes.xaml_language_namespace => "x:\{name}"
    (_, StartMember(name)) => member_text(name)
    _ => "a directive"
  }
  site.error(
    "\{what} of \{parent.type_.name} needs objects that are not complete: \{names.join(", ")}",
  )
}

///|
/// The place of the value of the innermost object, an extension that `parent` holds and that waits. An item keeps
/// its position.
fn XamlObjectWriter::place_of(
  self : XamlObjectWriter,
  extension : ObjectFrame,
) -> Place raise @nodes.XamlWriteError {
  guard self.objects.get(self.objects.length() - 2)
    is Some({ open_member: Some(target), .. } as parent) else {
    return Result
  }
  match target.role {
    Property(definition) => Member(definition, target.site, target.naming)
    Items =>
      Item(
        self.queue_add(
          parent,
          Null,
          extension.item_type(),
          extension.key,
          extension.start,
        ),
      )
    Key => {
      parent.key.is_pending = true
      Key(parent.key)
    }
    _ => raise self.incomplete_content(parent, target, extension)
  }
}

///|
/// The object that waits for the innermost object. An extension in `x:Key` delays the dictionary and not the item,
/// whose add waits for the key (System.Xaml `Logic_DeferProvideValue`).
fn XamlObjectWriter::holder_of_innermost(
  self : XamlObjectWriter,
  is_extension~ : Bool,
) -> ObjectFrame? {
  let count = self.objects.length()
  guard self.objects.get(count - 2)
    is Some({ open_member: Some(target), .. } as parent) else {
    return None
  }
  match target.role {
    Items => Some(parent.queue())
    Key if is_extension && self.is_dictionary_entry(count - 2) =>
      self.objects.get(count - 3).map(container => container.queue())
    _ => Some(parent)
  }
}

///|
/// The queued adds and the end callback of `object`, which waits for nothing.
fn XamlObjectWriter::finish(
  self : XamlObjectWriter,
  object : ObjectFrame,
) -> Unit raise @nodes.XamlWriteError {
  self.flush_adds(object)
  if object.retrieved_from is None {
    object.initialize(object.runtime.end_init(), "end")
  }
}

///|
/// The value of the extension `object`, whose end callback has run, goes to its place.
fn XamlObjectWriter::provide_late(
  self : XamlObjectWriter,
  object : ObjectFrame,
  place : Place,
  services : @schema.ServiceContext,
) -> Unit raise @nodes.XamlWriteError {
  if object.instance is Some(Object(extension)) {
    let value = produced(object.scope, () => {
      provide_value(extension, object.runtime, services, object.start)
    })
    self.put(
      object.waiters.get(0).unwrap_or(object),
      place,
      value,
      object.start,
    )
  }
}

///|
/// The innermost object has left the stack. When it waits for nothing it is complete, and so are the references
/// to it, the objects that waited for them, and so on (System.Xaml `XamlObjectWriter.TriggerNameResolution`).
fn XamlObjectWriter::leave_stack(
  self : XamlObjectWriter,
  object : ObjectFrame,
) -> Unit raise @nodes.XamlWriteError {
  object.is_open = false
  if object.type_.is_name_scope() {
    self.close_scope(self.table.scopes[object.scope])
  }
  if object.pending > 0 {
    self.unfinished.push(object)
  } else if object.late is None {
    self.complete(object)
  }
  // The list grows while objects complete each other.
  for next = 0; next < self.work.length(); next = next + 1 {
    match self.work[next] {
      Ended(object) => {
        for waiter in object.waiters {
          waiter.pending -= 1
        }
        if object.place is Some((place, services)) {
          self.provide_late(object, place, services)
        }
        for waiter in object.waiters {
          self.end_if_ready(waiter)
        }
      }
      Resolve(reference, name, object) =>
        if self.look_up(reference, name)
          is Some({ value, owner: Some(owner), .. }) &&
          physical_equal(owner, object) {
          reference.missing -= 1
          if reference.missing == 0 {
            reference.holder.pending -= 1
            ignore(self.settle(reference, value))
            self.end_if_ready(reference.holder)
          }
        }
    }
  }
  self.work.clear()
}

///|
/// What `name`, a name of `reference`, stands for now.
fn XamlObjectWriter::look_up(
  self : XamlObjectWriter,
  reference : Reference,
  name : String,
) -> Named? raise @nodes.XamlWriteError {
  self.table.find_name(reference.fixup.scope, name) catch {
    error =>
      raise reference.site.error(
        "cannot look up the name \{name}: \{@schema.error_message(error)}",
      )
  }
}

///|
/// No more names come to `scope`. References in it can still find theirs in the enclosing scopes.
fn XamlObjectWriter::close_scope(
  self : XamlObjectWriter,
  scope : Scope,
) -> Unit {
  scope.is_closed = true
  guard scope.parent is Some(parent) else { return }
  let parent = self.table.scopes[parent]
  for name, references in scope.waiting {
    if scope.names.contains(name) {
      continue
    }
    match parent.waiting.get(name) {
      Some(waiting) => waiting.append(references)
      None => parent.waiting[name] = references
    }
  }
}

///|
/// `object` is off the stack and has ended. What waits for it goes to the list of work.
fn XamlObjectWriter::complete(
  self : XamlObjectWriter,
  object : ObjectFrame,
) -> Unit {
  object.is_complete = true
  if object.place is Some(_) || !object.waiters.is_empty() {
    self.work.push(Ended(object))
  }
  if object.name is Some((scope, name)) {
    let waiting = self.table.scopes[scope].waiting
    if waiting.get(name) is Some(references) {
      waiting.remove(name)
      for reference in references {
        self.work.push(Resolve(reference, name, object))
      }
    }
  }
}

///|
/// End `object` when nothing that it waits for is missing any more.
fn XamlObjectWriter::end_if_ready(
  self : XamlObjectWriter,
  object : ObjectFrame,
) -> Unit raise @nodes.XamlWriteError {
  if object.pending == 0 && !object.is_open && !object.is_complete {
    self.finish(object)
    self.complete(object)
  }
}

///|
/// Finish the load after the end of the root, as System.Xaml `XamlObjectWriter.CompleteNameReferences`: assign the
/// direct references that are left, run the producers that still wait, each once, and then end the objects that still
/// wait for each other.
fn XamlObjectWriter::complete_references(
  self : XamlObjectWriter,
) -> Unit raise @nodes.XamlWriteError {
  self.table.is_ending = true
  let missing = []
  let waiting = self.references.filter(reference => !reference.is_done)
  for reference in waiting {
    guard reference.fixup is { producer: None, names: [name], .. } else {
      continue
    }
    match self.look_up(reference, name) {
      None => missing.push(reference)
      Some({ value, owner, .. }) if missing.is_empty() => {
        reference.target = owner
        ignore(self.settle(reference, value))
      }
      // The load fails, so nothing more is assigned.
      Some(_) => ()
    }
  }
  if missing is [first, ..] {
    let names = missing.map(reference => {
      "\{reference.fixup.names.join(", ")} at \{reference.site.position()}"
    })
    raise first.site.error("unresolved names: \{names.join(", ")}")
  }
  for reference in waiting {
    if reference.fixup.producer is Some(_) {
      self.table.found.clear()
      let value = self.settle(reference, Null)
      // The holder needs the object that the producer found, as for a direct reference.
      reference.target = self.table.found
        .iter()
        .find_first(owner => owner.instance == Some(value))
    }
  }
  if self.root_names is None {
    self.set_root_names()
  }
  self.finish_in_order()
}

///|
/// The objects that wait for each other at the end of the load, with what each needs before its end. The node
/// `2 * i` is the end of the object `i`, and the node `2 * i + 1` the value of that object, an extension.
priv struct Needs {
  objects : Array[ObjectFrame]
  needs : Array[Array[Int32]]
}

///|
/// The nodes of the objects that are not complete. An object needs the objects that it holds and then those that it
/// refers to, in document order.
fn XamlObjectWriter::needs(self : XamlObjectWriter) -> Needs {
  let objects = self.unfinished.filter(object => !object.is_complete)
  let needs = Array::makei(objects.length() * 2, i => {
    if i % 2 == 1 {
      [i - 1]
    } else {
      []
    }
  })
  for i, object in objects {
    object.node = i * 2
  }
  for object in objects {
    for waiter in object.waiters {
      needs[waiter.node].push(
        if object.place is Some(_) {
          object.node + 1
        } else {
          object.node
        },
      )
    }
  }
  for reference in self.references {
    if reference.target is Some(target) &&
      !target.is_complete &&
      !(reference.place is Result) {
      needs[reference.holder.node].push(target.node)
    }
  }
  { objects, needs, }
}

///|
/// End the objects that wait for each other, and give the values of the extensions among them. Each comes after what
/// it needs, except in a cycle of references, which System.Xaml enters "at an arbitrary point": here it is the
/// first reference in document order. An extension in such a cycle can give no value, which is an error.
fn XamlObjectWriter::finish_in_order(
  self : XamlObjectWriter,
) -> Unit raise @nodes.XamlWriteError {
  let { objects, needs, } = self.needs()
  let order = DependencyOrder::new(needs)
  for reference in self.references {
    if !reference.is_done && !(reference.place is Result) {
      // An object has the items that its own collection waits for before it ends.
      let mut first = reference.holder
      while first.retrieved_from is Some(_) && first.waiters is [owner, ..] {
        first = owner
      }
      order.visit(first.node)
    }
  }
  for object in objects {
    order.visit(object.node + (if object.place is Some(_) { 1 } else { 0 }))
  }
  for cycle in order.cycles {
    let extensions = cycle
      .iter()
      .filter(node => node % 2 == 1)
      .map(node => objects[node / 2])
      .collect()
    extensions.sort_by_key(extension => extension.start.index)
    if extensions is [first, ..] {
      let types = extensions.map(extension => extension.type_.name.to_string())
      types.dedup()
      raise first.start.error(
        "a cycle of references: \{types.join(", ")} waits for an object that waits for its value",
      )
    }
  }
  for node in order.sorted {
    let object = objects[node / 2]
    if node % 2 == 0 {
      self.finish(object)
    } else if object.place is Some((place, services)) {
      self.provide_late(object, place, services)
    }
  }
}

///|
/// A depth-first walk of a graph without recursion, which also finds its cycles (Tarjan's strongly connected
/// components).
priv struct DependencyOrder {
  needs : Array[Array[Int32]]
  /// When the walk came to each node, from 1, or 0.
  entered : Array[Int32]
  /// The earliest open node that each node leads to.
  earliest : Array[Int32]
  is_open : Array[Bool]
  /// The nodes whose component is not known yet.
  open : Array[Int32]
  mut count : Int32
  /// The nodes, each after what it needs unless they are in one cycle.
  sorted : Array[Int32]
  /// The components of more than one node.
  cycles : Array[Array[Int32]]
}

///|
fn DependencyOrder::new(needs : Array[Array[Int32]]) -> DependencyOrder {
  let length = needs.length()
  {
    needs,
    entered: Array::make(length, 0),
    earliest: Array::make(length, 0),
    is_open: Array::make(length, false),
    open: [],
    count: 0,
    sorted: [],
    cycles: [],
  }
}

///|
/// Walk from `start`. The last need comes first, as in System.Xaml, which returns the walk "in backwards order".
fn DependencyOrder::visit(self : DependencyOrder, start : Int32) -> Unit {
  if self.entered[start] > 0 {
    return
  }
  // The path from `start`, with how many needs of each node are left.
  let path = [(start, self.enter(start))]
  while path is [.., (node, left)] {
    if left > 0 {
      path[path.length() - 1] = (node, left - 1)
      let next = self.needs[node][left - 1]
      if self.entered[next] == 0 {
        path.push((next, self.enter(next)))
      } else if self.is_open[next] {
        self.reaches(node, self.entered[next])
      }
      continue
    }
    ignore(path.pop())
    self.sorted.push(node)
    if path is [.., (parent, _)] {
      self.reaches(parent, self.earliest[node])
    }
    if self.earliest[node] == self.entered[node] {
      let component = []
      while self.open.pop() is Some(member_) {
        self.is_open[member_] = false
        component.push(member_)
        if member_ == node {
          break
        }
      }
      if component.length() > 1 {
        self.cycles.push(component)
      }
    }
  }
}

///|
/// Come to `node`, and give the number of its needs.
fn DependencyOrder::enter(self : DependencyOrder, node : Int32) -> Int32 {
  self.count += 1
  self.entered[node] = self.count
  self.earliest[node] = self.count
  self.is_open[node] = true
  self.open.push(node)
  self.needs[node].length()
}

///|
fn DependencyOrder::reaches(
  self : DependencyOrder,
  node : Int32,
  other : Int32,
) -> Unit {
  if other < self.earliest[node] {
    self.earliest[node] = other
  }
}