checker: default field fixes

pull/6338/head
Alexander Medvednikov 2020-09-09 14:05:56 +02:00
parent e018509ba6
commit 925f1781b3
3 changed files with 17 additions and 7 deletions

View File

@ -365,13 +365,16 @@ pub fn (mut c Checker) struct_decl(decl ast.StructDecl) {
field.default_expr.position()) field.default_expr.position())
} }
// Check for unnecessary inits like ` = 0` and ` = ''` // Check for unnecessary inits like ` = 0` and ` = ''`
if field.typ.is_ptr() {
continue
}
if field.default_expr is ast.IntegerLiteral as x { if field.default_expr is ast.IntegerLiteral as x {
if x.val == '0' { if x.val == '0' {
c.error('unnecessary default value of `0`: struct fields are zeroed by default', c.error('unnecessary default value of `0`: struct fields are zeroed by default',
field.pos) field.pos)
} }
} else if field.default_expr is ast.StringLiteral as x { } else if field.default_expr is ast.StringLiteral as x {
if x.val == "''" { if x.val == '' {
c.error("unnecessary default value of '': struct fields are zeroed by default", c.error("unnecessary default value of '': struct fields are zeroed by default",
field.pos) field.pos)
} }

View File

@ -4,3 +4,10 @@ vlib/v/checker/tests/struct_unneeded_default.vv:2:2: error: unnecessary default
| ~~~~~~ | ~~~~~~
3 | s string = '' 3 | s string = ''
4 | } 4 | }
vlib/v/checker/tests/struct_unneeded_default.vv:3:2: error: unnecessary default value of '': struct fields are zeroed by default
1 | struct Test {
2 | n int = 0
3 | s string = ''
| ~~~~~~~~~
4 | }
5 |

View File

@ -2,8 +2,8 @@ module main
struct Anything { struct Anything {
mut: mut:
name string = '' name string
keepo int = 0 keepo int
} }
fn (a Anything) str() string { fn (a Anything) str() string {
@ -34,8 +34,8 @@ fn test_array_of_ptrs_to_structs_can_be_printed() {
// (note the str method defined on (a &T), instead on (a T)) // (note the str method defined on (a &T), instead on (a T))
struct PstrAnything { struct PstrAnything {
mut: mut:
name string = '' name string
keepo int = 0 keepo int
} }
fn (a &PstrAnything) str() string { fn (a &PstrAnything) str() string {
@ -64,7 +64,7 @@ fn test_array_of_ptrs_to_structs_can_be_printed_when_structs_have_str_with_ptr()
// //
fn test_stack_array_of_structs_can_be_printed_when_structs_have_ordinary_str() { fn test_stack_array_of_structs_can_be_printed_when_structs_have_ordinary_str() {
mut t := [3]Anything mut t := [3]Anything{}
t[0] = Anything{ t[0] = Anything{
name: '012' name: '012'
} }
@ -86,7 +86,7 @@ fn test_stack_array_of_structs_can_be_printed_when_structs_have_ordinary_str() {
fn test_stack_array_of_structs_can_be_printed_when_structs_have_str_with_ptr() { fn test_stack_array_of_structs_can_be_printed_when_structs_have_str_with_ptr() {
// this generates a C error // this generates a C error
mut pt := [3]PstrAnything mut pt := [3]PstrAnything{}
pt[0] = PstrAnything{ pt[0] = PstrAnything{
name: 'P012' name: 'P012'
} }