Skip to content

Commit c752e5e

Browse files
committed
checker: add a suggestion for misspelled field names in struct literals
1 parent d3aa770 commit c752e5e

File tree

4 files changed

+25
-2
lines changed

4 files changed

+25
-2
lines changed

vlib/v/checker/struct.v

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
module checker
44

55
import v.ast
6+
import v.util
67

78
pub fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
89
mut struct_sym, struct_typ_idx := c.table.find_sym_and_type_idx(node.name)
@@ -391,7 +392,8 @@ pub fn (mut c Checker) struct_init(mut node ast.StructInit) ast.Type {
391392
ast.StructField{}
392393
}
393394
if !exists {
394-
c.error('unknown field `$field.name` in struct literal of type `$type_sym.name`',
395+
existing_fields := c.table.struct_fields(type_sym).map(it.name)
396+
c.error(util.new_suggestion(field.name, existing_fields).say('unknown field `$field.name` in struct literal of type `$type_sym.name`'),
395397
field.pos)
396398
continue
397399
}

vlib/v/checker/tests/struct_unknown_field.out

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
vlib/v/checker/tests/struct_unknown_field.vv:8:3: error: unknown field `bar` in struct literal of type `Test`
1+
vlib/v/checker/tests/struct_unknown_field.vv:8:3: error: unknown field `bar` in struct literal of type `Test`.
2+
1 possibility: `foo`.
23
6 | t := Test{
34
7 | foo: true
45
8 | bar: false
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
vlib/v/checker/tests/unknown_field_in_struct_literal.vv:10:2: error: unknown field `pos` in struct literal of type `TileLine`.
2+
Did you mean `ypos`?
3+
8 |
4+
9 | hline := TileLine{
5+
10 | pos: 123
6+
| ~~~~~~~~
7+
11 | }
8+
12 | println(hline)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
struct TileLine {
2+
ypos int
3+
mut:
4+
field [5]int
5+
points int
6+
shifts int
7+
}
8+
9+
hline := TileLine{
10+
pos: 123
11+
}
12+
println(hline)

0 commit comments

Comments
 (0)