-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.go
8770 lines (7316 loc) · 273 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
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
// A work in progress implementation of Conception in Go.
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"go/ast"
"go/build"
"go/importer"
"go/parser"
"go/printer"
"go/token"
"go/types"
"io"
"io/ioutil"
"log"
"math"
"net"
"net/http"
_ "net/http/pprof"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
textscanner "text/scanner"
"text/tabwriter"
"time"
"github.com/bradfitz/iter"
"github.com/go-gl/gl/v2.1/gl"
"github.com/go-gl/glfw/v3.3/glfw"
"github.com/go-gl/mathgl/mgl64"
"github.com/mattn/go-runewidth"
intmath "github.com/pkg/math"
"github.com/shurcooL-legacy/Conception-go/pkg/analysis"
"github.com/shurcooL-legacy/Conception-go/pkg/exp11"
"github.com/shurcooL-legacy/Conception-go/pkg/exp12"
"github.com/shurcooL-legacy/Conception-go/pkg/exp13"
"github.com/shurcooL-legacy/Conception-go/pkg/exp14"
"github.com/shurcooL-legacy/Conception-go/pkg/gist4727543"
"github.com/shurcooL-legacy/Conception-go/pkg/gist5504644"
"github.com/shurcooL-legacy/Conception-go/pkg/gist6003701"
. "github.com/shurcooL-legacy/Conception-go/pkg/gist7480523"
. "github.com/shurcooL-legacy/Conception-go/pkg/gist7576154"
. "github.com/shurcooL-legacy/Conception-go/pkg/gist7651991"
. "github.com/shurcooL-legacy/Conception-go/pkg/gist7802150"
"github.com/shurcooL-legacy/Conception-go/pkg/httpstoppable"
"github.com/shurcooL-legacy/Conception-go/pkg/legacyvcs"
"github.com/shurcooL-legacy/Conception-go/pkg/markdown_http"
"github.com/shurcooL-legacy/Conception-go/pkg/multilinecontent"
"github.com/shurcooL-legacy/Conception-go/pkg/u10"
"github.com/shurcooL-legacy/Conception-go/pkg/u6"
"github.com/shurcooL-legacy/octicons"
"github.com/shurcooL/github_flavored_markdown/gfmstyle"
"github.com/shurcooL/go-goon"
"github.com/shurcooL/go-goon/bypass"
"github.com/shurcooL/go/gddo"
"github.com/shurcooL/go/open"
"github.com/shurcooL/go/pipeutil"
"github.com/shurcooL/go/printerutil"
"github.com/shurcooL/go/reflectfind"
"github.com/shurcooL/go/reflectsource"
"github.com/shurcooL/httpfs/union"
"github.com/shurcooL/httpgzip"
"github.com/shurcooL/markdownfmt/markdown"
"github.com/sourcegraph/go-diff/diff"
"golang.org/x/net/websocket"
"golang.org/x/tools/godoc/vfs"
goimports "golang.org/x/tools/imports"
"gopkg.in/pipe.v2"
"github.com/shurcooL-legacy/Conception-go/caret"
"github.com/shurcooL-legacy/Conception-go/event"
)
var modeFlag = flag.Int("mode", 1, "Mode.")
var headlessFlag = flag.Bool("headless", false, "Headless mode.")
var keepRunning = true
var redraw = true
var windowPointer = &Pointer{VirtualCategory: event.Windowing}
var mousePointer = &Pointer{VirtualCategory: event.Pointing}
var keyboardPointer = &Pointer{VirtualCategory: event.Typing}
var websocketPointer *Pointer // TEST
var buildOutput caret.MultilineContentI
var goCompileErrorsTest GoCompileErrorsTest
var goCompileErrorsManagerTest GoCompileErrorsManagerTest
var booVcs *exp12.Directory
var windowFocusedEvent DepNode2ManualI = &DepNode2Manual{} // TEST.
// Colors
var (
nearlyWhiteColor = mgl64.Vec3{0.975, 0.975, 0.975}
veryLightColor = mgl64.Vec3{0.95, 0.95, 0.95}
lightColor = mgl64.Vec3{0.85, 0.85, 0.85}
grayColor = mgl64.Vec3{0.75, 0.75, 0.75}
darkColor = mgl64.Vec3{0.35, 0.35, 0.35}
veryDarkColor = mgl64.Vec3{0.1, 0.1, 0.1}
nearlyBlackColor = mgl64.Vec3{0.025, 0.025, 0.025}
highlightColor = mgl64.Vec3{0.898, 0.765, 0.396} // Yellowish on-hover border color.
selectedTextColor = mgl64.Vec3{195 / 255.0, 212 / 255.0, 242 / 255.0}
selectedTextDarkColor = selectedTextColor.Mul(0.75)
selectedTextInactiveColor = mgl64.Vec3{225 / 255.0, 235 / 255.0, 250 / 255.0}
selectedEntryColor = mgl64.Vec3{0.21, 0.45, 0.84}
selectedEntryInactiveColor = lightColor
lightRedColor = mgl64.Vec3{1, 0.867, 0.867}
lightGreenColor = mgl64.Vec3{0.867, 1, 0.867}
mediumRedColor = mgl64.Vec3{1, 0.767, 0.767}
mediumGreenColor = mgl64.Vec3{0.767, 1, 0.767}
darkRedColor = mgl64.Vec3{1, 0.667, 0.667}
darkGreenColor = mgl64.Vec3{0.667, 1, 0.667}
)
var np = mgl64.Vec2{} // np stands for "No Position" and it's basically the (0, 0) position, used when it doesn't matter
// TODO: Remove these
var globalWindow *glfw.Window
var keepUpdatedTEST = []DepNode2I{}
var globalParsedFile *parsedFile
var globalGoSymbols SliceStringer
var con2RunBinPath = filepath.Join(os.TempDir(), "Conception-go", "Con2RunBin")
// ---
type ChangeListener interface {
NotifyChange()
}
type ChangeListenerFunc func()
func (f ChangeListenerFunc) NotifyChange() {
f()
}
// ---
type DepNodeI interface {
AddChangeListener(l ChangeListener)
}
type DepNode struct {
changeListeners []ChangeListener
}
func (this *DepNode) AddChangeListener(l ChangeListener) {
this.changeListeners = append(this.changeListeners, l)
l.NotifyChange() // TODO: In future, don't literally NotifyChange() right away, as this can lead to duplicate work; instead mark as "need to update" for next run
}
// Pre-condition: l is a change listener that exists
func (this *DepNode) RemoveChangeListener(l ChangeListener) {
for i := range this.changeListeners {
if this.changeListeners[i] == l {
// Delete
copy(this.changeListeners[i:], this.changeListeners[i+1:])
this.changeListeners[len(this.changeListeners)-1] = nil
this.changeListeners = this.changeListeners[:len(this.changeListeners)-1]
//println("removed ith element of originally this many", i, len(this.changeListeners)+1)
return
}
}
panic("RemoveChangeListener: ChangeListener to be deleted wasn't found.")
}
func (this *DepNode) NotifyAllListeners() {
// TODO: In future, don't literally NotifyChange() right away, as this can lead to duplicate work; instead mark as "need to update" for next run
for _, changeListener := range this.changeListeners {
changeListener.NotifyChange()
}
}
// ---
type Widgeter interface {
PollLogic()
io.Closer
Layout()
LayoutNeeded()
Render()
Hit(mgl64.Vec2) []Widgeter
ProcessEvent(InputEvent) // TODO: Upgrade to MatchEventQueue() or so
ContainsWidget(widget, target Widgeter) bool // Returns true if target is widget or within it.
Pos() *mgl64.Vec2
Size() *mgl64.Vec2
HoverPointers() map[*Pointer]bool
Parent() Widgeter
SetParent(Widgeter)
ParentToLocal(mgl64.Vec2) mgl64.Vec2
DepNodeI
}
type Widgeters []Widgeter
type Widget struct {
pos mgl64.Vec2
size mgl64.Vec2
hoverPointers map[*Pointer]bool
parent Widgeter
DepNode
}
func NewWidget(pos, size mgl64.Vec2) Widget {
return Widget{pos: pos, size: size, hoverPointers: map[*Pointer]bool{}}
}
func (_ *Widget) PollLogic() {}
func (_ *Widget) Close() error { return nil }
func (w *Widget) Layout() {
if w.parent != nil {
w.parent.Layout()
}
}
func (_ *Widget) LayoutNeeded() {}
func (_ *Widget) Render() {}
func (w *Widget) Hit(ParentPosition mgl64.Vec2) []Widgeter {
LocalPosition := w.ParentToLocal(ParentPosition)
Hit := (LocalPosition[0] >= 0 &&
LocalPosition[1] >= 0 &&
LocalPosition[0] <= w.size[0] &&
LocalPosition[1] <= w.size[1])
if Hit {
return []Widgeter{w}
} else {
return nil
}
}
func (w *Widget) ProcessEvent(inputEvent InputEvent) {}
func (_ *Widget) ContainsWidget(widget, target Widgeter) bool {
return widget == target
}
func (w *Widget) Pos() *mgl64.Vec2 { return &w.pos }
func (w *Widget) Size() *mgl64.Vec2 { return &w.size }
func (w *Widget) HoverPointers() map[*Pointer]bool {
return w.hoverPointers
}
func (w *Widget) Parent() Widgeter { return w.parent }
func (w *Widget) SetParent(p Widgeter) { w.parent = p }
func (w *Widget) ParentToLocal(ParentPosition mgl64.Vec2) (LocalPosition mgl64.Vec2) {
return ParentPosition.Sub(w.pos)
}
type WidgeterS struct{ Widgeter }
func (w WidgeterS) GlobalToParent(GlobalPosition mgl64.Vec2) (ParentPosition mgl64.Vec2) {
switch w.Parent() {
case nil:
ParentPosition = GlobalPosition
default:
ParentPosition = WidgeterS{w.Parent()}.GlobalToLocal(GlobalPosition)
}
return ParentPosition
}
func (w WidgeterS) GlobalToLocal(GlobalPosition mgl64.Vec2) (LocalPosition mgl64.Vec2) {
return w.ParentToLocal(WidgeterS{w}.GlobalToParent(GlobalPosition))
}
// ---
type CustomWidget struct {
Widget
PollLogicFunc func(this *CustomWidget)
RenderFunc func()
ProcessEventFunc func(inputEvent InputEvent)
CloseFunc func() error
}
func (this *CustomWidget) PollLogic() {
if this.PollLogicFunc != nil {
this.PollLogicFunc(this)
} else {
this.Widget.PollLogic()
}
}
func (this *CustomWidget) Render() {
if this.RenderFunc != nil {
this.RenderFunc()
} else {
this.Widget.Render()
}
}
func (this *CustomWidget) ProcessEvent(inputEvent InputEvent) {
if this.ProcessEventFunc != nil {
this.ProcessEventFunc(inputEvent)
} else {
this.Widget.ProcessEvent(inputEvent)
}
}
func (this *CustomWidget) Close() error {
if this.CloseFunc == nil {
return nil
}
return this.CloseFunc()
}
// ---
type Test1Widget struct {
Widget
}
func NewTest1Widget(pos mgl64.Vec2) *Test1Widget {
return &Test1Widget{Widget: NewWidget(pos, mgl64.Vec2{300, 300})}
}
func (w *Test1Widget) Render() {
DrawNBox(w.pos, w.size)
gl.Color3d(0, 0, 0)
//PrintText(w.pos, goon.Sdump(inputEventQueue))
//x := gist5504644.GetDocPackageAll("gist.github.com/5694308.git")
//PrintText(w.pos, strings.Join(x.Imports, "\n"))
/*files, _ := ioutil.ReadDir("/Users/Dmitri/Dropbox/Work/2013/GoLand/src/")
for lineIndex, file := range files {
if file.IsDir() {
PrintText(w.pos.Add(mathgl.Vec2d{0, float64(16 * lineIndex)}), ">>>> " + file.Name() + "/ (FOLDER)")
} else {
PrintText(w.pos.Add(mathgl.Vec2d{0, float64(16 * lineIndex)}), file.Name())
}
}*/
//PrintText(w.pos, readFileOrEmpty("/Users/Dmitri/Dropbox/Work/2013/GoLand/src/PrintPackageSummary.go"))
//pkg := GetThisGoPackage()
//PrintText(w.pos, pkg.ImportPath+" - "+pkg.Name)
//PrintText(w.pos, string(debug.Stack()))
//PrintText(w.pos, GetThisGoSourceFilepath())
//PrintText(w.pos.Add(mathgl.Vec2d{0, 16}), GetThisGoSourceDir())
//PrintText(w.pos.Add(mathgl.Vec2d{0, 2 * 16}), GetThisGoPackage().ImportPath)
/*x := gist5504644.GetDocPackageAll(gist5504644.BuildPackageFromSrcDir(GetThisGoSourceDir()))
for lineIndex, y := range x.Vars {
PrintText(w.pos.Add(mathgl.Vec2d{0, float64(16 * lineIndex)}), printerutil.SprintAstBare(y.Decl))
}*/
/*kat := widgets[len(widgets)-2].(*KatWidget)
PrintText(w.pos, fmt.Sprintf("%d %s", kat.mode, kat.mode.String()))*/
}
// ---
type Test2Widget struct {
*TextBoxWidget
field *float64
}
func NewTest2Widget(pos mgl64.Vec2, field *float64) *Test2Widget {
return &Test2Widget{TextBoxWidget: NewTextBoxWidgetExternalContent(pos, NewMultilineContentFuncInstant(func() string { return strings.TrimSuffix(goon.Sdump(*field), "\n") }), nil), field: field}
}
func (w *Test2Widget) Hit(ParentPosition mgl64.Vec2) []Widgeter {
if len(w.Widget.Hit(ParentPosition)) > 0 {
return []Widgeter{w}
} else {
return nil
}
}
func (w *Test2Widget) ProcessEvent(inputEvent InputEvent) {
if inputEvent.Pointer.VirtualCategory == event.Pointing && inputEvent.Pointer.State.Button(0) && (inputEvent.EventTypes[event.SliderEvent] && inputEvent.InputId == 0) {
*w.field += inputEvent.Sliders[0]
}
}
// ---
type parsedFile struct {
fset *token.FileSet
fileAst *ast.File
err error
DepNode2
}
func (t *parsedFile) Update() {
started := time.Now()
defer func() { fmt.Println("parsedFile.Update:", time.Since(started).Seconds()*1000, "ms") }()
source := t.GetSources()[0].(caret.MultilineContentI)
fset := token.NewFileSet()
fileAst, err := parser.ParseFile(fset, "", source.Content(), parser.ParseComments|parser.AllErrors)
{
//fileAst.Decls[0].(*ast.GenDecl).Specs = append(fileAst.Decls[0].(*ast.GenDecl).Specs, &ast.ImportSpec{Path: &ast.BasicLit{Kind: token.STRING, Value: `"yay/new/import"`}})
//astutil.AddImport(fset, fileAst, "yay/new/import")
}
t.fset = fset
t.fileAst = fileAst
t.err = err
}
func NewTest3Widget(pos mgl64.Vec2, source *TextBoxWidget) (*LiveGoroutineExpeWidget, *parsedFile) {
parsedFile := &parsedFile{}
parsedFile.AddSources(source.Content)
params := func() interface{} {
return []interface{}{
source.caretPosition.Logical(),
parsedFile.fset,
parsedFile.fileAst,
}
}
action := func(params interface{}) string {
index := params.([]interface{})[0].(uint32)
fset := params.([]interface{})[1].(*token.FileSet)
fileAst := params.([]interface{})[2].(*ast.File)
query := func(i interface{}) bool {
if f, ok := i.(ast.Node); ok && (uint32(f.Pos())-1 <= index && index <= uint32(f.End())-1) {
return true
}
return false
}
found := reflectfind.All(fileAst, query)
if len(found) == 0 {
return ""
}
smallest := uint64(math.MaxUint64)
var smallestV interface{}
for v := range found {
size := uint64(v.(ast.Node).End() - v.(ast.Node).Pos())
if size < smallest {
smallestV = v
smallest = size
}
}
out := fmt.Sprintf("%d-%d, ", smallestV.(ast.Node).Pos()-1, smallestV.(ast.Node).End()-1)
out += fmt.Sprintf("%p, %T\n", smallestV, smallestV)
out += printerutil.SprintAst(fset, smallestV) + "\n\n"
// This is can be huge if ran on root AST node of large Go files, so don't
if _, huge := smallestV.(*ast.File); !huge {
buf := new(bytes.Buffer)
_ = ast.Fprint(buf, fset, smallestV, nil)
out += buf.String()
out += goon.Sdump(smallestV)
}
return out
}
w := NewLiveGoroutineExpeWidget(pos, true, []DepNode2I{parsedFile, source.caretPosition}, params, action)
return w, parsedFile
}
// ---
type typeCheckedPackage struct {
fset *token.FileSet
files []*ast.File
tpkg *types.Package
info *types.Info
DepNode2
}
func (t *typeCheckedPackage) Update() {
started := time.Now()
defer func() { fmt.Println("typeCheckedPackage.Update:", time.Since(started).Seconds()*1000, "ms") }()
goPackageSelecter := t.GetSources()[0].(GoPackageSelecter)
if goPackageSelecter.GetSelectedGoPackage() == nil {
t.fset = nil
t.files = nil
t.tpkg = nil
t.info = nil
return
}
bpkg := goPackageSelecter.GetSelectedGoPackage().Bpkg
fset := token.NewFileSet()
files, err := gist5504644.ParseFiles(fset, bpkg.Dir, append(bpkg.GoFiles, bpkg.CgoFiles...)...)
if err != nil {
t.fset = nil
t.files = nil
t.tpkg = nil
t.info = nil
return
}
t.fset = fset
t.files = files
cfg := &types.Config{Importer: importer.Default()}
info := &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Implicits: make(map[ast.Node]types.Object),
Selections: make(map[*ast.SelectorExpr]*types.Selection),
Scopes: make(map[ast.Node]*types.Scope),
}
tpkg, err := cfg.Check(bpkg.ImportPath, fset, files, info)
if err == nil {
t.tpkg = tpkg
t.info = info
} else {
if strings.Contains(err.Error(), "could not import C") {
// To add support, can use the same strategy as honnef.co/go/importer did
// and fallback to a gcimporter.
log.Println("type checking Cgo packages currently unsupported")
}
t.tpkg = nil
t.info = nil
}
}
// HACK
var Test4WidgetIdent *ast.Ident
func FindFileAst(fset *token.FileSet, file *token.File, fileAsts []*ast.File) *ast.File {
for _, fileAst := range fileAsts {
if fset.File(fileAst.Package) == file {
return fileAst
}
}
return nil
}
func NewTest4Widget(pos mgl64.Vec2, goPackageSelecter GoPackageSelecter, source *TextBoxWidget) (*LiveGoroutineExpeWidget, *typeCheckedPackage) {
typeCheckedPackage := &typeCheckedPackage{}
typeCheckedPackage.AddSources(goPackageSelecter, source.Content)
params := func() interface{} {
fileUri, _ := source.Content.GetUriForProtocol("file://")
return []interface{}{
source.caretPosition.Logical(),
fileUri,
typeCheckedPackage.fset,
typeCheckedPackage.files,
typeCheckedPackage.info,
}
}
action := func(params interface{}) string {
index := params.([]interface{})[0].(uint32)
fileUri := params.([]interface{})[1].(FileUri)
fset := params.([]interface{})[2].(*token.FileSet)
files := params.([]interface{})[3].([]*ast.File)
//tpkg := typeCheckedPackage.tpkg
info := params.([]interface{})[4].(*types.Info)
if fset == nil {
return "fset == nil"
}
// Figure out the file index and token.Pos of caret in that file
var fileAst *ast.File
var caretPos token.Pos
fset.Iterate(func(file *token.File) bool {
if fileUri == FileUri("file://"+file.Name()) {
fileAst = FindFileAst(fset, file, files)
caretPos = file.Pos(int(index))
return false
}
return true
})
if fileAst == nil {
return "fileAst == null, caretPos == token.NoPos"
}
var found2 []ast.Node
ast.Inspect(fileAst, func(n ast.Node) bool {
if n != nil && n.Pos() <= caretPos && caretPos <= n.End() {
found2 = append(found2, n)
return true
}
return false
})
if len(found2) == 0 {
return ""
}
out := ""
smallestV := found2[len(found2)-1]
for _, v := range found2 {
size := v.End() - v.Pos()
out += fmt.Sprintf("%T %d-%d [%d]\n", v, v.Pos()-1, v.End()-1, size)
}
out += "\n"
out += fmt.Sprintf("%d-%d, %p, %T\n\n", smallestV.Pos()-1, smallestV.End()-1, (interface{})(smallestV), smallestV)
out += printerutil.SprintAst(fset, smallestV) + "\n\n"
if ident, ok := smallestV.(*ast.Ident); ok {
Test4WidgetIdent = ident // HACK
if obj := findTypesObject(info, ident); obj != nil {
out += ">>> " + typeChainString(obj.Type())
if constObj, ok := obj.(*types.Const); ok {
out += fmt.Sprintf(" = %v", constObj.Val())
}
out += "\n\n"
} else {
out += "nil obj\n\n"
}
}
// This is can be huge if ran on root AST node of large Go files, so don't
if _, huge := smallestV.(*ast.File); !huge {
buf := new(bytes.Buffer)
_ = ast.Fprint(buf, fset, smallestV, nil)
out += buf.String()
out += goon.Sdump(smallestV)
out += goon.SdumpExpr(fset)
}
return out
}
w := NewLiveGoroutineExpeWidget(pos, true, []DepNode2I{typeCheckedPackage, source.caretPosition}, params, action)
return w, typeCheckedPackage
}
func NewTypeUnderCaretWidget(pos mgl64.Vec2, goPackageSelecter GoPackageSelecter, source *TextBoxWidget, typeCheckedPackage *typeCheckedPackage) *LiveGoroutineExpeWidget {
params := func() interface{} {
fileUri, _ := source.Content.GetUriForProtocol("file://")
return []interface{}{
source.caretPosition.Logical(),
fileUri,
typeCheckedPackage.fset,
typeCheckedPackage.files,
typeCheckedPackage.info,
}
}
action := func(params interface{}) string {
index := params.([]interface{})[0].(uint32)
fileUri := params.([]interface{})[1].(FileUri)
fset := params.([]interface{})[2].(*token.FileSet)
files := params.([]interface{})[3].([]*ast.File)
//tpkg := typeCheckedPackage.tpkg
info := params.([]interface{})[4].(*types.Info)
if fset == nil {
return "fset == nil"
}
// Figure out the file index and token.Pos of caret in that file
var fileAst *ast.File
var caretPos token.Pos
fset.Iterate(func(file *token.File) bool {
if fileUri == FileUri("file://"+file.Name()) {
fileAst = FindFileAst(fset, file, files)
caretPos = file.Pos(int(index))
return false
}
return true
})
if fileAst == nil {
return "fileAst == null, caretPos == token.NoPos"
}
var found2 []ast.Node
ast.Inspect(fileAst, func(n ast.Node) bool {
if n != nil && n.Pos() <= caretPos && caretPos <= n.End() {
found2 = append(found2, n)
return true
}
return false
})
if len(found2) == 0 {
return ""
}
out := ""
smallestV := found2[len(found2)-1]
if ident, ok := smallestV.(*ast.Ident); ok {
Test4WidgetIdent = ident // HACK
if obj := findTypesObject(info, ident); obj != nil {
out += typeChainString(obj.Type())
if constObj, ok := obj.(*types.Const); ok {
out += fmt.Sprintf(" = %v", constObj.Val())
}
} else {
out += "nil Object"
}
}
return out
}
w := NewLiveGoroutineExpeWidget(pos, true, []DepNode2I{typeCheckedPackage, source.caretPosition}, params, action)
return w
}
func findTypesObject(info *types.Info, ident *ast.Ident) (obj types.Object) {
if info != nil {
switch {
case info.Uses[ident] != nil:
obj = info.Uses[ident]
case info.Defs[ident] != nil:
obj = info.Defs[ident]
}
}
return obj
}
// typeChainString returns the full type chain as a string.
func typeChainString(t types.Type) string {
out := fmt.Sprintf("%s", t)
for {
if t == t.Underlying() {
break
} else {
t = t.Underlying()
}
out += fmt.Sprintf(" -> %s", t)
}
return out
}
// ---
type SliceStringerS struct {
entries []fmt.Stringer
DepNode2Manual
}
func NewSliceStringerS(entries ...string) *SliceStringerS {
s := &SliceStringerS{}
for _, entry := range entries {
s.entries = append(s.entries, json.Number(entry))
}
return s
}
func NewSliceStringerAllGoPackages(path string) *SliceStringerS {
f, err := os.Open(path)
if err != nil {
panic(err)
}
defer f.Close()
var importers gddo.Importers
if err := json.NewDecoder(f).Decode(&importers); err != nil {
panic(err)
}
s := &SliceStringerS{}
for _, entry := range importers.Results {
s.entries = append(s.entries, json.Number(entry.Path))
}
return s
}
func (this *SliceStringerS) Get(index uint64) fmt.Stringer {
return this.entries[index]
}
func (this *SliceStringerS) Len() uint64 {
return uint64(len(this.entries))
}
var oracleModes = NewSliceStringerS("callees", "callers", "callgraph", "callstack", "describe", "freevars", "implements", "peers", "referrers")
func NewTest6OracleWidget(pos mgl64.Vec2, goPackageSelecter GoPackageSelecter, source *TextBoxWidget) Widgeter {
mode := NewSelecterWidget(np, oracleModes, nil)
params := func() interface{} {
fileUri, _ := source.Content.GetUriForProtocol("file://")
return []interface{}{
source.caretPosition.Logical(),
fileUri,
goPackageSelecter,
mode.GetSelected().String(),
}
}
action := func(params interface{}) string {
caretPosition := params.([]interface{})[0].(uint32)
fileUri := params.([]interface{})[1].(FileUri)
goPackageSelecter := params.([]interface{})[2].(GoPackageSelecter)
mode := params.([]interface{})[3].(string)
if pkg := goPackageSelecter.GetSelectedGoPackage(); pkg != nil && fileUri != "" && mode != "" {
cmd := exec.Command("oracle", fmt.Sprintf("--pos=%s:#%d", fileUri[len("file://"):], caretPosition), mode, pkg.Bpkg.ImportPath)
out, err := cmd.CombinedOutput()
if err != nil {
return strings.Join(cmd.Args, " ") + "\nError:\n" + err.Error() + "\nOutput:\n" + string(out)
}
return strings.Join(cmd.Args, " ") + "\n" + string(out)
} else {
return "<no file or mode selected>"
}
}
w := NewLiveGoroutineExpeWidget(pos, false, []DepNode2I{source.caretPosition, goPackageSelecter, mode}, params, action)
return NewFlowLayoutWidget(pos, Widgeters{mode, w}, nil)
}
// ---
// NOTE: I'm probably not going to use doc.Package because it duplicates AST stuff from other packages, and doesn't point back to real code...
// Instead, I mimic doc.Package functionality, but stack it on top of types.Package rather than a duplicated ast.Package.
/*type docPackage struct {
dpkg *doc.Package
DepNode2
}
func (this *docPackage) Update() {
goPackage := this.GetSources()[0].(ImportPathFoundSelecter)
importPath := ""
if goPackage.GetSelected() != nil {
importPath = goPackage.GetSelected().ImportPath()
}
// TODO: Factor out bpkg into buildPackage DepNode2
bpkg, err := gist5504644.BuildPackageFromImportPath(importPath)
if err != nil {
this.dpkg = nil
return
}
dpkg, err := gist5504644.GetDocPackageAll(bpkg, nil)
if err != nil {
this.dpkg = nil
return
}
this.dpkg = dpkg
}*/
// ---
type NodeStringer interface {
ast.Node
fmt.Stringer
}
type nodeStringer struct {
ast.Node
str string
}
func NewNodeStringer(node ast.Node) NodeStringer {
return nodeStringer{Node: node, str: printerutil.SprintAstBare(node)}
}
func (this nodeStringer) String() string { return this.str }
type twoNodeStringer struct {
pos, end token.Pos
str string
}
func NewTwoNodeStringer(node0, node1 ast.Node, str string) NodeStringer {
return twoNodeStringer{pos: node0.Pos(), end: node1.End(), str: str}
}
func (this twoNodeStringer) Pos() token.Pos { return this.pos }
func (this twoNodeStringer) End() token.Pos { return this.end }
func (this twoNodeStringer) String() string { return this.str }
// ---
type goSymbols struct {
entries []NodeStringer
DepNode2
}
func (this *goSymbols) Get(index uint64) fmt.Stringer {
return this.entries[index]
}
func (this *goSymbols) Len() uint64 {
return uint64(len(this.entries))
}
/*func (this *goSymbols) Update() {
dpkg := this.GetSources()[0].(*docPackage).dpkg
if dpkg == nil {
this.entries = nil
return
}
this.entries = nil
for _, f := range dpkg.Funcs {
this.entries = append(this.entries, NewNodeStringer(f.Decl))
}
for _, t := range dpkg.Types {
for _, f := range t.Funcs {
this.entries = append(this.entries, NewNodeStringer(f.Decl))
}
for _, m := range t.Methods {
this.entries = append(this.entries, NewNodeStringer(m.Decl))
}
}
}
func NewTest5Widget(pos mathgl.Vec2d, goPackage *GoPackageListingPureWidget, source *TextBoxWidget) *ListWidget {
docPackage := &docPackage{}
docPackage.AddSources(goPackage, source.Content)
goSymbols := &goSymbols{}
goSymbols.AddSources(docPackage)
w := NewListWidget(np, goSymbols)
return w
}*/
type goSymbolsB struct {
goSymbols
}
func (this *goSymbolsB) Update() {
files := this.GetSources()[0].(*typeCheckedPackage).files
if files == nil {
this.entries = nil
return
}
// Mimic doc.Package functionality, but stack it on top of types.Package rather than a duplicated ast.Package
// https://code.google.com/p/go/source/browse/src/pkg/go/doc/reader.go?name=release#456
this.entries = nil
for _, fileAst := range files {
for _, decl := range fileAst.Decls {
switch d := decl.(type) {
case *ast.FuncDecl:
funcDeclSignature := &ast.FuncDecl{Recv: d.Recv, Name: d.Name, Type: d.Type}
nodeStringer := nodeStringer{Node: d, str: printerutil.SprintAstBare(funcDeclSignature)}
this.entries = append(this.entries, nodeStringer)
}
}
}
}
type goSymbolsC struct {
goSymbols
}
func (this *goSymbolsC) Update() {
fileAst := this.GetSources()[0].(*parsedFile).fileAst
if fileAst == nil {
this.entries = nil
return
}
// Mimic doc.Package functionality, but stack it on top of ast.File rather than a duplicated ast.Package
// https://code.google.com/p/go/source/browse/src/pkg/go/doc/reader.go?name=release#456
this.entries = nil
for _, decl := range fileAst.Decls {
switch d := decl.(type) {
case *ast.FuncDecl:
if d.Recv != nil {
name := "(" + printerutil.SprintAstBare(d.Recv.List[0].Type) + ") " + d.Name.String()
this.entries = append(this.entries, NewTwoNodeStringer(d.Recv, d.Name, name))
} else {