This repository has been archived by the owner on Jan 5, 2019. It is now read-only.
forked from emicklei/proto
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoption.go
115 lines (107 loc) · 2.48 KB
/
option.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
115
package proto
import "fmt"
// Option is a protoc compiler option
type Option struct {
Name string
Constant Literal
IsEmbedded bool
IsCustom bool // TODO needed?
}
// Accept dispatches the call to the visitor.
func (o *Option) Accept(v Visitor) {
v.VisitOption(o)
}
// columns returns printable source tokens
func (o *Option) columns() (cols []aligned) {
if !o.IsEmbedded {
cols = append(cols, leftAligned("option"))
} else {
cols = append(cols, leftAligned(" ["))
}
cols = append(cols, leftAligned(o.Name), leftAligned("="), rightAligned(o.Constant.String()))
if o.IsEmbedded {
cols = append(cols, leftAligned("]"))
}
return
}
// parse reads an Option body
// ( ident | "(" fullIdent ")" ) { "." ident } "=" constant ";"
func (o *Option) parse(p *Parser) error {
tok, lit := p.scanIgnoreWhitespace()
switch tok {
case tIDENT:
o.Name = lit
case tLEFTPAREN:
tok, lit = p.scanIgnoreWhitespace()
if tok != tIDENT {
return p.unexpected(lit, "identifier")
}
o.Name = lit
tok, lit = p.scanIgnoreWhitespace()
if tok != tRIGHTPAREN {
return p.unexpected(lit, ")")
}
default:
return p.unexpected(lit, "identifier or (")
}
tok, lit = p.scanIgnoreWhitespace()
if tok == tDOT {
// extend identifier
tok, lit = p.scanIgnoreWhitespace()
if tok != tIDENT {
return p.unexpected(lit, "postfix identifier")
}
o.Name = fmt.Sprintf("%s.%s", o.Name, lit)
tok, lit = p.scanIgnoreWhitespace()
}
if tok != tEQUALS {
return p.unexpected(lit, "=")
}
l := new(Literal)
if err := l.parse(p); err != nil {
return err
}
o.Constant = *l
return nil
}
// Literal represents intLit,floatLit,strLit or boolLit
type Literal struct {
Source string
IsString bool
}
// String returns the source (if quoted then use double quote).
func (l Literal) String() string {
if l.IsString {
return "\"" + l.Source + "\""
}
return l.Source
}
func (l *Literal) parse(p *Parser) error {
tok, lit := p.scanIgnoreWhitespace()
// stringLiteral?
if tok == tQUOTE {
ident := p.s.scanUntil('"')
if len(ident) == 0 {
return p.unexpected(lit, "quoted string")
}
l.Source, l.IsString = ident, true
return nil
}
// stringLiteral?
if tok == tSINGLEQUOTE {
ident := p.s.scanUntil('\'')
if len(ident) == 0 {
return p.unexpected(lit, "single quoted string")
}
l.Source, l.IsString = ident, true
return nil
}
// float, bool or intLit ?
if lit == "-" { // TODO token?
_, rem := p.s.scanIdent()
l.Source = "-" + rem
return nil
}
l.Source = lit
return nil
}