// How the mode `RoundTrip` chooses between attributes and element content (design D26).
//
// The reader gives the construction directives of an object first, then the other attributes and then the
// other elements. In that stream the members are in three parts:
//
// - the leading construction directives and `x:Key`, as attributes up to some member and then as elements,
// - attributes, in the order of their groups,
// - elements.
//
// The writer starts from the forms of `XamlXmlWriter`. It then reads the element content back with the code
// of the reader. A member that is read as something else there becomes an attribute, and so does each member
// before it.

///|
/// The forms of the members of one object. Members are named by their indices.
priv struct Layout {
  attributes : Array[Int32]
  body : Array[BodyMember]
  /// Whether the element gets `xml:space="preserve"`.
  adds_space : Bool
  /// Whether white space is preserved in the element.
  preserves_space : Bool
  /// Whether an empty element has an end tag.
  keeps_end_tag : Bool
}

///|
priv struct BodyMember {
  index : Int32
  /// Whether the member has an element of its own. The values of others are in the element of the object.
  has_tag : Bool
  /// What the mode `SystemXaml` writes for the first value, if it is not the usual form.
  first_text : String?
}

///|
/// What the element content around an object needs of the element of the object.
priv struct Demand {
  /// Whether `x:Key` has to be an attribute, or an element.
  mut key : Bool?
  /// Whether the element needs an end tag, so that white space before it is read.
  mut end_tag : Bool
  /// Whether the element cannot get declarations.
  mut no_declarations : Bool
}

///|
fn Demand::new() -> Demand {
  { key: None, end_tag: false, no_declarations: false, }
}

///|
/// How an object can be written in braces.
#derive(Eq)
priv enum BracesForm {
  NoBraces
  /// The reader reads it back.
  Readable
  /// `XamlXmlWriter` writes it too.
  Usual
}

///|
/// A member cannot have the form that is tried.
priv suberror Misfit {
  /// The member has to be an attribute, for the reason that the text tells about the node.
  NeedsAttribute(Int32, node~ : Int32, message~ : String)
  /// The member has to be an element.
  NeedsElement(Int32, node~ : Int32, message~ : String)
}

///|
fn Misfit::unwritable(self : Misfit) -> Unwritable {
  match self {
    NeedsAttribute(_, node~, message~) | NeedsElement(_, node~, message~) =>
      Unwritable(node, message)
  }
}

///|
/// The members of one object while their forms are tried.
priv struct Trial {
  writing : Writing
  id : Int32
  object : ObjectNode
  element : @syntax.NamedType
  /// The members to place, by their indices.
  order : Array[Int32]
  /// Whether each member of `order` can be an attribute.
  attributable : Array[Bool]
  /// Whether the element also gets attributes that are not in `order`.
  has_others : Bool
  /// Whether an object that is only read back in braces can be an element with other nodes.
  accepts_changes : Bool
  /// Whether white space is preserved around the element.
  outer_space : Bool
  /// The space setting of the object itself: whether it is `preserve`. `None` when it has none.
  own_space : Bool?
  /// Whether the content property gets a property element.
  mut tags_content : Bool
}

///|
/// The forms of the members of the object `id`, which is the element `element`.
fn Writing::round_trip_layout(
  self : Writing,
  id : Int32,
  element : @syntax.NamedType,
  outer_space : Bool,
) -> Layout raise Unwritable {
  let object = self.document.objects[id]
  self.trial(id, element, outer_space, _ => false).place() catch {
    _ => {
      // No form gives the same nodes. Directives that are only attributes can still move, and positional
      // parameters can be expanded.
      let floating = object.members.mapi((index, m) => {
        let is_floating = m.target.name
          is (Directive(..) | UnknownDirective(..)) &&
          self.member_spelling(element, object, m, Attribute) is Some(_) &&
          m.values is [Text(_, _)] &&
          self.tag_spelling(element, object, m) is None &&
          !is_implicit(m.target)
        (index, is_floating)
      })
      let trial = self.trial(id, element, outer_space, index => {
        floating[index].1
      })
      let trial = { ..trial, accepts_changes: true, tags_content: false, }
      let layout = trial.place() catch { misfit => raise misfit.unwritable() }
      layout.attributes.append(
        floating.filter(entry => entry.1).map(entry => entry.0),
      )
      layout
    }
  }
}

///|
/// The members of the object `id` without those that are `floating`, which are attributes anyway.
fn Writing::trial(
  self : Writing,
  id : Int32,
  element : @syntax.NamedType,
  outer_space : Bool,
  floating : (Int32) -> Bool,
) -> Trial {
  let object = self.document.objects[id]
  let mut has_others = false
  let order = []
  for index, m in object.members {
    if floating(index) {
      has_others = true
    } else if is_content_member(element, m) &&
      self.document.items(m) is ([], Some(got)) &&
      self.document.objects[got].members
      .iter()
      .all(m => m.target.name == @syntax.items_directive) {
      // A get object without items is nothing in the content.
      continue
    } else {
      order.push(index)
    }
  }
  {
    writing: self,
    id,
    object,
    element,
    order,
    attributable: order.map(index => {
      self.can_be_attribute(element, object, object.members[index])
    }),
    has_others,
    accepts_changes: false,
    outer_space,
    own_space: own_space(object),
    tags_content: false,
  }
}

///|
fn Writing::can_be_attribute(
  self : Writing,
  element : @syntax.NamedType,
  object : ObjectNode,
  m : MemberNode,
) -> Bool {
  !is_implicit(m.target) &&
  (match m.values {
    [Text(_, _)] => true
    [Object(child)] => self.braces[child] != NoBraces
    _ => false
  }) &&
  self.member_spelling(element, object, m, Attribute) is Some(_)
}

///|
/// Whether `target` is a directive that has no name in a document (`XamlXmlWriter.IsImplicit`).
fn is_implicit(target : @syntax.NamedMember) -> Bool {
  target.name == @syntax.items_directive ||
  target.name == @syntax.initialization_directive ||
  target.name == @syntax.positional_parameters_directive ||
  target.name == @syntax.unknown_content_directive
}

///|
fn is_construction(m : MemberNode) -> Bool {
  @syntax.is_construction_directive(m.target.name)
}

///|
fn is_key(m : MemberNode) -> Bool {
  m.target.name == @syntax.key_directive
}

///|
fn Trial::at(self : Trial, position : Int32) -> MemberNode {
  self.object.members[self.order[position]]
}

///|
/// Whether `XamlXmlWriter` writes the member at `position` as an attribute when that is possible.
fn Trial::prefers_attribute(self : Trial, position : Int32) -> Bool {
  let m = self.at(position)
  let is_content = self.is_content(m)
  self.attributable[position] &&
  (match m.values {
    [Text("", _)] => true
    [Text(_, _)] =>
      !(m.target.definition is Some(definition) &&
      (
        definition.is_collection_directive() ||
        (is_content && self.writing.takes_text(definition))
      ))
    [Object(child)] => !is_content && self.writing.braces[child] == Usual
    _ => false
  })
}

///|
/// Whether no element of the member at `position` is read as the same value, whatever is around it.
fn Trial::needs_attribute(self : Trial, position : Int32) -> Bool {
  let m = self.at(position)
  match m.values {
    [Text("", _)] => true
    [Object(child)] if !self.accepts_changes &&
      self.writing.braces[child] != NoBraces &&
      !self.writing.keeps_nodes[child] => true
    _ =>
      // Nothing around a property element changes how its values are read.
      !self.is_content(m) &&
      (try self.read_back([], [position], needs_space=false) catch {
        _ => true
      } noraise {
        _ => false
      })
  }
}

///|
/// Whether `m` is the content property of the object.
fn Trial::is_content(self : Trial, m : MemberNode) -> Bool {
  is_content_member(self.element, m)
}

///|
fn is_content_member(element : @syntax.NamedType, m : MemberNode) -> Bool {
  element.definition is Some(definition) &&
  definition.content_member() is Some(found) &&
  found.member_name() == m.target.name
}

///|
/// Whether a string can be assigned to the member, so that `XamlXmlWriter` writes it as content.
fn Writing::takes_text(self : Writing, definition : @schema.XamlMember) -> Bool {
  self.document.types.context.is_assignable(
    @schema.string_type,
    definition.value_type.unwrap_or(@schema.object_type),
  )
}

///|
/// Place the members so that the reader gives them in the same order.
fn Trial::place(self : Trial) -> Layout raise Misfit {
  let count = self.order.length()
  // The construction directives and the key that can come first.
  let mut body_start = 0
  while body_start < count &&
        (is_construction(self.at(body_start)) || is_key(self.at(body_start))) {
    body_start += 1
  }
  let mut directives_end = 0
  while directives_end < body_start &&
        self.attributable[directives_end] &&
        (directives_end == 0 || !is_key(self.at(directives_end - 1))) {
    directives_end += 1
  }
  let mut attributes_end = body_start
  while attributes_end < count &&
        self.attributable[attributes_end] &&
        !is_construction(self.at(attributes_end)) &&
        (
          attributes_end == body_start ||
          self.group(attributes_end) >= self.group(attributes_end - 1)
        ) {
    attributes_end += 1
  }
  // An attribute that forces the constructor changes what the initialization text is.
  if self.order[:body_start]
    .iter()
    .any(index => {
      let m = self.object.members[index]
      m.target.name == @syntax.initialization_directive &&
      !(m.values is [Text("", _)])
    }) {
    for position in body_start.. directives_end || attributes > attributes_end {
        raise NeedsAttribute(
          position,
          node=self.at(position).start,
          message="the key cannot have the form that the content around the object needs",
        )
      }
    }
  }
  // Those that are known to need it, so that they do not take a try each.
  for position in attributes.. body_start && first < body_start && is_key(self.at(first)) {
      // The reader puts the element of a key behind the attributes, unless a construction directive in an
      // element comes before it.
      if first < directives_end {
        first += 1
      } else if first > directives {
        first -= 1
      } else if attributes == body_start {
        last = body_start
        attributes_end = body_start
      } else {
        raise self.moved(first, "after")
      }
    }
    let layout = self.lay_out(body_start, first, last) catch {
      NeedsAttribute(position, ..) as misfit => {
        if position < body_start && position < directives_end {
          directives = position + 1
        } else if position >= body_start && position < attributes_end {
          attributes = position + 1
        } else if !self.tags_content && self.is_content(self.at(position)) {
          self.tags_content = true
        } else {
          // The elements before the member or after it can be the reason.
          attributes = last + 1
          while last > body_start &&
                attributes < attributes_end &&
                self.is_neutral(attributes - 1) &&
                self.is_neutral(attributes) {
            attributes += 1
          }
          if attributes > attributes_end {
            raise misfit
          }
        }
        continue
      }
      NeedsElement(position, ..) as misfit => {
        if position < attributes {
          raise misfit
        }
        attributes_end = position
        continue
      }
    }
    if (layout.adds_space || self.has_others) &&
      first + 1 < body_start &&
      is_key(self.at(first)) {
      // An attribute that is not in the order takes the key behind the construction directives after it, unless one
      // in an element comes before it.
      if first < directives_end {
        directives = first + 1
      } else if first > directives {
        directives_end = first - 1
      } else {
        raise self.moved(first, "after")
      }
      continue
    }
    return layout
  }
}

///|
/// Whether the members after the one at `position` are read in the same way when it is an attribute and when it is an
/// element, if there is an element between them.
fn Trial::is_neutral(self : Trial, position : Int32) -> Bool {
  let m = self.at(position)
  !is_implicit(m.target) &&
  !is_construction(m) &&
  !is_key(m) &&
  !self.is_content(m) &&
  self.element.is_forced_by(m.target) == (m.target.name is Member(..))
}

///|
fn Trial::group(self : Trial, position : Int32) -> @syntax.AttributeGroup {
  self.element.attribute_group(self.at(position).target)
}

///|
/// The end of the attributes that start at `start`, when at least those up to `least` and at most those up
/// to `most` are attributes.
fn Trial::end_of_attributes(
  self : Trial,
  start : Int32,
  least : Int32,
  most : Int32,
) -> Int32 raise Misfit {
  let count = self.order.length()
  let keeps_order = (end : Int32) => {
    // The reader moves a construction directive ahead of the attributes, unless another member comes
    // before it. A key does not count as one.
    end == start ||
    end == count ||
    !(is_construction(self.at(end)) ||
    (
      is_key(self.at(end)) &&
      end + 1 < count &&
      is_construction(self.at(end + 1))
    ))
  }
  let mut end = least
  while end < most && self.prefers_attribute(end) {
    end += 1
  }
  let usual = end
  while end >= least {
    if keeps_order(end) {
      return end
    }
    end -= 1
  }
  for end in (usual + 1)..<=most {
    if keeps_order(end) {
      return end
    }
  }
  raise self.moved(usual, "before")
}

///|
/// The error for a member that the reader gives before those that come before it, or after those that come after it.
fn Trial::moved(self : Trial, position : Int32, place : String) -> Misfit {
  let m = self.at(position)
  NeedsAttribute(
    position,
    node=m.start,
    message="the reader would give \{m.target.label()} \{place} the members that come \{place} it",
  )
}

///|
/// Lay out the members with those before `first` and those from `body_start` to `last` as attributes.
fn Trial::lay_out(
  self : Trial,
  body_start : Int32,
  first : Int32,
  last : Int32,
) -> Layout raise Misfit {
  let count = self.order.length()
  let positions = Array::makei(body_start - first, offset => first + offset)
  let after = Array::makei(count - last, offset => last + offset)
  if last > body_start && last < count && is_key(self.at(last)) {
    // The key stays behind the attributes only when no construction directive comes before it.
    positions.insert(0, last)
    ignore(after.remove(0))
  }
  positions.append(after)
  let attributes = Array::makei(first, position => position)
  attributes.append(
    Array::makei(last - body_start, offset => body_start + offset),
  )
  // White space before the element of a key is no text, but behind it, and the reader then puts the key behind the
  // text when there is an attribute. It also puts the key behind that attribute, so only one that is not in the order
  // can be there.
  let has_space = last == body_start &&
    positions is [first, second] &&
    is_key(self.at(second)) &&
    self.at(first).target.name == @syntax.initialization_directive &&
    self.at(first).values is [Text(text, _)] &&
    text != "" &&
    @syntax.is_space(text)
  if has_space {
    positions.swap(0, 1)
  }
  self.read_back(attributes, positions, needs_space=has_space)
}

///|
/// The space setting of the object itself: whether it is `preserve`. `None` when it has none.
fn own_space(object : ObjectNode) -> Bool? {
  object.members
  .iter()
  .find_first(m => m.target.name == space_directive)
  .map(m => m.values is [Text("preserve", _)])
}

///|
/// Read the element content of the members at `positions` as the reader does, and check that it gives the
/// same values.
fn Trial::read_back(
  self : Trial,
  attributes : Array[Int32],
  positions : Array[Int32],
  needs_space~ : Bool,
) -> Layout raise Misfit {
  let document = self.writing.document
  for position in positions {
    for item in document.items(self.at(position)).0 {
      if item is Object(child) {
        self.writing.demands[child] = Demand::new()
      }
    }
  }
  let preserves_space = self.own_space.unwrap_or(self.outer_space)
  let content = @syntax.Content::new(
    self.element,
    forced_constructor=attributes
      .iter()
      .any(position => self.element.is_forced_by(self.at(position).target)),
    preserves_space~,
  )
  let body = self.forms(positions, content.forced_constructor)
  let reading = {
    trial: self,
    content,
    can_add_space: self.own_space is None && !preserves_space,
    adds_space: needs_space && self.own_space is None,
    attributes,
  }
  let mut keeps_end_tag = false
  for place in 0.. 1 {
        let other = body[if place == 0 { 1 } else { 0 }].0
        raise NeedsAttribute(
          other,
          node~,
          message="the reader gives the empty initialization text only for an object without other content",
        )
      }
      guard self.element.needs_initialization() ||
        self.element.name == @schema.string_type else {
        raise NeedsAttribute(
          position,
          node~,
          message="the reader gives no initialization text for an empty element of this type",
        )
      }
      keeps_end_tag = true
      continue
    }
    if has_tag {
      if self.writing.tag_spelling(self.element, self.object, m) is None {
        raise NeedsAttribute(
          position,
          node=m.start,
          message="\{m.target.label()} cannot be written as an element",
        )
      }
      content.close_member()
      content.open_element(m.target)
      reading.read_member(position, has_tag, None)
      content.close_member()
    } else {
      let next = body.get(place + 1)
      let item = match next {
        Some((next, false)) => document.items(self.at(next)).0.get(0)
        _ => None
      }
      let after : AfterItem = match (next, item) {
        (None, _) => Tag(EndTag)
        (_, Some(item)) => Next(item)
        _ => Tag(MemberTag)
      }
      reading.read_member(position, has_tag, Some(after))
    }
  }
  {
    attributes: attributes.map(position => self.order[position]),
    body: body.map(entry => {
      index: self.order[entry.0],
      has_tag: entry.1,
      first_text: None,
    }),
    adds_space: reading.adds_space,
    preserves_space: preserves_space || reading.adds_space,
    keeps_end_tag,
  }
}

///|
/// The members at `positions` that are written, each with whether it has an element of its own.
fn Trial::forms(
  self : Trial,
  positions : Array[Int32],
  forced_constructor : Bool,
) -> Array[(Int32, Bool)] {
  let mut forced_constructor = forced_constructor
  let body = []
  for position in positions {
    let m = self.at(position)
    let is_content = !self.tags_content && self.is_content(m)
    let has_tag = !is_implicit(m.target) &&
      !(is_content && self.opens_content(m, forced_constructor))
    if has_tag && m.target.name is Member(..) {
      forced_constructor = true
    }
    body.push((position, has_tag))
  }
  body
}

///|
/// Whether the first value of the content property `m` opens it in the content of the object.
fn Trial::opens_content(
  self : Trial,
  m : MemberNode,
  forced_constructor : Bool,
) -> Bool {
  guard self.writing.document.items(m) is ([item, ..], got) else {
    return false
  }
  let types = self.writing.document.types
  let is_got = got is Some(_)
  let opening = (has_key : Bool) => {
    let content = @syntax.Content::new(
      self.element,
      forced_constructor~,
      preserves_space=false,
    )
    match item {
      Text(text, _) => {
        guard is_got ||
          (
            text != "" &&
            m.target.definition is Some(definition) &&
            self.writing.takes_text(definition)
          ) else {
          return @syntax.Opening::InOpenMember
        }
        content.open_for_text(types, EndTag)
      }
      Object(child) =>
        content.open_for_object(types, self.first_value(child, has_key))
    }
  }
  [true, false]
  .iter()
  .any(has_key => {
    match opening(has_key) {
      OpensContent(_) => !is_got
      OpensContentItems(_) => is_got
      _ => false
    }
  })
}

///|
/// What the reader knows about the object `child` when it starts. `has_key` tells whether its key, if it
/// has one, is an attribute.
fn Trial::first_value(
  self : Trial,
  child : Int32,
  has_key : Bool,
) -> @syntax.FirstValue {
  let object = self.writing.document.objects[child]
  {
    type_name: object.type_.name,
    is_markup_extension: object.type_.definition is Some(definition) &&
    definition.is_markup_extension(),
    has_key: has_key && object.members.iter().any(is_key),
  }
}

///|
/// What follows a value.
priv enum AfterItem {
  Tag(@syntax.NextTag)
  Next(Item)
}

///|
/// The content of an element while it is read back.
priv struct ReadingBack {
  trial : Trial
  content : @syntax.Content
  can_add_space : Bool
  mut adds_space : Bool
  /// The positions of the attributes.
  attributes : Array[Int32]
}

///|
/// Read the values of the member at `position`. `after` is what follows them, if the member has no element
/// of its own.
fn ReadingBack::read_member(
  self : ReadingBack,
  position : Int32,
  has_tag : Bool,
  after : AfterItem?,
) -> Unit raise Misfit {
  let trial = self.trial
  let document = trial.writing.document
  let m = trial.at(position)
  let (values, got) = document.items(m)
  if got is Some(id) &&
    document.objects[id].members
    .iter()
    .find_first(other => other.target.name != @syntax.items_directive)
    is Some(other) {
    raise NeedsAttribute(
      position,
      node=other.start,
      message="a get object has no element, so it can only hold items",
    )
  }
  if values.is_empty() && !has_tag {
    raise NeedsAttribute(
      position,
      node=m.end,
      message="\{m.target.label()} has no element, so it needs a value",
    )
  }
  let is_expected = (opening : @syntax.Opening, place : Int32) => {
    match opening {
      InOpenMember => place > 0 || (has_tag && got is None)
      _ if place > 0 => false
      OpensItemsOfMember => has_tag && got is Some(_)
      OpensItems => m.target.name == @syntax.items_directive
      OpensUnknownContent => m.target.name == @syntax.unknown_content_directive
      OpensInitialization =>
        m.target.name == @syntax.initialization_directive &&
        values.length() == 1
      OpensContent(_) => !has_tag && got is None && trial.is_content(m)
      OpensContentItems(_) => !has_tag && got is Some(_) && trial.is_content(m)
    }
  }
  for place in 0.. Next(next)
      None => after.unwrap_or(Tag(EndTag))
    }
    let node = match got {
      Some(id) if place == 0 => document.objects[id].start
      _ => document.index_of(item)
    }
    let problem = match item {
      Text(text, node) =>
        self.read_text(position, text, node, next, opening => {
          is_expected(opening, place)
        })
      Object(child) =>
        self.read_object(position, child, opening => is_expected(opening, place))
    }
    if problem {
      if !self.content.forced_constructor &&
        trial.element.definition is Some(definition) &&
        @syntax.converts_from_text(definition) &&
        item is Text(_, _) &&
        self.attributes
        .iter()
        .find_first(position => trial.at(position).target.name is Member(..))
        is Some(name_alias) {
        raise NeedsElement(
          name_alias,
          node~,
          message="the reader would take the text for the initialization text",
        )
      }
      raise NeedsAttribute(
        position,
        node~,
        message="the reader would not give this as the value of \{m.target.label()}",
      )
    }
  }
}

///|
/// Read `text` before `next`. The result tells whether it is read as a value of another member.
fn ReadingBack::read_text(
  self : ReadingBack,
  position : Int32,
  text : String,
  node : Int32,
  next : AfterItem,
  is_expected : (@syntax.Opening) -> Bool,
) -> Bool raise Misfit {
  let types = self.trial.writing.document.types
  if text == "" {
    raise NeedsAttribute(
      position,
      node~,
      message="an element has no content for an empty text",
    )
  }
  // What the reader gives for the text before an object depends on the element of that object.
  let read = (tag : @syntax.NextTag) => {
    let preserving = { ..self.content, preserves_space: true, }
    let space = if self.content.text(types, text, tag) == Some(text) {
      false
    } else if self.can_add_space &&
      preserving.text(types, text, tag) == Some(text) {
      true
    } else {
      return None
    }
    let content = { ..self.content, open: self.content.open, }
    if is_expected(content.open_for_text(types, tag)) {
      Some((space, true))
    } else {
      Some((space, false))
    }
  }
  let mut tag : @syntax.NextTag = EndTag
  match next {
    Tag(found) => tag = found
    Next(Text(_, second)) => {
      let message = "the reader would give this text and the text before it as one value"
      if self.trial.at(position).end < second &&
        self.attributes.last() is Some(between) &&
        between > position {
        // The texts are in two members, and the element of one between them keeps them apart.
        raise NeedsElement(between, node=second, message~)
      }
      raise NeedsAttribute(position, node=second, message~)
    }
    Next(Object(child)) => {
      let object = self.trial.writing.document.objects[child]
      let demand = self.trial.writing.demands[child]
      let tag_of = (has_key : Bool, is_empty : Bool, is_new : Bool) => {
        @syntax.NextTag::ObjectTag({
          value: self.trial.first_value(child, has_key),
          is_empty,
          has_declarations: is_new || !object.declarations.is_empty(),
          trims: object.type_.trims(),
        })
      }
      let is_good = (tag : @syntax.NextTag) => read(tag) is Some((_, true))
      let has_key = is_good(tag_of(true, false, false))
      tag = tag_of(has_key, false, false)
      if is_good(tag) {
        demand.end_tag = !is_good(tag_of(has_key, true, false))
        demand.no_declarations = !is_good(tag_of(has_key, false, true))
        if object.members.iter().any(is_key) &&
          is_good(tag_of(!has_key, false, false)) != is_good(tag) {
          demand.key = Some(has_key)
        }
      }
    }
  }
  guard read(tag) is Some((space, _)) else {
    raise NeedsAttribute(
      position,
      node~,
      message="the reader would change the white space of this text",
    )
  }
  if space {
    self.adds_space = true
  }
  let opening = self.content.open_for_text(types, tag)
  if !(opening is OpensInitialization) && self.content.open is Content {
    self.content.close_member()
  }
  !is_expected(opening)
}

///|
/// Read the object `child`. The result tells whether it is read as a value of another member.
fn ReadingBack::read_object(
  self : ReadingBack,
  position : Int32,
  child : Int32,
  is_expected : (@syntax.Opening) -> Bool,
) -> Bool raise Misfit {
  let trial = self.trial
  let writing = trial.writing
  let types = writing.document.types
  let object = writing.document.objects[child]
  if object.kind is Got {
    return true
  }
  if !trial.accepts_changes &&
    writing.braces[child] != NoBraces &&
    !writing.keeps_nodes[child] {
    raise NeedsAttribute(
      position,
      node=object.start,
      message="the object is only read back in braces",
    )
  }
  let demand = writing.demands[child]
  let is_good = (has_key : Bool) => {
    let content = { ..self.content, open: self.content.open, }
    is_expected(
      content.open_for_object(types, trial.first_value(child, has_key)),
    )
  }
  // The text before the object can already need its key in one form.
  let has_key = demand.key.unwrap_or(is_good(true))
  if demand.key is None &&
    object.members.iter().any(is_key) &&
    is_good(has_key) != is_good(!has_key) {
    demand.key = Some(has_key)
  }
  let opening = self.content.open_for_object(
    types,
    trial.first_value(child, has_key),
  )
  self.content.end_object(trims=object.type_.trims())
  !is_expected(opening)
}