From 6d35f68242c47a68983f3d3816db4916affaca56 Mon Sep 17 00:00:00 2001 From: kawa-yoiko <45892908+kawa-yoiko@users.noreply.github.com> Date: Fri, 30 Aug 2019 17:16:39 +0800 Subject: [PATCH] parser: restore outer variable in index exprs --- compiler/fn.v | 6 +++--- compiler/parser.v | 1 + compiler/tests/mut_test.v | 32 ++++++++++++++++++++++++++++++++ examples/nbody.v | 4 ++-- 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/compiler/fn.v b/compiler/fn.v index 535ccdaf67..f69206deab 100644 --- a/compiler/fn.v +++ b/compiler/fn.v @@ -53,7 +53,7 @@ fn (f mut Fn) close_scope() { f.defer_text = f.defer_text.left(f.scope_level + 1) } -fn (f &Fn) mark_var_used(v Var) { +fn (f mut Fn) mark_var_used(v Var) { for i, vv in f.local_vars { if vv.name == v.name { //mut ptr := &f.local_vars[i] @@ -64,7 +64,7 @@ fn (f &Fn) mark_var_used(v Var) { } } -fn (f &Fn) mark_var_changed(v Var) { +fn (f mut Fn) mark_var_changed(v Var) { for i, vv in f.local_vars { if vv.name == v.name { //mut ptr := &f.local_vars[i] @@ -75,7 +75,7 @@ fn (f &Fn) mark_var_changed(v Var) { } } -fn (f &Fn) known_var(name string) bool { +fn (f mut Fn) known_var(name string) bool { v := f.find_var(name) return v.name.len > 0 } diff --git a/compiler/parser.v b/compiler/parser.v index 76263afab5..776c116d25 100644 --- a/compiler/parser.v +++ b/compiler/parser.v @@ -1946,6 +1946,7 @@ fn (p mut Parser) index_expr(typ_ string, fn_ph int) string { if close_bracket { p.gen(']/*r$typ $v.is_mut*/') } + p.expr_var = v } // TODO move this from index_expr() // TODO if p.tok in ... diff --git a/compiler/tests/mut_test.v b/compiler/tests/mut_test.v index bedd0e83dd..61cea17da6 100644 --- a/compiler/tests/mut_test.v +++ b/compiler/tests/mut_test.v @@ -1,3 +1,13 @@ +struct A { +pub mut: + v []int +} + +struct B { +pub mut: + a []A +} + fn foo(b int, a mut []int) { a[0] = 7 a << 4 @@ -17,4 +27,26 @@ fn test_mut() { //mut b := mut a //b = 10 +} + +fn test_mut_2() { + zero := 0 + + mut b := B{} + b.a << A{} + + b.a[0].v = [9, 8, 7] + + b.a[0].v << 6 + b.a[zero].v << 5 + + b.a[0].v[zero] = 3 + b.a[0].v[b.a[zero].v[zero]] += 1b.a[0].v[b.a[0].v[zero]] += 1 + + assert b.a[0].v.len == 5 + assert b.a[0].v[0] == 3 + assert b.a[0].v[1] == 8 + assert b.a[0].v[2] == 7 + assert b.a[0].v[3] == 8 + assert b.a[0].v[4] == 5 } diff --git a/examples/nbody.v b/examples/nbody.v index 71106947b7..5fa23a457b 100644 --- a/examples/nbody.v +++ b/examples/nbody.v @@ -32,7 +32,7 @@ pub mut: s []Position } -fn advance(sys System, dt f64) { +fn advance(sys mut System, dt f64) { for i := 0; i < N - 1; i++ { mut _vx := sys.v[i].x mut _vy := sys.v[i].y @@ -125,7 +125,7 @@ offsetmomentum(mut sys) println('${energy(sys):.9f}') //-0.169075164 for i := 0; i < 50000000; i++ { - advance(sys, 0.01) + advance(mut sys, 0.01) } println('${energy(sys):.9f}') //-0.169059907