Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrapping subtraction/negation operator oddities #8574

Closed
jmc-88 opened this issue Apr 19, 2021 · 2 comments · Fixed by #8599
Closed

Wrapping subtraction/negation operator oddities #8574

jmc-88 opened this issue Apr 19, 2021 · 2 comments · Fixed by #8599
Milestone

Comments

@jmc-88
Copy link
Contributor

jmc-88 commented Apr 19, 2021

The table of operators in the Zig documentation contains the following:

Syntax Relevant Types Description Example
a -% b a -%= b Integers Wrapping Subtraction.
  • Guaranteed to have twos-complement wrapping behavior.
  • Invokes Peer Type Resolution for the operands. See also @subWithOverflow.
@as(u32, 0) -% 1 == std.math.maxInt(u32)
-%a Integers Wrapping Negation.
  • Guaranteed to have twos-complement wrapping behavior.
-%@as(i32, std.math.minInt(i32)) == std.math.minInt(i32)

I would expect the unary -% to behave identically to @as(some_unsigned_type, 0) -% 1, but instead here's what I'm seeing:

Operation Expected Result Actual Result
@as(u32, 0) -% 1 std.math.maxInt(u32) std.math.maxInt(u32)
-%@as(u32, 1) std.math.maxInt(u32) invalid wrapping negation type: 'u32'
-%1 (not sure... it's a comptime_int, maybe it just shouldn't wrap?) 0

The compilation error on -%@as(u32, 1) is particularly interesting. I can't link the source on GitHub since the file is 1.5 MiB big (!), but the failure happens in src/stage1/ir.cpp, inside ir_eval_negation_scalar():

    bool ok_type = ((scalar_type->id == ZigTypeIdInt && scalar_type->data.integral.is_signed) ||
        scalar_type->id == ZigTypeIdComptimeInt || (is_float && !is_wrap_op));

    if (!ok_type) {
        const char *fmt = is_wrap_op ? "invalid wrapping negation type: '%s'" : "invalid negation type: '%s'";
        return ir_add_error(ira, source_instr, buf_sprintf(fmt, buf_ptr(&scalar_type->name)));
    }

I don't know why the requirement for scalar_type->data.integral.is_signed: the wrapping behavior is especially useful on unsigned types. A quick git blame indicates this check has existed since all the way back to 0ad580f.

@jmc-88 jmc-88 changed the title Wrapping subtraction/negation oeprator oddities Wrapping subtraction/negation operator oddities Apr 19, 2021
@Vexu
Copy link
Member

Vexu commented Apr 19, 2021

Wrapping negation of unsigned integers was accepted in #1770.

@LemonBoy
Copy link
Contributor

See also #7951.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants