From 140c7ea88908d1a3ccaf69efac39a778bffd6f0a Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Thu, 22 May 2025 11:32:00 +0300 Subject: [PATCH] parser: allow `mut static counter := 0` inside `unsafe {}` blocks (prepare for removing a `-translated` mode quirk) --- .../tests/static_vars_in_translated_mode.out | 2 +- vlib/v/parser/assign.v | 6 +++--- vlib/v/tests/static_vars_test.v | 13 +++++++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/vlib/v/checker/tests/static_vars_in_translated_mode.out b/vlib/v/checker/tests/static_vars_in_translated_mode.out index 0ad137ff4..4f35064ef 100644 --- a/vlib/v/checker/tests/static_vars_in_translated_mode.out +++ b/vlib/v/checker/tests/static_vars_in_translated_mode.out @@ -1,4 +1,4 @@ -vlib/v/checker/tests/static_vars_in_translated_mode.vv:2:13: error: static variables are supported only in translated mode or in @[unsafe] fn +vlib/v/checker/tests/static_vars_in_translated_mode.vv:2:13: error: static variables are supported only in -translated mode, `unsafe{}` blocks, or in `@[unsafe] fn` 1 | fn counter() int { 2 | mut static icounter := 0 | ~~~~~~~~ diff --git a/vlib/v/parser/assign.v b/vlib/v/parser/assign.v index 6d3f17c2b..7bd0beada 100644 --- a/vlib/v/parser/assign.v +++ b/vlib/v/parser/assign.v @@ -208,9 +208,9 @@ fn (mut p Parser) partial_assign_stmt(left []ast.Expr) ast.Stmt { if mut lx.info is ast.IdentVar { share = lx.info.share if lx.info.is_static { - if !p.pref.translated && !p.is_translated && !p.pref.is_fmt - && !p.inside_unsafe_fn { - return p.error_with_pos('static variables are supported only in translated mode or in @[unsafe] fn', + if !p.inside_unsafe && !p.pref.translated && !p.is_translated + && !p.pref.is_fmt && !p.inside_unsafe_fn { + return p.error_with_pos('static variables are supported only in -translated mode, `unsafe{}` blocks, or in `@[unsafe] fn`', lx.pos) } is_static = true diff --git a/vlib/v/tests/static_vars_test.v b/vlib/v/tests/static_vars_test.v index 5d51d5197..de286afa6 100644 --- a/vlib/v/tests/static_vars_test.v +++ b/vlib/v/tests/static_vars_test.v @@ -14,3 +14,16 @@ fn test_static_vars_work() { assert xfoo() == 44 assert xfoo() == 45 } + +fn test_static_vars_in_unsafe_blocks() { + f := fn () int { + unsafe { + mut static counter := 0 + counter++ + return counter + } + } + assert f() == 1 + assert f() == 2 + dump(f()) // 3 +} -- 2.39.5