XAML for MoonBit: node streams, schema contexts, readers and writers that load and save object graphs
| Package | Purpose |
|---|---|
| moonrockz/xaml | The trait Xaml, from_text and to_text, 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 |
| moonrockz/xaml/reader | XAML readers: a XAML text reader with diagnostics and an object reader that saves objects |
| moonrockz/xaml/writer | XAML writers: a XAML text writer and an object writer that creates objects |
///|
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>
),
)
}| 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 |
///|
#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>
),
)
}| 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 |
///|
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]))
}///|
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, .. }),
],
)
}| 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 |
///|
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' />")
}| 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 |
| 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. 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 |
| 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 |
impl Xaml for XamlDecimalimpl Xaml for XamlTimeSpanpub struct Member[V] {
// private fields
}pub struct Members {
// private fields
}fn SaveSettings::new(require_explicit_content_visibility? : Bool, writer_mode? : WriterMode) -> SaveSettingspub struct XamlChoice[T] {
// private fields
}fn[T, V : Xaml] XamlChoice::add_case(self : XamlChoice[T], wrap : (V) -> T, unwrap : (T) -> V?) -> Unitfn[T] XamlChoice::add_constant(self : XamlChoice[T], key : XamlKey[T], value : T, is_case : (T) -> Bool) -> Unitfn[T, P] XamlChoice::add_object(self : XamlChoice[T], key : XamlKey[T], unwrap : (T) -> P?, describe : (XamlObjectType[P]) -> ((Members) -> T raise)) -> Unitpub struct XamlCodec[T] {
// private fields
}pub struct XamlKey[T] {
// private fields
}fn[T] XamlKey::object(self : XamlKey[T], describe : (XamlObjectType[T]) -> ((Members) -> T raise)) -> XamlCodec[T]pub struct XamlObjectType[T] {
// private fields
}fn[T, V : Xaml] XamlObjectType::add_list(self : XamlObjectType[T], name : String, get : (T) -> Array[V], content? : Bool) -> Member[Array[V]]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]]fn[T, V : Xaml] XamlObjectType::add_member(self : XamlObjectType[T], name : String, get : (T) -> V, default? : V, content? : Bool) -> Member[V]fn[T] XamlObjectType::add_name(self : XamlObjectType[T], name : String, get : (T) -> String) -> Member[String]fn[R : XamlReader] load(reader : R, schema_context : SchemaContext, settings? : LoadSettings) -> LoadResult raise XamlWriteErrorfn parse(text : String, schema_context : SchemaContext, settings? : LoadSettings) -> LoadResult raise XamlWriteErrorfn save(value : XamlValue, schema_context : SchemaContext, settings? : SaveSettings) -> String raise XamlWriteErrorfn version() -> StringInstall
Download zipXAML for MoonBit: node streams, schema contexts, readers and writers that load and save object graphs