From f2060d431ec1c3e07d614afd7b70a2214c26b648 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 28 Apr 2020 15:52:01 +0800 Subject: [PATCH] checker: check division by zero --- vlib/v/checker/checker.v | 4 ++++ vlib/v/checker/tests/division_by_zero_err.out | 5 +++++ vlib/v/checker/tests/division_by_zero_err.vv | 3 +++ 3 files changed, 12 insertions(+) create mode 100644 vlib/v/checker/tests/division_by_zero_err.out create mode 100644 vlib/v/checker/tests/division_by_zero_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 87c28a295d..b4d8fb99b1 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -355,6 +355,10 @@ pub fn (mut c Checker) infix_expr(infix_expr mut ast.InfixExpr) table.Type { return table.bool_type } .plus, .minus, .mul, .div { + if infix_expr.op == .div && infix_expr.right is ast.IntegerLiteral && + infix_expr.right.str().int() == 0 { + c.error('division by zero', infix_expr.right.position()) + } if left.kind in [.array, .array_fixed, .map, .struct_] && !left.has_method(infix_expr.op.str()) { c.error('mismatched types `$left.name` and `$right.name`', infix_expr.left.position()) } else if right.kind in [.array, .array_fixed, .map, .struct_] && !right.has_method(infix_expr.op.str()) { diff --git a/vlib/v/checker/tests/division_by_zero_err.out b/vlib/v/checker/tests/division_by_zero_err.out new file mode 100644 index 0000000000..8f6d126f4f --- /dev/null +++ b/vlib/v/checker/tests/division_by_zero_err.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/division_by_zero_err.v:2:12: error: division by zero + 1| fn main() { + 2| println(1/0) + ^ + 3| } diff --git a/vlib/v/checker/tests/division_by_zero_err.vv b/vlib/v/checker/tests/division_by_zero_err.vv new file mode 100644 index 0000000000..996814a9a6 --- /dev/null +++ b/vlib/v/checker/tests/division_by_zero_err.vv @@ -0,0 +1,3 @@ +fn main() { + println(1/0) +}