# XAML readers

The package `moonrockz/xaml/reader`.

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

- `XamlTextReader` reads a XAML document in a `String`, in the style of System.Xaml `XamlXmlReader`.
- [`XamlObjectReader`](#the-object-reader) reads a graph of objects, in the style of System.Xaml `XamlObjectReader`.

## The text reader

```mbt check
///|
test "read a document" {
  let button = @nodes.XamlTypeName::new("urn:ui", "Button")
  let context = @schema.SchemaContextBuilder::new()
    .add_type(
      @schema.XamlTypeDefinition::new(
        "urn:ui",
        "Button",
        content_property="Content",
      ).add_member("Content", value_type=@schema.object_type),
    )
    .build()
  let reader = @reader.XamlTextReader::new(
    "<Button xmlns=\"urn:ui\">OK</Button>", context,
  )
  let nodes = []
  while reader.read() {
    if reader.node() is Some(node) {
      nodes.push(node)
    }
  }
  assert_eq(nodes, [
    NamespaceDeclaration(prefix="", namespace_uri="urn:ui"),
    StartObject(button),
    StartMember(Member(owner=button, name="Content")),
    Value(String("OK")),
    EndMember,
    EndObject,
  ])
  assert_eq(reader.diagnostics().length(), 0)
}
```

`@nodes.transfer` copies the nodes and their spans to a writer.

### Settings

| Argument of `XamlTextReader::new` | Meaning |
| --- | --- |
| `text` | The XAML document |
| `schema_context` | The registered types, members, directives and namespaces |
| `local_scope?` | The scope of `clr-namespace:N` and `clr-namespace:N;assembly=`, which resolve to nothing without it |
| `max_depth?` | How many object elements can be nested, 512 by default |
| `max_extension_depth?` | How many markup extensions can be nested in one attribute value, 128 by default |
| `understood_namespaces?` | Namespaces that [markup compatibility](#markup-compatibility) does not leave out although nothing is registered in them |

The reader reads the document as `read` asks for nodes and does not recurse, so higher limits do not
risk a stack overflow.

### Markup compatibility

Tools add attributes and elements that only they need, such as `d:DesignWidth`. Names in the namespace
`http://schemas.openxmlformats.org/markup-compatibility/2006`, usually with the prefix `mc`, say what other readers leave
out. The reader gives the nodes of the document without that markup and without the `mc:` names.

```mbt check
///|
test "leave out design-time attributes" {
  let button = @nodes.XamlTypeName::new("urn:ui", "Button")
  let context = @schema.SchemaContextBuilder::new()
    .add_type(
      @schema.XamlTypeDefinition::new("urn:ui", "Button").add_member(
        "Content",
        value_type=@schema.object_type,
      ),
    )
    .build()
  let text =
    #|<Button xmlns="urn:ui"
    #|        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    #|        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    #|        mc:Ignorable="d"
    #|        d:DesignWidth="200" Content="OK"/>
  let reader = @reader.XamlTextReader::new(text, context)
  let members = []
  while reader.read() {
    if reader.node() is Some(StartMember(name)) {
      members.push(name)
    }
  }
  assert_eq(members, [Member(owner=button, name="Content")])
  assert_eq(reader.diagnostics().length(), 0)
}
```

| Markup | Meaning |
| --- | --- |
| `mc:Ignorable="d e"` | Leave out the names in the namespaces of these prefixes, on this element and in it, when the reader does not understand the namespace |
| `mc:ProcessContent="d:Group e:*"` | Replace these ignorable elements by their content |
| `mc:AlternateContent` | Read the first `mc:Choice` whose `Requires` lists only understood namespaces, else `mc:Fallback`, else nothing |
| `mc:MustUnderstand="v2"` | Give an error when the reader does not understand these namespaces |
| `mc:PreserveElements`, `mc:PreserveAttributes` | Nothing, but their lists are checked |

The reader understands the namespaces that the schema context registers, the XAML language namespaces, every
`clr-namespace:` namespace in `local_scope`, and `understood_namespaces`.

An older namespace that `add_namespace_subsumption` registers is read as the newer one. The nodes have the newer one
too, also those of the declarations.

- Markup that is left out has to be well-formed XML with declared prefixes. Only these rules apply inside it.
- Text around removed tags is joined, as beside a comment.
- An element that is replaced by its content does not count for `max_depth`. Its namespace declarations apply to the
  names in it, but have no nodes. So a prefix in a text that a converter reads, such as the name of a type, is not declared.

### Markup extensions

An attribute value in braces, such as `{local:Echo 'a, b', Count=2, Next={x:Null}}`, gives the nodes of
an object. Positional arguments are the values of `x:_PositionalParameters`, named arguments are members.
A `\` escapes the next character, and `{}` at the start of a value or argument makes the rest text.

A name in braces stands for the type `NameExtension`, else for `Name`. An element name stands for `Name`,
else for `NameExtension`. The type does not have to be a markup extension.

### White space

White space is space, tab, LF and CR. White space alone is content only in a collection that is
registered as white-space significant, in an unknown member, and in a few places under
`xml:space="preserve"`. In other text each run of white space becomes one space, and the spaces at the
start and the end of the content and beside an element that trims its surroundings are dropped.

Comments, processing instructions and CDATA sections part a text into pieces, which are joined. A piece that is only
white space is dropped when another piece has text, so `a<!-- --> <!-- -->b` is `ab`.

Under `xml:space="preserve"` content stays as it is. An element inherits `xml:space`, and the reader gives
it as a directive too.

### Diagnostics

At the first XML or XAML error `read` returns false, and `diagnostics` holds that one error with its
range in the document. `read` may have given nodes before it. The reader never raises.

```mbt check
///|
test "report an error" {
  let context = @schema.SchemaContextBuilder::new().build()
  let reader = @reader.XamlTextReader::new("<Button q:Tag=\"1\"/>", context)
  while reader.read() {

  }
  guard reader.diagnostics().iter().collect() is [diagnostic] else {
    fail("expected one diagnostic")
  }
  assert_eq(diagnostic.code, "undeclared-prefix")
  assert_eq(diagnostic.message, "the namespace prefix \"q\" is not declared")
  assert_eq(diagnostic.span.map(span => span.start.column), Some(9))
}
```

| Code | Error |
| --- | --- |
| `xml-malformed` | The document is not well-formed XML |
| `xml-doctype` | The document has a document type declaration |
| `xml-namespace` | A name or a declaration breaks Namespaces in XML 1.0 |
| `undeclared-prefix` | A name has a prefix that is not declared |
| `malformed-namespace` | A name is in a malformed `clr-namespace:` or `using:` namespace |
| `ambiguous-type` | Several scopes register the type of a `using:` namespace |
| `malformed-type-arguments` | The value of `x:TypeArguments` is not a list of type names, or an element has the directive with both XAML language namespaces |
| `malformed-member-name` | Nothing follows the `.` of a dotted name |
| `misplaced-attribute` | A property element or directive element has an attribute |
| `misplaced-property-element` | A property element or directive element is not directly in an object element |
| `misplaced-directive` | A directive that is allowed only as an attribute is an element |
| `unsupported-xdata` | The document has an `x:XData` element |
| `depth-limit` | An object element is nested more deeply than `max_depth` |
| `malformed-markup-extension` | An attribute value in braces breaks the syntax of markup extensions |
| `extension-depth-limit` | A markup extension is nested more deeply than `max_extension_depth` |
| `unknown-compatibility-name` | Markup compatibility has no such element or attribute, or not in this place |
| `malformed-compatibility-list` | The value of a compatibility attribute breaks the syntax of its list |
| `not-ignorable` | A list has names of a namespace that `mc:Ignorable` on the same element does not list |
| `not-understood` | `mc:MustUnderstand` lists a namespace that the reader does not understand |
| `malformed-alternate-content` | `mc:AlternateContent`, `mc:Choice` or `mc:Fallback` has a wrong attribute, child or place |
| `missing-root` | Markup compatibility removes the root element and leaves no object in its place |

Unknown types, members and directives are not errors, and neither is a member that is set twice. The
reader gives nodes that keep their names, as System.Xaml does, and loading reports them.

### Deliberate differences from System.Xaml

- White space between East Asian characters becomes a space, as it does everywhere. System.Xaml drops a
  line feed with one more white-space character there.
- Decoded carriage returns, such as `&#13;`, stay in attribute values and in preserved text.
- Comments, processing instructions and CDATA sections do not split text, so they do not change which
  white space is content.
- Text beside an element that trims its surroundings is trimmed also when the element declares
  namespaces.
- A directive element that is allowed only as an attribute, such as `<x:Name>`, is an error.
- An empty directive element such as `<x:Arguments/>` is a member without values. System.Xaml looks for its end tag.
- Two attributes that set the member with the `x:Name` alias are both read, and loading reports the duplicate.
  System.Xaml keeps the last one.
- An attribute without a prefix is never a directive, also on an element of the XAML language namespace.
- A named argument without a value, as in `{local:Echo a, Count=}`, is an error.
- A named argument with a prefix that is not declared is an error.
- The bracket pairs of an argument apply to that argument only, not to the extensions in it.
- `xmlns:xml="http://www.w3.org/XML/1998/namespace"`, which is allowed and changes nothing, has no node. System.Xaml
  fails for it on the root, and gives a node for it on other elements that its writer rejects.
- When a namespace is read as a newer one, and that one as another that does not resolve, the last one that
  resolves counts. System.Xaml takes the original namespace or fails, depending on what it read before.
- An empty element tag means the same as a start tag and an end tag. System.Xaml rejects a selected
  `<mc:Choice Requires="u"/>`, and applies the `mc:Ignorable` of an empty element that is replaced by its content
  to the next element.

## The object reader

`XamlObjectReader` gives the nodes of a document that loads as an equal graph. It reads the objects through the
getters, enumerators and converters that the schema context registers. With a writer it saves a graph.

```mbt check
///|
priv struct Gauge {
  name : String
  value : Double
  next : @nodes.XamlValue
}

///|
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(
  value : Double,
  name~ : String = "",
  next~ : @nodes.XamlValue = Null,
) -> @nodes.XamlValue {
  let type_ = @nodes.XamlTypeName::new("urn:ui", "Gauge")
  Object(gauge_key.wrap(type_, { name, value, next, }))
}

///|
fn gauge_context() -> @schema.SchemaContext raise {
  let definition = @schema.XamlTypeDefinition::new("urn:ui", "Gauge")
    .object_key(gauge_key)
    .add_constructor([], (_, _) => gauge(0.0))
    .add_member(
      "Name",
      value_type=@schema.string_type,
      getter=target => String(gauge_of(target).name),
      // Saving only needs to know that there is a setter.
      setter=(_, _) => (),
      default_value=String(""),
    )
    .add_member(
      "Value",
      value_type=@schema.double_type,
      getter=target => Double(gauge_of(target).value),
      setter=(_, _) => (),
      default_value=Double(0.0),
    )
    .add_member(
      "Next",
      value_type=@schema.object_type,
      getter=target => gauge_of(target).next,
      setter=(_, _) => (),
      default_value=Null,
    )
    .aliased_member(Name, "Name")
  @schema.SchemaContextBuilder::new().add_type(definition).build()
}

///|
fn saved(value : @nodes.XamlValue) -> String raise {
  let context = gauge_context()
  let writer = @writer.XamlTextWriter::new(context)
  @nodes.transfer(@reader.XamlObjectReader::new(value, context), writer)
  writer.text().unwrap_or("")
}

///|
test "save objects" {
  let last = gauge(7.5, name="last")
  assert_eq(
    saved(gauge(1.0, next=last)),
    "<Gauge xmlns=\"urn:ui\" Value=\"1\"><Gauge.Next><Gauge Name=\"last\" Value=\"7.5\"/></Gauge.Next></Gauge>",
  )
}
```

`XamlObjectReader::new` reads the whole graph, so changes after it have no effect on the nodes. It reads it again when an
object has a name that it generated for an earlier one, so getters and converters can be called more than once. It does not
recurse, and 100,000 objects take between 0.3 and 2 seconds, whether they are nested or in one collection.

### What is written

- A member needs a getter, and a setter or a container that loading fills. `visibility=Hidden` leaves it out.
- A member with a setter and a default value is written when its value differs from the default. Otherwise
  the should-serialize check decides, and without one the member is written. Empty read-only containers are left out.
- A save reader replaces the getter for saving. `None` from it means that the member is not set.
- The attached members that the store of a type lists follow the same rules.
- Only registered getters, save readers, checks, enumerators, stores, descriptors, converters and serializers run. The
  constructors and factory methods of the types do not.
- `ObjectReaderSettings::new(require_explicit_content_visibility=true)` writes read-only containers only when
  they register the visibility `Content` or a should-serialize check.

### The form of a value

A value is text when its value serializer or converter writes text and loading converts text back. A converter
can give a markup extension instead, which comes before its text. Anything else is an object. A list is an
`x:Array`, null is `x:Null`, and a type value is the text of its name or an `x:Type`.

| An object of a type with | is written with |
| --- | --- |
| A constructor without parameters | Its members |
| An instance descriptor | `x:Arguments`, and `x:FactoryMethod` for a factory method. A complete descriptor leaves out the members, unless the type has an `x:Name` alias or the object has attached members |
| Members that name the parameters of a constructor | `x:Arguments` and the other members |

A markup extension with an instance descriptor has positional parameters when its arguments are text or
extensions that fit in braces. Without a descriptor its constructor without parameters comes first.

### Shared objects

An object in several places is written once, and the other places have an `x:Reference` to it. The name is the value of
the `x:Name` alias, or `__ReferenceID0` and so on, without the names that the graph has already. Objects whose key has an
equality are values, and neither they nor objects with text are shared.

Register a hash with `ObjectKey::new(hash=...)` for types with many objects. Without one, the reader compares each
object with all others of the key, and 100,000 of them take minutes and not a second.

Each name scope has its own names, as when loading. An object that only another scope has is written again.

### Errors

When the graph cannot be written, `read` gives no node, and `diagnostics` has one error with the code
`unsavable-object`. It names the type and the member. Objects have no range in a document.

| Cause | Example |
| --- | --- |
| A type or member is not registered | The type of an object, or an attached member of the store |
| A registered function fails | A getter, an enumerator, a converter |
| A container has no enumerator | `collection` without `item_enumerator` |
| Nothing constructs the object | No constructor without parameters, no descriptor and no constructor for the members that name parameters |
| A descriptor does not fit | An unknown factory method, one of another generic type, or the wrong number or type of arguments |
| Text would lose something | An attached member on a value that becomes text |
| An object never ends | An object that becomes text and has itself in an attached member |
| A name does not work | A name that is no string, two objects with one name in a scope, or a reference that another object with that name would get |

Some graphs are written and then fail to load, as in System.Xaml: an object that its own constructor arguments or
array items hold, and a reference to an object as the key of a name scope.

By default the nodes have members with text before `x:Arguments`, as in System.Xaml. The object writer rejects that. Use
one of these:

- `ObjectReaderSettings::new(construction_first=true)` puts the directives that construct an object before its
  other members, and the key, the other directives and the name before the rest, as the text reader does. These nodes
  are for the object writer, to copy a graph, and for the `RoundTrip` mode of the text writer.
- The `SystemXaml` mode of the text writer takes the default order and writes the members as attributes, which the text
  reader gives after the construction.

### Deliberate differences from System.Xaml

- Root declarations are sorted by ordinal prefix comparison.
- The prefix of a CLR-style namespace is always valid. The first letters of `X.M.L.N.S` give `xmlns` in System.Xaml, which
  then cannot write the document.
- A list without an item type is an `x:Array` of the common type of its items.
- References are checked: each one must get its object when the document loads.
- A name scope that has a name keeps it when something refers to it. System.Xaml writes a second one, and the
  document does not load.
- A collection or dictionary in a settable member always has its own element. System.Xaml writes the items of some
  alone. Then the document does not load when the member starts as null, the load adds them to the items that the
  member starts with, and a first item that the member takes is read as its value. Saving calls no constructors, so it
  does not know with what a member starts.
- A generated name is not one that an object of the graph has. System.Xaml reports two objects with one name.
- A key in a dictionary of name scopes belongs to the scope of its item, as when loading.
- An entry whose `x:Key` alias has the key and is not written, for example because it is hidden, has an `x:Key`. System.Xaml
  writes neither, and the key is lost.
- An extension that does not fit in braces is written in `x:Arguments`. System.Xaml writes a reference to
  an extension that is not in the document.
- An extension from a factory method has `x:Arguments`. System.Xaml writes positional parameters beside the
  factory method, which does not load.
- A factory method of another generic type is an error. System.Xaml writes it with the type arguments, which does not load.
- An object whose constructor takes its `x:Name` alias keeps that name.
- Members beside the constructor-argument members are always written.
