/
enums.go
106 lines (99 loc) · 1.72 KB
/
enums.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
// Copyright (C) 2015 A.Newman
//
package main
import (
"io"
)
type Enums struct {
Package string
Imports []string
Enums []EnumDefinition
Filename string
Time string
User string
}
type Enumerator struct {
Enum string
Tag string
}
type EnumDefinition struct {
TypeName string
BaseType Token
Enumerators []Enumerator
}
func ParseToEnd(r io.ReadCloser, e *Enums) error {
err := Parse(r, e)
r.Close()
return err
}
var (
intTypes = []Token{
TokByte,
TokInt,
TokUint,
TokInt8,
TokUint8,
TokInt16,
TokUint16,
TokInt32,
TokUint32,
TokInt64,
TokUint64,
}
)
func Parse(r io.Reader, e *Enums) error {
inEnum := false
var def EnumDefinition
p := NewParser(r)
p.MustMatch(TokPackage)
var ok bool
e.Package, ok = p.MustMatch(TokIdent)
if !ok {
return p.Err
}
for !p.Done() {
if inEnum {
if _, match := p.Match(TokRBrace); match {
e.Enums = append(e.Enums, def)
inEnum = false
} else {
tok, ok := p.MustMatch(TokIdent)
if !ok {
break
}
enum := Enumerator{tok, tok}
if tag, hasTag := p.Match(TokTag); hasTag {
enum.Tag = tag
}
def.Enumerators = append(def.Enumerators, enum)
}
} else {
_, ok = p.MustMatch(TokType)
if !ok {
break
}
def.TypeName, ok = p.MustMatch(TokIdent)
if !ok {
break
}
_, ok = p.MustMatch(TokEnum)
if !ok {
break
}
if _, matched := p.Match(TokLBrace); matched {
def.BaseType = TokInt
} else if baseType, matched := p.MatchOneOf(intTypes); matched {
def.BaseType = baseType
_, ok = p.MustMatch(TokLBrace)
if !ok {
break
}
} else {
return p.Syntax("expected '{' or <int-type>")
}
inEnum = true
def.Enumerators = nil
}
}
return p.Err
}