-
Notifications
You must be signed in to change notification settings - Fork 2
/
declaration.go
60 lines (47 loc) · 1.44 KB
/
declaration.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
package varnamelen
import "strings"
// identDeclaration is an ident declaration.
type identDeclaration struct {
// name is the name of the ident.
name string
// constant is true if the declaration is actually declaring a constant.
constant bool
// typ is the type of the ident. Not used for constants.
typ string
}
// A declarationError is returned when an ident declaration cannot be parsed.
type declarationError string
// mustParseIdentDeclaration parses and returns an ident declaration parsed from decl.
func mustParseIdentDeclaration(decl string) identDeclaration {
d, _ := parseIdentDeclaration(decl)
return d
}
// parseIdentDeclaration parses and returns an ident declaration parsed from decl.
func parseIdentDeclaration(decl string) (identDeclaration, error) {
if strings.HasPrefix(decl, "const ") {
name := strings.TrimPrefix(decl, "const ")
if strings.TrimSpace(name) == "" {
return identDeclaration{}, declarationError(decl)
}
return identDeclaration{
name: name,
constant: true,
}, nil
}
parts := strings.SplitN(decl, " ", 2)
if len(parts) != 2 {
return identDeclaration{}, declarationError(decl)
}
return identDeclaration{
name: parts[0],
typ: parts[1],
}, nil
}
// matchType returns true if typ matches d.typ.
func (d identDeclaration) matchType(typ string) bool {
return d.typ == typ
}
// Error implements error.
func (e declarationError) Error() string {
return string(e) + ": invalid declaration"
}