From d180324413b2e2bef98ba6fc97ad075688f83398 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Wed, 18 Sep 2019 14:28:11 +0300 Subject: [PATCH] find_field: use optional --- compiler/parser.v | 4 ++-- compiler/table.v | 33 ++++++++++++++++++++------------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/compiler/parser.v b/compiler/parser.v index 91ca3e43b7..4308645b81 100644 --- a/compiler/parser.v +++ b/compiler/parser.v @@ -1818,7 +1818,7 @@ fn (p mut Parser) dot(str_typ string, method_ph int) string { // field if has_field { struct_field := if typ.name != 'Option' { p.table.var_cgen_name(field_name) } else { field_name } - field := p.table.find_field(typ, struct_field) + field := p.table.find_field(typ, struct_field) or { panic('field') } if !field.is_mut && !p.has_immutable_field { p.has_immutable_field = true p.first_immutable_field = field @@ -2786,7 +2786,7 @@ fn (p mut Parser) struct_init(typ string) string { if field in inited_fields { p.error('already initialized field `$field` in `$t.name`') } - f := t.find_field(field) + f := t.find_field(field) or { panic('field') } inited_fields << field p.gen_struct_field_init(field) p.check(.colon) diff --git a/compiler/table.v b/compiler/table.v index 32fe017cc6..8c2ad64b7f 100644 --- a/compiler/table.v +++ b/compiler/table.v @@ -400,36 +400,43 @@ fn (table mut Table) add_field(type_name, field_name, field_type string, is_mut } fn (t &Type) has_field(name string) bool { - field := t.find_field(name) - return (field.name != '') + _ := t.find_field(name) or { return false } + return true } fn (t &Type) has_enum_val(name string) bool { return name in t.enum_vals } -fn (t &Type) find_field(name string) Var { +fn (t &Type) find_field(name string) ?Var { for field in t.fields { if field.name == name { return field } } - //println('ret Var{}') - return Var{} + return none } fn (table &Table) type_has_field(typ &Type, name string) bool { - field := table.find_field(typ, name) - return (field.name != '') + _ := table.find_field(typ, name) or { return false } + return true } -fn (table &Table) find_field(typ &Type, name string) Var { - field := typ.find_field(name) - if field.name.len == 0 && typ.parent.len > 0 { - parent := table.find_type(typ.parent) - return parent.find_field(name) +fn (table &Table) find_field(typ &Type, name string) ?Var { + for field in typ.fields { + if field.name == name { + return field + } } - return field + if typ.parent != '' { + parent := table.find_type(typ.parent) + for field in parent.fields { + if field.name == name { + return field + } + } + } + return none } fn (table mut Table) add_method(type_name string, f Fn) {