Skip to content

Commit

Permalink
checker: add scope validation for struct (fix #22437) (#22449)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Oct 9, 2024
1 parent 4c82b01 commit 72b4804
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 1 deletion.
4 changes: 3 additions & 1 deletion vlib/v/ast/types.v
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ pub mut:
@[minify]
pub struct Struct {
pub:
attrs []Attr
attrs []Attr
scope &Scope = unsafe { nil }
is_local bool
pub mut:
embeds []Type
fields []StructField
Expand Down
5 changes: 5 additions & 0 deletions vlib/v/checker/struct.v
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,11 @@ fn (mut c Checker) struct_init(mut node ast.StructInit, is_field_zero_struct_ini
mut old_cur_struct_generic_types := []ast.Type{}
mut old_cur_struct_concrete_types := []ast.Type{}
if struct_sym.info is ast.Struct {
if struct_sym.info.is_local && struct_sym.info.scope != unsafe { nil }
&& !struct_sym.info.scope.contains(node.pos.pos) {
c.error('struct `${struct_sym.name}` was declared in a local scope outside current scope',
node.pos)
}
// check if the generic param types have been defined
for ct in struct_sym.info.concrete_types {
ct_sym := c.table.sym(ct)
Expand Down
7 changes: 7 additions & 0 deletions vlib/v/checker/tests/struct_scope_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
vlib/v/checker/tests/struct_scope_err.vv:16:8: error: struct `Foobar` was declared in a local scope outside current scope
14 |
15 | fn x() {
16 | fb := Foobar{7, 8}
| ~~~~~~~~~~~~
17 | println(fb.bar)
18 | }
18 changes: 18 additions & 0 deletions vlib/v/checker/tests/struct_scope_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
fn main() {

struct Foobar {
foo int
bar int
}

if true {
fb := Foobar{5, 6}
println(fb.foo)
x()
}
}

fn x() {
fb := Foobar{7, 8}
println(fb.bar)
}
2 changes: 2 additions & 0 deletions vlib/v/parser/struct.v
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,8 @@ fn (mut p Parser) struct_decl(is_anon bool) ast.StructDecl {
generic_types: generic_types
attrs: attrs
is_anon: is_anon
is_local: p.inside_fn
scope: p.scope
}
is_pub: is_pub
}
Expand Down

0 comments on commit 72b4804

Please sign in to comment.