From 3647fc6633fd28f1c97721c0072bc309c8a1996b Mon Sep 17 00:00:00 2001 From: ChAoS_UnItY <43753315+ChAoSUnItY@users.noreply.github.com> Date: Sun, 10 Oct 2021 06:55:25 +0800 Subject: [PATCH] parser: perform constant folding before checking size of fixed array (#12126) --- vlib/v/parser/parse_type.v | 14 +++++++++++++- vlib/v/tests/constant_array_size_test.v | 12 ++++++++++++ vlib/v/transformer/transformer.v | 6 +++--- 3 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 vlib/v/tests/constant_array_size_test.v diff --git a/vlib/v/parser/parse_type.v b/vlib/v/parser/parse_type.v index c1a30f001d..201ac927fc 100644 --- a/vlib/v/parser/parse_type.v +++ b/vlib/v/parser/parse_type.v @@ -3,6 +3,7 @@ // that can be found in the LICENSE file. module parser +import v.transformer import v.ast import v.util import v.token @@ -26,7 +27,18 @@ pub fn (mut p Parser) parse_array_type() ast.Type { if const_field.expr is ast.IntegerLiteral { fixed_size = const_field.expr.val.int() } else { - show_non_const_error = true + if const_field.expr is ast.InfixExpr { + t := transformer.new_transformer(p.pref) + folded_expr := t.infix_expr(const_field.expr) + + if folded_expr is ast.IntegerLiteral { + fixed_size = folded_expr.val.int() + } else { + show_non_const_error = true + } + } else { + show_non_const_error = true + } } } else { if p.pref.is_fmt { diff --git a/vlib/v/tests/constant_array_size_test.v b/vlib/v/tests/constant_array_size_test.v new file mode 100644 index 0000000000..9b575ba1e7 --- /dev/null +++ b/vlib/v/tests/constant_array_size_test.v @@ -0,0 +1,12 @@ +const ( + c_a_s = 1 + c_b_s = 1 + 1 + c_c_s = c_b_s + 1 // this should be also fold by transformer since it's a constant +) + +fn test_consant_array_size() { + mut a := [c_a_s]int{} + a = [1]! + mut b := [c_b_s]int{} + b = [1, 2]! +} diff --git a/vlib/v/transformer/transformer.v b/vlib/v/transformer/transformer.v index 61a2d915ee..a91a3a2776 100644 --- a/vlib/v/transformer/transformer.v +++ b/vlib/v/transformer/transformer.v @@ -26,7 +26,7 @@ pub fn (t Transformer) transform(ast_file &ast.File) { } } -fn (t Transformer) stmt(mut node ast.Stmt) { +pub fn (t Transformer) stmt(mut node ast.Stmt) { match mut node { ast.EmptyStmt {} ast.NodeError {} @@ -88,14 +88,14 @@ fn (t Transformer) stmt(mut node ast.Stmt) { } } -fn (t Transformer) expr(node ast.Expr) ast.Expr { +pub fn (t Transformer) expr(node ast.Expr) ast.Expr { match node { ast.InfixExpr { return t.infix_expr(node) } else { return node } } } -fn (t Transformer) infix_expr(original ast.InfixExpr) ast.Expr { +pub fn (t Transformer) infix_expr(original ast.InfixExpr) ast.Expr { mut node := original node.left = t.expr(node.left) node.right = t.expr(node.right)