-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtype.go
99 lines (91 loc) · 2.13 KB
/
type.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
package main
import (
"fmt"
"strings"
"unicode"
)
// Type describes a concrete type.
type Type struct {
Pkg string
PkgName string
Name string
Aliased bool
Pointer bool
}
func isIdentifier(s string) (bool, int) {
if len(s) == 0 {
return false, -1
}
firstRune := []rune(s)[0]
if !unicode.IsLetter(firstRune) && firstRune != '_' {
return false, 0
}
firstError := strings.IndexFunc(s, func(r rune) bool {
return !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_'
})
if firstError != -1 {
return false, firstError
}
return true, -1
}
func validateType(t Type) (Type, error) {
if ok, idx := isIdentifier(t.Name); !ok {
return t, fmt.Errorf("invalid type: %v (at %v)", t.Name, idx)
}
if ok, idx := isIdentifier(t.PkgName); !ok && idx != -1 {
return t, fmt.Errorf("invalid package name: %v (at %v)", t.PkgName, idx)
}
return t, nil
}
// ParseType parses a type string.
// The following formats are accepted:
// ConcreteType
// pkg/pkg/pkg.ConcreteType
// ("pkg/pkg/go-pkg")pkg.ConcreteType
// *ConcreteType
// *pkg/pkg/pkg.ConcreteType
// *("pkg/pkg/go-pkg")pkg.ConcreteType
func ParseType(s string) (Type, error) {
Pointer := false
if strings.HasPrefix(s, "*") {
s = s[1:]
Pointer = true
}
dotIdx := strings.LastIndex(s, ".")
if dotIdx == -1 {
return validateType(Type{
Pkg: "",
PkgName: "",
Name: s,
Pointer: Pointer,
})
}
packagePart := s[:dotIdx]
typeName := s[dotIdx+1:]
pkgImport := packagePart
pkgName := packagePart
aliased := false
if strings.HasPrefix(packagePart, `("`) {
closeIdx := strings.LastIndex(packagePart, `")`)
if closeIdx == -1 {
return Type{
Pkg: packagePart,
PkgName: packagePart,
Name: typeName,
Pointer: Pointer,
}, fmt.Errorf(`invalid type specification %v: missing closing ")`, s)
}
pkgImport = packagePart[2:closeIdx]
pkgName = packagePart[closeIdx+2:]
aliased = true
} else if slashIdx := strings.LastIndex(packagePart, "/"); slashIdx != -1 {
pkgName = packagePart[slashIdx+1:]
}
return validateType(Type{
Pkg: pkgImport,
PkgName: pkgName,
Name: typeName,
Aliased: aliased,
Pointer: Pointer,
})
}