Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: zmathfunc: min, max, sum throw error if result equals 0



On Sun, Mar 7, 2021 at 1:57 PM Daniel Shahaf <d.s@xxxxxxxxxxxxxxxxxx> wrote:
>
> Bart Schaefer wrote on Sun, 07 Mar 2021 21:39 +00:00:
>
> > Is it worth testing invalid cases?  Such as uses outside math context
> > where the arguments are not syntax checked?
>
> If you have ideas, feel free to write them and post them; I'll
> transplant them into Z02 once I have committed it.

One possibility below; I'll follow up if I think of more.

With your patch adding "true" at the end, we get this:

% zsh_math_func_min "foo bar" x y z
zsh_math_func_min:7: bad math expression: operator expected at `bar'
zsh_math_func_min:7: bad math expression: operator expected at `bar'
zsh_math_func_min:7: bad math expression: operator expected at `bar'
zsh_math_func_min:9: bad math expression: operator expected at `bar'
toltec-ubuntu% echo $?
0

Doesn't seem as though anything that prints that many error messages
should return zero.

> > Because of the way math context works, if any of $@ is a string that
> > can be interpreted as a math expression, the above will evaluate it at
> > least twice (and up to $# times in the case of $1).  This could have
> > side-effects.
>
> Could you post a regression test for this?

In thinking more about it, I believe this only matters when the
function is called outside of math context.  In math context, the
arguments are all going to be evaluated down to numbers before they
are passed to the function.

% (( x = 0 )); zsh_math_func_min "x += 2" 4 5 6
% print $x
8
% (( (x = 0), min("x += 2", 4, 5, 6) ))
% print $x
2

> Related to code as it is in master, are «(( $arg < result ))» and
> «(( arg < result ))» equivalent?

No, but again math context matters.

% arg="x += 2" x=0 result=0
% (( $arg > result )) && result=$arg
% print $result $x $(( result )) $x
x += 2 1 3 3
% x=0 result=0
% (( arg > result )) && (( result=arg ))
% print $result $x $(( result )) $x
4 4 4 4

> > zsh_math_func_min() {
> >   local result=$(( $1 ))
>
> Doesn't this still do multiple string-to-number conversions?

I don't think so ... the $(( ... )) should turn $1 into a single
number assigned to result.  What are you thinking about?




Messages sorted by: Reverse Date, Date, Thread, Author