Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Deeply nested array indexes #231

Merged
merged 2 commits into from
Nov 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions liquid-compiler/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,14 @@ pub fn unexpected_token_error_string(expected: &str, actual: Option<String>) ->
// creates an expression, which wraps everything that gets rendered
fn parse_expression(tokens: &[Token], options: &LiquidOptions) -> Result<Box<Renderable>> {
match tokens.get(0) {
Some(&Token::Identifier(ref x))
Some(&Token::Identifier(_))
if tokens.len() > 1 && (tokens[1] == Token::Dot || tokens[1] == Token::OpenSquare) =>
{
let mut result = tokens[0]
.to_arg()?
.into_variable()
.expect("identifiers must be variables");
let indexes = parse_indexes(&tokens[1..])?;
let mut result = Variable::with_literal(x.clone());
result.extend(indexes);
Ok(Box::new(result))
}
Expand Down Expand Up @@ -344,6 +347,7 @@ mod test_parse_expression {
use super::*;

use liquid_interpreter::Context;
use liquid_value::Array;
use liquid_value::Object;
use liquid_value::Value;

Expand Down Expand Up @@ -401,6 +405,32 @@ mod test_parse_expression {
let result = result.render(&mut context).unwrap();
assert_eq!("42", result);
}

#[test]
fn array_index_access() {
let tokens = granularize("post[0]").unwrap();
let mut context = Context::new();
let mut post = Array::new();
post.push(Value::scalar(42i32));
context.stack_mut().set_global("post", Value::Array(post));

let result = parse_expression(&tokens, &null_options()).unwrap();
let result = result.render(&mut context).unwrap();
assert_eq!("42", result);
}

#[test]
fn mixed_access() {
let tokens = granularize("post.child[0]").unwrap();
let mut context = Context::new();
let mut post = Object::new();
post.insert("child".into(), Value::Array(vec![Value::scalar(42i32)]));
context.stack_mut().set_global("post", Value::Object(post));

let result = parse_expression(&tokens, &null_options()).unwrap();
let result = result.render(&mut context).unwrap();
assert_eq!("42", result);
}
}

#[cfg(test)]
Expand Down
3 changes: 0 additions & 3 deletions liquid-error/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,6 @@ const ERROR_DESCRIPTION: &str = "liquid";
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "{}: {}", ERROR_DESCRIPTION, self.inner.msg)?;
if let Some(ref cause) = self.inner.cause {
writeln!(f, "cause: {}", cause)?;
}
for trace in &self.inner.user_backtrace {
if let Some(trace) = trace.get_trace() {
writeln!(f, "from: {}", trace)?;
Expand Down
8 changes: 5 additions & 3 deletions liquid-interpreter/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,15 +169,17 @@ impl<'g> Stack<'g> {
let mut indexes = path.iter();
let key = indexes
.next()
.ok_or_else(|| Error::with_msg("No index provided"))?;
.ok_or_else(|| Error::with_msg("No variable provided"))?;
let key = key.to_str();
let value = self.get_root(key.as_ref())?;

indexes.fold(Ok(value), |value, index| {
let value = value?;
let child = value.get(index);
let child = child.ok_or_else(|| {
Error::with_msg("Invalid index").context("index", key.as_ref().to_owned())
Error::with_msg("Unknown index")
.context("variable", format!("{}", path))
.context("index", format!("{}", index))
})?;
Ok(child)
})
Expand All @@ -190,7 +192,7 @@ impl<'g> Stack<'g> {
}
}
self.globals
.ok_or_else(|| Error::with_msg("Invalid index").context("index", name.to_owned()))
.ok_or_else(|| Error::with_msg("Unknown variable").context("variable", name.to_owned()))
.and_then(|g| g.get(name))
.or_else(|err| self.get_index(name).ok_or_else(|| err))
}
Expand Down
16 changes: 16 additions & 0 deletions liquid-interpreter/src/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ impl Expression {
Expression::Literal(Value::scalar(literal))
}

/// Convert into a literal if possible.
pub fn into_literal(self) -> Option<Value> {
match self {
Expression::Literal(x) => Some(x),
Expression::Variable(_) => None,
}
}

/// Convert into a variable, if possible.
pub fn into_variable(self) -> Option<Variable> {
match self {
Expression::Literal(_) => None,
Expression::Variable(x) => Some(x),
}
}

/// Convert to a `Value`.
pub fn evaluate(&self, context: &Context) -> Result<Value> {
let val = match *self {
Expand Down
1 change: 1 addition & 0 deletions liquid-interpreter/src/filter_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ impl FilterChain {
entry = f
.filter(&entry, &*arguments)
.chain("Filter error")
.context_with(|| ("filter".to_owned(), format!("{}", self)))
.context_with(|| ("input".to_owned(), format!("{}", &entry)))
.context_with(|| ("args".to_owned(), itertools::join(&arguments, ", ")))?;
}
Expand Down
2 changes: 1 addition & 1 deletion liquid-interpreter/src/globals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ pub trait Globals: fmt::Debug {
impl Globals for Object {
fn get<'a>(&'a self, name: &str) -> Result<&'a Value> {
self.get(name)
.ok_or_else(|| Error::with_msg("Invalid index").context("index", name.to_owned()))
.ok_or_else(|| Error::with_msg("Unknown variable").context("variable", name.to_owned()))
}
}
2 changes: 1 addition & 1 deletion src/filters/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn abs(input: &Value, args: &[Value]) -> FilterResult {
.to_integer()
.map(|i| Value::scalar(i.abs()))
.or_else(|| s.to_float().map(|i| Value::scalar(i.abs())))
.ok_or_else(|| invalid_input("Numeric value expected")),
.ok_or_else(|| invalid_input("Numeric expected")),
_ => Err(invalid_input("Number expected")),
}
}
Expand Down