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

Re: Example / partial fix for printf with math expressions



2024-02-23 15:23:52 -0800, Bart Schaefer:
> No attachment, so beware line wrap.
> 
> This repairs (printf "%d" ...) but obviously hasn't touched any of the
> several other places where bin_print() calls matheval() and friends.
> Upshot, math expects to get metafied strings, bin_print() does not (or
> at least not always) pass them that way.
> 
> I also did not investigate whether curarg needs a known length rather
> than calling metafy with -1, but since math is internally going to
> stop at nul bytes anyway, I don't think it matters.
[...]

Ah sorry, I hadn't seen that message when replying in the other
thread.

The math parser seems to work OK with NULs at least in:

$ typeset -A a
$ typeset -p a
typeset -A a=( [$'\C-@']=1 )
$ let $'b = (a = ##\0) + 32'; echo $a $b
0 32


With and without your example patch applied however:

$ printf '%d\n' $'a[\0]++'
zsh: invalid subscript
0

With the one below using curlen / len[argp-args]:

$ typeset -A a
$ printf '%d\n' $'a[\0]++'
0
$ typeset -p a
typeset -A a=( [$'\C-@']=1 )

diff --git a/Src/builtin.c b/Src/builtin.c
index dd352c146..f72d14da4 100644
--- a/Src/builtin.c
+++ b/Src/builtin.c
@@ -5247,7 +5247,8 @@ bin_print(char *name, char **args, Options ops, int func)
 		    }
 		}
 		if (*argp) {
-		    width = (int)mathevali(*argp++);
+		    width = (int)mathevali(metafy(*argp, len[argp - args], META_USEHEAP));
+		    argp++;
 		    if (errflag) {
 			errflag &= ~ERRFLAG_ERROR;
 			ret = 1;
@@ -5281,7 +5282,8 @@ bin_print(char *name, char **args, Options ops, int func)
 		    }
 
 		    if (*argp) {
-			prec = (int)mathevali(*argp++);
+			prec = (int)mathevali(metafy(*argp, len[argp - args], META_USEHEAP));
+			argp++;
 			if (errflag) {
 			    errflag &= ~ERRFLAG_ERROR;
 			    ret = 1;
@@ -5465,7 +5467,7 @@ bin_print(char *name, char **args, Options ops, int func)
  		    	*d++ = 'l';
 #endif
 		    	*d++ = 'l', *d++ = *c, *d = '\0';
-			zlongval = (curarg) ? mathevali(curarg) : 0;
+			zlongval = (curarg) ? mathevali(metafy(curarg, curlen, META_HEAPDUP)) : 0;
 			if (errflag) {
 			    zlongval = 0;
 			    errflag &= ~ERRFLAG_ERROR;
@@ -5516,7 +5518,7 @@ bin_print(char *name, char **args, Options ops, int func)
 			if (!curarg)
 			    zulongval = (zulong)0;
 			else if (!zstrtoul_underscore(curarg, &zulongval))
-			    zulongval = mathevali(curarg);
+			    zulongval = mathevali(metafy(curarg, curlen, META_HEAPDUP));
 			if (errflag) {
 			    zulongval = 0;
 			    errflag &= ~ERRFLAG_ERROR;





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