-
Notifications
You must be signed in to change notification settings - Fork 14
/
goapi.go
3711 lines (3530 loc) · 90.9 KB
/
goapi.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 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Api computes the exported API of a set of Go packages.
//
// 2012.10.17 fixed for any package
// visualfc
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"go/ast"
"go/build"
"go/doc"
"go/parser"
"go/printer"
"go/token"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
)
// Flags
var (
checkFile *string
allowNew *bool
exceptFile *string
nextFile *string
verbose *bool
allmethods *bool
alldecls *bool
showpos *bool
separate *string
dep_parser *bool
defaultCtx *bool
customCtx *string
cursorStd *bool
)
func init() {
_checkFile := ""
checkFile = &_checkFile
_allowNew := true
allowNew = &_allowNew
_exceptFile := ""
exceptFile = &_exceptFile
_nextFile := ""
nextFile = &_nextFile
_verbose := false
verbose = &_verbose
_allmethods := true
allmethods = &_allmethods
_alldecls := false
alldecls = &_alldecls
_showpos := false
showpos = &_showpos
_separate := ", "
separate = &_separate
_dep_parser := true
dep_parser = &_dep_parser
_defaultCtx := false
defaultCtx = &_defaultCtx
_customCtx := ""
customCtx = &_customCtx
_cursorStd := false
cursorStd = &_cursorStd
registry.Register("doc", func(_ *Broker) Caller {
return &goApi{
Env: map[string]string{},
}
})
}
type CursorInfo struct {
pkg string
file string
pos token.Pos
src []byte
std bool
info *TypeInfo
}
func usage() {
fmt.Fprintf(os.Stderr, `usage: api [std|all|package...|local-dir]
api std
api -default_ctx=true fmt flag
api -default_ctx=true -a ./cmd/go
`)
flag.PrintDefaults()
}
// contexts are the default contexts which are scanned, unless
// overridden by the -contexts flag.
var contexts = []*build.Context{
{GOOS: "linux", GOARCH: "386", CgoEnabled: true},
{GOOS: "linux", GOARCH: "386"},
{GOOS: "linux", GOARCH: "amd64", CgoEnabled: true},
{GOOS: "linux", GOARCH: "amd64"},
{GOOS: "linux", GOARCH: "arm"},
{GOOS: "darwin", GOARCH: "386", CgoEnabled: true},
{GOOS: "darwin", GOARCH: "386"},
{GOOS: "darwin", GOARCH: "amd64", CgoEnabled: true},
{GOOS: "darwin", GOARCH: "amd64"},
{GOOS: "windows", GOARCH: "amd64"},
{GOOS: "windows", GOARCH: "386"},
{GOOS: "freebsd", GOARCH: "amd64"},
{GOOS: "freebsd", GOARCH: "386"},
}
func contextName(c *build.Context) string {
s := c.GOOS + "-" + c.GOARCH
if c.CgoEnabled {
return s + "-cgo"
}
return s
}
func osArchName(c *build.Context) string {
return c.GOOS + "-" + c.GOARCH
}
func parseContext(c string) *build.Context {
parts := strings.Split(c, "-")
if len(parts) < 2 {
return nil
// log.Fatalf("bad context: %q", c)
}
bc := &build.Context{
GOOS: parts[0],
GOARCH: parts[1],
}
if len(parts) == 3 {
if parts[2] == "cgo" {
// bc.CgoEnabled = true
} else {
// log.Fatalf("bad context: %q", c)
}
}
return bc
}
func setCustomContexts() {
contexts = []*build.Context{}
for _, c := range strings.Split(*customCtx, ",") {
contexts = append(contexts, parseContext(c))
}
}
type goApi struct {
Fn string
Src string
Env map[string]string
Offset int
TabIndent bool
TabWidth int
}
func (m *goApi) Call() (interface{}, string) {
res := []*Doc{}
if runtime.GOOS == "windows" {
if m.Offset > len(m.Src) {
m.Offset = len(m.Src)
}
m.Offset += strings.Count(m.Src[:m.Offset], "\t") * 3
}
dir, file := filepath.Split(m.Fn)
pkgs := []string{dir}
line := fmt.Sprintf("%s:%d", file, m.Offset)
context := &build.Context{}
contexts := []*build.Context{context}
context.GOROOT = m.Env["GOROOT"]
context.GOPATH = m.Env["GOPATH"]
context.GOOS = m.Env["GOOS"]
context.GOARCH = m.Env["GOARCH"]
context.CgoEnabled = m.Env["CGO_ENABLED"] == "1"
if context.GOOS == "" {
context.GOOS = runtime.GOOS
}
pos, info := GoApi(&line, pkgs, contexts)
if pos.IsValid() {
doc := &Doc{}
doc.Col = pos.Column - 1
doc.Row = pos.Line - 1
doc.Fn = pos.Filename
doc.Name = info.Name
doc.Kind = info.Kind.String()
res = append(res, doc)
}
return res, ""
}
func GoApi(lookupCursorInfo *string, pkgs []string, contexts []*build.Context) (thePos token.Position, theInfo *TypeInfo) {
// flag.Usage = usage
// flag.Parse()
defer func() {
// debug.PrintStack()
}()
if !strings.Contains(runtime.Version(), "weekly") && !strings.Contains(runtime.Version(), "devel") {
if *nextFile != "" {
fmt.Printf("Go version is %q, ignoring -next %s\n", runtime.Version(), *nextFile)
*nextFile = ""
}
}
// if flag.NArg() == 0 {
// flag.Usage()
// return
// }
if *verbose {
now := time.Now()
defer func() {
log.Println("time", time.Now().Sub(now))
}()
}
// var pkgs []string
// if flag.Arg(0) == "std" || flag.Arg(0) == "all" {
// out, err := exec.Command("go", "list", "-e", flag.Arg(0)).Output()
// if err != nil {
// log.Fatal(err)
// }
// pkgs = strings.Fields(string(out))
// } else {
// pkgs = flag.Args()
// }
var curinfo CursorInfo
if *lookupCursorInfo != "" {
pos := strings.Index(*lookupCursorInfo, ":")
if pos != -1 {
curinfo.file = (*lookupCursorInfo)[:pos]
if i, err := strconv.Atoi((*lookupCursorInfo)[pos+1:]); err == nil {
curinfo.pos = token.Pos(i)
}
}
}
if len(pkgs) == 1 && curinfo.pos != token.NoPos {
curinfo.pkg = pkgs[0]
}
if *cursorStd {
src, err := ioutil.ReadAll(os.Stdin)
if err == nil {
curinfo.src = src
curinfo.std = true
}
}
if *customCtx != "" {
*defaultCtx = false
setCustomContexts()
}
var features []string
w := NewWalker()
if curinfo.pkg != "" {
w.cursorInfo = &curinfo
}
w.sep = *separate
if *defaultCtx {
w.context = &build.Default
for _, pkg := range pkgs {
w.wantedPkg[pkg] = true
}
for _, pkg := range pkgs {
w.WalkPackage(pkg)
}
features = w.Features("")
} else {
for _, c := range contexts {
c.Compiler = build.Default.Compiler
}
for _, pkg := range pkgs {
w.wantedPkg[pkg] = true
}
var featureCtx = make(map[string]map[string]bool) // feature -> context name -> true
for _, context := range contexts {
w.context = context
w.ctxName = contextName(w.context) + ":"
for _, pkg := range pkgs {
w.WalkPackage(pkg)
}
if w.cursorInfo != nil && w.cursorInfo.info != nil {
goto lookup
}
}
for pkg, p := range w.packageMap {
if w.wantedPkg[p.name] {
pos := strings.Index(pkg, ":")
if pos == -1 {
continue
}
ctxName := pkg[:pos]
for _, f := range p.Features() {
if featureCtx[f] == nil {
featureCtx[f] = make(map[string]bool)
}
featureCtx[f][ctxName] = true
}
}
}
for f, cmap := range featureCtx {
if len(cmap) == len(contexts) {
features = append(features, f)
continue
}
comma := strings.Index(f, ",")
for cname := range cmap {
f2 := fmt.Sprintf("%s (%s)%s", f[:comma], cname, f[comma:])
features = append(features, f2)
}
}
sort.Strings(features)
}
lookup:
if w.cursorInfo != nil {
info := w.cursorInfo.info
if info == nil {
// os.Exit(1)
return
}
// fmt.Println("kind,", info.Kind)
// fmt.Println("name,", info.Name)
// if info.Type != "" {
// fmt.Println("type,", strings.TrimLeft(info.Type, "*"))
// }
if info.Name == info.Type || info.Type == "" {
// fmt.Printf("info, %s, %s\n", info.Kind, info.Name)
} else {
// fmt.Printf("info, %s, %s, %s\n", info.Kind, info.Name, info.Type)
}
if info.Kind == KindImport || info.Kind == KindPackage {
if p := w.findPackage(info.Name); p != nil {
// fmt.Println("help,", p.name)
}
}
if info.T != nil {
for _, text := range []string{info.Name, info.Type} {
typ := strings.TrimLeft(text, "*")
pos := strings.Index(typ, ".")
if pos != -1 {
if p := w.findPackage(typ[:pos]); p != nil {
// fmt.Println("help,", p.name+typ[pos:])
break
}
}
}
return w.fset.Position(info.T.Pos()), info
// fmt.Println("pos,", w.fset.Position(info.T.Pos()))
}
return
}
fail := false
defer func() {
if fail {
// os.Exit(1)
}
}()
bw := bufio.NewWriter(os.Stdout)
defer bw.Flush()
if *checkFile == "" {
for _, f := range features {
fmt.Fprintf(bw, "%s\n", f)
}
return
}
if *checkFile == "" {
for _, f := range features {
fmt.Fprintf(bw, "%s\n", f)
}
return
}
required := fileFeatures(*checkFile)
optional := fileFeatures(*nextFile)
exception := fileFeatures(*exceptFile)
fail = !compareAPI(bw, features, required, optional, exception)
return
}
func set(items []string) map[string]bool {
s := make(map[string]bool)
for _, v := range items {
s[v] = true
}
return s
}
var spaceParensRx = regexp.MustCompile(` \(\S+?\)`)
func featureWithoutContext(f string) string {
if !strings.Contains(f, "(") {
return f
}
return spaceParensRx.ReplaceAllString(f, "")
}
func compareAPI(w io.Writer, features, required, optional, exception []string) (ok bool) {
ok = true
optionalSet := set(optional)
exceptionSet := set(exception)
featureSet := set(features)
sort.Strings(features)
sort.Strings(required)
take := func(sl *[]string) string {
s := (*sl)[0]
*sl = (*sl)[1:]
return s
}
for len(required) > 0 || len(features) > 0 {
switch {
case len(features) == 0 || (len(required) > 0 && required[0] < features[0]):
feature := take(&required)
if exceptionSet[feature] {
fmt.Fprintf(w, "~%s\n", feature)
} else if featureSet[featureWithoutContext(feature)] {
// okay.
} else {
fmt.Fprintf(w, "-%s\n", feature)
ok = false // broke compatibility
}
case len(required) == 0 || (len(features) > 0 && required[0] > features[0]):
newFeature := take(&features)
if optionalSet[newFeature] {
// Known added feature to the upcoming release.
// Delete it from the map so we can detect any upcoming features
// which were never seen. (so we can clean up the nextFile)
delete(optionalSet, newFeature)
} else {
fmt.Fprintf(w, "+%s\n", newFeature)
if !*allowNew {
ok = false // we're in lock-down mode for next release
}
}
default:
take(&required)
take(&features)
}
}
// In next file, but not in API.
var missing []string
for feature := range optionalSet {
missing = append(missing, feature)
}
sort.Strings(missing)
for _, feature := range missing {
fmt.Fprintf(w, "±%s\n", feature)
}
return
}
func fileFeatures(filename string) []string {
bs, err := ioutil.ReadFile(filename)
if err != nil {
return nil
// log.Fatalf("Error reading file %s: %v", filename, err)
}
text := strings.TrimSpace(string(bs))
if text == "" {
return nil
}
return strings.Split(text, "\n")
}
func isExtract(name string) bool {
if *alldecls {
return true
}
return ast.IsExported(name)
}
// pkgSymbol represents a symbol in a package
type pkgSymbol struct {
pkg string // "net/http"
symbol string // "RoundTripper"
}
//expression kind
type Kind int
const (
KindBuiltin Kind = iota
KindPackage
KindImport
KindVar
KindConst
KindInterface
KindParam
KindStruct
KindMethod
KindField
KindType
KindFunc
KindChan
KindArray
KindMap
KindSlice
)
func (k Kind) String() string {
switch k {
case KindBuiltin:
return "builtin"
case KindPackage:
return "package"
case KindImport:
return "import"
case KindVar:
return "var"
case KindConst:
return "const"
case KindParam:
return "param"
case KindInterface:
return "interface"
case KindStruct:
return "struct"
case KindMethod:
return "method"
case KindField:
return "field"
case KindType:
return "type"
case KindFunc:
return "func"
case KindChan:
return "chan"
case KindMap:
return "map"
case KindArray:
return "array"
case KindSlice:
return "slice"
}
return fmt.Sprintf("unknown-%v", k)
}
//expression type
type TypeInfo struct {
Kind Kind
Name string
Type string
X ast.Expr
T ast.Expr
}
type ExprType struct {
X ast.Expr
T string
}
type Package struct {
dpkg *doc.Package
apkg *ast.Package
interfaceMethods map[string]([]method)
interfaces map[string]*ast.InterfaceType //interface
structs map[string]*ast.StructType //struct
types map[string]ast.Expr //type
functions map[string]method //function
consts map[string]*ExprType //const => type
vars map[string]*ExprType //var => type
name string
dir string
sep string
deps []string
features map[string](token.Pos) // set
}
func NewPackage() *Package {
return &Package{
interfaceMethods: make(map[string]([]method)),
interfaces: make(map[string]*ast.InterfaceType),
structs: make(map[string]*ast.StructType),
types: make(map[string]ast.Expr),
functions: make(map[string]method),
consts: make(map[string]*ExprType),
vars: make(map[string]*ExprType),
features: make(map[string](token.Pos)),
sep: ", ",
}
}
func (p *Package) Features() (fs []string) {
for f, ps := range p.features {
if *showpos {
fs = append(fs, f+p.sep+strconv.Itoa(int(ps)))
} else {
fs = append(fs, f)
}
}
sort.Strings(fs)
return
}
func (p *Package) findType(name string) ast.Expr {
for k, v := range p.interfaces {
if k == name {
return v
}
}
for k, v := range p.structs {
if k == name {
return v
}
}
for k, v := range p.types {
if k == name {
return v
}
}
return nil
}
func funcRetType(ft *ast.FuncType, index int) ast.Expr {
if ft.Results != nil {
pos := 0
for _, fi := range ft.Results.List {
if fi.Names == nil {
if pos == index {
return fi.Type
}
pos++
} else {
for _ = range fi.Names {
if pos == index {
return fi.Type
}
pos++
}
}
}
}
return nil
}
func findFunction(funcs []*doc.Func, name string) (*ast.Ident, *ast.FuncType) {
for _, f := range funcs {
if f.Name == name {
return &ast.Ident{Name: name, NamePos: f.Decl.Pos()}, f.Decl.Type
}
}
return nil, nil
}
func (p *Package) findSelectorType(name string) ast.Expr {
if t, ok := p.vars[name]; ok {
return &ast.Ident{
NamePos: t.X.Pos(),
Name: t.T,
}
}
if t, ok := p.consts[name]; ok {
return &ast.Ident{
NamePos: t.X.Pos(),
Name: t.T,
}
}
if t, ok := p.functions[name]; ok {
return t.ft
}
for k, v := range p.structs {
if k == name {
return &ast.Ident{
NamePos: v.Pos(),
Name: name,
}
}
}
for k, v := range p.interfaces {
if k == name {
return &ast.Ident{
NamePos: v.Pos(),
Name: name,
}
}
}
for k, v := range p.types {
if k == name {
return v
}
}
return nil
}
func (p *Package) findCallFunc(name string) ast.Expr {
if fn, ok := p.functions[name]; ok {
return fn.ft
}
if s, ok := p.structs[name]; ok {
return s
}
if t, ok := p.types[name]; ok {
return t
}
if v, ok := p.vars[name]; ok {
if strings.HasPrefix(v.T, "func(") {
e, err := parser.ParseExpr(v.T + "{}")
if err == nil {
return e
}
}
}
return nil
}
func (p *Package) findCallType(name string, index int) ast.Expr {
if fn, ok := p.functions[name]; ok {
return funcRetType(fn.ft, index)
}
if s, ok := p.structs[name]; ok {
return &ast.Ident{
NamePos: s.Pos(),
Name: name,
}
}
if t, ok := p.types[name]; ok {
return &ast.Ident{
NamePos: t.Pos(),
Name: name,
}
}
return nil
}
func (p *Package) findMethod(typ, name string) (*ast.Ident, *ast.FuncType) {
if t, ok := p.interfaces[typ]; ok && t.Methods != nil {
for _, fd := range t.Methods.List {
switch ft := fd.Type.(type) {
case *ast.FuncType:
for _, ident := range fd.Names {
if ident.Name == name {
return ident, ft
}
}
}
}
}
for k, v := range p.interfaceMethods {
if k == typ {
for _, m := range v {
if m.name == name {
return &ast.Ident{Name: name, NamePos: m.pos}, m.ft
}
}
}
}
if p.dpkg == nil {
return nil, nil
}
for _, t := range p.dpkg.Types {
if t.Name == typ {
return findFunction(t.Methods, name)
}
}
return nil, nil
}
type Walker struct {
context *build.Context
fset *token.FileSet
scope []string
// features map[string](token.Pos) // set
lastConstType string
curPackageName string
sep string
ctxName string
curPackage *Package
constDep map[string]*ExprType // key's const identifier has type of future value const identifier
packageState map[string]loadState
packageMap map[string]*Package
interfaces map[pkgSymbol]*ast.InterfaceType
selectorFullPkg map[string]string // "http" => "net/http", updated by imports
wantedPkg map[string]bool // packages requested on the command line
cursorInfo *CursorInfo
localvar map[string]*ExprType
}
func NewWalker() *Walker {
return &Walker{
fset: token.NewFileSet(),
// features: make(map[string]token.Pos),
packageState: make(map[string]loadState),
interfaces: make(map[pkgSymbol]*ast.InterfaceType),
packageMap: make(map[string]*Package),
selectorFullPkg: make(map[string]string),
wantedPkg: make(map[string]bool),
localvar: make(map[string]*ExprType),
sep: ", ",
}
}
// loadState is the state of a package's parsing.
type loadState int
const (
notLoaded loadState = iota
loading
loaded
)
func (w *Walker) Features(ctx string) (fs []string) {
for pkg, p := range w.packageMap {
if w.wantedPkg[p.name] {
if ctx == "" || strings.HasPrefix(pkg, ctx) {
fs = append(fs, p.Features()...)
}
}
}
sort.Strings(fs)
return
}
// fileDeps returns the imports in a file.
func fileDeps(f *ast.File) (pkgs []string) {
for _, is := range f.Imports {
fpkg, err := strconv.Unquote(is.Path.Value)
if err != nil {
// log.Fatalf("error unquoting import string %q: %v", is.Path.Value, err)
}
if fpkg != "C" {
pkgs = append(pkgs, fpkg)
}
}
return
}
func (w *Walker) findPackage(pkg string) *Package {
if full, ok := w.selectorFullPkg[pkg]; ok {
if w.ctxName != "" {
ctxName := w.ctxName + full
for k, v := range w.packageMap {
if k == ctxName {
return v
}
}
}
for k, v := range w.packageMap {
if k == full {
return v
}
}
}
return nil
}
func (w *Walker) findPackageOSArch(pkg string) *Package {
if full, ok := w.selectorFullPkg[pkg]; ok {
ctxName := osArchName(w.context) + ":" + full
for k, v := range w.packageMap {
if k == ctxName {
return v
}
}
}
return nil
}
// WalkPackage walks all files in package `name'.
// WalkPackage does nothing if the package has already been loaded.
func (w *Walker) WalkPackage(pkg string) {
if build.IsLocalImport(pkg) {
wd, err := os.Getwd()
if err != nil {
if *verbose {
log.Println(err)
}
return
}
dir := filepath.Clean(filepath.Join(wd, pkg))
bp, err := w.context.ImportDir(dir, 0)
if err != nil {
if *verbose {
log.Println(err)
}
return
}
if w.wantedPkg[pkg] == true {
w.wantedPkg[bp.Name] = true
delete(w.wantedPkg, pkg)
}
if w.cursorInfo != nil && w.cursorInfo.pkg == pkg {
w.cursorInfo.pkg = bp.Name
}
w.WalkPackageDir(bp.Name, bp.Dir, bp)
} else if filepath.IsAbs(pkg) {
bp, err := w.context.ImportDir(pkg, 0)
if err != nil {
if *verbose {
log.Println(err)
}
}
if w.wantedPkg[pkg] == true {
w.wantedPkg[bp.Name] = true
delete(w.wantedPkg, pkg)
}
if w.cursorInfo != nil && w.cursorInfo.pkg == pkg {
w.cursorInfo.pkg = bp.Name
}
w.WalkPackageDir(bp.Name, bp.Dir, bp)
} else {
bp, err := w.context.Import(pkg, "", build.FindOnly)
if err != nil {
if *verbose {
log.Println(err)
}
return
}
w.WalkPackageDir(pkg, bp.Dir, nil)
}
}
func (w *Walker) WalkPackageDir(name string, dir string, bp *build.Package) {
ctxName := w.ctxName + name
curName := name
switch w.packageState[ctxName] {
case loading:
// log.Fatalf("import cycle loading package %q?", name)
return
case loaded:
return
}
w.packageState[ctxName] = loading
w.selectorFullPkg[name] = name
defer func() {
w.packageState[ctxName] = loaded
}()
sname := name[strings.LastIndex(name, "/")+1:]
apkg := &ast.Package{
Files: make(map[string]*ast.File),
}
if bp == nil {
bp, _ = w.context.ImportDir(dir, 0)
}
if bp == nil {
return
}
if w.ctxName != "" {
isCgo := (len(bp.CgoFiles) > 0) && w.context.CgoEnabled
if isCgo {
curName = ctxName
} else {
isOSArch := false
for _, file := range bp.GoFiles {
if isOSArchFile(w.context, file) {
isOSArch = true