# XAML writers

The package `moonrockz/xaml/writer`.

Two writers of XAML node streams, which implement the `XamlWriter` trait of `moonrockz/xaml/nodes` and resolve
names with a `SchemaContext` from `moonrockz/xaml/schema`:

- `XamlTextWriter` writes a XAML document in a `String`, in the style of System.Xaml `XamlXmlWriter`.
- [`XamlObjectWriter`](#the-object-writer) creates the objects that the stream describes, in the style of
  System.Xaml `XamlObjectWriter`.

## The text writer

```mbt check
///|
fn button_context() -> @schema.SchemaContext raise {
  @schema.SchemaContextBuilder::new()
  .add_type(
    @schema.XamlTypeDefinition::new(
      "urn:ui",
      "Button",
      content_property="Content",
    )
    .add_member("Content", value_type=@schema.object_type)
    .add_member("Tag", value_type=@schema.object_type),
  )
  .build()
}

///|
test "write a document" {
  let button = @nodes.XamlTypeName::new("urn:ui", "Button")
  let writer = @writer.XamlTextWriter::new(button_context())
  let nodes : Array[@nodes.XamlNode] = [
    NamespaceDeclaration(prefix="", namespace_uri="urn:ui"),
    StartObject(button),
    StartMember(Member(owner=button, name="Tag")),
    Value(String("{a}")),
    EndMember,
    StartMember(Member(owner=button, name="Content")),
    Value(String("OK")),
    EndMember,
    EndObject,
  ]
  for node in nodes {
    writer.write_node(node)
  }
  writer.close()
  assert_eq(
    writer.text(),
    Some("<Button xmlns=\"urn:ui\" Tag=\"{}{a}\">OK</Button>"),
  )
}
```

The form of a node can depend on the nodes after it, so the writer keeps the nodes and writes the document
when the root object ends. `close` completes open members and objects. `text` gives the document after a
successful `close`, and `None` before that or after an error.

`@nodes.transfer` copies the nodes and their spans from a reader and closes the writer.

```mbt check
///|
test "write what a reader gives" {
  let context = button_context()
  let reader = @reader.XamlTextReader::new(
    "<Button xmlns='urn:ui'><Button.Content><Button>  a</Button></Button.Content></Button>",
    context,
  )
  let writer = @writer.XamlTextWriter::new(context, indent=true)
  @nodes.transfer(reader, writer)
  inspect(
    writer.text().unwrap_or(""),
    content=(
      #|<Button xmlns="urn:ui">
      #|  <Button>a</Button>
      #|</Button>
    ),
  )
}
```

### Settings

| Argument of `XamlTextWriter::new` | Meaning |
| --- | --- |
| `schema_context` | The registered types, members, directives, namespaces and preferred prefixes |
| `mode?` | What to do where the output of System.Xaml would be read as other nodes, `RoundTrip` by default |
| `indent?` | Whether elements are on lines of their own, with two spaces for each level. Off by default |

Line breaks are LF. Indentation is left out where white space can be content: in white-space significant
collections, in the content of unknown types and members, under `xml:space="preserve"` and beside text.

The writer does not recurse, so deep streams do not risk a stack overflow. An indented document grows with
the square of its depth.

### Modes

| Mode | Result |
| --- | --- |
| `RoundTrip` | A form that the text reader gives back as the same nodes, or an error for the node that has none |
| `SystemXaml` | The forms and errors of `XamlXmlWriter`, also where the output is read as other nodes or not at all |

Both modes start from the same choice: a member with one text or one markup extension is an attribute as long
as the members before it are, objects and text of the content property are element content, and everything
else is a property element. The table shows where they differ.

| Case | `RoundTrip` | `SystemXaml` |
| --- | --- | --- |
| A text that needs `xml:space="preserve"` in a property element or a later item | The attribute is on the object element | Error |
| An empty text or an extension with positional parameters after element content | The members before it are attributes too | `<T.M></T.M>`, and the parameters are expanded |
| A member that the reader would give in another place, such as the `x:Name` alias | Property element | Attribute |
| A member without a value | Empty element | Error |
| `Extension` at the end of the name of a markup extension | Kept when the short name is another type | Always dropped |
| An argument in braces with a bracket, a tab or a `{` at its start | Quoted, with `{}` before a `{` | Quoted only for `'`, `"`, `,`, `=`, `{`, `}`, `\` and a space |
| A prefix that is missing or hidden by an inner declaration | Declared on the object element, unless an outer one is visible | Declared on the element of the name, so the member is no attribute |
| A directive when only the empty prefix has its namespace | Gets another prefix | Written without a prefix |

```mbt check
///|
test "the modes differ" {
  let button = @nodes.XamlTypeName::new("urn:ui", "Button")
  let write = (mode : @writer.WriterMode) => {
    let writer = @writer.XamlTextWriter::new(button_context(), mode~)
    let nodes : Array[@nodes.XamlNode] = [
      NamespaceDeclaration(prefix="", namespace_uri="urn:ui"),
      StartObject(button),
      StartMember(Member(owner=button, name="Content")),
      Value(String("OK")),
      EndMember,
      StartMember(Member(owner=button, name="Tag")),
      Value(String("")),
    ]
    for node in nodes {
      writer.write_node(node)
    }
    writer.close()
    writer.text().unwrap_or("")
  }
  assert_eq(
    write(RoundTrip),
    "<Button xmlns=\"urn:ui\" Content=\"OK\" Tag=\"\"/>",
  )
  assert_eq(
    write(SystemXaml),
    "<Button xmlns=\"urn:ui\">OK<Button.Tag></Button.Tag></Button>",
  )
}
```

### What a round trip keeps

When `RoundTrip` writes the stream of a text reader, reading the document again gives the same nodes, except
for these:

- an added `xml:space="preserve"`,
- added namespace declarations, and their order on one element,
- an attached event that is registered as a pair with an instance event, which is read as that event.

In other streams these change as well: a directive that is allowed only as an attribute can move, positional
parameters of an extension in element content become members, null becomes `x:Null`, an empty `x:String`
loses its empty text, and a get object without items in the content property disappears.

Unknown types, members and directives are written by name.

### Errors

An error names the node by its index, with its span in the source when there is one. The writer then has no
document and reports the same error from every later call. These are errors in both modes:

- values other than text and null, because the writer does not convert values,
- characters that XML does not allow, and surrogates without the other half of their pair,
- names that are not XML names,
- two namespace declarations on one element with the same prefix or the same URI, a declaration of the prefix `xml`,
  and declarations that break Namespaces in XML 1.0,
- a name without a namespace on an element that declares a default namespace or has another name in the one in scope,
- a member that is set twice, a second value in a member that holds one, and two texts in a row,
- a get object in a member that is not a collection or dictionary,
- nodes that are not balanced.

In the mode `RoundTrip` it is also an error when no form gives the nodes back. Examples are a get object whose
first item the reader would assign to the member, an attached member with the name of an instance member of
the element, and an empty text behind an element that cannot be an attribute.

### Deliberate differences from System.Xaml

- The mode `RoundTrip` uses other forms than `XamlXmlWriter`, or fails, where its output would be read as
  other nodes. The design of `add-xaml-foundation` gives the reasons (D26).
- `close` writes a text that has no end member yet. `XamlXmlWriter` drops it.
- Namespace declarations are sorted by the ordinal order of their prefixes, and come before other attributes.
- A type with type arguments always has the attribute `x:TypeArguments`. `XamlXmlWriter` writes an element when
  a prefix is missing.
- In the mode `SystemXaml` a first item that starts with a space is written once. `XamlXmlWriter` writes it
  twice.

## The object writer

`XamlObjectWriter` creates objects, sets members and adds items while the nodes arrive. The functions that it
calls are those that the schema context registers. `result` gives the root object after a successful `close`,
and `None` before that or after an error. The result is `Null` for a document such as `<x:Null/>`.

```mbt check
///|
priv struct Gauge {
  mut value : Double
  mut label : String
}

///|
let gauge_key : @nodes.ObjectKey[Gauge] = @nodes.ObjectKey::new()

///|
fn gauge_of(target : @nodes.XamlObject) -> Gauge raise {
  guard gauge_key.unwrap(target) is Some(gauge) else {
    raise @schema.ValueError("not a Gauge")
  }
  gauge
}

///|
fn gauge_context(
  more~ : Array[@schema.XamlTypeDefinition] = [],
) -> @schema.SchemaContext raise {
  let gauge = @schema.XamlTypeDefinition::new("urn:ui", "Gauge")
    .object_key(gauge_key)
    .add_constructor([], (_, _) => {
      let gauge = { value: 0.0, label: "", }
      Object(gauge_key.wrap(@nodes.XamlTypeName::new("urn:ui", "Gauge"), gauge))
    })
    .add_member("Value", value_type=@schema.double_type, setter=(target, value) => {
      if value is Double(value) {
        gauge_of(target).value = value
      }
    })
    .add_member("Label", value_type=@schema.string_type, setter=(target, value) => {
      if value is String(label) {
        gauge_of(target).label = label
      }
    })
  let builder = @schema.SchemaContextBuilder::new().add_type(gauge)
  for definition in more {
    ignore(builder.add_type(definition))
  }
  builder.build()
}

///|
test "load an object" {
  let context = gauge_context()
  let reader = @reader.XamlTextReader::new(
    "<Gauge xmlns='urn:ui' Value='12.5' Label='Speed'/>", context,
  )
  let writer = @writer.XamlObjectWriter::new(context)
  @nodes.transfer(reader, writer)
  guard writer.result() is Some(Object(root)) else { fail("no object") }
  let gauge = gauge_of(root)
  assert_eq(gauge.value, 12.5)
  assert_eq(gauge.label, "Speed")
}
```

### How an object is made

| Step | When |
| --- | --- |
| Constructor or factory method | At the first member that is not a construction directive, `x:Key`, `xml:space` or an `x:Uid` without an alias, else at the end of the object |
| Begin callback | Right after it. Objects from initialization text have none |
| Assignment to the parent | At the end of the object, or after the begin callback when its type is usable during initialization. Dictionary entries and markup extensions are never early |
| End callback | After the assignment, when the members and items are complete. A markup extension has it before it gives its value |

- The constructor is the one without parameters, the one that the types of the `x:Arguments` values select, or,
  for a markup extension in braces, the one with the number of its positional parameters. `x:FactoryMethod`
  names a factory method of the type, or of another one as `prefix:Type.Method`.
- Text of a member goes to the type converter of the member or of its type. Objects and the results of markup
  extensions are assigned without conversion.
- A member without a setter gets items through its getter. A dictionary item has the key `x:Key`, converted with
  the key type, or the value of the member that is the `x:Key` alias of its type.
- An event member gives its nodes to the event adder, unchanged and in one call. Nothing in it is created. For
  [routed events](../schema/README.mbt.md#events) there is an adder, which finds the handler by its name.
- `xml:base` is an absolute URI on the root. Converters and markup extensions get it in their services.
- `x:Class` is the full name of the type of the root, as [below](#a-root-object).
- `x:Uid` and `xml:lang` set the alias members of the type and are ignored without one. The compile-time
  directives, such as `x:Code`, `x:FieldModifier` and `x:DataType`, and `x:ConnectionId` set nothing. Their values
  are converted, evaluated or constructed as those of members and then dropped, so `x:ConnectionId="a"` is an error.

The writer does not recurse, so deep streams do not risk a stack overflow.

### A root object

With `root_object` in the settings the writer sets the members of your object instead of creating a root, as
`RootObjectInstance` of `XamlObjectWriterSettings` does. So a type can fill itself from a document:

```mbt check
///|
let speed_gauge_type : @nodes.XamlTypeName = @nodes.XamlTypeName::new(
  "clr-namespace:Car;assembly=Car", "SpeedGauge",
)

///|
/// A gauge that derives from `Gauge` and has the members that the document gives it.
fn new_speed_gauge(text : String) -> Gauge raise {
  let speed_gauge = @schema.XamlTypeDefinition::new_clr(
    "Car",
    "Car",
    "SpeedGauge",
    base_type=@nodes.XamlTypeName::new("urn:ui", "Gauge"),
  ).object_key(gauge_key)
  let context = gauge_context(more=[speed_gauge])
  let gauge = { value: 0.0, label: "", }
  let root_object = gauge_key.wrap(speed_gauge_type, gauge)
  let writer = @writer.XamlObjectWriter::new(
    context,
    settings=@writer.LoadSettings::new(root_object~),
  )
  @nodes.transfer(@reader.XamlTextReader::new(text, context), writer)
  assert_true(writer.result() == Some(Object(root_object)))
  gauge
}

///|
test "a type that fills itself" {
  let gauge = new_speed_gauge(
    (
      #|<Gauge xmlns='urn:ui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
      #|       x:Class='Car.SpeedGauge' Label='Speed' Value='12.5'/>
    ),
  )
  assert_eq(gauge.label, "Speed")
  assert_eq(gauge.value, 12.5)
}
```

- The type of the object is that of the root element or derives from it. The members in the document are those of the
  element's type, so a `Gauge` element has no member that only `SpeedGauge` has.
- `x:Class` is optional. It must be exactly the full name of the type of the root object, also of one that the load
  creates. The full name is the CLR-style namespace and the name, so a type without such a namespace has none, and
  neither has a generic type.
- The begin callback comes first, before any member, and the end callback last. `x:Arguments` and `x:FactoryMethod` on the
  root are errors, because the object exists.
- A load that fails leaves the object with the members and items that were set before the error, and without its end
  callback.
- Initialization text, such as `<Point>1,2</Point>`, does not fill the object. The type converter gives a new one, which is the
  result, and yours has only had its begin callback. A type that fills itself compares the result with itself, or does not
  load such documents.
- Loading into an object again adds to its collections, and to its name scope when it is one. A name that the scope has for
  another object is then an error.
- When the root element is a markup extension, the result is the value that your object gives.

### Names and references

`x:Name`, or the member that a type registers as its alias, gives an object a name. `x:Reference` gives the object
with a name, which can come later in the document. `root_name_scope` finds the named objects after a successful
`close`.

```mbt check
///|
priv struct Place {
  mut next : @nodes.XamlValue
}

///|
let place_key : @nodes.ObjectKey[Place] = @nodes.ObjectKey::new()

///|
fn place_of(value : @nodes.XamlValue) -> Place raise {
  guard value is Object(handle) && place_key.unwrap(handle) is Some(place) else {
    raise @schema.ValueError("not a Place")
  }
  place
}

///|
test "names and references" {
  let name = @nodes.XamlTypeName::new("urn:ui", "Place")
  let place = @schema.XamlTypeDefinition::new("urn:ui", "Place")
    .object_key(place_key)
    .add_constructor([], (_, _) => Object(place_key.wrap(name, { next: Null, })))
    .add_member("Next", value_type=@schema.object_type, setter=(target, value) => {
      place_of(Object(target)).next = value
    })
  let context = @schema.SchemaContextBuilder::new().add_type(place).build()
  let text =
    #|<Place xmlns='urn:ui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Name='first'>
    #|  <Place.Next>
    #|    <Place x:Name='second' Next='{x:Reference first}'/>
    #|  </Place.Next>
    #|</Place>
  let writer = @writer.XamlObjectWriter::new(context)
  @nodes.transfer(@reader.XamlTextReader::new(text, context), writer)
  guard writer.result() is Some(root) &&
    writer.root_name_scope() is Some(names) &&
    names.find("second") is Some(second) else {
    fail("no result")
  }
  assert_true(place_of(root).next == second)
  assert_true(place_of(second).next == root)
  assert_true(names.find("third") is None)
}
```

- The root has a name scope: the object itself when its type registers scope operations (`name_scope`), else the
  scope in its name-scope property, else a new one. Below the root, each object whose type registers scope
  operations has its own scope. Its own name is in the scope around it.
- The scope of a [root object](#a-root-object) keeps the names that it had before the load, and references find them.
- A reference takes the object from the first scope outward that has the name. An object that is complete comes
  at once. Any other one comes when it is complete, or at the end of the document when it waits for the reference
  itself, as an ancestor does.
- The object with the reference has its end callback after that. A collection adds the items in document order, so
  later items wait too. A markup extension gives its value when its members and items are there.
- A reference that waits works in members, items and `x:Key`. In other directives and in the positional parameters
  of a markup extension the object must come earlier in the document.
- Two objects with one name in a scope are an error, and so are names that no object has at the end of the
  document, all in one error. A markup extension that waits for an object that needs its value is an error too.

When `close` ends a document that is not complete, references that still wait are not set, as in System.Xaml.
`transfer` reports such a document.

Register a hash with the object key of a collection type when a document has thousands of collections that wait at
one time. Without a hash the writer searches all of them.

This release gives a load no names from outside, and has no list of all names in a scope and no event when a scope
is complete (`IXamlNameResolver.GetAllNamesAndValuesInScope`, `OnNameScopeInitializationComplete`).

### Markup extensions and converters

The object writer evaluates your markup extensions and type converters with a `ServiceContext`. It says where the value
goes and what is known there:

| Field | Content |
| --- | --- |
| `target_object`, `target_member` | The object and the member that get the value. The value of a directive has no member, and the root and a constructor argument have neither |
| `root_object`, `parents` | The root, and the objects of the enclosing elements, the nearest first. Objects that do not exist yet are not there |
| `resolve_type`, `resolve_prefix`, `prefixes` | The names of types and the namespaces at this place in the document |
| `name_resolver` | The named objects, searched from the name scope of this place outward |
| `base_uri` | The `xml:base` of the root |

The resolver gives an object only when it is complete, so a name that comes later in the document has none yet. Then ask
the resolver for a token with the names that are missing, and return it as the value. The writer runs the extension or
the converter again when these objects are complete. This extension adds up gauges that can come after it:

```mbt check
///|
let sum_key : @nodes.ObjectKey[Ref[String]] = @nodes.ObjectKey::new()

///|
fn sum_of_gauges(
  names : String,
  context : @schema.ServiceContext,
) -> @nodes.XamlValue raise {
  guard context.name_resolver is Some(resolver) else {
    raise @schema.ValueError("no names here")
  }
  let mut sum = 0.0
  let missing = []
  for name in names.split(" ") {
    match resolver.resolve(name.to_owned()) {
      Some({ value: Object(gauge), .. }) => sum += gauge_of(gauge).value
      _ => missing.push(name.to_owned())
    }
  }
  if missing.is_empty() {
    return Double(sum)
  }
  guard resolver.fixup_token(missing) is Some(token) else {
    raise @schema.ValueError("no gauges named \{missing.join(", ")}")
  }
  Object(token)
}

///|
test "an extension that waits for names" {
  let name = @nodes.XamlTypeName::new("urn:ui", "SumExtension")
  let sum = @schema.XamlTypeDefinition::new("urn:ui", "SumExtension")
    .object_key(sum_key)
    .add_constructor(
      [@schema.XamlParameter::new("names", @schema.string_type)],
      (_, arguments) => {
        guard arguments[0] is String(names) else {
          raise @schema.ValueError("no names")
        }
        Object(sum_key.wrap(name, Ref(names)))
      },
    )
    .markup_extension((extension, context) => {
      guard sum_key.unwrap(extension) is Some(names) else {
        raise @schema.ValueError("not a SumExtension")
      }
      sum_of_gauges(names.val, context)
    })
  let context = gauge_context(more=[sum])
  let text =
    #|<x:Array Type='Gauge' xmlns='urn:ui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    #|  <Gauge Value='{Sum "left right"}'/>
    #|  <Gauge x:Name='left' Value='2.5'/>
    #|  <Gauge x:Name='right' Value='4'/>
    #|</x:Array>
  let writer = @writer.XamlObjectWriter::new(context)
  @nodes.transfer(@reader.XamlTextReader::new(text, context), writer)
  guard writer.result() is Some(root) &&
    @schema.as_array(root) is Some({ items, .. }) &&
    items[0] is Object(total) else {
    fail("no gauges")
  }
  assert_eq(gauge_of(total).value, 6.5)
}
```

- Each run has the same context, and can return another token. An extension gets its members and its end callback only
  once. The object that gets the value has its end callback after the last run.
- A token waits for objects that complete after it, so leave out the names that the resolver has found. What still waits at
  the end of the document runs once more there. That includes a producer that waits for its own parent. Then the
  resolver gives each object with a name and says in `fully_initialized` whether it is complete, and `fixup_token`
  gives `None`: return a value or raise an error.
- `fixup_token([name], can_assign_directly=true)` takes one name. The writer assigns the object itself, without
  another run, and a name that is missing is an error, as with `x:Reference`.
- The converter of an initialization text, such as `<Point>right of ok</Point>`, gives the object of its element. When it
  waits, the object gets its `x:Name` after the second run and has no end callback, as in System.Xaml.
- The places where a token works are those of a reference that waits. At the root it waits for the end of the document.
- A context can be kept and used after the load, but the names are gone then.

### Load settings

`XamlObjectWriter::new` takes the schema context and `LoadSettings`:

| Argument of `LoadSettings::new` | Meaning |
| --- | --- |
| `root_object?` | The [object](#a-root-object) that the root element stands for |
| `local_scope?` | The scope of `clr-namespace:N` and `clr-namespace:N;assembly=`, for names in values. Give the reader the same one |
| `max_depth?` | How deep object elements nest, 512 by default. The text reader applies it |
| `max_extension_depth?` | How deep markup extensions nest in one attribute value, 128 by default. The text reader applies it |
| `understood_namespaces?` | Namespaces that [markup compatibility](../reader/README.mbt.md#markup-compatibility) does not leave out. The text reader applies it |
| `event_handlers?` | A handle that every event adder receives, which is that of a [`HandlerTable`](../schema/README.mbt.md#events) for routed events |

### Errors

An error names the node by its index, with its span in the source when there is one. It is the node that the
reason is about: the value that does not convert, the member that does not exist, the object that its collection
rejects. The writer then has no result and reports the same error from every later call. The constructors,
setters and adders that ran before the error keep their effects.

```mbt check
///|
test "an error with its place" {
  let text = "<Gauge xmlns='urn:ui' Value='fast'/>"
  let context = gauge_context()
  let writer = @writer.XamlObjectWriter::new(context)
  let place = try
    @nodes.transfer(@reader.XamlTextReader::new(text, context), writer)
  catch {
    InvalidNode(span=Some(span), ..) =>
      text[span.start.offset:span.end.offset].to_owned()
    error => raise error
  } noraise {
    _ => fail("no error")
  }
  assert_eq(place, "fast")
  assert_true(writer.result() is None)
}
```

### Deliberate differences from System.Xaml

- A member takes an instance of its type only. System.Xaml sets an `Int32` as a `Double`. MAUI and Avalonia do not.
- Null for a member of a value type that is not nullable is an error, as in Avalonia and for a dependency property in
  WPF. A CLR property gets the zero value in System.Xaml and MAUI.
- A second object in a member that holds one is an error before it is created, not after.
- `x:Arguments` works on dictionary types, where System.Xaml asks for a key of each argument.
- Items stay in document order when a markup extension among them waits, and when two members give one
  collection that waits. System.Xaml fails or changes the order.
- An extension or a converter can wait for a name at the root and in the text of an `x:Key`, several of them can wait for
  one name until the end, and a token can be kept and returned again. System.Xaml gives its token as the
  value or fails.
- After initialization text has replaced a root object, extensions and converters get the new one as the root.
  System.Xaml gives the old one when the root was asked for before.
- `x:Class` is compared with the full name only. System.Xaml also tries it with the root namespace of the assembly.
