@@ -197,6 +197,37 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
197
197
}
198
198
}
199
199
}
200
+
201
+ // Do not allow comparing nil to non-pointers
202
+ if node.left.is_nil () {
203
+ mut final_type := right_type
204
+ if mut right_sym.info is ast.Alias
205
+ && right_sym.info.parent_type.is_any_kind_of_pointer () {
206
+ final_type = right_sym.info.parent_type
207
+ }
208
+ if ! final_type.is_any_kind_of_pointer () && (right_final_sym.kind != .function
209
+ || (right_final_sym.language != .c && right_final_sym.kind == .placeholder))
210
+ && ! right_final_sym.is_heap () {
211
+ rt := c.table.sym (right_type).name
212
+ c.error ('cannot compare with `nil` because `${rt} ` is not a pointer' ,
213
+ node.pos)
214
+ }
215
+ }
216
+
217
+ if node.right.is_nil () {
218
+ mut final_type := left_type
219
+ if mut left_sym.info is ast.Alias
220
+ && left_sym.info.parent_type.is_any_kind_of_pointer () {
221
+ final_type = left_sym.info.parent_type
222
+ }
223
+ if ! final_type.is_any_kind_of_pointer () && (left_final_sym.kind != .function
224
+ || (left_final_sym.language != .c && left_final_sym.kind == .placeholder))
225
+ && ! left_final_sym.is_heap () {
226
+ lt := c.table.sym (left_type).name
227
+ c.error ('cannot compare with `nil` because `${lt} ` is not a pointer' ,
228
+ node.pos)
229
+ }
230
+ }
200
231
}
201
232
.key_in, .not_in {
202
233
match right_final_sym.kind {
@@ -542,6 +573,9 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
542
573
c.error ('unwrapped Option cannot be compared in an infix expression' ,
543
574
opt_comp_pos)
544
575
}
576
+ if node.left.is_nil () || node.right.is_nil () {
577
+ c.error ('cannot use `${node.op.str()} ` with `nil`' , node.pos)
578
+ }
545
579
}
546
580
.key_like {
547
581
node.promoted_type = ast.bool_type
0 commit comments