-
Notifications
You must be signed in to change notification settings - Fork 243
/
emit.go
1484 lines (1326 loc) · 47.2 KB
/
emit.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
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
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 2016 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package indexer
import (
"context"
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"net/url"
"path"
"strconv"
"strings"
"kythe.io/kythe/go/extractors/govname"
"kythe.io/kythe/go/util/metadata"
"kythe.io/kythe/go/util/schema/edges"
"kythe.io/kythe/go/util/schema/facts"
"kythe.io/kythe/go/util/schema/nodes"
"github.com/golang/protobuf/proto"
"golang.org/x/tools/go/types/typeutil"
cpb "kythe.io/kythe/proto/common_go_proto"
spb "kythe.io/kythe/proto/storage_go_proto"
)
// EmitOptions control the behaviour of the Emit function. A nil options
// pointer provides default values.
type EmitOptions struct {
// If true, emit nodes for standard library packages when they are first
// encountered. This is helpful if you want to index a package in isolation
// where data for the standard library are not available.
EmitStandardLibs bool
// If true, emit code facts containing MarkedSource messages.
EmitMarkedSource bool
// If true, emit linkages specified by metadata rules.
EmitLinkages bool
// If true, emit childof edges for an anchor's semantic scope.
EmitAnchorScopes bool
// If set, use this as the base URL for links to godoc. The import path is
// appended to the path of this URL to obtain the target URL to link to.
DocBase *url.URL
// If true, the doc/uri fact is only emitted for go std library packages.
OnlyEmitDocURIsForStandardLibs bool
// If enabled, all VNames emitted by the indexer are assigned the
// compilation unit's corpus.
UseCompilationCorpusForAll bool
// If set, all stdlib nodes are assigned this corpus. This takes precedence
// over UseCompilationCorpusForAll for stdlib nodes.
OverrideStdlibCorpus string
}
func (e *EmitOptions) emitMarkedSource() bool {
if e == nil {
return false
}
return e.EmitMarkedSource
}
func (e *EmitOptions) emitAnchorScopes() bool {
if e == nil {
return false
}
return e.EmitAnchorScopes
}
// shouldEmit reports whether the indexer should emit a node for the given
// vname. Presently this is true if vname denotes a standard library and the
// corresponding option is enabled.
func (e *EmitOptions) shouldEmit(vname *spb.VName) bool {
return e != nil && e.EmitStandardLibs && govname.IsStandardLibrary(vname)
}
// docURL returns a documentation URL for the specified package, if one is
// specified by the options, or "" if not.
func (e *EmitOptions) docURL(pi *PackageInfo) string {
if e == nil || e.DocBase == nil {
return ""
}
if e.OnlyEmitDocURIsForStandardLibs && !govname.IsStandardLibrary(pi.VName) {
return ""
}
u := *e.DocBase
u.Path = path.Join(u.Path, pi.ImportPath)
return u.String()
}
// An impl records that a type A implements an interface B.
type impl struct{ A, B types.Object }
// Emit generates Kythe facts and edges to represent pi, and writes them to
// sink. In case of errors, processing continues as far as possible before the
// first error encountered is reported.
func (pi *PackageInfo) Emit(ctx context.Context, sink Sink, opts *EmitOptions) error {
if opts == nil {
opts = &EmitOptions{}
}
e := &emitter{
ctx: ctx,
pi: pi,
sink: sink,
opts: opts,
impl: make(map[impl]struct{}),
anchored: make(map[ast.Node]struct{}),
fmeta: make(map[*ast.File]bool),
}
// Emit a node to represent the package as a whole.
e.writeFact(pi.VName, facts.NodeKind, nodes.Package)
if url := e.opts.docURL(pi); url != "" {
e.writeFact(pi.VName, facts.DocURI, url)
}
e.emitPackageMarkedSource(pi)
// Emit facts for all the source files claimed by this package.
for file, text := range pi.SourceText {
vname := pi.FileVName(file)
e.writeFact(vname, facts.NodeKind, nodes.File)
e.writeFact(vname, facts.Text, text)
// All Go source files are encoded as UTF-8, which is the default.
e.writeEdge(vname, pi.VName, edges.ChildOf)
}
// Traverse the AST of each file in the package for xref entries.
for _, file := range pi.Files {
e.cmap = ast.NewCommentMap(pi.FileSet, file, file.Comments)
e.writeDoc(file.Doc, pi.VName) // capture package comments
e.writeRef(file.Name, pi.VName, edges.DefinesBinding) // define a binding for the package
ast.Walk(newASTVisitor(func(node ast.Node, stack stackFunc) bool {
switch n := node.(type) {
case *ast.Ident:
e.visitIdent(n, stack)
case *ast.FuncDecl:
e.visitFuncDecl(n, stack)
case *ast.FuncLit:
e.visitFuncLit(n, stack)
case *ast.ValueSpec:
e.visitValueSpec(n, stack)
case *ast.TypeSpec:
e.visitTypeSpec(n, stack)
case *ast.ImportSpec:
e.visitImportSpec(n, stack)
case *ast.AssignStmt:
e.visitAssignStmt(n, stack)
case *ast.RangeStmt:
e.visitRangeStmt(n, stack)
case *ast.CompositeLit:
e.visitCompositeLit(n, stack)
case *ast.IndexExpr:
e.visitIndexExpr(n, stack)
case *ast.IndexListExpr:
e.visitIndexListExpr(n, stack)
}
return true
}), file)
}
// Emit edges from each named type to the interface types it satisfies, for
// those interface types that are known to this compiltion.
e.emitSatisfactions()
// TODO(fromberger): Add diagnostics for type-checker errors.
for _, err := range pi.Errors {
log.Printf("WARNING: Type resolution error: %v", err)
}
return e.firstErr
}
type emitter struct {
ctx context.Context
pi *PackageInfo
sink Sink
opts *EmitOptions
impl map[impl]struct{} // see checkImplements
rmap map[*ast.File]map[int]metadata.Rules // see applyRules
fmeta map[*ast.File]bool // see applyRules
anchored map[ast.Node]struct{} // see writeAnchor
firstErr error
cmap ast.CommentMap // current file's CommentMap
}
type refKind int
const (
readRef refKind = iota
writeRef
readWriteRef
)
func exprRefKind(tgt ast.Expr, stack stackFunc, depth int) refKind {
switch parent := stack(depth + 1).(type) {
case *ast.AssignStmt:
// Check if identifier is being assigned; we assume this is not a definition
// and checked by the caller.
for _, lhs := range parent.Lhs {
if lhs == tgt {
switch parent.Tok {
case token.ASSIGN, token.DEFINE:
return writeRef
default: // +=, etc.
return readWriteRef
}
}
}
case *ast.IncDecStmt:
return readWriteRef
case *ast.SelectorExpr:
if id, ok := tgt.(*ast.Ident); ok && id == parent.Sel {
return exprRefKind(parent, stack, depth+1)
}
case *ast.KeyValueExpr:
if tgt == parent.Key {
return writeRef
}
}
return readRef
}
// visitIdent handles referring identifiers. Declaring identifiers are handled
// as part of their parent syntax.
func (e *emitter) visitIdent(id *ast.Ident, stack stackFunc) {
obj := e.pi.Info.Uses[id]
if obj == nil {
// Defining identifiers are handled by their parent nodes.
return
}
if sig, ok := obj.Type().(*types.Signature); ok && sig.RecvTypeParams().Len() > 0 {
// Lookup the original non-instantiated method to reference.
if n, ok := deref(sig.Recv().Type()).(*types.Named); ok {
f, _, _ := types.LookupFieldOrMethod(n.Origin(), true, obj.Pkg(), obj.Name())
if f != nil {
obj = f
}
}
}
// Receiver type parameter identifiers are both usages and definitions; take
// the opportunity to emit a binding and do not continue to emit a Ref edge.
if def, ok := e.pi.Info.Defs[id].(*types.TypeName); ok && def == obj {
e.writeBinding(id, nodes.TVar, nil)
return
}
var target *spb.VName
if n, ok := obj.(*types.TypeName); ok && obj.Pkg() == nil {
// Handle type arguments in instantiated types.
target = e.emitType(n.Type())
} else {
target = e.pi.ObjectVName(obj)
}
if target == nil {
// This should not happen in well-formed packages, but can if the
// extractor gets confused. Avoid emitting confusing references in such
// cases. Note that in this case we need to emit a fresh anchor, since
// we aren't otherwise emitting a reference.
e.writeNodeDiagnostic(id, diagnostic{
Message: fmt.Sprintf("Unable to identify the package for %q", id.Name),
})
return
}
var refs []*spb.VName
refKind := exprRefKind(id, stack, 0)
if refKind == readRef || refKind == readWriteRef {
refs = append(refs, e.writeRef(id, target, edges.Ref))
}
if refKind == writeRef || refKind == readWriteRef {
refs = append(refs, e.writeRef(id, target, edges.RefWrites))
}
if e.opts.emitAnchorScopes() {
parent := e.callContext(stack).vname
for _, ref := range refs {
e.writeEdge(ref, parent, edges.ChildOf)
}
}
if call, ok := isCall(id, obj, stack); ok {
callAnchor := e.writeRef(call, target, edges.RefCall)
// Paint an edge to the function blamed for the call, or if there is
// none then to the package initializer.
e.writeEdge(callAnchor, e.callContext(stack).vname, edges.ChildOf)
}
}
// visitFuncDecl handles function and method declarations and their parameters.
func (e *emitter) visitFuncDecl(decl *ast.FuncDecl, stack stackFunc) {
info := &funcInfo{vname: new(spb.VName)}
e.pi.function[decl] = info
// Get the type of this function, even if its name is blank.
obj, _ := e.pi.Info.Defs[decl.Name].(*types.Func)
if obj == nil {
return // a redefinition, for example
}
// Special case: There may be multiple package-level init functions, so
// override the normal signature generation to include a discriminator.
if decl.Recv == nil && obj.Name() == "init" {
e.pi.numInits++
e.pi.sigs[obj] = fmt.Sprintf("%s#%d", e.pi.Signature(obj), e.pi.numInits)
}
info.vname = e.mustWriteBinding(decl.Name, nodes.Function, nil)
e.writeDef(decl, info.vname)
e.writeDoc(decl.Doc, info.vname)
// For concrete methods: Emit the receiver if named, and connect the method
// to its declaring type.
sig := obj.Type().(*types.Signature)
if sig.Recv() != nil {
// The receiver is treated as parameter 0.
if names := decl.Recv.List[0].Names; names != nil {
if recv := e.writeBinding(names[0], nodes.Variable, info.vname); recv != nil {
e.writeEdge(info.vname, recv, edges.ParamIndex(0))
}
}
// The method should be a child of its (named) enclosing type.
if named, _ := deref(sig.Recv().Type()).(*types.Named); named != nil {
base := e.pi.ObjectVName(named.Obj())
e.writeEdge(info.vname, base, edges.ChildOf)
}
}
e.emitParameters(decl.Type, sig, info)
}
// rewrittenCorpusForVName returns the new corpus that should be assigned to the
// given vname based on the OverrideStdlibCorpus and UseCompilationCorpusForAll options
func (e *emitter) rewrittenCorpusForVName(v *spb.VName) string {
if e.opts.OverrideStdlibCorpus != "" && v.GetCorpus() == govname.GolangCorpus {
return e.opts.OverrideStdlibCorpus
}
if e.opts.UseCompilationCorpusForAll {
return e.pi.VName.GetCorpus()
}
if v.GetCorpus() == "" {
// If the VName doesn't specify a corpus, use the compilation unit's corpus
return e.pi.VName.GetCorpus()
}
return v.GetCorpus()
}
// emitTApp emits a tapp node and returns its VName. The new tapp is emitted
// with given constructor and parameters. The constructor's kind is also
// emitted if this is the first time seeing it.
func (e *emitter) emitTApp(ms *cpb.MarkedSource, ctorKind string, ctor *spb.VName, params ...*spb.VName) *spb.VName {
if ctorKind != "" && e.pi.typeEmitted.Add(ctor.Signature) {
e.writeFact(ctor, facts.NodeKind, ctorKind)
if ctorKind == nodes.TBuiltin {
e.emitBuiltinMarkedSource(ctor)
}
}
components := []interface{}{ctor}
for _, p := range params {
components = append(components, p)
}
v := &spb.VName{Language: govname.Language, Signature: hashSignature(components)}
v.Corpus = e.rewrittenCorpusForVName(v)
if e.pi.typeEmitted.Add(v.Signature) {
e.writeFact(v, facts.NodeKind, nodes.TApp)
e.writeEdge(v, ctor, edges.ParamIndex(0))
for i, p := range params {
e.writeEdge(v, p, edges.ParamIndex(i+1))
}
if ms != nil && e.opts.emitMarkedSource() {
e.emitCode(v, ms)
}
}
return v
}
// emitType emits the type as a node and returns its VName. VNames are cached
// so the type nodes are only emitted the first time they are seen.
func (e *emitter) emitType(typ types.Type) *spb.VName {
v, ok := e.pi.typeVName[typ]
if ok {
return v
}
switch typ := typ.(type) {
case *types.Named:
if typ.TypeArgs().Len() == 0 {
v = e.pi.ObjectVName(typ.Obj())
} else {
// Instantiated Named types produce tapps
ctor := e.emitType(typ.Origin())
args := typ.TypeArgs()
var params []*spb.VName
for i := 0; i < args.Len(); i++ {
params = append(params, e.emitType(args.At(i)))
}
v = e.emitTApp(genericTAppMS, "", ctor, params...)
}
case *types.Basic:
v = govname.BasicType(typ)
if e.pi.typeEmitted.Add(v.Signature) {
e.writeFact(v, facts.NodeKind, nodes.TBuiltin)
e.emitBuiltinMarkedSource(v)
}
case *types.Array:
v = e.emitTApp(arrayTAppMS(typ.Len()), nodes.TBuiltin, govname.ArrayConstructorType(typ.Len()), e.emitType(typ.Elem()))
case *types.Slice:
v = e.emitTApp(sliceTAppMS, nodes.TBuiltin, govname.SliceConstructorType(), e.emitType(typ.Elem()))
case *types.Pointer:
v = e.emitTApp(pointerTAppMS, nodes.TBuiltin, govname.PointerConstructorType(), e.emitType(typ.Elem()))
case *types.Chan:
v = e.emitTApp(chanTAppMS(typ.Dir()), nodes.TBuiltin, govname.ChanConstructorType(typ.Dir()), e.emitType(typ.Elem()))
case *types.Map:
v = e.emitTApp(mapTAppMS, nodes.TBuiltin, govname.MapConstructorType(), e.emitType(typ.Key()), e.emitType(typ.Elem()))
case *types.Tuple: // function return types
v = e.emitTApp(tupleTAppMS, nodes.TBuiltin, govname.TupleConstructorType(), e.visitTuple(typ)...)
case *types.Signature: // function types
ms := &cpb.MarkedSource{
Kind: cpb.MarkedSource_TYPE,
Child: []*cpb.MarkedSource{{
Kind: cpb.MarkedSource_PARAMETER_LOOKUP_BY_PARAM,
LookupIndex: 3,
PreText: "func(",
PostChildText: ", ",
PostText: ")",
}},
}
params := e.visitTuple(typ.Params())
if typ.Variadic() && len(params) > 0 {
// Convert last parameter type from slice type to variadic type.
last := len(params) - 1
if slice, ok := typ.Params().At(last).Type().(*types.Slice); ok {
params[last] = e.emitTApp(variadicTAppMS, nodes.TBuiltin, govname.VariadicConstructorType(), e.emitType(slice.Elem()))
}
}
var ret *spb.VName
if typ.Results().Len() == 1 {
ret = e.emitType(typ.Results().At(0).Type())
} else {
ret = e.emitType(typ.Results())
}
if typ.Results().Len() != 0 {
ms.Child = append(ms.Child, &cpb.MarkedSource{
Kind: cpb.MarkedSource_BOX,
PreText: " ",
Child: []*cpb.MarkedSource{{
Kind: cpb.MarkedSource_LOOKUP_BY_PARAM,
LookupIndex: 1,
}},
})
}
var recv *spb.VName
if r := typ.Recv(); r != nil {
recv = e.emitType(r.Type())
ms.Child = append([]*cpb.MarkedSource{{
Kind: cpb.MarkedSource_BOX,
PreText: "(",
PostText: ") ",
Child: []*cpb.MarkedSource{{
Kind: cpb.MarkedSource_LOOKUP_BY_PARAM,
LookupIndex: 2,
}},
}}, ms.Child...)
} else {
recv = e.emitType(types.NewTuple())
}
v = e.emitTApp(ms, nodes.TBuiltin, govname.FunctionConstructorType(),
append([]*spb.VName{ret, recv}, params...)...)
case *types.Interface:
v = &spb.VName{Language: govname.Language, Signature: hashSignature(typ)}
if e.pi.typeEmitted.Add(v.Signature) {
e.writeFact(v, facts.NodeKind, nodes.Interface)
if e.opts.emitMarkedSource() {
e.emitCode(v, &cpb.MarkedSource{
Kind: cpb.MarkedSource_TYPE,
PreText: typ.String(),
})
}
}
case *types.Struct:
v = &spb.VName{Language: govname.Language, Signature: hashSignature(typ)}
if e.pi.typeEmitted.Add(v.Signature) {
e.writeFact(v, facts.NodeKind, nodes.Record)
if e.opts.emitMarkedSource() {
e.emitCode(v, &cpb.MarkedSource{
Kind: cpb.MarkedSource_TYPE,
PreText: typ.String(),
})
}
}
case *types.TypeParam:
v = e.pi.ObjectVName(typ.Obj())
default:
log.Printf("WARNING: unknown type %T: %+v", typ, typ)
}
e.pi.typeVName[typ] = v
return v
}
func (e *emitter) emitTypeOf(expr ast.Expr) *spb.VName { return e.emitType(e.pi.Info.TypeOf(expr)) }
func (e *emitter) visitTuple(t *types.Tuple) []*spb.VName {
size := t.Len()
ts := make([]*spb.VName, size)
for i := 0; i < size; i++ {
ts[i] = e.emitType(t.At(i).Type())
}
return ts
}
// visitFuncLit handles function literals and their parameters. The signature
// for a function literal is named relative to the signature of its parent
// function, or the file scope if the literal is at the top level.
func (e *emitter) visitFuncLit(flit *ast.FuncLit, stack stackFunc) {
fi := e.callContext(stack)
if fi == nil {
log.Panic("Function literal without a context: ", flit)
}
fi.numAnons++
info := &funcInfo{vname: proto.Clone(fi.vname).(*spb.VName)}
info.vname.Language = govname.Language
info.vname.Signature += "$" + strconv.Itoa(fi.numAnons)
e.pi.function[flit] = info
e.writeDef(flit, info.vname)
e.writeFact(info.vname, facts.NodeKind, nodes.Function)
if sig, ok := e.pi.Info.Types[flit].Type.(*types.Signature); ok {
e.emitParameters(flit.Type, sig, info)
}
}
// visitValueSpec handles variable and constant bindings.
func (e *emitter) visitValueSpec(spec *ast.ValueSpec, stack stackFunc) {
kind := nodes.Variable
if stack(1).(*ast.GenDecl).Tok == token.CONST {
kind = nodes.Constant
}
doc := specComment(spec, stack)
for _, id := range spec.Names {
target := e.writeBinding(id, kind, e.nameContext(stack))
if target == nil {
continue // type error (reported elsewhere)
}
e.writeDoc(doc, target)
}
// Handle members of anonymous types declared in situ.
if spec.Type != nil {
e.emitAnonMembers(spec.Type)
}
for _, v := range spec.Values {
if lit, ok := v.(*ast.CompositeLit); ok {
e.emitAnonMembers(lit.Type)
}
}
}
// visitTypeSpec handles type declarations, including the bindings for fields
// of struct types and methods of interfaces.
func (e *emitter) visitTypeSpec(spec *ast.TypeSpec, stack stackFunc) {
obj := e.pi.Info.Defs[spec.Name]
if obj == nil {
return // type error
}
target := e.mustWriteBinding(spec.Name, "", e.nameContext(stack))
e.writeDef(spec, target)
e.writeDoc(specComment(spec, stack), target)
mapFields(spec.TypeParams, func(i int, id *ast.Ident) {
v := e.writeBinding(id, nodes.TVar, nil)
e.writeEdge(target, v, edges.TParamIndex(i))
})
// Emit type-specific structure.
switch t := obj.Type().Underlying().(type) {
case *types.Struct:
e.writeFact(target, facts.NodeKind, nodes.Record)
e.writeFact(target, facts.Subkind, nodes.Struct)
// Add parent edges for all fields, including promoted ones.
for i, n := 0, t.NumFields(); i < n; i++ {
e.writeEdge(e.pi.ObjectVName(t.Field(i)), target, edges.ChildOf)
}
// Add bindings for the explicitly-named fields in this declaration.
// Parent edges were already added, so skip them here.
if st, ok := spec.Type.(*ast.StructType); ok {
mapFields(st.Fields, func(i int, id *ast.Ident) {
target := e.writeVarBinding(id, nodes.Field, nil)
f := st.Fields.List[i]
e.writeDoc(firstNonEmptyComment(f.Doc, f.Comment), target)
e.emitAnonMembers(f.Type)
})
// Handle anonymous fields. Such fields behave as if they were
// named by the base identifier of their type.
for _, field := range st.Fields.List {
if len(field.Names) != 0 {
continue // already handled above
}
id, ok := e.pi.findFieldName(field.Type)
obj := e.pi.Info.Defs[id]
if ok && obj != nil {
// Don't write a fresh anchor here; we already wrote one as
// part of the ref to the type, and we don't want duplicate
// outputs.
anchor := e.pi.AnchorVName(e.pi.Span(id))
target := e.pi.ObjectVName(obj)
e.writeEdge(anchor, target, edges.DefinesBinding)
e.writeFact(target, facts.NodeKind, nodes.Variable)
e.writeFact(target, facts.Subkind, nodes.Field)
e.writeDoc(firstNonEmptyComment(field.Doc, field.Comment), target)
}
}
}
case *types.Interface:
e.writeFact(target, facts.NodeKind, nodes.Interface)
// Add parent edges for all methods, including inherited ones.
for i, n := 0, t.NumMethods(); i < n; i++ {
e.writeEdge(e.pi.ObjectVName(t.Method(i)), target, edges.ChildOf)
}
// Mark the interface as an extension of any embedded interfaces.
for i, n := 0, t.NumEmbeddeds(); i < n; i++ {
if named, ok := t.EmbeddedType(i).(*types.Named); ok {
if eobj := named.Obj(); e.checkImplements(obj, eobj) {
e.writeEdge(target, e.pi.ObjectVName(eobj), edges.Extends)
}
}
}
// Add bindings for the explicitly-named methods in this declaration.
// Parent edges were already added, so skip them here.
if it, ok := spec.Type.(*ast.InterfaceType); ok {
mapFields(it.Methods, func(_ int, id *ast.Ident) {
e.writeBinding(id, nodes.Function, nil)
})
}
default:
// We model a newtype form whose underlying type is not already a
// struct (e.g., "type Foo int") as if it were a record with a single
// unexported field of the underlying type. That is not really what Go
// does, but it is close enough for the graph model to work. Since
// there is no actual field declaration, however, we don't emit that.
e.writeFact(target, facts.NodeKind, nodes.Record)
e.writeFact(target, facts.Subkind, nodes.Type)
}
}
// visitImportSpec handles references to imported packages.
func (e *emitter) visitImportSpec(spec *ast.ImportSpec, stack stackFunc) {
ipath, _ := strconv.Unquote(spec.Path.Value)
if vPath, ok := e.pi.Vendored[ipath]; ok {
ipath = vPath
}
pkg := e.pi.Dependencies[ipath]
target := e.pi.PackageVName[pkg]
if target == nil {
log.Printf("Unable to resolve import path %q", ipath)
return
}
e.writeRef(spec.Path, target, edges.RefImports)
if e.opts.shouldEmit(target) && !e.pi.standardLib.Contains(ipath) {
e.writeFact(target, facts.NodeKind, nodes.Package)
e.pi.standardLib.Add(ipath)
}
}
// visitAssignStmt handles bindings introduced by short-declaration syntax in
// assignment statments, e.g., "x, y := 1, 2".
func (e *emitter) visitAssignStmt(stmt *ast.AssignStmt, stack stackFunc) {
if stmt.Tok != token.DEFINE {
return // no new bindings in this statement
}
// Not all the names in a short declaration assignment may be defined here.
// We only add bindings for newly-defined ones, of which there must be at
// least one in a well-typed program.
up := e.nameContext(stack)
for _, expr := range stmt.Lhs {
if id, _ := expr.(*ast.Ident); id != nil {
// Add a binding only if this is the definition site for the name.
if obj := e.pi.Info.Defs[id]; obj != nil && obj.Pos() == id.Pos() {
e.mustWriteBinding(id, nodes.Variable, up)
}
}
}
// TODO(fromberger): Add information about initializers where available.
}
// visitRangeStmt handles the bindings introduced by a for ... range statement.
func (e *emitter) visitRangeStmt(stmt *ast.RangeStmt, stack stackFunc) {
if stmt.Tok != token.DEFINE {
return // no new bindings in this statement
}
// In a well-typed program, the key and value will always be identifiers.
up := e.nameContext(stack)
if key, _ := stmt.Key.(*ast.Ident); key != nil {
e.writeBinding(key, nodes.Variable, up)
}
if val, _ := stmt.Value.(*ast.Ident); val != nil {
e.writeBinding(val, nodes.Variable, up)
}
}
// visitCompositeLit handles references introduced by positional initializers
// in composite literals that construct (pointer to) struct values. Named
// initializers are handled separately.
func (e *emitter) visitCompositeLit(expr *ast.CompositeLit, stack stackFunc) {
if len(expr.Elts) == 0 {
return // no fields to initialize
}
tv, ok := e.pi.Info.Types[expr]
if !ok {
log.Printf("WARNING: Unable to determine composite literal type (%s)", e.pi.FileSet.Position(expr.Pos()))
return
}
sv, ok := deref(tv.Type.Underlying()).(*types.Struct)
if !ok {
return // non-struct type, e.g. a slice; nothing to do here
}
if n := sv.NumFields(); n < len(expr.Elts) {
// Embedded struct fields from an imported package may not appear in
// the list if the import did not succeed. To remain robust against
// such cases, don't try to read into the fields of a struct type if
// the counts don't line up. The information we emit will still be
// correct, we'll just miss some initializers.
log.Printf("ERROR: Struct has %d fields but %d initializers (skipping)", n, len(expr.Elts))
return
}
for i, elt := range expr.Elts {
// The keys for key-value initializers are handled upstream of us, so
// we need only handle the values. But note that key-value initializers
// may not be in order, so we have to take care to get the right field.
// Positional fields must be in order, in well-formed code.
switch t := elt.(type) {
case *ast.KeyValueExpr:
f, ok := fieldIndex(t.Key, sv)
if !ok {
log.Printf("ERROR: Found no field index for %v (skipping)", t.Key)
continue
}
e.emitPosRef(t.Value, sv.Field(f), edges.RefInit)
default:
e.emitPosRef(t, sv.Field(i), edges.RefInit)
}
}
}
// visitIndexExpr handles references to instantiated types with a single type
// parameter.
func (e *emitter) visitIndexExpr(expr *ast.IndexExpr, stack stackFunc) {
if n, ok := e.pi.Info.TypeOf(expr).(*types.Named); ok && n.TypeArgs().Len() > 0 {
e.writeRef(expr, e.emitType(n), edges.Ref)
}
}
// visitIndexListExpr handles references to instantiated types with multiple
// type parameters.
func (e *emitter) visitIndexListExpr(expr *ast.IndexListExpr, stack stackFunc) {
if n, ok := e.pi.Info.TypeOf(expr).(*types.Named); ok && n.TypeArgs().Len() > 0 {
e.writeRef(expr, e.emitType(n), edges.Ref)
}
}
// emitPosRef emits an anchor spanning loc, pointing to obj.
func (e *emitter) emitPosRef(loc ast.Node, obj types.Object, kind string) {
target := e.pi.ObjectVName(obj)
file, start, end := e.pi.Span(loc)
anchor := e.pi.AnchorVName(file, start, end)
e.writeAnchor(loc, anchor, start, end)
e.writeEdge(anchor, target, kind)
}
// emitParameters emits parameter edges for the parameters of a function type,
// given the type signature and info of the enclosing declaration or function
// literal.
func (e *emitter) emitParameters(ftype *ast.FuncType, sig *types.Signature, info *funcInfo) {
paramIndex := 0
// If there is a receiver, it is treated as param.0.
if sig.Recv() != nil {
paramIndex++
}
// Emit bindings and parameter edges for the parameters.
mapFields(ftype.Params, func(i int, id *ast.Ident) {
if sig.Params().At(i) != nil {
if param := e.writeBinding(id, nodes.Variable, info.vname); param != nil {
e.writeEdge(info.vname, param, edges.ParamIndex(paramIndex))
field := ftype.Params.List[i]
e.emitAnonMembers(field.Type)
// Field object does not associate any comments with the parameter; use CommentMap to find them
e.writeDoc(firstNonEmptyComment(e.cmap.Filter(field).Comments()...), param)
}
}
paramIndex++
})
// Emit bindings for any named result variables.
// Results are not considered parameters.
mapFields(ftype.Results, func(i int, id *ast.Ident) {
e.writeBinding(id, nodes.Variable, info.vname)
})
// Emit bindings for type parameters
mapFields(ftype.TypeParams, func(i int, id *ast.Ident) {
v := e.writeBinding(id, nodes.TVar, nil)
e.writeEdge(info.vname, v, edges.TParamIndex(i))
})
}
// emitAnonMembers checks whether expr denotes an anonymous struct or interface
// type, and if so emits bindings for its member fields/methods. The resulting
// members do not parent to the type, since it has no referential identity; but
// we do capture documentation in the unlikely event someone wrote any.
func (e *emitter) emitAnonMembers(expr ast.Expr) {
if st, ok := expr.(*ast.StructType); ok {
mapFields(st.Fields, func(i int, id *ast.Ident) {
target := e.writeVarBinding(id, nodes.Field, nil) // no parent
e.writeDoc(firstNonEmptyComment(st.Fields.List[i].Doc, st.Fields.List[i].Comment), target)
})
} else if it, ok := expr.(*ast.InterfaceType); ok {
mapFields(it.Methods, func(i int, id *ast.Ident) {
target := e.writeBinding(id, nodes.Function, nil) // no parent
e.writeDoc(firstNonEmptyComment(it.Methods.List[i].Doc, it.Methods.List[i].Comment), target)
})
}
}
// An override represents the relationship that x overrides y.
type override struct {
x, y types.Object
}
// overrides represents a set of override relationships we've already generated.
type overrides map[override]bool
// seen reports whether an x overrides y was already cached, and if not adds it
// to the set.
func (o overrides) seen(x, y types.Object) bool {
ov := override{x: x, y: y}
ok := o[ov]
if !ok {
o[ov] = true
}
return ok
}
// emitSatisfactions visits each named type known through the compilation being
// indexed, and emits edges connecting it to any known interfaces its method
// set satisfies.
func (e *emitter) emitSatisfactions() {
// Find all the Named types mentioned in this compilation.
var allTypes []*types.Named
// For the current source package, use all names, even local ones.
for _, obj := range e.pi.Info.Defs {
if obj, ok := obj.(*types.TypeName); ok {
if n, ok := obj.Type().(*types.Named); ok {
allTypes = append(allTypes, n)
}
}
}
// Include instance types.
for _, t := range e.pi.Info.Types {
if n, ok := t.Type.(*types.Named); ok && n.TypeArgs().Len() > 0 {
allTypes = append(allTypes, n)
}
}
// For dependencies, we only have access to package-level types, not those
// defined by inner scopes.
for _, pkg := range e.pi.Dependencies {
scope := pkg.Scope()
for _, name := range scope.Names() {
if obj, ok := scope.Lookup(name).(*types.TypeName); ok {
// Note that the names of some "named" types that are brought
// in from dependencies may not be known at this point -- the
// compiled package headers omit the names if they are not
// needed. Skip such cases, even though they would qualify if
// we had the source package.
if n, ok := obj.Type().(*types.Named); ok && obj.Name() != "" {
allTypes = append(allTypes, n)
}
}
}
}
// Shared Context across all generic assignability checks.
tctx := types.NewContext()
// Cache the method set of each named type in this package.
var msets typeutil.MethodSetCache
// Cache the overrides we've noticed to avoid duplicate entries.
cache := make(overrides)
for _, x := range allTypes {
xobj := x.Obj()
if xobj.Pkg() != e.pi.Package {
continue // not from this package
}
// Check whether x is a named type with methods; if not, skip it.
if len(typeutil.IntuitiveMethodSet(x, &msets)) == 0 {
continue // no methods to consider
}
// N.B. This implementation is quadratic in the number of visible
// interfaces, but that's probably OK since are only considering a
// single compilation.
// Check the method sets of both x and pointer-to-x for overrides.
xmset := msets.MethodSet(xobj.Type())
pxmset := msets.MethodSet(types.NewPointer(xobj.Type()))
for _, y := range allTypes {
yobj := y.Obj()
if xobj == yobj {
continue
}
ymset := msets.MethodSet(yobj.Type())
ifx, ify := isInterface(x), isInterface(y)
switch {
case ifx && ify && ymset.Len() > 0:
// x and y are both interfaces. Note that extension is handled
// elsewhere as part of the type spec for the interface.
if assignableTo(tctx, x, y) {
e.writeSatisfies(xobj, yobj)
}
if assignableTo(tctx, y, x) {
e.writeSatisfies(yobj, xobj)
}
case ifx:
// y is a concrete type
pymset := msets.MethodSet(types.NewPointer(y))
if assignableTo(tctx, y, x) {
e.writeSatisfies(yobj, xobj)
e.emitOverrides(ymset, pymset, xmset, cache)
}
case ify && ymset.Len() > 0:
// x is a concrete type
if assignableTo(tctx, x, y) {
e.writeSatisfies(xobj, yobj)
e.emitOverrides(xmset, pxmset, ymset, cache)
}
default:
// Both x and y are concrete.
}
}
}
}
// Add xm-(overrides)-ym for each concrete method xm with a corresponding
// abstract method ym.
func (e *emitter) emitOverrides(xmset, pxmset, ymset *types.MethodSet, cache overrides) {
for i, n := 0, ymset.Len(); i < n; i++ {
ym := ymset.At(i)
yobj := ym.Obj()