/
type_map.go
56 lines (45 loc) · 1.25 KB
/
type_map.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
package main
import (
"errors"
"strings"
"github.com/taylorchu/generic/rewrite"
)
// ParseTypeMap parses raw strings to type replacements.
func ParseTypeMap(args []string) (map[string]rewrite.Type, error) {
typeMap := make(map[string]rewrite.Type)
for _, arg := range args {
part := strings.Split(arg, "->")
if len(part) != 2 {
return nil, errors.New("RULE must be in form of `TypeXXX->OtherType`")
}
var (
from = strings.TrimSpace(part[0])
to = strings.TrimSpace(part[1])
)
if !strings.HasPrefix(from, "Type") {
return nil, errors.New("REPL type must start with `Type`")
}
var t rewrite.Type
if strings.Contains(to, ":") {
toPart := strings.Split(to, ":")
if len(toPart) != 2 {
return nil, errors.New("REPL type must be in form of DESTPATH:OtherType")
}
t.Import = []string{strings.TrimSpace(toPart[0])}
t.Expr = strings.TrimSpace(toPart[1])
if strings.Count(t.Expr, ".") != 1 {
return nil, errors.New("REPL type must contain one `.`")
}
} else {
t.Expr = to
if strings.Count(t.Expr, ".") != 0 {
return nil, errors.New("REPL type must not contain `.`")
}
}
if t.Expr == "" {
return nil, errors.New("REPL type cannot be empty")
}
typeMap[from] = t
}
return typeMap, nil
}