# moonrockz/xaml

XAML for MoonBit. You can use it as a serialization format: `from_text` creates a value of your type from a XAML document, and
`to_text` writes one. [The example](src/README.mbt.md) describes a struct, reads a document, changes a value and writes it
again. [`moonrockz/xaml-codegen`](../xaml-codegen/README.mbt.md) writes such descriptions from attributes. Below these functions are readers and writers of XAML node streams, which you can also use alone.

Add it with `moon add moonrockz/xaml`. While the version is 0.x, a minor release can have breaking changes.

The trait `Xaml` describes structs and enums for `from_text` and `to_text`. With
[types registered by hand](src/schema/README.mbt.md#types-registered-by-hand), `parse`, `load` and `save` work, with shared objects and circles, names and
references, constructor arguments, markup extensions, type converters, attached members and
[markup compatibility](src/reader/README.mbt.md#markup-compatibility) (`mc:Ignorable`). Your own
[markup extensions and type converters](src/writer/README.mbt.md#markup-extensions-and-converters) can wait for objects that
come later in the document. A document can also fill
[an object that exists already](src/schema/README.mbt.md#fill-an-object-that-exists). The specifications are in
`openspec/specs/` of the repository.

The module depends on `Milky2018/xml`, which reads the XML, and on `moonrockz/dependency-object`. Documents can create
[controls that are dependency objects](src/schema/README.mbt.md), set their dependency properties,
[add handlers to their events](src/schema/README.mbt.md#events) and have
[property paths](src/schema/README.mbt.md#property-paths) as values. Only the package `schema`
uses dependency objects, and you can use all packages without them.

| Package | Purpose |
| --- | --- |
| `moonrockz/xaml` | [The trait `Xaml`, `from_text` and `to_text`](src/README.mbt.md), `parse`, `load` and `save`, and `version()` |
| `moonrockz/xaml/nodes` | XAML node stream values, the reader and writer contracts, `transfer` and the balance rules |
| `moonrockz/xaml/schema` | XAML schema context: registered types, members, directives, namespaces, type converters, value serializers and [dependency objects](src/schema/README.mbt.md) |
| `moonrockz/xaml/reader` | XAML readers: a [XAML text reader](src/reader/README.mbt.md#the-text-reader) with diagnostics and an [object reader](src/reader/README.mbt.md#the-object-reader) that saves objects |
| `moonrockz/xaml/writer` | XAML writers: a [XAML text writer](src/writer/README.mbt.md#the-text-writer) and an [object writer](src/writer/README.mbt.md#the-object-writer) that creates objects |

## The model

MoonBit has no runtime reflection, so everything that System.Xaml finds by reflection and .NET
attributes is registered explicitly, by a description of the type or by hand, with a `SchemaContextBuilder`, whose `build()` reports every
conflicting registration at once and returns an immutable `SchemaContext`.

**Node stream.** A XAML node is a namespace declaration, start object, get object, end object, start
member, end member or value. Type names carry type arguments; member names are `Member`, `Attached`,
`Directive` or `UnknownDirective`. Values are null, Boolean, Byte, Int16, Int32, Int64, Single,
Double, a UTF-16 `Char`, String, lists and object handles; NaN equals NaN. Readers are pull readers
that give the current node and its source span; writers take spans through `set_source_span`, and
their errors carry the active span. `transfer` copies a reader to a writer, reports a reader that
ends with open frames and closes the writer once; `close()` completes open members and objects. The
validator applies the balance rules and a member cardinality rule: only collection directives,
`x:_UnknownContent`, event members and names that resolve to nothing hold several values. Comparison, hashing and text of nested names and values use
explicit work stacks.

**Types and members.** A type has one identity, its name in its preferred namespace, however many
XAML namespace URIs, CLR-style namespaces (`clr-namespace:N;assembly=S`, `using:N`) or subsumed
namespaces name it. Types are keyed by generic arity and closed over type arguments. Every type but
`x:Object` derives from `x:Object` unless it names a base type. Members are properties, attached
properties, events and attached events (set through event adders, optionally registered as a pair;
[routed events](src/schema/README.mbt.md#events) have them built in)
and directives; instance and attachable members have separate name spaces. Types register static
members for `x:Static`, constructors and named factory methods with typed parameters for
`x:Arguments`, collection and dictionary behavior with item and key types, markup extension
behavior with positional signatures, aliases of `x:Name`, `x:Key`, `x:Uid` and `xml:lang`, a content
property, both inherited, set or cleared, the white-space and `usable_during_initialization` flags,
name-scope access and initialization callbacks. Every context holds the directives and types of the
XAML language namespace, the built-in markup extensions `x:Null`, `x:Type`, `x:Static`, `x:Array` and
`x:Reference`, and `TypeValue`, the type of resolved type values, in `urn:moonrockz:xaml`.

**Names.** A type with scope operations, or a root with a name-scope property, gives the scope in which
`x:Name` registers objects and `x:Reference` finds them. `NameScope` in `urn:moonrockz:xaml` is the default
scope. [Names and references](src/writer/README.mbt.md#names-and-references) describes loading, and what this
release leaves out.

**Root objects.** A load can set the members of an object that you give it, instead of creating the root. The type of the
object is that of the root element or derives from it, and `x:Class`, when the document has it, is its full name.
[A root object](src/writer/README.mbt.md#a-root-object) describes it.

**Type converters and value serializers.** A `TypeConverter` converts text or other values to a type
and back, with capability checks in both directions; a `ValueSerializer` converts values to and from
text for saving. Both are registered on members, attached members and types and looked up in
System.Xaml's order. The language primitives, `x:Char`, `x:TimeSpan`, `x:Decimal`, `x:Uri`,
enumerations and type values have built-in converters. Converters and markup extensions receive a
`ServiceContext`.

**Save registrations.** Saving reads registered getters, save readers, item and entry enumerators,
default values, should-serialize checks, serialization visibility, member dependencies,
constructor-argument members, instance descriptors and attached member stores, all inherited by
derived types. [The object reader](src/reader/README.mbt.md#the-object-reader) describes how it uses them.

**Object keys, base views and key hashes.** An object is a `XamlObject` handle that an
`ObjectKey[T]` wraps and only that key reads back. A type with instance operations registers its key;
a derived type with its own key registers base views that adapt its handles to a base type's key, so
inherited setters, getters, adders, enumerators and callbacks run on the same instance, and `build()`
reports a missing view. A key may register an equality, which makes its handles values, and a hash
consistent with it, which saving uses to find shared objects. Saving many objects of a key without a hash is
slow.

## Memory

js and wasm-gc free a graph of objects when nothing uses it. native and wasm count references, so they
never free objects that refer to each other in a circle: a child with a reference to its parent, or a named root that
is its own name scope. A program that loads many such documents on native or wasm has to break each circle before it
drops the graph, by setting one of the members in it to null or by giving the root a new name scope. Graphs without
circles need nothing, and the readers and writers keep no objects after they are dropped.

## Deliberate differences from System.Xaml

Forced by MoonBit:

1. Registrations replace reflection and .NET attributes.
2. CLR-style namespace names map to registrations in named scopes, the analogue of assemblies.
3. Constructors and factory methods register their ordered parameter types.
4. `x:Decimal`, `x:TimeSpan`, `x:Uri` and `x:Array` values are object handles; `x:Single` is `Float`.
5. `x:Array` gives an `XamlArray` with its declared item type.
6. Objects are `XamlObject` handles read through `ObjectKey[T]`; derived types with their own key
   register base views, and keys may register a hash.
7. The service context is a record of fields, not `IServiceProvider.GetService(Type)`.
8. Type converters and value serializers are registered functions without a culture argument;
   enumerations, nullable value types and parse functions are registrations.
9. Saving reads registered getters, enumerators, defaults, checks, descriptors and stores.
10. Object identity is the object key's comparison; keys with a value equality stand for value types.
11. A plain list is saved as `x:Array` of its items' common type.
12. Resolved type values have the type `TypeValue` in `urn:moonrockz:xaml`.
13. `x:Class` has no retry with an assembly root namespace, and generic types have no full name.
14. CLR array-rank suffixes in type names are an error.

Owner decisions:

15. In element syntax the writer keeps the `Extension` suffix when the short name would resolve to
    another type.
16. Enumeration names match case exactly.
17. The 2009 XAML language URI is fully equivalent to the 2006 one.
18. Saved text uses LF line breaks on every target.
19. `save` checks that each written `x:Reference` resolves to the intended object.
20. The text writer's `close()` commits a buffered member value.
21. `x:Uri` input classes that the implementation does not reproduce (non-ASCII UNC host letters).

Forced by MoonBit, numbered last:

22. Namespace declarations are sorted by ordinal prefix comparison, without culture-aware collation.
23. `x:Single` text is parsed as a `Double` and then rounded, which can differ from .NET in the last
    digit for inputs with more than 17 significant digits.

Owner decisions about the text reader:

24. An empty directive element such as `<x:Arguments/>` is a member without values.
25. Two attributes that set the member with the `x:Name` alias are both read, and loading reports the
    duplicate.
26. A named markup extension argument with a prefix that is not declared is an error.

Owner decision about the text writer:

27. Where the output of System.Xaml would reread as other nodes, the writer uses another form or fails.
    The writer mode `SystemXaml` turns this and number 15 off.

About loading:

28. A second object in a member that holds one is an error before it is constructed, not after.
29. Removed: the value of a directive that loading ignores is converted, as in System.Xaml.
30. `x:Arguments` works on dictionary types, where System.Xaml asks for a key of each argument.
31. Null for a member of a value type that is not nullable is an error, as for a dependency property in WPF.
    System.Xaml sets a CLR property to zero.
32. Items stay in document order behind a markup extension that waits for a reference, and when two members
    give one collection, where System.Xaml fails or changes the order.

About saving:

33. Where the output of System.Xaml does not load or loses a value or a name, the object reader writes another
    form: for named name scopes, keys of name scopes, keys that a hidden member has, collections and dictionaries in
    settable members, which always have their own element, and some objects that are constructed with arguments. A factory
    method of another generic type is an error.
    [Its README](src/reader/README.mbt.md#the-object-reader) lists them.

About markup compatibility:

34. 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.
35. An empty element tag means the same as a start tag and an end tag, also for `mc:Choice` and for an element that
    is replaced by its content.

About markup extensions and converters that wait:

36. A markup extension or a type converter can wait for a name also at the root and in the text of an `x:Key`, several
    of them can wait for one name until the end, and one can return a token that it kept. System.Xaml gives its
    token as the value or fails.

About root objects that the caller gives:

37. After initialization text has replaced the object, markup extensions and converters get the new one as the root.
    System.Xaml gives the old one when the root was asked for before.

About types with a description (the trait `Xaml`):

38. A value is created once from all its members, so a circle of references is an error. System.Xaml sets the members of an object
    that exists. Types registered by hand can be in a circle here too.
39. A member without a default is required, as `required` in C#. System.Xaml leaves what the constructor set.
40. An enumeration has the positions of its names as numbers, and a number without a name is an error.

The design of `add-xaml-foundation`, in `openspec/changes/archive/` of the repository, gives the reasons for each. What differs from WPF for dependency objects is in the
[README of the package `schema`](src/schema/README.mbt.md#differences-from-wpf).
