///|
/// 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.
pub struct PathNamer {
priv owner : (@dependency.OwnerType) -> String raise
priv argument_type : (String) -> String raise
}
///|
/// `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.
pub fn PathNamer::new(
owner~ : (@dependency.OwnerType) -> String raise,
argument_type~ : (String) -> String raise,
) -> PathNamer {
{ owner, argument_type, }
}
///|
/// The path as text, with the types as they were written. `parse` with the same resolver and registry reads it as an equal path.
pub fn PropertyPath::print(self : PropertyPath) -> String {
print_segments(self.segments, (written, _) => written, (written, _) => written)
}
///|
/// The path as text, with the types as `namer` gives them. An error of `namer` is raised.
pub fn PropertyPath::print_with(
self : PropertyPath,
namer : PathNamer,
) -> String raise {
print_segments(self.segments, (_, owner) => (namer.owner)(owner), (_, name) => {
(namer.argument_type)(name)
})
}
///|
/// `name_owner` and `name_type` get a type as it was written, and what it is.
fn print_segments(
segments : ArrayView[PathSegment],
name_owner : (String, @dependency.OwnerType) -> String raise?,
name_type : (String, String) -> String raise?,
) -> String raise? {
if segments.is_empty() {
return "."
}
let out = StringBuilder()
for i, segment in segments {
if i > 0 && !(segment is Indexer(_)) {
out.write_char('.')
}
match segment {
Property(name) =>
out.write_string(if is_bare_name(name) { name } else { "(\{name})" })
Qualified(found, written~) => {
let owner = name_owner(written, found.owner_type())
out.write_string("(\{owner}.\{found.name()})")
}
// `[]` is an error.
Indexer([Text("")]) => out.write_string("[ ]")
Indexer(arguments) => {
out.write_char('[')
for j, argument in arguments {
if j > 0 {
out.write_char(',')
}
match argument {
Text(text) => write_escaped(out, text)
Typed(written~, type_name~, text~, ..) => {
out.write_char('(')
write_escaped(out, name_type(written, type_name))
out.write_char(')')
// A type without a value is text. The parser leaves out this space.
write_escaped(out, if text.is_empty() { " " } else { text })
}
}
}
out.write_char(']')
}
}
}
out.to_string()
}
///|
/// Write `text` so that the parser takes all of it for a part of an argument.
fn write_escaped(out : StringBuilder, text : String) -> Unit {
let (start, end) = trimmed_range(text, 0, text.length())
let mut written = 0
for at in 0..= end ||
text.at(at) is ('^' | ',' | '[' | ']' | '(' | ')') {
out.write_view(text[written:at])
out.write_char('^')
written = at
}
}
out.write_view(text[written:])
}