xaml

    XAML for MoonBit: node streams, schema contexts, readers and writers that load and save object graphs

    xaml
    xml
    serialization
    ui
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    17 hours ago
    Downloads
    12

    #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 describes a struct, reads a document, changes a value and writes it again. moonrockz/xaml-codegen 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, parse, load and save work, with shared objects and circles, names and references, constructor arguments, markup extensions, type converters, attached members and markup compatibility (mc:Ignorable). Your own markup extensions and type converters can wait for objects that come later in the document. A document can also fill an object that exists already. 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, set their dependency properties, add handlers to their events and have property paths as values. Only the package schema uses dependency objects, and you can use all packages without them.

    PackagePurpose
    moonrockz/xamlThe trait Xaml, from_text and to_text, parse, load and save, and version()
    moonrockz/xaml/nodesXAML node stream values, the reader and writer contracts, transfer and the balance rules
    moonrockz/xaml/schemaXAML schema context: registered types, members, directives, namespaces, type converters, value serializers and dependency objects
    moonrockz/xaml/readerXAML readers: a XAML text reader with diagnostics and an object reader that saves objects
    moonrockz/xaml/writerXAML writers: a XAML text writer and an 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 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 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 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 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:

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

    Forced by MoonBit, numbered last:

    1. Namespace declarations are sorted by ordinal prefix comparison, without culture-aware collation.
    2. 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:

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

    Owner decision about the text writer:

    1. 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:

    1. A second object in a member that holds one is an error before it is constructed, not after.
    2. Removed: the value of a directive that loading ignores is converted, as in System.Xaml.
    3. x:Arguments works on dictionary types, where System.Xaml asks for a key of each argument.
    4. 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.
    5. 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:

    1. 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 lists them.

    About markup compatibility:

    1. 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.
    2. 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:

    1. 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:

    1. 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):

    1. 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.
    2. A member without a default is required, as required in C#. System.Xaml leaves what the constructor set.
    3. 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.

    #Read and write values

    The package moonrockz/xaml.

    XAML as a serialization format: from_text creates a value of your type from a XAML document, and to_text writes one.

    Your type needs an implementation of the trait Xaml, which describes it once for both directions. The example is a task with smaller tasks in it. @xaml is the package moonrockz/xaml.

    ///|
    priv struct Task {
    id : String
    title : String
    done : Bool
    after : Task?
    tasks : Array[Task]
    }

    ///|
    let task_key : @xaml.XamlKey[Task] = @xaml.XamlKey::new("urn:tasks", "Task")

    ///|
    impl @xaml.Xaml for Task with fn xaml_codec() {
    task_key.object(t => {
    let id = t.add_name("Id", it => it.id)
    let title = t.add_member("Title", it => it.title)
    let done = t.add_member("Done", it => it.done, default=false)
    let after = t.add_member("After", it => it.after)
    let tasks = t.add_list("Tasks", it => it.tasks, content=true)
    m => {
    id: m.get(id),
    title: m.get(title),
    done: m.get(done),
    after: m.get(after),
    tasks: m.get(tasks),
    }
    })
    }

    ///|
    test "read, change and write" {
    let release : Task = @xaml.from_text(
    (
    #|<Task xmlns="urn:tasks" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Release">
    #| <Task Id="docs" Title="Write the docs" />
    #| <Task Title="Publish" After="{x:Reference docs}" />
    #|</Task>
    ),
    )
    guard release.tasks is [docs, { after: Some(after), .. } as publish] else {
    fail("no tasks")
    }
    // `After` has the same task as the list.
    assert_true(physical_equal(after, docs))
    let changed = { ..release, tasks: [docs, { ..publish, done: true, }], }
    inspect(
    @xaml.to_text(changed),
    content=(
    #|<Task xmlns="urn:tasks" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Release">
    #| <Task Id="docs" Title="Write the docs"/>
    #| <Task After="{x:Reference docs}" Done="True" Title="Publish"/>
    #|</Task>
    ),
    )
    }

    A description has three parts:

    1. XamlKey::new gives the XAML name of the type. Keep the key in a top-level let, because it is also the identity of the type.
    2. add_member and the functions like it name the members, each with the function that reads it from a value.
    3. The last function creates a value from all members. It runs when the document has given them, so a struct needs no mut fields.

    The program moonrockz/xaml-codegen can write the key and the implementation from attributes in the declaration of the type. This page shows what it writes, and what you need for a type that the attributes cannot describe.

    #Members

    FunctionMember
    add_member(name, get, default?, content?)A value of any type with a codec
    add_name(name, get)The name of the object, with which x:Reference finds it. It is "" when there is none
    add_list(name, get, content?)An Array
    add_map(name, get, content?)A Map, with the keys in x:Key

    • A member without a default is required, and a document without it is an error. An optional one, such as Task?, is None instead.
    • A member that equals its default is not written. Neither is an empty list or map, or an optional member with None.
    • content=true puts the member in the element itself. Other lists and maps are in an element such as <Task.Tasks>.

    Codecs are there for Bool, Byte, Int16, Int, Int64, Float, Double, Char, String, for XamlDecimal, XamlTimeSpan and XamlUri of the package schema, and for optional values. A list of lists has none, because the inner list would need a name in XAML: describe a struct with the inner list.

    #Enums and texts

    enumeration gives names to the values of an enum, and text describes a type by one text for the whole value. Both need Eq.

    ///|
    #derive(Eq)
    priv enum Priority {
    Low
    High
    }

    ///|
    let priority_key : @xaml.XamlKey[Priority] = @xaml.XamlKey::new(
    "urn:tasks", "Priority",
    )

    ///|
    impl @xaml.Xaml for Priority with fn xaml_codec() {
    priority_key.enumeration([("Low", Low), ("High", High)])
    }

    ///|
    #derive(Eq, Hash)
    priv struct Version {
    major : Int32
    minor : Int32
    }

    ///|
    let version_key : @xaml.XamlKey[Version] = @xaml.XamlKey::new(
    "urn:tasks", "Version",
    )

    ///|
    impl @xaml.Xaml for Version with fn xaml_codec() {
    version_key.text(
    parse=text => {
    guard text.split(".").map(part => part.to_owned()).to_array()
    is [major, minor] else {
    raise @schema.ValueError("a version is two numbers, such as 1.0")
    }
    { major: @string.parse_int(major), minor: @string.parse_int(minor), }
    },
    print=version => "\{version.major}.\{version.minor}",
    )
    }

    ///|
    priv struct Plan {
    priority : Priority
    releases : Map[Version, String]
    }

    ///|
    let plan_key : @xaml.XamlKey[Plan] = @xaml.XamlKey::new("urn:tasks", "Plan")

    ///|
    impl @xaml.Xaml for Plan with fn xaml_codec() {
    plan_key.object(t => {
    let priority = t.add_member("Priority", it => it.priority, default=Low)
    let releases = t.add_map("Releases", it => it.releases, content=true)
    m => { priority: m.get(priority), releases: m.get(releases), }
    })
    }

    ///|
    test "enums and texts" {
    let plan = {
    priority: High,
    releases: Map([({ major: 1, minor: 0, }, "Spring")]),
    }
    inspect(
    @xaml.to_text(plan),
    content=(
    #|<Plan xmlns="urn:tasks" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Priority="High">
    #| <x:String x:Key="1.0">Spring</x:String>
    #|</Plan>
    ),
    )
    }

    The keys of a map are primitives, enums with names or types with a text. The text of an enum follows Enum.Parse of .NET, so 1 means the second value too.

    #Different elements in one list

    XamlCodec::choice describes an enum whose cases hold values. The element selects the case, so each case needs a XAML type of its own. There are three kinds of cases:

    FunctionCase
    add_object(key, unwrap, describe)An element with the name of the key. The values of the case are its members
    add_constant(key, value, is_case)An empty element with the name of the key, for a case without values
    add_case(wrap, unwrap)The element or text of the one value that the case holds, whose type has a codec

    ///|
    priv enum Block {
    Image(width~ : Double, height~ : Double)
    Section(Array[Block])
    Rule
    }

    ///|
    let image_key : @xaml.XamlKey[Block] = @xaml.XamlKey::new("urn:pages", "Image")

    ///|
    let section_key : @xaml.XamlKey[Block] = @xaml.XamlKey::new(
    "urn:pages", "Section",
    )

    ///|
    let rule_key : @xaml.XamlKey[Block] = @xaml.XamlKey::new("urn:pages", "Rule")

    ///|
    impl @xaml.Xaml for Block with fn xaml_codec() {
    @xaml.XamlCodec::choice(c => {
    c.add_object(
    image_key,
    it => {
    if it is Image(width~, height~) {
    Some((width, height))
    } else {
    None
    }
    },
    t => {
    let width = t.add_member("Width", it => it.0)
    let height = t.add_member("Height", it => it.1)
    m => Image(width=m.get(width), height=m.get(height))
    },
    )
    c.add_object(
    section_key,
    it => if it is Section(blocks) { Some(blocks) } else { None },
    t => {
    let blocks = t.add_list("Blocks", it => it, content=true)
    m => Section(m.get(blocks))
    },
    )
    c.add_constant(rule_key, Block::Rule, it => it is Rule)
    })
    }

    ///|
    test "cases with members" {
    let block : Block = @xaml.from_text(
    (
    #|<Section xmlns="urn:pages">
    #| <Image Width="2" Height="3" />
    #| <Rule />
    #|</Section>
    ),
    )
    assert_true(block is Section([Image(width=2, height=3), Rule]))
    }

    unwrap gives the values of the case, which are a tuple when there are several, and the members read from them. The rest is as for XamlKey::object. One value in several places is one value again after reading, except for a case without values, which has no identity.

    add_case is for types that have an element of their own, or a text:

    ///|
    priv enum Entry {
    Task(Task)
    Plan(Plan)
    Note(String)
    }

    ///|
    impl @xaml.Xaml for Entry with fn xaml_codec() {
    @xaml.XamlCodec::choice(c => {
    c.add_case(it => Entry::Task(it), it => {
    if it is Task(x) {
    Some(x)
    } else {
    None
    }
    })
    c.add_case(it => Entry::Plan(it), it => {
    if it is Plan(x) {
    Some(x)
    } else {
    None
    }
    })
    c.add_case(it => Entry::Note(it), it => {
    if it is Note(x) {
    Some(x)
    } else {
    None
    }
    })
    })
    }

    ///|
    priv struct Board {
    entries : Array[Entry]
    }

    ///|
    let board_key : @xaml.XamlKey[Board] = @xaml.XamlKey::new("urn:tasks", "Board")

    ///|
    impl @xaml.Xaml for Board with fn xaml_codec() {
    board_key.object(t => {
    let entries = t.add_list("Entries", it => it.entries, content=true)
    m => { entries: m.get(entries), }
    })
    }

    ///|
    test "different elements" {
    let board : Board = @xaml.from_text(
    (
    #|<Board xmlns="urn:tasks" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    #| <x:String>Remember the changelog</x:String>
    #| <Task Title="Publish" />
    #| <Plan />
    #|</Board>
    ),
    )
    assert_true(
    board.entries
    is [
    Note("Remember the changelog"),
    Task({ title: "Publish", .. }),
    Plan({ priority: Low, .. }),
    ],
    )
    }

    #Errors

    ErrorMeaning
    XamlWriteError::ReaderFailedDiagnostics: the document is not valid XAML, or a value cannot be written
    XamlWriteError::InvalidNodeA value, a member or the root does not fit, with its place in the document
    CodecError::WrongDescriptionWhat is wrong in the descriptions, such as two members with one name. Every call raises it, whatever is in the document

    The function that creates a value can raise an error too, to reject members that do not go together:

    ///|
    priv struct Range {
    start : Int32
    end : Int32
    }

    ///|
    let range_key : @xaml.XamlKey[Range] = @xaml.XamlKey::new("urn:tasks", "Range")

    ///|
    impl @xaml.Xaml for Range with fn xaml_codec() {
    range_key.object(t => {
    let start = t.add_member("Start", it => it.start)
    let end = t.add_member("End", it => it.end)
    m => {
    let range = { start: m.get(start), end: m.get(end), }
    guard range.start <= range.end else {
    raise @schema.ValueError("the end is before the start")
    }
    range
    }
    })
    }

    ///|
    /// The message of the error in `text` and the part of it that the error is about.
    fn range_error(text : String) -> (String, String) raise {
    try {
    let _ : Range = @xaml.from_text(text)
    } catch {
    @nodes.XamlWriteError::InvalidNode(message~, span=Some(span), ..) =>
    (message, text[span.start.offset:span.end.offset].to_owned())
    error => raise error
    } noraise {
    _ => fail("no error")
    }
    }

    ///|
    test "errors with their places" {
    let (_, place) = range_error("<Range xmlns='urn:tasks' Start='1' End='x' />")
    assert_eq(place, "x")
    let (message, place) = range_error(
    "<Range xmlns='urn:tasks' Start='2' End='1' />",
    )
    assert_true(message.contains("the end is before the start"))
    assert_eq(place, "<Range xmlns='urn:tasks' Start='2' End='1' />")
    }

    #What comes back

    A value that to_text writes is equal after from_text. One value in several places is written once, with references to it, and is one value again. These do not come back:

    • Values that refer to each other in a circle. to_text writes them, and from_text gives an error, because it creates each value after those in it. Types registered by hand can be in a circle.
    • Values that nest deeper than max_depth of LoadSettings, which is 512, unless you read with a higher limit.
    • An empty name of a value in several places. to_text has to give it one, such as __ReferenceID0, and from_text puts it in the name member. A type without add_name has no such member.

    #Speed

    Times for a task with many smaller tasks of different titles, in a release build with MoonBit 1.0.0-rc1 on a desktop computer:

    TargetWrite 10,000Read 10,000Write 100,000Read 100,000
    js0.3 s0.15 s2.8 s1.4 s
    wasm-gc0.3 s0.2 s2.6 s1.4 s
    wasm0.9 s0.5 s8.6 s4.1 s
    native0.8 s0.4 s7.7 s4.1 s

    to_text finds a value again by its primitive and enum members. When these are equal in many different values of one type, it compares each with the others: 10,000 equal tasks take 1 to 5 s. A name or any other member that differs avoids it.

    A schema context is built once for each key. A choice has no key, so from_text and to_text build one at each call when the root is a choice, which takes about a millisecond.

    #Functions

    FunctionWhat it does
    from_text(text, settings?)Creates a value from a document
    to_text(value, settings?)Writes a value as an indented document with LF line breaks
    parse(text, context, settings?)Creates the objects of a document with types that are registered by hand. The result has the root and root_name_scope, which finds named objects
    load(reader, context, settings?)Does the same for the nodes of any reader
    save(value, context, settings?)Writes an object and everything that it reaches, as to_text does

    from_text, parse and load take LoadSettings. Only parse and load take its root_object. to_text and save take SaveSettings:

    Argument of SaveSettings::newMeaning
    writer_mode?RoundTrip, the default, keeps every text, and gives an error where no document can. SystemXaml writes what System.Xaml writes, which can lose empty texts and white space
    require_explicit_content_visibility?Writes a collection without a setter only when its member says so. Off by default. With it to_text leaves out lists and maps

    There is no result after an error of parse or load, but constructors and setters that ran before it keep their effects, also on an object in root_object.

    A graph of objects that save writes loads again as an equal one, with shared objects and circles. These do not:

    • An object that its own constructor arguments need. The document is saved and does not load, as in System.Xaml.
    • Objects that nest deeper than max_depth.
    • Values that are not in registered members, items or entries.
    • An object in two name scopes, which is written for each of them and loads as two objects.

    save knows the objects and not the document that they came from. It writes the value that a markup extension gave and not the extension, and no event handlers, xml:base or x:Class.

    On native and wasm, objects that refer to each other in a circle are not freed until you break the circle. Memory says more.

    #The packages behind it

    parse is the text reader with the object writer, and save is the object reader with the text writer. Their READMEs say how objects are created, which form each value gets, and what differs from System.Xaml.

    LoadSettings

    The settings of a load, in the style of System.Xaml XamlObjectWriterSettings.

    WriterMode

    What a XAML text writer does where the output of System.Xaml XamlXmlWriter would not be read as the same nodes (design D26).

    Xaml

    pub(open) trait Xaml {
    fn xaml_codec() -> XamlCodec[Self]
    }

    A type whose values XAML documents can hold. An implementation describes the type with an XamlKey in a top-level let.
    impl Xaml for Bool
    impl Xaml for Byte
    impl Xaml for Char
    impl Xaml for Int
    impl Xaml for Int16
    impl Xaml for Int64
    impl Xaml for Float
    impl Xaml for Double
    impl Xaml for String
    impl Xaml for Option[T]

    CodecError

    pub(all) suberror CodecError {
    WrongDescription(problems~ : ReadOnlyArray[String])
    } derive(Eq,
    Debug
    )

    What is wrong in the descriptions of the types that from_text or to_text needs.

    CodecError::message

    fn CodecError::message(self : CodecError) -> String

    LoadResult

    What parse and load give.

    On native and wasm, which count references, objects that refer to each other in a circle are freed only when the caller breaks the circle.

    Member

    pub struct Member[V] {
    // private fields
    }

    A member of a described type, with values of type V.

    Members

    pub struct Members {
    // private fields
    }

    What a document gives for the members of an object.

    Members::get

    fn[V] Members::get(self : Members, member_ : Member[V]) -> V raise

    The value of member_, or its default when the document does not give it.

    SaveSettings

    pub struct SaveSettings {
    require_explicit_content_visibility : Bool
    writer_mode :
    WriterMode

    }

    The settings of save.

    SaveSettings::new

    fn SaveSettings::new(require_explicit_content_visibility? : Bool, writer_mode? :
    WriterMode
    ) -> SaveSettings

    XamlChoice

    pub struct XamlChoice[T] {
    // private fields
    }

    The cases of a choice, for the function that XamlCodec::choice takes.

    XamlChoice::add_case

    fn[T, V : Xaml] XamlChoice::add_case(self : XamlChoice[T], wrap : (V) -> T, unwrap : (T) -> V?) -> Unit

    Add the case that is written as the value of type V that it holds. wrap puts one in the enum, and unwrap takes it out or gives None for another case. Each case needs XAML types of its own.

    XamlChoice::add_constant

    fn[T] XamlChoice::add_constant(self : XamlChoice[T], key : XamlKey[T], value : T, is_case : (T) -> Bool) -> Unit

    Add a case without values, which is an empty element with the XAML name of key. value is the case, and is_case says whether a value is it. Such values are all the same in XAML, so they are never written as references.

    XamlChoice::add_object

    fn[T, P] XamlChoice::add_object(self : XamlChoice[T], key : XamlKey[T], unwrap : (T) -> P?, describe : (XamlObjectType[P]) -> ((Members) -> T raise)) -> Unit

    Add a case that is an element of its own, with the XAML name of key.

    unwrap gives the values that the case holds, or None for another case. Several values can be a tuple. describe adds the members that read from them, and gives the function that creates the case, as for XamlKey::object.

    XamlCodec

    pub struct XamlCodec[T] {
    // private fields
    }

    How values of T become XAML, and how they are created from it. XamlKey and XamlCodec::choice make codecs.

    XamlCodec::choice

    fn[T] XamlCodec::choice(describe : (XamlChoice[T]) -> Unit) -> XamlCodec[T]

    Describe an enum whose cases hold values. A member or list with it takes the XAML types of all cases, and the type of an object selects the case. describe adds the cases.

    XamlKey

    pub struct XamlKey[T] {
    // private fields
    }

    The XAML name of T and the identity of its values. Keep it in a top-level let, because each call of XamlKey::new gives another identity.

    XamlKey::enumeration

    fn[T : Eq] XamlKey::enumeration(self : XamlKey[T], names : ArrayView[(String, T)]) -> XamlCodec[T]

    Describe an enum without payloads by the names of its values.

    The text rules are those of .NET Enum.Parse. So a text can also be the position of a value in names, and Low, High is the number that has the bits of both positions. A number without a name is an error.

    XamlKey::new

    fn[T] XamlKey::new(namespace_uri : String, name : String) -> XamlKey[T]

    The key of the XAML type name in the namespace namespace_uri.

    XamlKey::object

    fn[T] XamlKey::object(self : XamlKey[T], describe : (XamlObjectType[T]) -> ((Members) -> T raise)) -> XamlCodec[T]

    Describe a struct. describe adds the members and gives the function that creates a value from them. This function can raise an error to reject the members, and reading then fails with its message.

    XamlKey::text

    fn[T : Eq] XamlKey::text(self : XamlKey[T], parse~ : (String) -> T raise, print~ : (T) -> String raise) -> XamlCodec[T]

    Describe a type whose values each have one text, such as 1,2. print gives the text, and parse the value or an error. Equal values are the same in XAML, so they are never written as references.

    XamlObjectType

    pub struct XamlObjectType[T] {
    // private fields
    }

    The members of a XAML type, for the function that XamlKey::object or XamlChoice::add_object takes. Each method adds a member and gives what reads its value from the Members of an object.

    XamlObjectType::add_list

    fn[T, V : Xaml] XamlObjectType::add_list(self : XamlObjectType[T], name : String, get : (T) -> Array[V], content? : Bool) -> Member[Array[V]]

    Add the list name. It is empty when the document does not give it, and an empty list is not written. With content, the elements in the element itself are its items.

    XamlObjectType::add_map

    fn[T, K : Xaml + Eq + Hash, V : Xaml] XamlObjectType::add_map(self : XamlObjectType[T], name : String, get : (T) -> Map[K, V], content? : Bool) -> Member[Map[K, V]]

    Add the map name, whose entries have their keys in x:Key. The keys are primitives, enumerations or types with a text. The map is empty when the document does not give it, and an empty one is not written. With content, the elements in the element itself are its entries.

    XamlObjectType::add_member

    fn[T, V : Xaml] XamlObjectType::add_member(self : XamlObjectType[T], name : String, get : (T) -> V, default? : V, content? : Bool) -> Member[V]

    Add the member name, which get reads from a value.

    A document that does not give it has default, and a value that equals default is not written. Without a default the member is required, or None if it is optional. With content, what stands in the element itself is this member.

    XamlObjectType::add_name

    fn[T] XamlObjectType::add_name(self : XamlObjectType[T], name : String, get : (T) -> String) -> Member[String]

    Add the member name with the name of the object, which is "" when it has none. x:Name gives it too, and x:Reference finds the object by it.

    from_text

    fn[T : Xaml] from_text(text : String, settings? :
    LoadSettings
    ) -> T raise

    Read the XAML document text as a value of type T.

    It raises what parse raises: ReaderFailed when the document is not valid XAML, and InvalidNode with the place in text when a value cannot be created or the root is of another type. CodecError is for a description that cannot work.

    load

    Create the objects that the nodes of reader describe, as System.Xaml XamlServices.Load does. The errors are those of parse, with the places that the reader gives.

    The depth limits and the understood namespaces of the settings are for the text reader that parse makes, so they have no effect here. To copy a graph of objects, give a XamlObjectReader with the setting construction_first.

    parse

    Create the objects of the XAML document text, as System.Xaml XamlServices.Parse does.

    It raises ReaderFailed with the diagnostics when the document is not valid XAML, and InvalidNode with the place in text when the objects cannot be created. There is no result then, but the constructors and setters that ran before the error keep their effects.

    save

    Write value and the objects that it reaches as a XAML document, as System.Xaml XamlServices.Save does. Elements are on lines of their own, with two spaces for each level and LF line breaks, and there is no XML declaration.

    It raises ReaderFailed when a graph cannot be described, such as one with an object that nothing constructs, and InvalidNode when a value cannot be written, such as a text with a character that XML does not allow.

    to_text

    fn[T : Xaml] to_text(value : T, settings? : SaveSettings) -> String raise

    Write value as a XAML document, as save writes it. A value that is in several places is written once, with references to it.

    It raises what save raises, and CodecError for a description that cannot work.

    version

    fn version() -> String

    The version of the moonrockz/xaml module. mise run validate:versions keeps it equal to the version of the root moon.mod.