# 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`.

```mbt check
///|
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`](../../xaml-codegen/README.mbt.md) 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

| Function | Member |
| --- | --- |
| `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`.

```mbt check
///|
#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:

| Function | Case |
| --- | --- |
| `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 |

```mbt check
///|
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:

```mbt check
///|
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

| Error | Meaning |
| --- | --- |
| `XamlWriteError::ReaderFailed` | Diagnostics: the document is not valid XAML, or a value cannot be written |
| `XamlWriteError::InvalidNode` | A value, a member or the root does not fit, with its place in the document |
| `CodecError::WrongDescription` | What 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:

```mbt check
///|
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](schema/README.mbt.md#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:

| Target | Write 10,000 | Read 10,000 | Write 100,000 | Read 100,000 |
| --- | --- | --- | --- | --- |
| js | 0.3 s | 0.15 s | 2.8 s | 1.4 s |
| wasm-gc | 0.3 s | 0.2 s | 2.6 s | 1.4 s |
| wasm | 0.9 s | 0.5 s | 8.6 s | 4.1 s |
| native | 0.8 s | 0.4 s | 7.7 s | 4.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

| Function | What 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](schema/README.mbt.md#types-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`](writer/README.mbt.md#load-settings). Only `parse` and `load` take its `root_object`.
`to_text` and `save` take `SaveSettings`:

| Argument of `SaveSettings::new` | Meaning |
| --- | --- |
| `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](../README.mbt.md#memory) says more.

## The packages behind it

`parse` is the [text reader](reader/README.mbt.md#the-text-reader) with the
[object writer](writer/README.mbt.md#the-object-writer), and `save` is the
[object reader](reader/README.mbt.md#the-object-reader) with the [text writer](writer/README.mbt.md#the-text-writer).
Their READMEs say how objects are created, which form each value gets, and what differs from System.Xaml.
