Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker: check duplicate interfaces when implements for struct #22230

Merged
merged 5 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions vlib/v/checker/struct.v
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
// XTODO2
// cgen error if I use `println(sym)` without handling the option with `or{}`
struct_type := c.table.find_type_idx(node.name) // or { panic(err) }
mut names_used := []string{}
for t in node.implements_types {
t_sym := c.table.sym(t.typ)
if t_sym.info is ast.Interface {
Expand All @@ -350,6 +351,12 @@ fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
}
}
}
variant_name := c.table.type_to_str(t.typ)
if variant_name in names_used {
c.error('struct type ${node.name} cannot implement interface `${t_sym.name} more than once`',
t.pos)
}
names_used << variant_name
} else {
c.error('`${t_sym.name}` is not an interface type', t.pos)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
vlib/v/checker/tests/struct_implements_interface_more_than_once_err.vv:3:31: error: struct type Abc cannot implement interface `io.Writer more than once`
1 | import io { Writer }
2 |
3 | struct Abc implements Writer, Writer, Writer {
| ~~~~~~
4 | aaa string
5 | }
vlib/v/checker/tests/struct_implements_interface_more_than_once_err.vv:12:31: error: struct type Def cannot implement interface `io.Writer more than once`
10 |
11 | // vfmt off
12 | struct Def implements Writer, io.Writer {
| ~~
13 | aaa string
14 | }
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import io { Writer }

struct Abc implements Writer, Writer, Writer {
aaa string
}

fn (a Abc) write(buf []u8) !int {
return 42
}

// vfmt off
struct Def implements Writer, io.Writer {
aaa string
}
// vfmt on

fn (a Def) write(buf []u8) !int {
return 42
}
Loading