Commit 866c253e0e

Timon Kruiper <timonkruiper@gmail.com>
2019-08-28 23:12:42
Add compile error when shifting amount is not an int type
1 parent 8e3c56b
Changed files (2)
src/ir.cpp
@@ -13734,7 +13734,7 @@ static IrInstruction *ir_analyze_bit_shift(IrAnalyze *ira, IrInstructionBinOp *b
         return ira->codegen->invalid_instruction;
 
     if (op1->value.type->id != ZigTypeIdInt && op1->value.type->id != ZigTypeIdComptimeInt) {
-        ir_add_error(ira, &bin_op_instruction->base,
+        ir_add_error(ira, bin_op_instruction->op1,
             buf_sprintf("bit shifting operation expected integer type, found '%s'",
                 buf_ptr(&op1->value.type->name)));
         return ira->codegen->invalid_instruction;
@@ -13744,6 +13744,13 @@ static IrInstruction *ir_analyze_bit_shift(IrAnalyze *ira, IrInstructionBinOp *b
     if (type_is_invalid(op2->value.type))
         return ira->codegen->invalid_instruction;
 
+    if (op2->value.type->id != ZigTypeIdInt && op2->value.type->id != ZigTypeIdComptimeInt) {
+        ir_add_error(ira, bin_op_instruction->op2,
+            buf_sprintf("shift amount has to be an integer type, but found '%s'",
+                buf_ptr(&op2->value.type->name)));
+        return ira->codegen->invalid_instruction;
+    }
+
     IrInstruction *casted_op2;
     IrBinOp op_id = bin_op_instruction->op_id;
     if (op1->value.type->id == ZigTypeIdComptimeInt) {
test/compile_errors.zig
@@ -70,6 +70,26 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
         "tmp.zig:6:37: error: expected type '*i32', found 'bool'",
     );
 
+    cases.add(
+        "shift amount has to be an integer type",
+        \\export fn entry() void {
+        \\    const x = 1 << &u8(10);
+        \\}
+    ,
+        "tmp.zig:2:23: error: shift amount has to be an integer type, but found '*u8'",
+        "tmp.zig:2:17: note: referenced here",
+    );
+
+    cases.add(
+        "bit shifting only works on integer types",
+        \\export fn entry() void {
+        \\    const x = &u8(1) << 10;
+        \\}
+    ,
+        "tmp.zig:2:18: error: bit shifting operation expected integer type, found '*u8'",
+        "tmp.zig:2:22: note: referenced here",
+    );
+
     cases.add(
         "struct depends on itself via optional field",
         \\const LhsExpr = struct {