ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
32.42k stars 2.37k forks source link

Proposal: Make right shift mode explicit for signed integers #20367

Open N00byEdge opened 3 weeks ago

N00byEdge commented 3 weeks ago

Today, doing a >> b could use either arithmetic or logical shift right, currently this is chosen based on the signedness.

We solved this ambiguity with division, where you aren't allowed to just do a / b if the integer is signed (you have to choose which division mode to use explicitly with builtin functions. It feels only right to do the same thing for right shifting.

This proposal disallows a >> b for signed left hand sides and instead add explicit shift modes e.g. @arithmeticShiftRight/@sar and @logicalShiftRight/@shr. Also the naming of @shrExact should be overlooked (does it imply logical shift?) and the semantics should reflect the updated ones of the shift operator itself.

alexrp commented 3 weeks ago

As a data point, C#'s >> operator works like Zig's, but they later added >>> for logical right shift even on signed integers.

rohlem commented 3 weeks ago

This proposal doesn't seem to cover all combinations of operations and signedness. Afaik the reason an arithmetic shift is called that is that it keeps a value's sign the same (for right-shift by extending the sign bit by the shifted amount of bits, for left-shift asserting the sign doesn't change). As unsigned integers don't have a sign bit, there are two interpretations:

I don't really see a use case for allowing unsigned left operands in arithmetic shifts though. Forbidding them seems simpler: Then the user chooses by using either @bitCast or @intCast for the type conversion.

An alternative idea with minimized surface area would be to split logical and arithmetic shifts as proposed into separate operators and builtins, but additionally allow logical shifts only for unsigned and arithmetic shifts only for signed numbers. That would make the behavior perfectly clear, at the cost of a couple more explicit casts.

Naming nitpick, sar and shr are asymmetric. We could call them sar/slr, but it's probably easier to introduce another letter making them shar and shlr.

N00byEdge commented 3 weeks ago

Naming nitpick, sar and shr are asymmetric. We could call them sar/slr, but it's probably easier to introduce another letter making them shar and shlr.

Yeah, that makes sense to me.