Skip to content

Commit 566c0f8

Browse files
committed
interfaces: support variadic arguments in func signatures
Fixes #7.
1 parent f88ea5b commit 566c0f8

File tree

2 files changed

+22
-9
lines changed

2 files changed

+22
-9
lines changed

func.go

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,28 @@ import (
44
"bytes"
55
"fmt"
66
"sort"
7+
"strings"
78
)
89

910
// Func represents an interface function.
1011
type Func struct {
11-
Name string `json:"name,omitempty"` // name of the function
12-
Ins []Type `json:"ins,omitempty"` // input parameters
13-
Outs []Type `json:"outs,omitempty"` // output parameters
12+
Name string `json:"name,omitempty"` // name of the function
13+
Ins []Type `json:"ins,omitempty"` // input parameters
14+
Outs []Type `json:"outs,omitempty"` // output parameters
15+
IsVariadic bool // whether the function is variadic
1416
}
1517

18+
var variadic = strings.NewReplacer("[]", "...")
19+
1620
// String gives Go code representation of the function.
1721
func (f Func) String() string {
1822
var buf bytes.Buffer
1923
if len(f.Ins) == 0 {
2024
fmt.Fprintf(&buf, "%s()", f.Name)
2125
} else {
22-
fmt.Fprintf(&buf, "%s(%s", f.Name, f.Ins[0])
23-
for _, typ := range f.Ins[1:] {
24-
fmt.Fprintf(&buf, ", %s", typ)
26+
fmt.Fprintf(&buf, "%s(%s", f.Name, f.in(0))
27+
for i := range f.Ins[1:] {
28+
fmt.Fprintf(&buf, ", %s", f.in(i+1))
2529
}
2630
buf.WriteString(")")
2731
}
@@ -37,6 +41,14 @@ func (f Func) String() string {
3741
return buf.String()
3842
}
3943

44+
func (f Func) in(i int) string {
45+
if typ := f.Ins[i]; i == len(f.Ins)-1 && f.IsVariadic {
46+
return variadic.Replace(typ.String())
47+
} else {
48+
return typ.String()
49+
}
50+
}
51+
4052
// Deps gives a list of packages the function depends on. E.g. if the function
4153
// represents Serve(net.Listener, http.Handler) error, calling Deps() will
4254
// return []string{"http", "net"}.

interface.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,10 @@ func buildInterfaceForPkg(pkg *loader.PackageInfo, opts *Options) (Interface, er
132132
ins := sig.Params()
133133
outs := sig.Results()
134134
fn := Func{
135-
Name: method.Name(),
136-
Ins: make([]Type, ins.Len()),
137-
Outs: make([]Type, outs.Len()),
135+
Name: method.Name(),
136+
Ins: make([]Type, ins.Len()),
137+
Outs: make([]Type, outs.Len()),
138+
IsVariadic: sig.Variadic(),
138139
}
139140
for i := range fn.Ins {
140141
fn.Ins[i] = newType(ins.At(i))

0 commit comments

Comments
 (0)