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

master
yuyi 2022-05-04 12:06:52 +08:00 committed by GitHub
parent 1e9156fd71
commit f321422964
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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)
}
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_sym := c.table.sym(expr_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.name == g.comptime_for_field_var
&& 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
}
}