ietf-wg-jsonpath / draft-ietf-jsonpath-base

Development of a JSONPath internet draft
https://ietf-wg-jsonpath.github.io/draft-ietf-jsonpath-base/
Other
58 stars 20 forks source link

Are `&&` and `||` shortcutting #334

Closed gregsdennis closed 1 year ago

gregsdennis commented 1 year ago

In C# (and probably other C-style languages), there are two variants for these operators.

& and | are simple boolean logic. They evaluate all of their operands always (left to right).

&& and || are "short-circuit" logic. Their operands are evaluated left to right, and as soon as an outcome is known, it stops evaluating. For example, in 4==5 && 5==5, the 5==5 is never evaluated because 4==5 returns false so the evaluator knows the entire expression will be false.

This becomes important for C# as the operands may be methods which have side effects. If I am trying to parse a double, then use the double I parsed, I can do that all in one statement:

if (double.TryParse("definitely not a number", out var d) && LogWhetherPrime(d)) { ... }

(assume LogWhetherPrime(d) returns a bool)

In this case, LogWhetherPrime(d) never gets called, which means that no log entry is made. But if I use & instead

if (double.TryParse("definitely not a number", out var d) & LogWhetherPrime(d)) { ... }

LogWhetherPrime(d) will always be called and a log entry will always be created. (d will be the default double (0), but it will still be called.)

I'm not sure whether we care about such side effects in JSON Path (I'm leaning towards probably not), but it seems necessary to raise the issue. I expect that if we don't care about side effects, this comes down to an optimization strategy and implementor's choice.

glyn commented 1 year ago

This may become more important if certain function extensions end up having side effects. Perhaps we should say implementations MAY short circuit evaluation. Then it's up to users and function extensions to cope.

cabo commented 1 year ago

Actually, it would already become important as soon as we have exception-like semantics on subexpressions. I'd prefer not to have them.

cabo commented 1 year ago

2023-01-10 Interim: Add text that explicitly excludes side effects that affect the evaluation of JSONpath (e.g., beyond memoization or logging), but makes clear that short-circuiting is a valid implementation strategy; functions need to be pure functions.