Skip to content

Commit

Permalink
checker: add error for x as Y.field, suggesting using `(x as Y).fie…
Browse files Browse the repository at this point in the history
…ld` instead for clarity (#20725)
  • Loading branch information
Delta456 committed Feb 4, 2024
1 parent d0066ed commit 932574e
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 1 deletion.
4 changes: 4 additions & 0 deletions vlib/v/checker/checker.v
Expand Up @@ -1436,6 +1436,10 @@ fn (mut c Checker) selector_expr(mut node ast.SelectorExpr) ast.Type {
c.expr(mut node_expr)
name_type = node.expr.typ
}
ast.AsCast {
c.add_error_detail('for example `(${node.expr.expr} as ${c.table.type_to_str(node.expr.typ)}).${node.field_name}`')
c.error('indeterminate `as` cast, use parenthesis to clarity', node.expr.pos)
}
else {}
}
if name_type > 0 {
Expand Down
7 changes: 7 additions & 0 deletions vlib/v/checker/tests/as_cast_selector_expr_err.out
@@ -0,0 +1,7 @@
vlib/v/checker/tests/as_cast_selector_expr_err.vv:15:14: error: indeterminate `as` cast, use parenthesis to clarity
13 | fn main() {
14 | mut bar := Foobar(Bar{y: 123})
15 | println(bar as Bar.y == 123)
| ~~
16 | }
Details: for example `(bar as main.Bar).y`
16 changes: 16 additions & 0 deletions vlib/v/checker/tests/as_cast_selector_expr_err.vv
@@ -0,0 +1,16 @@
struct Foo {
mut:
x int
}

struct Bar {
mut:
y int
}

type Foobar = Foo | Bar

fn main() {
mut bar := Foobar(Bar{y: 123})
println(bar as Bar.y == 123)
}
2 changes: 1 addition & 1 deletion vlib/v/tests/as_cast_selector_test.v
Expand Up @@ -14,5 +14,5 @@ fn test_main() {
mut bar := Foobar(Bar{
y: 123
})
assert bar as Bar.y == 123
assert (bar as Bar).y == 123
}

0 comments on commit 932574e

Please sign in to comment.