parser: error on non local array/map methods & add tests

pull/7270/head
joe-conigliaro 2020-12-11 20:50:26 +11:00
parent a0d10a6606
commit d1224ffb5a
No known key found for this signature in database
GPG Key ID: C12F7136C08206F1
8 changed files with 33 additions and 2 deletions

View File

@ -1,4 +1,4 @@
pub fn (a []int) reduce(iter fn (int, int) int, accum_start int) int { pub fn reduce(a []int, iter fn (int, int) int, accum_start int) int {
iter(accum_start) iter(accum_start)
} }

View File

@ -281,7 +281,14 @@ fn (mut p Parser) fn_decl() ast.FnDecl {
// Do not allow to modify / add methods to types from other modules // Do not allow to modify / add methods to types from other modules
// arrays/maps dont belong to a module only their element types do // arrays/maps dont belong to a module only their element types do
// we could also check if kind is .array, .array_fixed, .map instead of mod.len // we could also check if kind is .array, .array_fixed, .map instead of mod.len
if type_sym.mod.len > 0 && type_sym.mod != p.mod && type_sym.language == .v { mut is_non_local := type_sym.mod.len > 0 && type_sym.mod != p.mod && type_sym.language == .v
// check maps & arrays, must be defined in same module as the elem type
if !is_non_local && type_sym.kind in [.array, .map] {
elem_type_sym := p.table.get_type_symbol(p.table.value_type(rec_type))
is_non_local = elem_type_sym.mod.len > 0 &&
elem_type_sym.mod != p.mod && elem_type_sym.language == .v
}
if is_non_local {
p.error_with_pos('cannot define new methods on non-local type $type_sym.name', p.error_with_pos('cannot define new methods on non-local type $type_sym.name',
rec_type_pos) rec_type_pos)
return ast.FnDecl{} return ast.FnDecl{}

View File

@ -0,0 +1,5 @@
vlib/v/parser/tests/method_decl_on_non_local_array.vv:1:7: error: cannot define new methods on non-local type []int
1 | fn (a []int) get_number() int {
| ~~~~~
2 | return 1
3 | }

View File

@ -0,0 +1,3 @@
fn (a []int) get_number() int {
return 1
}

View File

@ -0,0 +1,5 @@
vlib/v/parser/tests/method_decl_on_non_local_map.vv:1:7: error: cannot define new methods on non-local type map[string]string
1 | fn (a map[string]string) get_number() int {
| ~~~~~~~~~~~~~~~~~
2 | return 1
3 | }

View File

@ -0,0 +1,3 @@
fn (a map[string]string) get_number() int {
return 1
}

View File

@ -0,0 +1,5 @@
vlib/v/parser/tests/method_decl_on_non_local_type.vv:1:7: error: cannot define new methods on non-local type int
1 | fn (a int) get_number() int {
| ~~~
2 | return 1
3 | }

View File

@ -0,0 +1,3 @@
fn (a int) get_number() int {
return 1
}