Commit ca70ca7e26

Timon Kruiper <timonkruiper@gmail.com>
2019-09-05 18:43:54
Add compiler error when negating invalid type
1 parent 4a5bc89
Changed files (2)
src/ir.cpp
@@ -16565,6 +16565,15 @@ static IrInstruction *ir_analyze_negation(IrAnalyze *ira, IrInstructionUnOp *ins
     if (type_is_invalid(expr_type))
         return ira->codegen->invalid_instruction;
 
+    if (!(expr_type->id == ZigTypeIdInt || expr_type->id == ZigTypeIdComptimeInt ||
+        expr_type->id == ZigTypeIdFloat || expr_type->id == ZigTypeIdComptimeFloat ||
+        expr_type->id == ZigTypeIdVector))
+    {
+        ir_add_error(ira, &instruction->base,
+            buf_sprintf("negation of type '%s'", buf_ptr(&expr_type->name)));
+        return ira->codegen->invalid_instruction;
+    }
+
     bool is_wrap_op = (instruction->op_id == IrUnOpNegationWrap);
 
     ZigType *scalar_type = (expr_type->id == ZigTypeIdVector) ? expr_type->data.vector.elem_type : expr_type;
test/compile_errors.zig
@@ -2,6 +2,19 @@ const tests = @import("tests.zig");
 const builtin = @import("builtin");
 
 pub fn addCases(cases: *tests.CompileErrorContext) void {
+    cases.add(
+        "attempt to negate a non-integer, non-float or non-vector type",
+        \\fn foo() anyerror!u32 {
+        \\    return 1;
+        \\}
+        \\
+        \\export fn entry() void {
+        \\    const x = -foo();
+        \\}
+    ,
+        "tmp.zig:6:15: error: negation of type 'anyerror!u32'",
+    );
+
     cases.add(
         "attempt to create 17 bit float type",
         \\const builtin = @import("builtin");