-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathargfmt.go
114 lines (103 loc) · 2.51 KB
/
argfmt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"fmt"
"strings"
"github.com/avoronkov/spil/types"
)
type ArgFmt struct {
Args []Arg
// list argument that matches everything
Wildcard string
}
func (a *ArgFmt) Values() map[string]types.Type {
m := make(map[string]types.Type)
if a.Wildcard != "" {
m[a.Wildcard] = types.TypeList
} else {
for _, arg := range a.Args {
if arg.Name != "" {
m[arg.Name] = arg.T
}
}
}
return m
}
func MakeArgFmt(args ...Arg) (a *ArgFmt) {
a = &ArgFmt{}
for _, arg := range args {
a.Args = append(a.Args, arg)
}
return
}
func MakeWildcard(name string) *ArgFmt {
return &ArgFmt{Wildcard: name}
}
type Arg struct {
Name string
T types.Type
V types.Expr
}
func ParseArgFmt(argfmt types.Expr) (*ArgFmt, error) {
switch a := argfmt.(type) {
case types.Ident:
// pass arguments as list with specified name
return &ArgFmt{Wildcard: string(a)}, nil
case *types.Sexpr:
// bind arguments
result := &ArgFmt{}
for _, arg := range a.List {
switch r := arg.E.(type) {
case types.Int:
result.Args = append(result.Args, Arg{"", types.TypeInt, arg.E})
case types.Str:
result.Args = append(result.Args, Arg{"", types.TypeStr, arg.E})
case types.Bool:
result.Args = append(result.Args, Arg{"", types.TypeBool, arg.E})
case *types.Sexpr:
if !r.Empty() {
return nil, fmt.Errorf("Unexpected non-empty list in a list of arguments")
}
result.Args = append(result.Args, Arg{"", types.TypeList, arg.E})
case types.Ident:
if colon := strings.Index(string(r), ":"); colon >= 0 {
tp, ok := types.ParseType(string(r)[colon:])
if !ok {
return nil, fmt.Errorf("Unknown type is specified in argument %v", arg)
}
result.Args = append(result.Args, Arg{string(r)[:colon], tp, nil})
} else {
result.Args = append(result.Args, Arg{string(r), types.TypeUnknown, nil})
}
}
}
return result, nil
default:
return nil, fmt.Errorf("Expected arguments signature, found: %v", argfmt)
}
}
type Param struct {
T types.Type
V types.Expr
}
func MakeParametersFromArgs(args []types.Expr) (res []types.Value) {
for _, arg := range args {
p := types.Value{E: arg}
switch arg.(type) {
case types.Int:
p.T = types.TypeInt
case types.Str:
p.T = types.TypeStr
case types.Bool:
p.T = types.TypeBool
case types.List:
p.T = types.TypeList
case types.Ident:
// TODO maybe check that function exist
p.T = types.TypeFunc
default:
panic(fmt.Errorf("Unexpected Expr type: %v (%v)", arg, arg))
}
res = append(res, p)
}
return
}