# 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:

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

| Text | What it is |
| --- | --- |
| `Child.Width` | the 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 nothing | the 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:

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

```mbt check
///|
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](#members-of-values).

The paths of a XAML document use the prefixes of the document, see
[`moonrockz/xaml/schema`](../../../xaml/src/schema/README.mbt.md#property-paths).

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:

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

`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:

| Function | Whose members it registers |
| --- | --- |
| `register_value_type` | those of a MoonBit type, which its key stands for |
| `register_object_type` | those 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_optional` | none. 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`:

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

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

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

| Reason | What is wrong |
| --- | --- |
| `UnknownMember` | the value has no such property, or no indexer |
| `CannotStepInto` | the type of the value is not registered, or a path with a type needs a dependency object |
| `NullValue` | the value is null, and the path goes on |
| `InvalidArgument` | the arguments do not fit the indexer |
| `Raised` | the getter raised the error that the reason has |
| `RegistryMismatch` | the object belongs to another registry than the path |
| `ReadOnly`, `InvalidValue` | only 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 `AnyValue`s, 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.
