-
Notifications
You must be signed in to change notification settings - Fork 40
/
main.go
1497 lines (1252 loc) · 38.5 KB
/
main.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
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
863
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 Seamia Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run github.com/seamia/tools/assets/cmd/assets -src assets.txt -root .
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io"
"os"
"path"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"github.com/emicklei/proto"
"github.com/seamia/protodot/plus"
"github.com/seamia/tools/assets"
"github.com/seamia/tools/support"
)
type Kind int
const (
Unknown Kind = 0
Simple Kind = 1 iota
Enum
Message
Missing
)
const (
typenameRPC = "rpc"
typenameService = "service"
typenameEnum = "enum"
typenameMessage = "message"
typenameMissing = "missing"
appVersion = "generated by github.com/seamia/protodot"
entryGenerated = "generated"
generateSvg = "generate .svg file"
generatePng = "generate .png file"
)
// use explicit string type to alleviate potential mismatch problems
type OriginalName string // name as it appears in the source
type FullName string // fully qualified name = enough to identify the target (within given set of the source files). may have '.' in it
type UniqueName string // a short alias for a FullName
type tinfo struct {
fullname FullName // "one.two.three.WhatEver"
unique UniqueName // "WhatEver$1"
name string // "WhatEver"
typename string // "enum", ...
filename string
comment string
raw string
protopack string
parent FullName // full type of the parent
object interface{}
}
type pkgInfo struct {
packageName string
fileName string
dependencies []string
weak bool
missing bool
proto3 bool
}
type pbstate struct {
knownFiles map[string]*pkgInfo
types237 map[FullName]tinfo
translate map[OriginalName][]FullName
inclusions map[UniqueName]map[UniqueName]int
resolutions map[FullName]map[OriginalName]FullName // maps full.name short.type to full.type
diveDepth int
counter int
knownNames map[UniqueName]FullName // maps 'unique' to 'full'
dive bool
proto string
pkg string
rootDir string
writer *ForkWriter
outputFile string
selection string
incMapping map[string]string
}
func (pbs *pbstate) full2info(name FullName) *tinfo {
if back, found := pbs.types237[name]; found {
return &back
}
return nil
}
func (pbs *pbstate) unique2info(name UniqueName) *tinfo {
if full, found := pbs.knownNames[name]; found {
return pbs.full2info(full)
}
return nil
}
func (pbs *pbstate) currentPkgInfo() *pkgInfo {
if pbs != nil && pbs.knownFiles != nil && len(pbs.proto) > 0 {
if info, found := pbs.knownFiles[pbs.proto]; found {
return info
}
}
assert("somehow there is no pkgInfo available...")
return &pkgInfo{}
}
func NewPbs() *pbstate {
one := pbstate{}
one.knownFiles = make(map[string]*pkgInfo)
one.types237 = make(map[FullName]tinfo)
one.translate = make(map[OriginalName][]FullName)
one.inclusions = make(map[UniqueName]map[UniqueName]int)
one.resolutions = make(map[FullName]map[OriginalName]FullName)
one.counter = 100
one.knownNames = make(map[UniqueName]FullName)
one.dive = true
one.writer = NewForkWriter()
return &one
}
func (pbs *pbstate) AddWriter(target io.Writer) {
pbs.writer.AddWriter(target)
}
func (pbs *pbstate) target() io.Writer {
if pbs.writer != nil {
return pbs.writer
} else {
return os.Stdout
}
}
func (pbs *pbstate) addIncMapping(mapping map[string]string) {
if mapping != nil && len(mapping) > 0 {
if pbs.incMapping == nil {
pbs.incMapping = make(map[string]string)
}
for k, v := range mapping {
pbs.incMapping[k] = v
}
}
}
func (pbs *pbstate) getUniqueName(short OriginalName, full FullName) UniqueName {
if got, found := pbs.knownNames[UniqueName(short)]; found && got == full {
return UniqueName(short)
}
name := UniqueName(fmt.Sprintf("Ja_%d", pbs.counter))
pbs.counter
pbs.knownNames[name] = full
return UniqueName(name)
}
func (pbs *pbstate) addResolution(scope FullName, shorttype OriginalName, fulltype FullName) {
if _, found := pbs.resolutions[scope]; !found {
pbs.resolutions[scope] = make(map[OriginalName]FullName)
}
pbs.resolutions[scope][shorttype] = fulltype
}
func (pbs *pbstate) getResolution(scope FullName, shorttype OriginalName) *tinfo {
if fulltype, found := pbs.resolutions[scope][shorttype]; found {
if info, found := pbs.types237[fulltype]; found {
return &info
}
}
for _, info := range pbs.types237 {
if info.typename == typenameMissing && info.name == string(shorttype) {
return &info
}
}
// alert("*** failed to resolve type:", shorttype) - it is okay to fail resolutuin (while we're resolving)
return nil
}
func (pbs *pbstate) recordInclusion(from UniqueName, field string, to UniqueName) {
fullFrom := from
if len(field) > 0 {
fullFrom = UniqueName(":" field)
}
if _, there := pbs.inclusions[fullFrom]; !there {
pbs.inclusions[fullFrom] = make(map[UniqueName]int)
}
pbs.inclusions[fullFrom][to]
}
func renderMissingNode(name OriginalName, unique UniqueName, fullname FullName) string {
writer := bytes.NewBufferString("")
payload := EnumPayload{
Name: string(name),
Unique: unique,
FullName: fullname,
}
if err := plus.ApplyTemplate("missing.node", writer, payload); err != nil {
alert("failed to render", err)
return ""
}
return writer.String()
}
func (pbs *pbstate) recordMissingType(from UniqueName, missingType OriginalName) UniqueName {
fulltype := FullName("missing." string(from) "." string(missingType))
if info, found := pbs.types237[fulltype]; !found {
unique := pbs.getUniqueName(missingType, fulltype)
pbs.types237[fulltype] = tinfo{
typename: typenameMissing,
fullname: fulltype,
unique: unique,
name: string(missingType),
protopack: pbs.proto,
raw: renderMissingNode(OriginalName(missingType), unique, fulltype),
}
return unique
} else {
return info.unique
}
}
func (pbs *pbstate) recordMissingInclusion(from UniqueName, field string, missingType OriginalName) {
debug("****** Field [", field, "] from [", from, "] refers to non-existing type [", missingType, "] ******")
if options("show missing types") {
// 1. save type (if not already)
unique := pbs.recordMissingType(from, missingType)
// 2. record the connection
pbs.recordInclusion(from, field, unique)
}
}
func (pbs *pbstate) getInclusion(from UniqueName, field string) (UniqueName, map[UniqueName]int) {
fullFrom := from
if len(field) > 0 {
fullFrom = UniqueName(":" field)
}
if inc, found := pbs.inclusions[fullFrom]; found {
return fullFrom, inc
}
return "", nil
}
func (pbs *pbstate) applyTemplate(name string, payload interface{}) {
if err := plus.ApplyTemplate(name, pbs.target(), payload); err != nil {
alert("failed to render", err)
}
}
func (pbs *pbstate) expandSelection(selection string) ([]FullName, error) {
matches := make([]FullName, 0)
// deal with the special case(s) first
if selection == "*" {
// include only entities defined in the root file (and their dependencies)
for fulltype, info := range pbs.types237 {
if info.protopack == pbs.proto {
matches = append(matches, fulltype)
} else {
debug(" excluding:", fulltype)
}
}
return matches, nil
}
for _, root := range strings.Split(selection, ";") {
if len(root) == 0 {
continue
}
locals := make([]FullName, 0)
for fulltype := range pbs.types237 {
if strings.HasSuffix(string(fulltype), root) {
locals = append(locals, fulltype)
}
}
if len(locals) == 0 {
// let's do a more relaxed search
for fulltype := range pbs.types237 {
if strings.Index(string(fulltype), root) >= 0 {
locals = append(locals, fulltype)
}
}
}
if len(locals) == 0 {
status("Cannot find anything matching your selection:", root)
return nil, errors.New("Cannot find anything matching your selection:" root)
}
if len(locals) > 1 {
trace("Your selection [" root "] results in more than one entry:", locals)
return nil, errors.New(fmt.Sprint("Your selection [" root "] results in more than one entry:", locals))
}
matches = append(matches, locals[0])
}
return matches, nil
}
func (pbs *pbstate) showSelectedInclusion(selection string) {
// pbs.types237
// pbs.inclusions
status("limiting output to the following: ", selection)
matches, err := pbs.expandSelection(selection)
if err != nil {
status(err.Error())
return
}
// create new storage for the selections and their dependants
types := make(map[FullName]tinfo)
posttypes := make(map[FullName]tinfo)
inclusions := make(map[UniqueName]map[UniqueName]int)
for index := range matches {
info := pbs.types237[matches[index]]
if len(info.parent) > 0 {
parentInfo := pbs.types237[info.parent] // types237 map[FullName]tinfo
debug("", parentInfo)
}
debug("type of the selection:", info.typename)
switch info.typename {
case typenameService:
// just works =)
debug("------", info)
case typenameRPC:
// this is a bit elaborate
// service
// ...
// rpc -> request, response
// ...
rpc, ok := info.object.(*proto.RPC)
if ok {
parentType := info.parent
requestType := rpc.RequestType
returnsType := rpc.ReturnsType
// add 'parent' directly without all of its children
posttypes[parentType] = pbs.types237[parentType]
// add connections from 'parent' too children
for _, suffix := range []string{"_request", "_response"} {
from, to := pbs.getInclusion(pbs.types237[parentType].unique, rpc.Name suffix)
if to != nil {
inclusions[from] = to
}
}
for _, one := range []string{requestType, returnsType} {
if inf := pbs.getResolution(parentType, OriginalName(one)); inf != nil {
matches = append(matches, inf.fullname)
} else {
// todo: react here? maybe?
}
}
} else {
assert("failed to get an expected type")
}
case typenameMessage:
// nothing special here to do
debug("------", info)
default:
alert("entry of type [", info.typename, "] is not yet supported.")
}
}
for len(matches) > 0 {
candidate := matches[0]
matches = matches[1:]
trace("---------------------------- considering: ", candidate)
if _, found := types[candidate]; found {
trace(" already added:", candidate)
continue
}
types[candidate] = pbs.types237[candidate]
unique := types[candidate].unique ":"
for key, value := range pbs.inclusions {
if strings.HasPrefix(string(key), string(unique)) {
trace(" checking [", key, "]")
for child := range value {
if fullchild, found := pbs.knownNames[child]; found {
if _, found := types[fullchild]; !found {
// we have not seen this type before
matches = append(matches, fullchild)
trace(" adding [", child, "] [", value, "]")
} else {
trace(" already included [", fullchild, "]")
}
inclusions[key] = value
} else {
trace(" failed to find [", child, "]")
}
}
} else {
trace(" excluding [", key, "] cause it has no prefix [", unique, "]")
}
}
}
// copy posttypes to types237
for k, v := range posttypes {
types[k] = v
}
{
tmp := make([]string, 0, len(types))
for _, info := range types {
tmp = append(tmp, info.name)
}
trace("for your selections found the following dependencies:", tmp)
}
backupTypes, backupInclusions := pbs.types237, pbs.inclusions
pbs.types237, pbs.inclusions = types, inclusions
pbs.showInclusion(false, true)
pbs.types237, pbs.inclusions = backupTypes, backupInclusions
}
func (pbs *pbstate) showInclusion(groupByPackages bool, leaveRootPackageUnwrapped bool) {
payload := PBS{
Package: pbs.pkg,
Protoname: pbs.proto,
AppVersion: appVersion,
Timestamp: time.Now().Format(time.RFC850),
Selection: pbs.selection,
Options: "",
}
pbs.applyTemplate("document.header", payload)
pbs.applyTemplate("comment", "nodes")
if groupByPackages {
groups := make(map[string][]tinfo)
for _, info := range pbs.types237 {
if _, present := groups[info.protopack]; !present {
groups[info.protopack] = make([]tinfo, 0)
}
groups[info.protopack] = append(groups[info.protopack], info)
}
for group, members := range groups {
components := strings.Split(group, string(os.PathSeparator))
data := Cluster{
ProtoName: strings.Replace(group, "\\", "\\\\", -1),
ProtoNameKosher: support.NameToId(group, 12),
ShortName: components[len(components)-1],
}
if leaveRootPackageUnwrapped && group == pbs.proto {
pbs.applyTemplate("comment", "leaving the root package unwrapped")
for _, info := range members {
pbs.applyTemplate("entry", info.raw)
}
} else {
pbs.applyTemplate("cluster.prefix", data)
for _, info := range members {
pbs.applyTemplate("cluster.entry", info.raw)
}
pbs.applyTemplate("cluster.suffix", data)
}
}
} else {
for _, info := range pbs.types237 {
pbs.applyTemplate("entry", info.raw)
}
}
pbs.applyTemplate("comment", "connections")
var toTemplateName = map[string]string{
typenameEnum: "from.to.enum",
typenameMessage: "from.to.message",
typenameMissing: "from.to.missing",
}
// from, field, to
for from, tos := range pbs.inclusions {
for to := range tos {
bits := strings.Split(string(from), ":")
args := Relationship{
From: bits[0],
To: to, // UniqueName
ToName: "", // todo: fill these up later
ToType: "", // FullName
}
if len(bits) > 1 {
args.Field = bits[1]
}
tmplName := toTemplateName[pbs.types237[pbs.knownNames[to]].typename]
pbs.applyTemplate(tmplName, args)
// pbs.applyTemplate(isMessage[pbs.uniqueIsMessage(to)], args)
}
}
pbs.applyTemplate("document.footer", payload)
}
func (pbs *pbstate) uniqueIsMessage(unique UniqueName) bool {
if full, found := pbs.knownNames[unique]; found {
if info, found := pbs.types237[full]; found {
if info.typename == typenameMessage {
return true
}
}
}
return false
}
func (pbs *pbstate) handleSyntax(syntax *proto.Syntax) {
trace("\tsyntax:", syntax.Value)
pbs.currentPkgInfo().proto3 = (syntax.Value == "proto3")
}
func (pbs *pbstate) handleImport(imp *proto.Import) {
trace("\timport:", imp.Filename)
if pbs.dive {
prev, prev_pkg := pbs.proto, pbs.pkg
self := pbs.currentPkgInfo()
self.dependencies = append(self.dependencies, imp.Filename)
pbs.diveDepth
debug("-- leaving [", pbs.proto, "] and diving into", imp.Filename)
if !process(pbs, imp.Filename, "") {
// this file was missing ...
}
pbs.diveDepth--
pbs.pkg, pbs.proto = prev_pkg, prev
// pbs.proto = prev
debug("-- back to [", pbs.proto, "]")
}
}
func (pbs *pbstate) handlePackageDeclaration(pkg *proto.Package) {
trace("\tpackage:", pkg.Name)
pbs.pkg = pkg.Name
pbs.currentPkgInfo().packageName = pkg.Name
}
func (pbs *pbstate) saveMapping(short OriginalName, full FullName) {
// let's try to detect collisions
if _, found := pbs.translate[short]; found {
debug("ERROR: there is a collision for name:", short)
} else {
pbs.translate[short] = make([]FullName, 0, 1)
}
pbs.translate[short] = append(pbs.translate[short], full) // todo: do you need 'translate' ?
}
func (pbs *pbstate) handleEnumDeclaration(e *proto.Enum) {
fullname := getFullName(e)
unique := pbs.getUniqueName(OriginalName(e.Name), fullname)
pbs.saveMapping(OriginalName(e.Name), fullname)
writer := bytes.NewBufferString("")
payload := EnumPayload{
Name: e.Name,
Unique: unique,
FullName: fullname,
}
if err := plus.ApplyTemplate("enum.prefix", writer, payload); err != nil {
alert("failed to render", err)
}
for _, element := range e.Elements {
switch actual := element.(type) {
case *proto.EnumField:
payload.Name = actual.Name
payload.Value = strconv.Itoa(actual.Integer)
if err := plus.ApplyTemplate("enum.entry", writer, payload); err != nil {
alert("failed to render", err)
}
case *proto.Option:
ignoring("ignoring options for now")
case *proto.Comment:
ignoring("ignoring comment for now")
case *proto.Reserved:
ignoring("ignoring Reserved for now")
default:
rname := reflect.TypeOf(actual).Elem().Name()
unhandled("\t", "UNKNOWN2", actual, "", rname)
}
}
payload.Value = ""
if err := plus.ApplyTemplate("enum.suffix", writer, payload); err != nil {
alert("failed to render", err)
}
pbs.types237[fullname] = tinfo{
typename: typenameEnum,
fullname: fullname,
unique: unique,
name: e.Name,
filename: e.Position.Filename,
raw: writer.String(),
protopack: pbs.pkg,
}
}
func (pbs *pbstate) dbgPrintKnownResolutions(fullname FullName) {
debug("-------------------------------------- all known resolutions for:", fullname)
if all, found := pbs.resolutions[fullname]; found { // map[FullName]map[OriginalName]FullName
for k, v := range all {
debug(" ", k, " ---> ", v)
}
}
debug("--------------------------------------")
}
var typename2kind = map[string]Kind{
typenameEnum: Enum,
typenameMessage: Message,
typenameMissing: Missing,
}
func (pbs *pbstate) getKind(fullname FullName, what OriginalName) Kind {
if isSimpleType(string(what)) {
return Simple
}
if info := pbs.getResolution(fullname, what); info != nil {
if kind, found := typename2kind[info.typename]; found {
return kind
}
assert("Unknown typename [", info.typename, "] find while resolving type: ", what)
return Unknown
}
pbs.dbgPrintKnownResolutions(fullname)
assert("Unresolved type: ", what, "; source: ", fullname)
return Unknown
}
func getPackageName(pro *proto.Proto) string {
for _, element := range pro.Elements {
switch actual := element.(type) {
case *proto.Package:
return actual.Name
}
}
alert("Failed to find package name for: " pro.Filename)
return ""
}
const separator string = "."
func getParent(what proto.Visitee) string {
cmd := ""
switch parent := what.(type) {
case *proto.Proto:
cmd = getPackageName(parent)
case *proto.Message:
cmd = getParent(parent.Parent) separator parent.Name // the message declared in another message scope
case *proto.Group:
ignoring("ignoring group for now")
default:
rname := reflect.TypeOf(parent).Elem().Name()
unhandled("\t", "UNKNOWN3", parent, "", rname)
}
return cmd
}
func getFullName(what interface{}) FullName {
switch actual := what.(type) {
case *proto.Message:
return FullName(getParent(actual.Parent) separator actual.Name)
case *proto.Enum:
return FullName(getParent(actual.Parent) separator actual.Name)
case *proto.Service:
return FullName(getParent(actual.Parent) separator actual.Name)
default:
panic("not yet supported type")
}
}
func (pbs *pbstate) handleMessageDeclaration(msg *proto.Message) {
if msg.IsExtend {
debug("-- excluding 'extend' messages:", msg.Name)
return
}
parent := getParent(msg.Parent)
fullname := getFullName(msg)
unique := pbs.getUniqueName(OriginalName(msg.Name), fullname)
pbs.saveMapping(OriginalName(msg.Name), fullname)
debug("*** type definition:", pbs.pkg, ">>", msg.Name, ">>", parent, ">>>>>>>>", fullname)
pbs.types237[fullname] = tinfo{
typename: typenameMessage,
fullname: fullname,
unique: unique,
name: msg.Name,
filename: msg.Position.Filename,
comment: parent,
protopack: pbs.proto,
}
}
func (pbs *pbstate) resolveType(full FullName, local OriginalName) {
if isSimpleType(string(local)) {
// no need to resolve simple types237
return
}
if info := pbs.getResolution(full, local); info != nil {
// looks like we already know what 'local' type maps to
return
}
if occurrences := len(pbs.translate[local]); occurrences > 1 {
var found FullName
for _, one := range pbs.translate[local] {
namespace := one[:len(one)-len(local)-len(separator)]
if strings.HasPrefix(string(full), string(namespace)) {
if len(one) > len(found) {
found = one
}
}
}
if len(found) > 0 {
trace("", full, ", mapping ", local, " to ", found)
pbs.addResolution(full, local, found)
} else {
alert("!! there is more than one definition of type [", local, "], used in ", full, "", pbs.translate[local])
}
} else {
parts := strings.Split(string(local), ".")
if len(parts) > 1 {
var found FullName
for typename, typeinfo := range pbs.types237 {
if strings.HasSuffix(string(typename), string(local)) {
prefix := typename[:len(typename)-len(local)]
if strings.HasSuffix(string(prefix), separator) {
prefix = prefix[:len(prefix)-len(separator)]
}
if strings.HasPrefix(string(full), string(prefix)) {
if len(typename) > len(found) {
found = typename
}
}
_ = typeinfo
trace("actual:", local, "; prefix:", prefix, "; full type", typename)
}
}
if len(found) > 0 {
trace("", full, ", mapping ", local, " to ", found)
pbs.addResolution(full, local, found)
} else {
alert("!! failed to find full.type.name for type [", local, "], used in ", full)
}
} else {
if names, found := pbs.translate[local]; found && len(names) == 1 {
pbs.addResolution(full, local, names[0])
} else {
alert("failed to resolve type:", local, "; scope:", full)
}
}
}
}
func (pbs *pbstate) handleMessageTypeResolution(msg *proto.Message) {
fullname := getFullName(msg)
for _, element := range msg.Elements {
switch actual := element.(type) {
case *proto.Oneof:
for _, element := range actual.Elements {
switch fact := element.(type) {
case *proto.OneOfField:
if !isSimpleType(fact.Type) {
pbs.resolveType(fullname, OriginalName(fact.Type))
}
}
}
case *proto.NormalField:
pbs.resolveType(fullname, OriginalName(actual.Type))
case *proto.MapField:
pbs.resolveType(fullname, OriginalName(actual.Type))
}
}
}
func (pbs *pbstate) handleServiceTypeResolution(srv *proto.Service) {
fullname := getFullName(srv)
for _, element := range srv.Elements {
switch actual := element.(type) {
case *proto.RPC:
pbs.resolveType(fullname, OriginalName(actual.RequestType))
pbs.resolveType(fullname, OriginalName(actual.ReturnsType))
}
}
}
var isRepeated = map[bool]string{
false: "",
true: "[...]",
}
func (pbs *pbstate) handleMessageBody(msg *proto.Message) {
if msg.IsExtend {
debug("-- excluding 'extend' messages:", msg.Name)
return
}
full := getFullName(msg)
info := pbs.types237[full]
message := msg.Name
debug("message", msg.Name, "-------------------------------------")
t := newTable(message, info.fullname, info.unique, "style")
for _, element := range msg.Elements {
switch actual := element.(type) {
case *proto.NormalField:
if !isSimpleType(actual.Type) {
if inf := pbs.getResolution(full, OriginalName(actual.Type)); inf != nil {
pbs.encounteredType(info.unique, actual.Name, inf.unique)
} else {
alert("failed to resolve", actual.Type)
pbs.recordMissingInclusion(info.unique, actual.Name, OriginalName(actual.Type))
}
}
repeated := isRepeated[actual.Repeated]
t.addRow(repeated, actual.Type, actual.Name, strconv.Itoa(actual.Sequence), pbs.getKind(full, OriginalName(actual.Type)))
break
case *proto.Enum:
debug("\t", "enum:", actual.Name)
case *proto.Reserved:
debug("\t", "reserved:", actual.FieldNames)
case *proto.Option:
debug("\t", "option:", actual.Name)
case *proto.Message:
debug("\t", "message:", actual.Name)
case *proto.Oneof:
pbs.onOneof(full, info.unique, actual)
t.addOneof(full, actual, pbs)
case *proto.MapField:
debug("\t", "map-field:", actual.Name, ", map<", actual.KeyType, ", ", actual.Type, ">")
// Q: can map be 'repeated' ?
t.addMapRow(actual.Name, actual.KeyType, actual.Type, strconv.Itoa(actual.Sequence), pbs.getKind(full, OriginalName(actual.Type)))
if !isSimpleType(actual.Type) {
if inf := pbs.getResolution(full, OriginalName(actual.Type)); inf != nil {
pbs.recordInclusion(info.unique, actual.Name, inf.unique)
} else {
alert("failed to resolve type [", actual.Type, "] from ", full)
pbs.recordMissingInclusion(info.unique, actual.Name, OriginalName(actual.Type))
}
}
case *proto.Comment:
ignoring("\t", "comment:", actual.Message())
case *proto.Extensions:
ignoring("\t", "extensions:", "--ignored for now")
case *proto.Group:
ignoring("ignoring group for now")
default:
rname := reflect.TypeOf(actual).Elem().Name()
unhandled("\t", "UNKNOWN4", actual, "", rname)
}
}
info.raw = t.generate()
pbs.types237[full] = info
}
func (pbs *pbstate) onOneof(fullname FullName, unique UniqueName, one *proto.Oneof) {
debug("oneof", one.Name)
if len(one.Elements) > 0 {
for _, element := range one.Elements {
switch actual := element.(type) {
case *proto.OneOfField:
debug("\t", "one-of-field:", actual.Name, ", type:", actual.Type)
if !isSimpleType(actual.Type) {
if inf := pbs.getResolution(fullname, OriginalName(actual.Type)); inf != nil {
pbs.encounteredType(unique, actual.Name, inf.unique)
} else {
alert("failed to get unique name for type", actual.Type)
pbs.recordMissingInclusion(unique, actual.Name, OriginalName(actual.Type))
}
}
case *proto.Option:
ignoring("ignoring options for now")
case *proto.Comment:
ignoring("ignoring comments for now")
case *proto.Group:
ignoring("ignoring group for now")
default:
rname := reflect.TypeOf(actual).Elem().Name()
unhandled("\t", "UNKNOWN5", actual, "", rname)
}
}
}
}
func (pbs *pbstate) handleOption(opt *proto.Option) {
value := opt.Constant.Source
debug("\t\t", "option", opt.Name, ":", value)
for _, one := range opt.AggregatedConstants {
debug("\t", "\t", "constant:", one.Name, ">>>", one.Literal.Source)
}
}
var isStreaming = map[bool]string{
false: "",
true: "stream",
}
func (pbs *pbstate) handleServiceDeclaration(srv *proto.Service) {
name := getFullName(srv)
pbs.saveMapping(OriginalName(srv.Name), name) // todo: need this?
srvUniqueName := pbs.getUniqueName(OriginalName(srv.Name), name)