diff --git a/vlib/v/gen/c/comptime.v b/vlib/v/gen/c/comptime.v index 57ad0402f0..c5e12c4236 100644 --- a/vlib/v/gen/c/comptime.v +++ b/vlib/v/gen/c/comptime.v @@ -536,18 +536,30 @@ fn (mut g Gen) comptime_if_cond(cond ast.Expr, pkg_exist bool) (bool, bool) { } .eq, .ne { // TODO Implement `$if method.args.len == 1` - if cond.left is ast.SelectorExpr && g.comptime_for_method.len > 0 + if cond.left is ast.SelectorExpr + && (g.comptime_for_field_var.len > 0 || g.comptime_for_method.len > 0) && cond.right is ast.StringLiteral { selector := cond.left as ast.SelectorExpr - if selector.expr is ast.Ident - && (selector.expr as ast.Ident).name == g.comptime_for_method_var && selector.field_name == 'name' { - is_equal := g.comptime_for_method == cond.right.val - if is_equal { - g.write('1') - } else { - g.write('0') + if selector.expr is ast.Ident && selector.field_name == 'name' { + if g.comptime_for_method_var.len > 0 + && (selector.expr as ast.Ident).name == g.comptime_for_method_var { + is_equal := g.comptime_for_method == cond.right.val + if is_equal { + g.write('1') + } else { + g.write('0') + } + return is_equal, true + } else if g.comptime_for_field_var.len > 0 + && (selector.expr as ast.Ident).name == g.comptime_for_field_var { + is_equal := g.comptime_for_field_value.name == cond.right.val + if is_equal { + g.write('1') + } else { + g.write('0') + } + return is_equal, true } - return is_equal, true } } if cond.left is ast.SelectorExpr || cond.right is ast.SelectorExpr { diff --git a/vlib/v/tests/comptime_name_check_test.v b/vlib/v/tests/comptime_name_check_test.v new file mode 100644 index 0000000000..70121958b7 --- /dev/null +++ b/vlib/v/tests/comptime_name_check_test.v @@ -0,0 +1,30 @@ +struct User { + name string + age int +} + +fn (u User) a() {} + +fn (u User) b() {} + +fn (u User) c() {} + +fn test_method_name() { + mut out := []string{} + $for field in User.methods { + $if field.name == 'b' { + out << 'ok' + } + } + assert out.len == 1 +} + +fn test_field_name() { + mut out := []string{} + $for field in User.fields { + $if field.name == 'name' { + out << 'ok' + } + } + assert out.len == 1 +}