zeek / spicy

C++ parser generator for dissecting protocols & files.
https://docs.zeek.org/projects/spicy
Other
249 stars 37 forks source link

Allow specifying an error message in `&requires` #1856

Open bbannier opened 2 months ago

bbannier commented 2 months ago

To surface more useful errors we allow specifying an error message for assert statements, e.g.,

assert False : "the things broke!!!1";

We could consider adding support for similar syntax for &requires, e.g.,

type X = unit {
    : uint8 &requires=($$ == 0 : "%d is not a good value" % $$);
};

To tweak messages for &requires one currently needs to use a field hook. Moving this to &requires seems natural and we already support multiple &requires attributes.

The current syntax is &requires=COND and above idea would be to add support for &requires=(COND [: EXPR_MSG]). We already can parse parentheses around COND so they might not be strictly needed.

rsmmr commented 2 months ago

Quick thought: I'd be reluctant to special-case &requires with a syntax that's not simply an expression (because expressions is what all other attributes expect, and this still looks like an expression). But we might be able to make this work with plain expressions actually if we change &requires to expect an expression of type result<bool>. And then add some short-cut constructor syntax that yields either true or an error, like $$==0 ?|| error"%d is not a good value" % $$). (Not saying that is the syntax we want, just a possible example; and interpolation doesn't work for errors yet, but would be easy to add.). This would also be backwards-compatible because a plain boolean coerces into result<bool>.