Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker: add check if as cast used incorrectly for selector-expr #20725

Merged
merged 4 commits into from
Feb 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
}
Loading