nickel-org / rust-mustache

mustache template library for rust
Other
204 stars 62 forks source link

Triggering `bug!` panic with `StrVal`s passed to sections #45

Closed ibabushkin closed 7 years ago

ibabushkin commented 7 years ago

Given a template such as this one:

{{# some_var }}
some text {{{ some_var }}}
{{/ some_var }}

and using

let mut data = HashMap::new();
data.insert("some_var", "some value");

as the data passed to the compiled template, I am receiving the following panic:

thread 'main' panicked at 'bug: unexpected value StrVal(some value). Please report this issue on GitHub if you find an input that triggers this case.'

A code search in the repo yields the following lines in src/template.rs as the culprit:

match self.find(path, stack) {
    None => {}
    Some(value) => {
        match *value {
            Bool(true) => {
                try!(self.render(wr, stack, children));
            }
            Bool(false) => {}
            VecVal(ref vs) => {
                for v in vs.iter() {
                    stack.push(v);
                    try!(self.render(wr, stack, children));
                    stack.pop();
                }
            }
            Map(_) => {
                stack.push(value);
                try!(self.render(wr, stack, children));
                stack.pop();
            }
            Fun(ref fcell) => {
                let f = &mut *fcell.borrow_mut();
                let tokens = try!(self.render_fun(src, otag, ctag, f));
                try!(self.render(wr, stack, &tokens));
            }
            OptVal(ref val) => {
                if let Some(ref val) = *val {
                    stack.push(val);
                    try!(self.render(wr, stack, children));
                    stack.pop();
                }
            }
            _ => bug!("unexpected value {:?}", value),
        }
    }
};

Now, the spec doesn't quite specify a clear behaviour on whether string values are to be interpreted as "thruthy", "falsey" or whether this decision is up to the host language's interpretation of this question. Now, in either case, either some filtering at template-compile-time should be done, or strings should be explicitly handled.

I can provide a fix for this (I suggest handling strings as true), but I'd like to know how the authors/maintainers see this issue.

therealbstern commented 7 years ago

Empty strings should be handled as "false" as they are a falsy value (see https://github.com/janl/mustache.js/issues/186 for a rationale).

therealbstern commented 7 years ago

FYI, the code referenced above seems to be at line 278.

ibabushkin commented 7 years ago

Does this commit https://github.com/ibabushkin/rust-mustache/commit/1bd7ebf9ecae6aad5f89f9016e9b315a1c2b8fc4 satisfy your requirements? If so, I'd open a pull-request.

jolhoeft commented 7 years ago

Yes please, we'd like a pull request.