#Property paths

    The package moonrockz/dependency-object/path.

    Property paths with the syntax and the behavior of WPF's PropertyPath, such as Customer.Orders[0].Total. A path names a value that you reach from an object through its properties. You can read and set it, and hear of its changes. @path in the examples is this package, and @dependency is moonrockz/dependency-object.

    #An order with a price

    A page shows an order. Page.Order can be null, and an order has a list of lines. The order and its lines are ordinary MoonBit objects, whose members are registered for paths, because MoonBit has no reflection:

    ///|
    let page_type : @dependency.OwnerType = try! @dependency.register_owner_type(
    "Page",
    )

    ///|
    let order_key : @dependency.ValueKey[Order?] = @dependency.ValueKey::new(
    "Order?",
    )

    ///|
    let order : @dependency.DependencyProperty[Order?] = try! @dependency.register(
    "Order",
    page_type,
    order_key,
    default_value=None,
    )

    ///|
    /// The lines have texts and prices.
    priv struct Order {
    lines : Array[(String, Int32)]
    /// Functions to call after a change.
    handlers : Map[Int32, () -> Unit raise]
    mut added : Int32
    }

    ///|
    impl Eq for Order with fn equal(self, other) {
    physical_equal(self, other)
    }

    ///|
    fn Order::new(lines : Array[(String, Int32)]) -> Order {
    { lines, handlers: Map([]), added: 0, }
    }

    ///|
    fn Order::set_price(self : Order, i : Int32, price : Int32) -> Unit raise {
    self.lines[i] = (self.lines[i].0, price)
    for handler in self.handlers.values().to_array() {
    handler()
    }
    }

    ///|
    /// Call `handler` after each change, until the returned function is called.
    fn Order::subscribe(self : Order, handler : () -> Unit raise) -> () -> Unit {
    let number = self.added
    self.added += 1
    self.handlers[number] = handler
    () => self.handlers.remove(number)
    }

    ///|
    fn init {
    try! register_order()
    }

    ///|
    fn register_order() -> Unit raise {
    // `Order?` can be null, and has the members of `Order`.
    let one : @dependency.ValueKey[Order] = @dependency.ValueKey::new("Order")
    @path.register_optional(order_key, one)
    let order = @path.register_value_type(one)
    order.add_property("Count", @dependency.int_key, get=order => {
    order.lines.length()
    })
    // `[0]` is the price of the first line.
    order.add_indexer(
    @path.int_parameter,
    @dependency.int_key,
    get=(order, i) => {
    guard order.lines.get(i) is Some((_, price)) else { fail("no line \{i}") }
    price
    },
    set=(order, i, price) => order.set_price(i, price),
    subscribe=(order, changed) => order.subscribe(changed),
    )
    }

    ///|
    test "read and set the price of an order" {
    let page = @dependency.DependencyObject::new(page_type)
    let source = @dependency.object_key.wrap(page)
    let price = @path.parse("Order[0]")
    page.set_value(order, Some(Order::new([("Tea", 3)])))
    assert_eq(price.get(source).read(@dependency.int_key), Some(3))
    price.set(source, @dependency.int_key.wrap(4))
    assert_eq(price.get(source).read(@dependency.int_key), Some(4))
    }

    ///|
    test "observe the price of an order" {
    let page = @dependency.DependencyObject::new(page_type)
    let log = []
    let price = @path.parse("Order[0]")
    let observer = price.observe(@dependency.object_key.wrap(page), result => {
    log.push(result.read(@dependency.int_key))
    })
    let first = Order::new([("Tea", 3)])
    page.set_value(order, Some(first))
    first.set_price(0, 4)
    page.set_value(order, Some(Order::new([("Coffee", 5)])))
    first.set_price(0, 6)
    observer.dispose()
    assert_eq(log, [None, Some(3), Some(4), Some(5)])
    }

    #The text of a path

    TextWhat it is
    Child.Widththe property Width of the value of the property Child
    Order[0], Cells[1,2]the indexer, with one or more arguments
    [0]the indexer of the source
    (Grid.Row), Child.(local:Grid.Row)a property of the type Grid, such as an attached property
    ., or nothingthe source itself

    White space around a name means nothing.

    parse reads the text, and raises a PathParseError with a code, a message and the place in the text:

    ///|
    test "an error in a path" {
    let error = try @path.parse("Order[0") catch {
    error => error.to_string()
    } noraise {
    _ => fail("expected an error")
    }
    inspect(error, content="an indexer has no `]`, at [5, 7) of the path")
    }

    #Types in a path

    A type such as Grid in (Grid.Row) is found by a PathResolver. It gets the prefix, if there is one, and the name. A path without types needs no resolver.

    ///|
    let grid_type : @dependency.OwnerType = try! @dependency.register_owner_type(
    "Grid",
    )

    ///|
    let row : @dependency.DependencyProperty[Int32] = try! @dependency.register_attached(
    "Row",
    grid_type,
    @dependency.int_key,
    default_value=0,
    )

    ///|
    let resolver : @path.PathResolver = @path.PathResolver::new(
    owner=(prefix, name) => {
    match (prefix, name) {
    (None, "Grid") => grid_type
    (None, _) => raise UnknownType
    _ => raise UnknownPrefix
    }
    },
    argument_type=(_, name) => {
    guard name is "String" else { raise UnknownType }
    Some(
    @path.ArgumentType::new("String", text => {
    @dependency.string_key.wrap(text)
    }),
    )
    },
    )

    ///|
    test "a type in a path" {
    let path = @path.parse("( Grid . Row )", resolver~)
    guard path.segments()[:] is [Qualified(Dependency(found), ..)] else {
    fail("not a property")
    }
    assert_eq(found, row.info())
    inspect(path, content="(Grid.Row)")
    }

    The property belongs to the type or to one from which it derives. A dependency property comes before a registered one.

    The paths of a XAML document use the prefixes of the document, see moonrockz/xaml/schema.

    Parentheses without a dot only mark a name: (Width) is Width. In them a name can have all characters, also white space, so ( Width ) is another name, and () is the empty one.

    #Arguments

    An argument is text, which the indexer converts. ^ makes the next character a part of the text, such as a , or a bracket, or white space at the beginning. An argument can also have a type, which argument_type of the resolver finds:

    ///|
    /// The arguments of the indexer in `text`.
    fn arguments(text : String) -> Array[String] raise {
    guard @path.parse(text, resolver~).segments()[:] is [Indexer(arguments)] else {
    fail("not an indexer")
    }
    arguments
    .iter()
    .map(argument => {
    match argument {
    Text(text) => text
    Typed(type_name~, text~, ..) => "\{type_name}: \{text}"
    }
    })
    .collect()
    }

    ///|
    test "arguments" {
    assert_eq(arguments("[a, b]"), ["a", "b"])
    assert_eq(arguments("[a^,b]"), ["a,b"])
    assert_eq(arguments("[(String)a, b]"), ["String: a", "b"])
    // Brackets nest one level deep.
    assert_eq(arguments("[a[1,2]]"), ["a[1,2]"])
    // Escaped white space stays when it comes last, but not in a typed argument.
    assert_eq(arguments("[^ a^ ]"), [" a "])
    assert_eq(arguments("[^ a^ ]"), [" a"])
    assert_eq(arguments("[(String)^ a^ ]"), ["String: a"])
    // One empty argument.
    assert_eq(arguments("[ ]"), [""])
    // Text, because there is no value after it, or no type in it.
    assert_eq(arguments("[(a)]"), ["(a)"])
    assert_eq(arguments("[()]"), ["()"])
    }

    When argument_type gives None, the argument is the text as it was written, with the parentheses. It raises an error when the type has to exist.

    print gives a text that parse reads as an equal path. print_with lets a PathNamer name the types, for a text that will have other prefixes. Two paths are equal when their names, the properties of their types, and their arguments are, so the prefixes do not matter.

    #Members of values

    A path steps into a dependency object without any registration, and finds its dependency properties by name, as in Child.Width. All other members are registered, usually once when the program starts:

    FunctionWhose members it registers
    register_value_typethose of a MoonBit type, which its key stands for
    register_object_typethose of the dependency objects of an owner type, and of the types that derive from it. The functions get the object, whose host is the control
    register_optionalnone. It makes None null, and gives the other values of the optional type the members of the type inside

    add_property and add_indexer add the members. A type has one indexer, and Parameters says what arguments it takes: int_parameter, string_parameter, one of Parameters::new with your own conversion, or several of them with then:

    ///|
    priv struct Sheet {
    cells : Map[(String, Int32), String]
    }

    ///|
    let sheet_key : @dependency.ValueKey[Sheet] = @dependency.ValueKey::by_identity(
    "Sheet",
    )

    ///|
    fn init {
    try! @path.register_value_type(sheet_key).add_indexer(
    @path.string_parameter.then(@path.int_parameter),
    @dependency.string_key,
    get=(sheet, at) => sheet.cells.get_or_default(at, ""),
    set=(sheet, at, text) => sheet.cells[at] = text,
    )
    }

    ///|
    test "an indexer with two parameters" {
    let sheet = sheet_key.wrap({ cells: Map([]), })
    let path = @path.parse("[B, 2]")
    path.set(sheet, @dependency.string_key.wrap("total"))
    assert_eq(path.get(sheet).read(@dependency.string_key), Some("total"))
    }

    A control has a dependency object in a field. Name it with inner, so that paths also find the members of the object on a value of the control. A path also looks inside the value that inner gives, and so on, so this must come to an end: a path into a value that is inside itself runs forever.

    ///|
    priv struct Slider {
    object : @dependency.DependencyObject
    }

    ///|
    let slider_key : @dependency.ValueKey[Slider] = @dependency.ValueKey::by_identity(
    "Slider",
    )

    ///|
    fn init {
    ignore(
    try! @path.register_value_type(slider_key, inner=slider => {
    Some(@dependency.object_key.wrap(slider.object))
    }),
    )
    }

    ///|
    test "a property of the object of a control" {
    let slider = { object: @dependency.DependencyObject::new(page_type), }
    slider.object.set_value(row, 2)
    let path = @path.parse("(Grid.Row)", resolver~)
    assert_eq(
    path.get(slider_key.wrap(slider)).read(@dependency.int_key),
    Some(2),
    )
    }

    A name is a dependency property of the object, or else a registered property: of the value, then of what is inside it, then of the type of the object, and then of its base types. The indexer is found in the same order. A path with a type, such as (Grid.Row), reads a dependency property of any object, as get_value does, but a registered one only of an object of the type.

    #Read

    get raises no error. Its result is a value or a failure:

    ///|
    test "a path that does not end" {
    let page = @dependency.DependencyObject::new(page_type)
    let source = @dependency.object_key.wrap(page)
    guard @path.parse("Order.Count").get(source) is Failure(failure) else {
    fail("expected a failure")
    }
    assert_true(failure.reason is NullValue)
    assert_eq(failure.segment, 1)
    inspect(failure, content="at `Count`: the value before it is null")
    // The order itself is null, and a value.
    guard @path.parse("Order").get(source) is Value(value) else {
    fail("expected a value")
    }
    assert_true(order_key.unwrap(value) is Some(None))
    }

    PathResult::read gives the value for a key, and None when there is a failure or a value of another type. A PathFailure has the segment, its place in the text, a message and a reason:

    ReasonWhat is wrong
    UnknownMemberthe value has no such property, or no indexer
    CannotStepIntothe type of the value is not registered, or a path with a type needs a dependency object
    NullValuethe value is null, and the path goes on
    InvalidArgumentthe arguments do not fit the indexer
    Raisedthe getter raised the error that the reason has
    RegistryMismatchthe object belongs to another registry than the path
    ReadOnly, InvalidValueonly in set: the member has no setter, or values of another type

    #Set

    set sets the local value of a dependency property, or calls the setter of a registered member. When the path does not reach the member, or the member does not take the value, it raises a PathSetError and changes nothing. An error of set_value or of the setter is raised as it is.

    #Observe

    observe calls its callback with the result of get, and again after each change on the path: of the value at the end, and of one before it, after which the observer follows the path from there and watches the new objects. It also hears when a path that failed works again.

    • A dependency property reports its changes by itself. A registered member needs subscribe, which calls the given function after each change, and returns a function that ends this. Without it, the observer reads the member again only when a value before it changes.
    • The callback gets a result for each change, also when it is equal to the last one.
    • When the callback changes the path, it is called again at once. After each change, the last result that it got is what get gives, as long as every member on the path reports its changes and no handler raises an error.
    • When a value before the end is replaced, and code that runs before the observer changes the old value, the callback still gets this change, as in WPF.
    • After dispose, the observer calls no getter any more, also when a getter, a subscribe or the function that ends one disposes it.
    • An error of the callback reaches the code that made the change. When the first call fails, observe raises the error and observes nothing.
    • Changes from the callback nest at most nesting_limit levels deep, together with all others.

    #Memory

    An observer and the objects on its path hold each other. js and wasm-gc free them together. native and wasm count references and never free such a circle, so call dispose before you drop the observer. After that it holds nothing.

    What is registered lives as long as its registry, as with the functions of the metadata of a property. A dependency object and a path hold their registry. So on native and wasm, a registered function must not hold an object or a path of a registry of your own, or nothing frees the registry. Use the value that the function gets.

    #Registries

    A path works with one registry, the one of the process unless you pass another one with registry~ to parse. The types that the resolver finds have to be of this registry. The functions that register members take a registry too, and a path fails on an object of another one.

    #Differences from WPF

    MoonBit forces these:

    1. Members are registered. WPF finds them by reflection. A type in a path is an owner type, so there is no (sys:String.Length).
    2. A type has one indexer. WPF has overloads and named indexers.
    3. Values are AnyValues, and null is a None. In WPF a value is an object, and each reference can be null.
    4. A member has subscribe. WPF listens to INotifyPropertyChanged and INotifyCollectionChanged.
    5. subscribe returns a function that ends it. .NET compares the handlers, and functions of MoonBit have no equality.
    6. An observer holds the objects on its path. WPF holds them weakly, and MoonBit has no weak references.
    7. Typed arguments are equal when their types and texts are. An AnyValue has no equality.
    8. A path belongs to a registry. WPF has one set of types for the process.

    These follow Avalonia and MAUI, which agree with each other and not with WPF:

    • A..B, A. and A[] are errors. WPF accepts them.
    • [()] and [()x] are the texts () and ()x. In WPF they are the empty text and x.

    These parts of the syntax of WPF are missing, and are errors:

    • /, the current item of a collection view. WPF also takes the current item when a path names a property that the collection does not have, and this package does not.
    • Path parameters, such as (0) and [(0)].
    • Generic types and static properties in parentheses.
    • A name that starts with #, which WPF reads as any other name. Avalonia uses it for the names of elements.

    PathParseError

    pub(all) suberror PathParseError {
    PathParseError(code~ : PathErrorCode, message~ : String, start~ : Int, end~ : Int)
    } derive(Eq,
    Debug
    )

    Why a text is no path. start and end are the part of the text that is wrong, in UTF-16 code units.

    PathParseError::to_string

    fn PathParseError::to_string(self : PathParseError) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    PathResolveError

    pub(all) suberror PathResolveError {
    UnknownPrefix
    UnknownType
    }

    Why a resolver cannot find a type.

    PathSetError

    pub(all) suberror PathSetError {
    SourcePath
    CannotSet(PathFailure)
    }

    Why a path did not set a value. Nothing was written then.

    PathSetError::to_string

    fn PathSetError::to_string(self : PathSetError) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    ArgumentType

    pub struct ArgumentType {
    // private fields
    }

    A type that an argument of an indexer can have.

    ArgumentType::new

    fn ArgumentType::new(name : String, parse : (String) ->
    AnyValue
    raise) -> ArgumentType

    name is the identity of the type: arguments are equal when their types have the same name and their texts are equal. parse makes the value of a text.

    FailureReason

    pub(all) enum FailureReason {
    UnknownMember
    CannotStepInto
    NullValue
    RegistryMismatch
    InvalidArgument
    ReadOnly
    InvalidValue
    Raised(Error)
    }

    Why a segment does not work.

    Parameters

    pub struct Parameters[P] {
    // private fields
    }

    The parameters of an indexer, whose arguments together are a P.

    Parameters::new

    fn[P] Parameters::new(key :
    ValueKey
    [P], parse : (String) -> P raise) -> Parameters[P]

    One parameter with values of key. parse makes the value of an argument that is text. An argument with a type has to have a value of key.

    Parameters::then

    fn[P, Q] Parameters::then(self : Parameters[P], other : Parameters[Q]) -> Parameters[(P, Q)]

    These parameters and then those of other.

    PathArgument

    pub enum PathArgument {
    Text(String)
    Typed(written~ : String, type_name~ : String, text~ : String, value~ :
    AnyValue
    )
    }

    An argument of an indexer.
    impl Eq for PathArgument

    PathErrorCode

    pub(all) enum PathErrorCode {
    PathSyntax
    UnmatchedParenthesis
    UnclosedIndexer
    EmptySegment
    EmptyIndexer
    UnsupportedSyntax
    UnknownPrefix
    UnknownOwner
    RegistryMismatch
    UnknownProperty
    UnknownArgumentType
    ArgumentConversion
    } derive(Eq,
    Debug
    )

    What is wrong with the text of a path.

    PathFailure

    pub struct PathFailure {
    segment : Int
    start : Int
    end : Int
    reason : FailureReason
    message : String
    }

    The first segment of a path that does not work, and why.
    impl Show for PathFailure

    PathFailure::to_string

    fn PathFailure::to_string(self : PathFailure) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    PathMember

    What a segment such as (Grid.Row) names.

    PathMember::name

    fn PathMember::name(self : PathMember) -> String

    PathMember::owner_type

    The type on which the member was registered, not one that add_owner added or that derives from it.

    PathNamer

    pub struct PathNamer {
    // private fields
    }

    Names the types in a path that is printed for another place than the one for which it was written, such as a XAML document with other prefixes.

    PathNamer::new

    fn PathNamer::new(owner~ : (
    OwnerType
    ) -> String raise, argument_type~ : (String) -> String raise) -> PathNamer

    owner gives the text for the owner type on which a member was registered, and argument_type that for the argument type with this name.

    PathObserver

    pub struct PathObserver {
    // private fields
    }

    Watches what a path gives for a source, until dispose.

    PathObserver::dispose

    fn PathObserver::dispose(self : PathObserver) -> Unit

    Stop watching. The callback is not called any more, also not for a change that is being notified now.

    PathResolver

    pub struct PathResolver {
    // private fields
    }

    Finds the types that a path names. Both functions get the prefix, when there is one, and the name.

    PathResolver::new

    fn PathResolver::new(owner? : (String?, String) ->
    OwnerType
    raise PathResolveError, argument_type? : (String?, String) -> ArgumentType? raise PathResolveError) -> PathResolver

    owner finds owner types, as in (local:Grid.Row), and argument_type the types of arguments, as in [(sys:Int32)42].

    An argument whose type is None is the text as it was written, as in WPF. Without argument_type, all arguments are text.

    PathResult

    pub(all) enum PathResult {
    Value(
    AnyValue
    )
    Failure(PathFailure)
    }

    What a path gives for a source.

    PathResult::read

    The value, when there is one and it has this key.

    PathSegment

    pub enum PathSegment {
    Property(String)
    Qualified(PathMember, written~ : String)
    Indexer(ReadOnlyArray[PathArgument])
    }

    A step of a path. written is a type as the path names it, which does not matter for the equality.
    impl Eq for PathSegment

    PathType

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

    A type whose values have members for paths. .NET finds these by reflection, which MoonBit does not have.

    PathType::add_indexer

    fn[T, P, V] PathType::add_indexer(self : PathType[T], parameters : Parameters[P], key :
    ValueKey
    [V], get~ : (T, P) -> V raise, set? : (T, P, V) -> Unit raise, subscribe? : (T, () -> Unit raise) -> (() -> Unit)) -> Unit raise
    DependencyError

    Add the indexer, with items of key. A type can have one.

    parameters says which arguments it takes, such as int_parameter. The rest is as for add_property. get and set also get the arguments, and subscribe is for a change of any item.

    PathType::add_property

    fn[T, V] PathType::add_property(self : PathType[T], name : String, key :
    ValueKey
    [V], get~ : (T) -> V raise, set? : (T, V) -> Unit raise, subscribe? : (T, () -> Unit raise) -> (() -> Unit)) -> Unit raise
    DependencyError

    Add a property with values of key.

    • get reads it. When it raises an error, the path has no value.
    • set writes it. Without it, the property is read-only.
    • subscribe calls the given function after each change of the property, and returns a function that ends this. Without it, an observer does not hear of the changes.

    PropertyPath

    pub struct PropertyPath {
    // private fields
    }

    A way from a value to another one, through properties and indexers, such as Child.(Grid.Row) or Items[0].Name.

    parse makes one. Two paths are equal when they have the same registry and equal segments, also when they were written differently.
    impl Eq for PropertyPath

    PropertyPath::get

    The value at the end of the path from source, or the first segment that does not work. This raises no errors.

    Most sources are dependency objects, which object_key wraps. A last segment that reads the None of an optional type gives this value.

    PropertyPath::observe

    fn PropertyPath::observe(self : PropertyPath, source :
    AnyValue
    , callback : (PathResult) -> Unit raise) -> PathObserver raise

    Call callback with what the path gives for source now, and again after each change on the path. The observer hears of the changes of dependency properties, and of registered members that have subscribe.

    After a change, the observer reads the changed member again, follows the path from there, and calls callback with the result, also when it is equal to the last one. An error of callback reaches the code that made the change, and the observer goes on. An error of the first call is raised here, and nothing is observed.

    The observer and the objects on the path hold each other. Call dispose before you drop them, because native and wasm do not free such a circle.

    PropertyPath::print

    fn PropertyPath::print(self : PropertyPath) -> String

    The path as text, with the types as they were written. parse with the same resolver and registry reads it as an equal path.

    PropertyPath::print_with

    fn PropertyPath::print_with(self : PropertyPath, namer : PathNamer) -> String raise

    The path as text, with the types as namer gives them. An error of namer is raised.

    PropertyPath::registry_id

    The identity of the registry that the path was parsed with. The path works only with the objects of this registry.

    PropertyPath::segments

    fn PropertyPath::segments(self : PropertyPath) -> ReadOnlyArray[PathSegment]

    The segments. A path without any, which is written as ., is the source itself.

    PropertyPath::set

    Set the last segment of the path from source to value. This sets the local value of a dependency property, or calls the setter of a registered property or indexer.

    It raises a PathSetError when the path does not reach the segment, or when the registered member does not take the value. An error of set_value or of the setter is raised as it is.

    PropertyPath::to_string

    fn PropertyPath::to_string(self : PropertyPath) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    int_parameter

    let int_parameter : Parameters[Int]

    A parameter for a number, such as the position in a list. It reads text as .NET reads an Int32.

    parse

    Read a path in the syntax of WPF's PropertyPath:

    • Child.Width are properties.
    • (Grid.Row) or (local:Grid.Row) is a member of an owner type, which resolver finds.
    • Items[0] and Cells[1,(sys:Int32)2] are indexers with their arguments. ^ before a character makes it a part of the argument.

    The empty text and . are the source itself. The path works with the types and objects of registry. One without owner types and types of arguments needs no resolver.

    register_object_type

    Let paths find members that are no dependency properties on the objects of the type owner, and of the types that derive from it. add_property and add_indexer add them. Their functions get the dependency object, whose host is the control.

    A type can be registered again, to add more members.

    register_optional

    Let paths step into the values of an optional type. None is a null value, and the others have the members that key has.

    register_value_type

    Let paths step into the values of key. add_property and add_indexer add the members.

    inner gives a value inside this one, whose members paths find too, such as the dependency object of a control. None means that the value is null. See register_optional for an optional type.

    A type can be registered again, to add more members, but it has at most one inner.

    string_parameter

    let string_parameter : Parameters[String]

    A parameter for text, such as the key in a map.