2020-05-09 15:15:43 -04:00
|
|
|
use crate::renderer::context_element::ContextElement;
|
|
|
|
use crate::renderer::WalkError;
|
2020-05-24 14:56:09 -04:00
|
|
|
use std::borrow::Borrow;
|
2020-05-09 15:15:43 -04:00
|
|
|
|
|
|
|
enum WalkResult<'a> {
|
|
|
|
NoWalk,
|
|
|
|
PartialWalk,
|
|
|
|
FullyWalked(&'a dyn ContextElement),
|
|
|
|
}
|
|
|
|
|
2020-05-24 15:21:30 -04:00
|
|
|
fn walk_path_from_single_level<'a, P, C>(context: &'a C, path: &[P]) -> WalkResult<'a>
|
2020-05-24 14:56:09 -04:00
|
|
|
where
|
|
|
|
P: Borrow<str>,
|
|
|
|
C: Borrow<dyn ContextElement + 'a>,
|
|
|
|
{
|
|
|
|
if path.is_empty() {
|
|
|
|
return WalkResult::FullyWalked(context.borrow());
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut walk_failure = WalkResult::NoWalk;
|
|
|
|
let mut output = context.borrow();
|
|
|
|
for elem in path.iter() {
|
|
|
|
match output.borrow().walk(elem.borrow()) {
|
|
|
|
Err(WalkError::CantWalk { .. }) => {
|
|
|
|
return walk_failure;
|
|
|
|
}
|
|
|
|
Ok(new_val) => {
|
|
|
|
walk_failure = WalkResult::PartialWalk;
|
|
|
|
output = new_val;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
WalkResult::FullyWalked(output)
|
|
|
|
}
|
|
|
|
|
2020-05-24 15:21:30 -04:00
|
|
|
pub fn walk_path<'a, B, P>(
|
2020-05-24 14:56:09 -04:00
|
|
|
breadcrumbs: &'a Vec<B>,
|
|
|
|
path: &Vec<P>,
|
|
|
|
) -> Result<&'a dyn ContextElement, WalkError>
|
|
|
|
where
|
|
|
|
B: Borrow<dyn ContextElement + 'a>,
|
|
|
|
P: Borrow<str>,
|
|
|
|
{
|
|
|
|
if path.is_empty() {
|
|
|
|
return Ok(breadcrumbs
|
|
|
|
.last()
|
|
|
|
.expect("Breadcrumbs should never be empty.")
|
|
|
|
.borrow());
|
|
|
|
}
|
|
|
|
if path
|
|
|
|
.first()
|
|
|
|
.expect("Already proved path is not empty")
|
|
|
|
.borrow()
|
|
|
|
== "."
|
|
|
|
{
|
2020-05-24 15:21:30 -04:00
|
|
|
return match walk_path_from_single_level(
|
2020-05-24 14:56:09 -04:00
|
|
|
breadcrumbs
|
|
|
|
.last()
|
|
|
|
.expect("Breadcrumbs should never be empty"),
|
|
|
|
&path[1..],
|
|
|
|
) {
|
|
|
|
// If no walking was done at all or we partially walked
|
|
|
|
// then stop trying to find anything because '.' restricts
|
|
|
|
// us to the current scope
|
|
|
|
WalkResult::NoWalk | WalkResult::PartialWalk => Err(WalkError::CantWalk),
|
|
|
|
WalkResult::FullyWalked(new_context) => Ok(new_context),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
for context in breadcrumbs.iter().rev() {
|
2020-05-24 15:21:30 -04:00
|
|
|
match walk_path_from_single_level(context, path) {
|
2020-05-24 14:56:09 -04:00
|
|
|
// If no walking was done at all, keep looping
|
|
|
|
WalkResult::NoWalk => {}
|
|
|
|
// If we partially walked then stop trying to find
|
|
|
|
// anything
|
|
|
|
WalkResult::PartialWalk => {
|
|
|
|
return Err(WalkError::CantWalk);
|
|
|
|
}
|
|
|
|
WalkResult::FullyWalked(new_context) => return Ok(new_context),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(WalkError::CantWalk)
|
|
|
|
}
|