checker, cgen: check comptime selector that has no field name (#14282)

yuyi 2022-05-04 12:06:52 +08:00 committed by Jef Roosens
parent 6c4f1ce196
commit 010ace62e1
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
4 changed files with 29 additions and 2 deletions

View File

@ -2661,7 +2661,7 @@ pub fn (mut c Checker) expr(node_ ast.Expr) ast.Type {
return c.comptime_call(mut node) return c.comptime_call(mut node)
} }
ast.ComptimeSelector { ast.ComptimeSelector {
node.left_type = c.unwrap_generic(c.expr(node.left)) node.left_type = c.expr(node.left)
expr_type := c.unwrap_generic(c.expr(node.field_expr)) expr_type := c.unwrap_generic(c.expr(node.field_expr))
expr_sym := c.table.sym(expr_type) expr_sym := c.table.sym(expr_type)
if expr_type != ast.string_type { if expr_type != ast.string_type {

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/comptime_selector_expr_type_err.vv:12:27: cgen error: `a` has no field named `value`
10 | for i in a {
11 | $for field in Row.fields {
12 | println('field $i: ' + a.$(field.name).str() )
| ^
13 | }
14 | }

View File

@ -0,0 +1,15 @@
module main
pub struct Row {
pub mut:
value string
}
fn main() {
a := []Row{}
for i in a {
$for field in Row.fields {
println('field $i: ' + a.$(field.name).str() )
}
}
}

View File

@ -20,7 +20,12 @@ fn (mut g Gen) comptime_selector(node ast.ComptimeSelector) {
if node.field_expr.expr is ast.Ident { if node.field_expr.expr is ast.Ident {
if node.field_expr.expr.name == g.comptime_for_field_var if node.field_expr.expr.name == g.comptime_for_field_var
&& node.field_expr.field_name == 'name' { && node.field_expr.field_name == 'name' {
g.write(c_name(g.comptime_for_field_value.name)) field_name := g.comptime_for_field_value.name
left_sym := g.table.sym(g.unwrap_generic(node.left_type))
_ := g.table.find_field_with_embeds(left_sym, field_name) or {
g.error('`$node.left` has no field named `$field_name`', node.left.pos())
}
g.write(c_name(field_name))
return return
} }
} }