-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
parse.js
769 lines (642 loc) · 18.9 KB
/
parse.js
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
var tokenize = require('./tokenize')
var MAX_RANGE = 0x1FFFFFFF
// "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire types) can be declared "packed"."
// https://developers.google.com/protocol-buffers/docs/encoding#optional
var PACKABLE_TYPES = [
// varint wire types
'int32', 'int64', 'uint32', 'uint64', 'sint32', 'sint64', 'bool',
// + ENUMS
// 64-bit wire types
'fixed64', 'sfixed64', 'double',
// 32-bit wire types
'fixed32', 'sfixed32', 'float'
]
var onfieldoptionvalue = function (tokens) {
var value = tokens.shift()
if (value !== '{') {
return value
}
value = {}
var field = ''
while (tokens.length) {
switch (tokens[0]) {
case '}':
tokens.shift()
return value
case ':':
tokens.shift()
value[field] = onfieldoptionvalue(tokens)
break
default:
field = tokens.shift()
}
}
}
var onfieldoptions = function (tokens) {
var opts = {}
while (tokens.length) {
switch (tokens[0]) {
case '[':
case ',': {
tokens.shift()
var name = tokens.shift()
if (name === '(') { // handling [(A) = B]
name = tokens.shift()
tokens.shift() // remove the end of bracket
}
var field = []
if (tokens[0][0] === '.') {
field = tokens[0].substr(1).split('.')
tokens.shift()
}
if (tokens[0] !== '=') throw new Error('Unexpected token in field options: ' + tokens[0])
tokens.shift()
if (tokens[0] === ']') throw new Error('Unexpected ] in field option')
// for option (A).b.c
// path will be ['A', 'b'] and lastFieldName 'c'
var path = [name].concat(field)
var lastFieldName = path.pop()
// opt references opts.A.b
var opt = path.reduce(function (opt, n, index) {
if (opt[n] == null) {
opt[n] = {}
}
return opt[n]
}, opts)
// now set opt['c'] that references opts.A.b['c']
opt[lastFieldName] = onfieldoptionvalue(tokens)
break
}
case ']':
tokens.shift()
return opts
default:
throw new Error('Unexpected token in field options: ' + tokens[0])
}
}
throw new Error('No closing tag for field options')
}
var onfield = function (tokens) {
var field = {
name: null,
type: null,
tag: -1,
map: null,
oneof: null,
required: false,
repeated: false,
options: {}
}
while (tokens.length) {
switch (tokens[0]) {
case '=':
tokens.shift()
field.tag = Number(tokens.shift())
break
case 'map':
field.type = 'map'
field.map = { from: null, to: null }
tokens.shift()
if (tokens[0] !== '<') throw new Error('Unexpected token in map type: ' + tokens[0])
tokens.shift()
field.map.from = tokens.shift()
if (tokens[0] !== ',') throw new Error('Unexpected token in map type: ' + tokens[0])
tokens.shift()
field.map.to = tokens.shift()
if (tokens[0] !== '>') throw new Error('Unexpected token in map type: ' + tokens[0])
tokens.shift()
field.name = tokens.shift()
break
case 'repeated':
case 'required':
case 'optional':
var t = tokens.shift()
field.required = t === 'required'
field.repeated = t === 'repeated'
field.type = tokens.shift()
field.name = tokens.shift()
break
case '[':
field.options = onfieldoptions(tokens)
break
case ';':
if (field.name === null) throw new Error('Missing field name')
if (field.type === null) throw new Error('Missing type in message field: ' + field.name)
if (field.tag === -1) throw new Error('Missing tag number in message field: ' + field.name)
tokens.shift()
return field
default:
throw new Error('Unexpected token in message field: ' + tokens[0])
}
}
throw new Error('No ; found for message field')
}
var onmessagebody = function (tokens) {
var body = {
enums: [],
options: {},
messages: [],
fields: [],
extends: [],
extensions: null
}
while (tokens.length) {
switch (tokens[0]) {
case 'map':
case 'repeated':
case 'optional':
case 'required':
body.fields.push(onfield(tokens))
break
case 'enum':
body.enums.push(onenum(tokens))
break
case 'message':
body.messages.push(onmessage(tokens))
break
case 'extensions':
body.extensions = onextensions(tokens)
break
case 'oneof':
tokens.shift()
var name = tokens.shift()
if (tokens[0] !== '{') throw new Error('Unexpected token in oneof: ' + tokens[0])
tokens.shift()
while (tokens[0] !== '}') {
tokens.unshift('optional')
var field = onfield(tokens)
field.oneof = name
body.fields.push(field)
}
tokens.shift()
break
case 'extend':
body.extends.push(onextend(tokens))
break
case ';':
tokens.shift()
break
case 'reserved':
tokens.shift()
while (tokens[0] !== ';') {
tokens.shift()
}
break
case 'option':
var opt = onoption(tokens)
if (body.options[opt.name] !== undefined) throw new Error('Duplicate option ' + opt.name)
body.options[opt.name] = opt.value
break
default:
// proto3 does not require the use of optional/required, assumed as optional
// "singular: a well-formed message can have zero or one of this field (but not more than one)."
// https://developers.google.com/protocol-buffers/docs/proto3#specifying-field-rules
tokens.unshift('optional')
body.fields.push(onfield(tokens))
}
}
return body
}
var onextend = function (tokens) {
var out = {
name: tokens[1],
message: onmessage(tokens)
}
return out
}
var onextensions = function (tokens) {
tokens.shift()
var from = Number(tokens.shift())
if (isNaN(from)) throw new Error('Invalid from in extensions definition')
if (tokens.shift() !== 'to') throw new Error("Expected keyword 'to' in extensions definition")
var to = tokens.shift()
if (to === 'max') to = MAX_RANGE
to = Number(to)
if (isNaN(to)) throw new Error('Invalid to in extensions definition')
if (tokens.shift() !== ';') throw new Error('Missing ; in extensions definition')
return { from: from, to: to }
}
var onmessage = function (tokens) {
tokens.shift()
var lvl = 1
var body = []
var msg = {
name: tokens.shift(),
options: {},
enums: [],
extends: [],
messages: [],
fields: []
}
if (tokens[0] !== '{') throw new Error('Expected { but found ' + tokens[0])
tokens.shift()
while (tokens.length) {
if (tokens[0] === '{') lvl++
else if (tokens[0] === '}') lvl--
if (!lvl) {
tokens.shift()
body = onmessagebody(body)
msg.enums = body.enums
msg.messages = body.messages
msg.fields = body.fields
msg.extends = body.extends
msg.extensions = body.extensions
msg.options = body.options
return msg
}
body.push(tokens.shift())
}
if (lvl) throw new Error('No closing tag for message')
}
var onpackagename = function (tokens) {
tokens.shift()
var name = tokens.shift()
if (tokens[0] !== ';') throw new Error('Expected ; but found ' + tokens[0])
tokens.shift()
return name
}
var onsyntaxversion = function (tokens) {
tokens.shift()
if (tokens[0] !== '=') throw new Error('Expected = but found ' + tokens[0])
tokens.shift()
var version = tokens.shift()
switch (version) {
case '"proto2"':
version = 2
break
case '"proto3"':
version = 3
break
default:
throw new Error('Expected protobuf syntax version but found ' + version)
}
if (tokens[0] !== ';') throw new Error('Expected ; but found ' + tokens[0])
tokens.shift()
return version
}
var onenumvalue = function (tokens) {
if (tokens.length < 4) throw new Error('Invalid enum value: ' + tokens.slice(0, 3).join(' '))
if (tokens[0] === 'reserved') {
tokens.shift()
while (tokens[0] !== ';') {
tokens.shift()
}
tokens.shift()
return null
}
if (tokens[1] !== '=') throw new Error('Expected = but found ' + tokens[1])
if (tokens[3] !== ';' && tokens[3] !== '[') throw new Error('Expected ; or [ but found ' + tokens[1])
var name = tokens.shift()
tokens.shift()
var val = {
value: null,
options: {}
}
val.value = Number(tokens.shift())
if (tokens[0] === '[') {
val.options = onfieldoptions(tokens)
}
tokens.shift() // expecting the semicolon here
return {
name: name,
val: val
}
}
var onenum = function (tokens) {
tokens.shift()
var options = {}
var e = {
name: tokens.shift(),
values: {},
options: {}
}
if (tokens[0] !== '{') throw new Error('Expected { but found ' + tokens[0])
tokens.shift()
while (tokens.length) {
if (tokens[0] === '}') {
tokens.shift()
// there goes optional semicolon after the enclosing "}"
if (tokens[0] === ';') tokens.shift()
return e
}
if (tokens[0] === 'option') {
options = onoption(tokens)
e.options[options.name] = options.value
continue
}
var val = onenumvalue(tokens)
if (val !== null) {
e.values[val.name] = val.val
}
}
throw new Error('No closing tag for enum')
}
var onoption = function (tokens) {
var name = null
var value = null
var parse = function (value) {
if (value === 'true') return true
if (value === 'false') return false
return value.replace(/^"+|"+$/gm, '')
}
while (tokens.length) {
if (tokens[0] === ';') {
tokens.shift()
return { name: name, value: value }
}
switch (tokens[0]) {
case 'option':
tokens.shift()
var hasBracket = tokens[0] === '('
if (hasBracket) tokens.shift()
name = tokens.shift()
if (hasBracket) {
if (tokens[0] !== ')') throw new Error('Expected ) but found ' + tokens[0])
tokens.shift()
}
if (tokens[0][0] === '.') {
name += tokens.shift()
}
break
case '=':
tokens.shift()
if (name === null) throw new Error('Expected key for option with value: ' + tokens[0])
value = parse(tokens.shift())
if (name === 'optimize_for' && !/^(SPEED|CODE_SIZE|LITE_RUNTIME)$/.test(value)) {
throw new Error('Unexpected value for option optimize_for: ' + value)
} else if (value === '{') {
// option foo = {bar: baz}
value = onoptionMap(tokens)
}
break
default:
throw new Error('Unexpected token in option: ' + tokens[0])
}
}
}
var onoptionMap = function (tokens) {
var parse = function (value) {
if (value === 'true') return true
if (value === 'false') return false
return value.replace(/^"+|"+$/gm, '')
}
var map = {}
while (tokens.length) {
if (tokens[0] === '}') {
tokens.shift()
return map
}
var hasBracket = tokens[0] === '('
if (hasBracket) tokens.shift()
var key = tokens.shift()
if (hasBracket) {
if (tokens[0] !== ')') throw new Error('Expected ) but found ' + tokens[0])
tokens.shift()
}
var value = null
switch (tokens[0]) {
case ':':
if (map[key] !== undefined) throw new Error('Duplicate option map key ' + key)
tokens.shift()
value = parse(tokens.shift())
if (value === '{') {
// option foo = {bar: baz}
value = onoptionMap(tokens)
}
map[key] = value
if (tokens[0] === ';') {
tokens.shift()
}
break
case '{':
tokens.shift()
value = onoptionMap(tokens)
if (map[key] === undefined) map[key] = []
if (!Array.isArray(map[key])) throw new Error('Duplicate option map key ' + key)
map[key].push(value)
break
default:
throw new Error('Unexpected token in option map: ' + tokens[0])
}
}
throw new Error('No closing tag for option map')
}
var onimport = function (tokens) {
tokens.shift()
var file = tokens.shift().replace(/^"+|"+$/gm, '')
if (tokens[0] !== ';') throw new Error('Unexpected token: ' + tokens[0] + '. Expected ";"')
tokens.shift()
return file
}
var onservice = function (tokens) {
tokens.shift()
var service = {
name: tokens.shift(),
methods: [],
options: {}
}
if (tokens[0] !== '{') throw new Error('Expected { but found ' + tokens[0])
tokens.shift()
while (tokens.length) {
if (tokens[0] === '}') {
tokens.shift()
// there goes optional semicolon after the enclosing "}"
if (tokens[0] === ';') tokens.shift()
return service
}
switch (tokens[0]) {
case 'option':
var opt = onoption(tokens)
if (service.options[opt.name] !== undefined) throw new Error('Duplicate option ' + opt.name)
service.options[opt.name] = opt.value
break
case 'rpc':
service.methods.push(onrpc(tokens))
break
default:
throw new Error('Unexpected token in service: ' + tokens[0])
}
}
throw new Error('No closing tag for service')
}
var onrpc = function (tokens) {
tokens.shift()
var rpc = {
name: tokens.shift(),
input_type: null,
output_type: null,
client_streaming: false,
server_streaming: false,
options: {}
}
if (tokens[0] !== '(') throw new Error('Expected ( but found ' + tokens[0])
tokens.shift()
if (tokens[0] === 'stream') {
tokens.shift()
rpc.client_streaming = true
}
rpc.input_type = tokens.shift()
if (tokens[0] !== ')') throw new Error('Expected ) but found ' + tokens[0])
tokens.shift()
if (tokens[0] !== 'returns') throw new Error('Expected returns but found ' + tokens[0])
tokens.shift()
if (tokens[0] !== '(') throw new Error('Expected ( but found ' + tokens[0])
tokens.shift()
if (tokens[0] === 'stream') {
tokens.shift()
rpc.server_streaming = true
}
rpc.output_type = tokens.shift()
if (tokens[0] !== ')') throw new Error('Expected ) but found ' + tokens[0])
tokens.shift()
if (tokens[0] === ';') {
tokens.shift()
return rpc
}
if (tokens[0] !== '{') throw new Error('Expected { but found ' + tokens[0])
tokens.shift()
while (tokens.length) {
if (tokens[0] === '}') {
tokens.shift()
// there goes optional semicolon after the enclosing "}"
if (tokens[0] === ';') tokens.shift()
return rpc
}
if (tokens[0] === 'option') {
var opt = onoption(tokens)
if (rpc.options[opt.name] !== undefined) throw new Error('Duplicate option ' + opt.name)
rpc.options[opt.name] = opt.value
} else {
throw new Error('Unexpected token in rpc options: ' + tokens[0])
}
}
throw new Error('No closing tag for rpc')
}
var parse = function (buf) {
var tokens = tokenize(buf.toString())
// check for isolated strings in tokens by looking for opening quote
for (var i = 0; i < tokens.length; i++) {
if (/^("|')([^'"]*)$/.test(tokens[i])) {
var j
if (tokens[i].length === 1) {
j = i + 1
} else {
j = i
}
// look ahead for the closing quote and collapse all
// in-between tokens into a single token
for (j; j < tokens.length; j++) {
if (/^[^'"\\]*(?:\\.[^'"\\]*)*("|')$/.test(tokens[j])) {
tokens = tokens.slice(0, i).concat(tokens.slice(i, j + 1).join('')).concat(tokens.slice(j + 1))
break
}
}
}
}
var schema = {
syntax: 3,
package: null,
imports: [],
enums: [],
messages: [],
options: {},
extends: []
}
var firstline = true
while (tokens.length) {
switch (tokens[0]) {
case 'package':
schema.package = onpackagename(tokens)
break
case 'syntax':
if (!firstline) throw new Error('Protobuf syntax version should be first thing in file')
schema.syntax = onsyntaxversion(tokens)
break
case 'message':
schema.messages.push(onmessage(tokens))
break
case 'enum':
schema.enums.push(onenum(tokens))
break
case 'option':
var opt = onoption(tokens)
if (schema.options[opt.name]) throw new Error('Duplicate option ' + opt.name)
schema.options[opt.name] = opt.value
break
case 'import':
schema.imports.push(onimport(tokens))
break
case 'extend':
schema.extends.push(onextend(tokens))
break
case 'service':
if (!schema.services) schema.services = []
schema.services.push(onservice(tokens))
break
default:
throw new Error('Unexpected token: ' + tokens[0])
}
firstline = false
}
// now iterate over messages and propagate extends
schema.extends.forEach(function (ext) {
schema.messages.forEach(function (msg) {
if (msg.name === ext.name) {
ext.message.fields.forEach(function (field) {
if (!msg.extensions || field.tag < msg.extensions.from || field.tag > msg.extensions.to) {
throw new Error(msg.name + ' does not declare ' + field.tag + ' as an extension number')
}
msg.fields.push(field)
})
}
})
})
schema.messages.forEach(function (msg) {
msg.fields.forEach(function (field) {
var fieldSplit
var messageName
var nestedEnumName
var message
function enumNameIsFieldType (en) {
return en.name === field.type
}
function enumNameIsNestedEnumName (en) {
return en.name === nestedEnumName
}
if (field.options && field.options.packed === 'true') {
if (PACKABLE_TYPES.indexOf(field.type) === -1) {
// let's see if it's an enum
if (field.type.indexOf('.') === -1) {
if (msg.enums && msg.enums.some(enumNameIsFieldType)) {
return
}
} else {
fieldSplit = field.type.split('.')
if (fieldSplit.length > 2) {
throw new Error('what is this?')
}
messageName = fieldSplit[0]
nestedEnumName = fieldSplit[1]
schema.messages.some(function (msg) {
if (msg.name === messageName) {
message = msg
return msg
}
})
if (message && message.enums && message.enums.some(enumNameIsNestedEnumName)) {
return
}
}
throw new Error(
'Fields of type ' + field.type + ' cannot be declared [packed=true]. ' +
'Only repeated fields of primitive numeric types (types which use ' +
'the varint, 32-bit, or 64-bit wire types) can be declared "packed". ' +
'See https://developers.google.com/protocol-buffers/docs/encoding#optional'
)
}
}
})
})
return schema
}
module.exports = parse