authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-05-10 00:21:27-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-05-10 00:21:27-04:00
log63f6676fee83883736af794eaddb4d0ccb890c06
treef01f8a01902267451d7c8e57de75157e475f1141
parent623741171629055a22a35bb8278d81a81dcffbde

add compile error for casting negative value to...

...unsigned integer at compile-time

2 files changed, 15 insertions(+), 0 deletions(-)

src/ir.cpp+7
......@@ -7053,6 +7053,13 @@ static IrInstruction *ir_analyze_widen_or_shorten(IrAnalyze *ira, IrInstruction
70537053 ConstExprValue *val = ir_resolve_const(ira, target, UndefBad);
70547054 if (!val)
70557055 return ira->codegen->invalid_instruction;
7056 if (val->data.x_bignum.is_negative && wanted_type->id == TypeTableEntryIdInt &&
7057 !wanted_type->data.integral.is_signed)
7058 {
7059 ir_add_error(ira, source_instr,
7060 buf_sprintf("attempt to cast negative value to unsigned integer"));
7061 return ira->codegen->invalid_instruction;
7062 }
70567063 IrInstruction *result = ir_create_const(&ira->new_irb, source_instr->scope,
70577064 source_instr->source_node, wanted_type);
70587065 result->value = *val;
test/compile_errors.zig+8
......@@ -1801,4 +1801,12 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
18011801 \\}
18021802 ,
18031803 ".tmp_source.zig:2:7: error: remainder division with 'i32' and 'i32': signed integers and floats must use @rem or @mod");
1804
1805 cases.add("cast negative value to unsigned integer",
1806 \\comptime {
1807 \\ const value: i32 = -1;
1808 \\ const unsigned = u32(value);
1809 \\}
1810 ,
1811 ".tmp_source.zig:3:25: error: attempt to cast negative value to unsigned integer");
18041812}