Commit 78a9a465a3

Andrew Kelley <superjoe30@gmail.com>
2018-09-18 00:58:50
add compile error for non-optional types compared against null
closes #1539
1 parent 6c71e9a
Changed files (2)
src/ir.cpp
@@ -11571,6 +11571,9 @@ static ZigType *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp *bin_op
             ir_link_new_instruction(is_non_null, &bin_op_instruction->base);
         }
         return ira->codegen->builtin_types.entry_bool;
+    } else if (op1->value.type->id == ZigTypeIdNull || op2->value.type->id == ZigTypeIdNull) {
+        ir_add_error_node(ira, source_node, buf_sprintf("comparison against null can only be done with optionals"));
+        return ira->codegen->builtin_types.entry_invalid;
     }
 
     if (op1->value.type->id == ZigTypeIdErrorSet && op2->value.type->id == ZigTypeIdErrorSet) {
test/compile_errors.zig
@@ -1,6 +1,16 @@
 const tests = @import("tests.zig");
 
 pub fn addCases(cases: *tests.CompileErrorContext) void {
+    cases.add(
+        "comparing a non-optional pointer against null",
+        \\export fn entry() void {
+        \\    var x: i32 = 1;
+        \\    _ = &x == null;
+        \\}
+    ,
+        ".tmp_source.zig:3:12: error: comparison against null can only be done with optionals",
+    );
+
     cases.add(
         "non error sets used in merge error sets operator",
         \\export fn foo() void {