forked from emicklei/proto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
419 lines (389 loc) · 10.4 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// Copyright (c) 2017 Ernest Micklei
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package proto
import (
"bytes"
"fmt"
"sort"
"text/scanner"
)
// Option is a protoc compiler option
type Option struct {
Position scanner.Position
Comment *Comment
Name string
Constant Literal
IsEmbedded bool
// AggregatedConstants is DEPRECATED. These Literals are populated into Constant.OrderedMap
AggregatedConstants []*NamedLiteral
InlineComment *Comment
Parent Visitee
}
// parse reads an Option body
// ( ident | "(" fullIdent ")" ) { "." ident } "=" constant ";"
func (o *Option) parse(p *Parser) error {
pos, tok, lit := p.nextIdentifier()
if tLEFTPAREN == tok {
pos, tok, lit = p.nextIdentifier()
if tok != tIDENT {
if !isKeyword(tok) {
return p.unexpected(lit, "option full identifier", o)
}
}
pos, tok, _ = p.next()
if tok != tRIGHTPAREN {
return p.unexpected(lit, "option full identifier closing )", o)
}
o.Name = fmt.Sprintf("(%s)", lit)
} else {
if tCOMMENT == tok {
nc := newComment(pos, lit)
if o.Comment != nil {
o.Comment.Merge(nc)
} else {
o.Comment = nc
}
return o.parse(p)
}
// non full ident
if tIDENT != tok {
if !isKeyword(tok) {
return p.unexpected(lit, "option identifier", o)
}
}
o.Name = lit
}
pos, tok, lit = p.next()
if tDOT == tok {
// extend identifier
pos, tok, lit = p.nextIdent(true) // keyword allowed as start
if tok != tIDENT {
if !isKeyword(tok) {
return p.unexpected(lit, "option postfix identifier", o)
}
}
o.Name = fmt.Sprintf("%s.%s", o.Name, lit)
pos, tok, lit = p.next()
}
if tEQUALS != tok {
return p.unexpected(lit, "option value assignment =", o)
}
r := p.peekNonWhitespace()
var err error
// values of an option can have illegal escape sequences
// for the standard Go scanner used by this package.
p.ignoreIllegalEscapesWhile(func() {
if '{' == r {
// aggregate
p.next() // consume {
err = o.parseAggregate(p)
} else {
// non aggregate
l := new(Literal)
l.Position = pos
if e := l.parse(p); e != nil {
err = e
}
o.Constant = *l
}
})
return err
}
// inlineComment is part of commentInliner.
func (o *Option) inlineComment(c *Comment) {
o.InlineComment = c
}
// Accept dispatches the call to the visitor.
func (o *Option) Accept(v Visitor) {
v.VisitOption(o)
}
// Doc is part of Documented
func (o *Option) Doc() *Comment {
return o.Comment
}
// Literal represents intLit,floatLit,strLit or boolLit or a nested structure thereof.
type Literal struct {
Position scanner.Position
Source string
IsString bool
// It not nil then the entry is actually a comment with line(s)
// modelled this way because Literal is not an elementContainer
Comment *Comment
// The rune use to delimit the string value (only valid iff IsString)
QuoteRune rune
// literal value can be an array literal value (even nested)
Array []*Literal
// literal value can be a map of literals (even nested)
// DEPRECATED: use OrderedMap instead
Map map[string]*Literal
// literal value can be a map of literals (even nested)
// this is done as pairs of name keys and literal values so the original ordering is preserved
OrderedMap LiteralMap
}
var emptyRune rune
// LiteralMap is like a map of *Literal but preserved the ordering.
// Can be iterated yielding *NamedLiteral values.
type LiteralMap []*NamedLiteral
// Get returns a Literal from the map.
func (m LiteralMap) Get(key string) (*Literal, bool) {
for _, each := range m {
if each.Name == key {
// exit on the first match
return each.Literal, true
}
}
return new(Literal), false
}
// SourceRepresentation returns the source (use the same rune that was used to delimit the string).
func (l Literal) SourceRepresentation() string {
var buf bytes.Buffer
if l.IsString {
if l.QuoteRune == emptyRune {
buf.WriteRune('"')
} else {
buf.WriteRune(l.QuoteRune)
}
}
buf.WriteString(l.Source)
if l.IsString {
if l.QuoteRune == emptyRune {
buf.WriteRune('"')
} else {
buf.WriteRune(l.QuoteRune)
}
}
return buf.String()
}
// parse expects to read a literal constant after =.
func (l *Literal) parse(p *Parser) error {
pos, tok, lit := p.next()
// handle special element inside literal, a comment line
if isComment(lit) {
nc := newComment(pos, lit)
if l.Comment == nil {
l.Comment = nc
} else {
l.Comment.Merge(nc)
}
// continue with remaining entries
return l.parse(p)
}
if tok == tLEFTSQUARE {
// collect array elements
array := []*Literal{}
// if it's an empty array, consume the close bracket, set the Array to
// an empty array, and return
r := p.peekNonWhitespace()
if ']' == r {
pos, _, _ := p.next()
l.Array = array
l.IsString = false
l.Position = pos
return nil
}
for {
e := new(Literal)
if err := e.parse(p); err != nil {
return err
}
array = append(array, e)
_, tok, lit := p.next()
if tok == tCOMMA {
continue
}
if tok == tRIGHTSQUARE {
break
}
return p.unexpected(lit, ", or ]", l)
}
l.Array = array
l.IsString = false
l.Position = pos
return nil
}
if tLEFTCURLY == tok {
l.Position, l.Source, l.IsString = pos, "", false
constants, err := parseAggregateConstants(p, l)
if err != nil {
return nil
}
l.OrderedMap = LiteralMap(constants)
return nil
}
if "-" == lit {
// negative number
if err := l.parse(p); err != nil {
return err
}
// modify source and position
l.Position, l.Source = pos, "-"+l.Source
return nil
}
source := lit
iss := isString(lit)
if iss {
source, l.QuoteRune = unQuote(source)
}
l.Position, l.Source, l.IsString = pos, source, iss
// peek for multiline strings
for {
pos, tok, lit := p.next()
if isString(lit) {
line, _ := unQuote(lit)
l.Source += line
} else {
p.nextPut(pos, tok, lit)
break
}
}
return nil
}
// NamedLiteral associates a name with a Literal
type NamedLiteral struct {
*Literal
Name string
// PrintsColon is true when the Name must be printed with a colon suffix
PrintsColon bool
}
// parseAggregate reads options written using aggregate syntax.
// tLEFTCURLY { has been consumed
func (o *Option) parseAggregate(p *Parser) error {
constants, err := parseAggregateConstants(p, o)
literalMap := map[string]*Literal{}
for _, each := range constants {
literalMap[each.Name] = each.Literal
}
o.Constant = Literal{Map: literalMap, OrderedMap: constants, Position: o.Position}
// reconstruct the old, deprecated field
o.AggregatedConstants = collectAggregatedConstants(literalMap)
return err
}
// flatten the maps of each literal, recursively
// this func exists for deprecated Option.AggregatedConstants.
func collectAggregatedConstants(m map[string]*Literal) (list []*NamedLiteral) {
for k, v := range m {
if v.Map != nil {
sublist := collectAggregatedConstants(v.Map)
for _, each := range sublist {
list = append(list, &NamedLiteral{
Name: k + "." + each.Name,
PrintsColon: true,
Literal: each.Literal,
})
}
} else {
list = append(list, &NamedLiteral{
Name: k,
PrintsColon: true,
Literal: v,
})
}
}
// sort list by position of literal
sort.Sort(byPosition(list))
return
}
type byPosition []*NamedLiteral
func (b byPosition) Less(i, j int) bool {
return b[i].Literal.Position.Line < b[j].Literal.Position.Line
}
func (b byPosition) Len() int { return len(b) }
func (b byPosition) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func parseAggregateConstants(p *Parser, container interface{}) (list []*NamedLiteral, err error) {
for {
pos, tok, lit := p.nextIdentifier()
if tRIGHTSQUARE == tok {
p.nextPut(pos, tok, lit)
// caller has checked for open square ; will consume rightsquare, rightcurly and semicolon
return
}
if tRIGHTCURLY == tok {
return
}
if tSEMICOLON == tok {
// just consume it
continue
//return
}
if tCOMMENT == tok {
// assign to last parsed literal
// TODO: see TestUseOfSemicolonsInAggregatedConstants
continue
}
if tCOMMA == tok {
if len(list) == 0 {
err = p.unexpected(lit, "non-empty option aggregate key", container)
return
}
continue
}
if tIDENT != tok && !isKeyword(tok) {
err = p.unexpected(lit, "option aggregate key", container)
return
}
// workaround issue #59 TODO
if isString(lit) && len(list) > 0 {
// concatenate with previous constant
s, _ := unQuote(lit)
list[len(list)-1].Source += s
continue
}
key := lit
printsColon := false
// expect colon, aggregate or plain literal
pos, tok, lit = p.next()
if tCOLON == tok {
// consume it
printsColon = true
pos, tok, lit = p.next()
}
// see if nested aggregate is started
if tLEFTCURLY == tok {
nested, fault := parseAggregateConstants(p, container)
if fault != nil {
err = fault
return
}
// create the map
m := map[string]*Literal{}
for _, each := range nested {
m[each.Name] = each.Literal
}
list = append(list, &NamedLiteral{
Name: key,
PrintsColon: printsColon,
Literal: &Literal{Map: m, OrderedMap: LiteralMap(nested)}})
continue
}
// no aggregate, put back token
p.nextPut(pos, tok, lit)
// now we see plain literal
l := new(Literal)
l.Position = pos
if err = l.parse(p); err != nil {
return
}
list = append(list, &NamedLiteral{Name: key, Literal: l, PrintsColon: printsColon})
}
}
func (o *Option) parent(v Visitee) { o.Parent = v }