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

[PATCH] count multibyte and metafied characters correctly for math ops errors



On Wed, Feb 21, 2024 at 11:55 PM Stephane Chazelas
<stephane@xxxxxxxxxxxx> wrote:
>
> $ ((1+|ÃÃÃÃÃÃ))
> zsh: bad math expression: operand expected at `|ÃÃÃÃ\M-C...'

As Stephane also pointed out, ÃÃÃÃÃÃ is a valid identifier, so it's
not farfetched that someone could make a typo using one in a math
expression.

The code added here could be made into a utility [metalen() is almost
there] but as I don't know of anywhere else this is needed, I just
inlined it.  I looked through the other mb_* routines in utils.c but
they all appeared to do what would be extraneous work for this
purpose.
diff --git a/Src/math.c b/Src/math.c
index 50b69d6a1..d97dae238 100644
--- a/Src/math.c
+++ b/Src/math.c
@@ -1557,21 +1557,32 @@ checkunary(int mtokc, char *mptr)
 	    errmsg = 2;
     }
     if (errmsg) {
-	int len, over = 0;
+	int len = 0, over = 0;
 	char *errtype = errmsg == 2 ? "operator" : "operand";
 	while (inblank(*mptr))
 	    mptr++;
-	len = ztrlen(mptr);
-	if (len > 10) {
-	    len = 10;
-	    over = 1;
+	if (isset(MULTIBYTE))
+	    MB_CHARINIT();
+	while (over < 10 && mptr[len]) {
+	    if (isset(MULTIBYTE))
+		len += MB_METACHARLEN(mptr+len);
+	    else
+		len += (mptr[len] == Meta ? 2 : 1);
+	    ++over;
+	}
+	if ((over = mptr[len])) {
+	    mptr = dupstring(mptr);
+	    if (mptr[len] == Meta)
+		mptr[len+1] = 0;
+	    else
+		mptr[len] = 0;
 	}
 	if (!*mptr)
 	    zerr("bad math expression: %s expected at end of string",
 		errtype);
 	else
-	    zerr("bad math expression: %s expected at `%l%s'",
-		 errtype, mptr, len, over ? "..." : "");
+	    zerr("bad math expression: %s expected at `%s%s'",
+		 errtype, mptr, over ? "..." : "");
     }
     unary = !(tp & OP_OPF);
 }


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