Skip to content

Commit 3176e7a

Browse files
authored
transformer: simplify (literal) and (ident) expressions too (#25440)
1 parent 396ef5c commit 3176e7a

2 files changed

Lines changed: 18 additions & 7 deletions

File tree

‎vlib/v/transformer/tests/const_infix_expr_test.v‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ import v.parser
44
import v.checker
55
import v.transformer
66

7-
fn test_const_infix_expr() {
7+
fn test_const_par_expr_and_infix_expr() {
88
println(@LOCATION)
99
source_text := '
1010
const k = 2
1111
fn main() {
12-
x := [(k-1)*2]int{}
12+
x := [(k+1)-2+(2*(k))]int{}
1313
}
1414
'
1515
mut table := ast.new_table()
@@ -19,15 +19,15 @@ fn main() {
1919
checker_.check(mut prog)
2020
mut t := transformer.new_transformer_with_table(table, vpref)
2121

22-
// get the `InfixExpr`(`(k-1)*2`) from table
23-
main_fn := unsafe { table.cur_fn[0] }
22+
// get the `InfixExpr`(`(k+1)-2+(2*(k))`) from table
23+
main_fn := table.cur_fn
2424
assign_stmt := main_fn.stmts[0] as ast.AssignStmt
2525
array_init_expr := assign_stmt.right[0] as ast.ArrayInit
2626
mut dim_expr := array_init_expr.exprs[0] as ast.InfixExpr
2727
dump(dim_expr)
2828

29-
// verify `infix_expr` work as expected
29+
// verify `infix_expr` and `par_expr` work as expected
3030
folded_expr := t.infix_expr(mut dim_expr)
3131
dump(folded_expr)
32-
assert '${folded_expr}' == '(1) * 2'
32+
assert '${folded_expr}' == '5'
3333
}

‎vlib/v/transformer/transformer.v‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -650,7 +650,18 @@ pub fn (mut t Transformer) expr(mut node ast.Expr) ast.Expr {
650650
}
651651
}
652652
ast.ParExpr {
653-
node.expr = t.expr(mut node.expr)
653+
mut inner_expr := t.expr(mut node.expr)
654+
if inner_expr in [
655+
ast.IntegerLiteral,
656+
ast.FloatLiteral,
657+
ast.BoolLiteral,
658+
ast.StringLiteral,
659+
ast.StringInterLiteral,
660+
ast.CharLiteral,
661+
ast.Ident,
662+
] {
663+
return inner_expr
664+
}
654665
}
655666
ast.PostfixExpr {
656667
node.expr = t.expr(mut node.expr)

0 commit comments

Comments
 (0)