From 633d5f27be2e6a41ad74c39a5489178fc7e8cde3 Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 5 Sep 2024 10:19:10 +0800 Subject: [PATCH] cgen: fix generic options with reserved ident (#22164) --- vlib/v/gen/c/assign.v | 4 ++-- .../generic_options_with_reserved_ident_test.v | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/generics/generic_options_with_reserved_ident_test.v diff --git a/vlib/v/gen/c/assign.v b/vlib/v/gen/c/assign.v index 3f209d757..5e58f97eb 100644 --- a/vlib/v/gen/c/assign.v +++ b/vlib/v/gen/c/assign.v @@ -25,7 +25,7 @@ fn (mut g Gen) expr_with_opt_or_block(expr ast.Expr, expr_typ ast.Type, var_expr } else { '${expr}' } - g.writeln('if (${expr_var}.state != 0) { // assign') + g.writeln('if (${c_name(expr_var)}.state != 0) { // assign') if expr is ast.Ident && expr.or_expr.kind == .propagate_option { g.writeln('\tpanic_option_not_set(_SLIT("none"));') } else { @@ -37,7 +37,7 @@ fn (mut g Gen) expr_with_opt_or_block(expr ast.Expr, expr_typ ast.Type, var_expr // handles stmt block which returns something // e.g. { return none } if stmts.len > 0 && stmts.last() is ast.ExprStmt && stmts.last().typ != ast.void_type { - g.gen_or_block_stmts(var_expr.str(), '', stmts, ret_typ, false) + g.gen_or_block_stmts(c_name(var_expr.str()), '', stmts, ret_typ, false) } else { // handles stmt block which doesn't returns value // e.g. { return } diff --git a/vlib/v/tests/generics/generic_options_with_reserved_ident_test.v b/vlib/v/tests/generics/generic_options_with_reserved_ident_test.v new file mode 100644 index 000000000..499ef6256 --- /dev/null +++ b/vlib/v/tests/generics/generic_options_with_reserved_ident_test.v @@ -0,0 +1,15 @@ +pub fn f[T](defaults ?T) T { + default := defaults or { T{} } + dump(default) + return default +} + +fn test_generic_options_with_reserved_ident() { + ret1 := f(123) + println(ret1) + assert ret1 == 123 + + ret2 := f('hello') + println(ret2) + assert ret2 == 'hello' +} -- 2.39.5