Skip to content

Commit

Permalink
feat(error): Improve missing variable errors
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Nov 19, 2018
1 parent 45c5d39 commit d6e1aea
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 4 deletions.
26 changes: 22 additions & 4 deletions liquid-interpreter/src/globals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,28 @@ impl Globals for Object {
}

fn get_variable<'a>(&'a self, path: PathRef) -> Result<&'a Value> {
self.try_get_variable(path).ok_or_else(|| {
let path = itertools::join(path.iter(), ".");
Error::with_msg("Unknown index").context("variable", format!("{}", path))
})
if let Some(res) = self.try_get_variable(path) {
return Ok(res);
} else {
for cur_idx in 1..path.len() {
let subpath_end = path.len() - cur_idx;
let subpath = &path[0..subpath_end];
if let Some(parent) = self.try_get_variable(subpath) {
let subpath = itertools::join(subpath.iter(), ".");
let index = &path[subpath_end];
let available = itertools::join(parent.keys(), ", ");
return Err(Error::with_msg("Unknown index")
.context("variable", format!("{}", subpath))
.context("requested index", format!("{}", index))
.context("available indexes", format!("{}", available)));
}
}

let available = itertools::join(self.keys(), ", ");
return Err(Error::with_msg("Unknown variable")
.context("requested variable", path[0].to_str().into_owned())
.context("available variables", available));
}
}
}

Expand Down
8 changes: 8 additions & 0 deletions liquid-value/src/scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,14 @@ impl From<&'static str> for Scalar {
}
}

impl From<borrow::Cow<'static, str>> for Scalar {
fn from(s: borrow::Cow<'static, str>) -> Self {
Scalar {
0: ScalarEnum::Str(s),
}
}
}

impl PartialEq<Scalar> for Scalar {
fn eq(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
Expand Down
21 changes: 21 additions & 0 deletions liquid-value/src/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,27 @@ impl Value {
}
}

/// All keys
pub fn keys(&self) -> Vec<Scalar> {
match *self {
Value::Array(ref x) => {
let start: i32 = 0;
let end = x.len() as i32;
let mut keys: Vec<_> = (start..end).map(|i| Scalar::new(i)).collect();
keys.push(Scalar::new("first"));
keys.push(Scalar::new("last"));
keys
}
Value::Object(ref x) => x.keys().map(|s| {
match *s {
borrow::Cow::Borrowed(s) => Scalar::new(s),
borrow::Cow::Owned(ref s) => Scalar::new(s.to_owned()),
}
}).collect(),
_ => vec![],
}
}

/// Access a contained `Value`.
pub fn get<'s>(&'s self, index: &Scalar) -> Option<&'s Self> {
match *self {
Expand Down

0 comments on commit d6e1aea

Please sign in to comment.