-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathex.go
More file actions
1532 lines (1403 loc) · 39 KB
/
ex.go
File metadata and controls
1532 lines (1403 loc) · 39 KB
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 2020 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.
package main
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
"path"
"strconv"
"strings"
"rsc.io/rf/refactor"
)
// exArgs holds the result of parsing an ex command invocation.
type exArgs struct {
snap *refactor.Snapshot
patternPkg *refactor.Package
targets []*refactor.Package
avoids []types.Object
stricts map[types.Object]bool
implicits map[types.Object]bool
code string
codePos token.Pos
rewrites []example
typeAssert bool // command is typeassert not ex
}
type example struct {
old ast.Node
new ast.Node
}
func cmdEx(snap *refactor.Snapshot, text string) error {
ex, err := parseEx(snap, text, false)
if err != nil {
return err
}
if err := ex.check(); err != nil {
return err
}
ex.run()
return nil
}
func cmdTypeAssert(snap *refactor.Snapshot, text string) error {
ex, err := parseEx(snap, text, true)
if err != nil {
return err
}
if err := ex.check(); err != nil {
return err
}
ex.runTypeAssert()
return nil
}
func cutGo(text, sep string) (before, after string, ok bool, err error) {
before, after, ok = cut(text, sep)
return before, after, ok, nil
}
func parseEx(snap *refactor.Snapshot, text string, isTypeAssert bool) (*exArgs, error) {
fset := token.NewFileSet()
text = strings.TrimSpace(text)
if text == "" {
return nil, newErrUsage("missing block")
}
i := strings.Index(text, "{")
if i < 0 || text[len(text)-1] != '}' {
return nil, newErrUsage("malformed block - missing { }")
}
before := strings.TrimSpace(text[:i])
patternPkg := snap.Target()
targets := []*refactor.Package{patternPkg}
if before != "" {
targets = nil
items, _ := snap.EvalList(before)
Items:
for _, item := range items {
if item.Kind == refactor.ItemNotFound {
return nil, newErrPrecondition("%s not found", item.Name)
}
if item.Kind != refactor.ItemDir {
return nil, newErrPrecondition("%s is not a package", item.Name)
}
pkgPath := item.Name
if pkgPath == "." || strings.HasPrefix(pkgPath, "./") || strings.HasPrefix(pkgPath, "../") {
pkgPath = path.Join(snap.Target().PkgPath, pkgPath)
}
for _, p := range snap.Packages() {
if p.PkgPath == pkgPath {
targets = append(targets, p)
continue Items
}
}
return nil, newErrPrecondition("cannot find package %s", pkgPath)
}
}
text = strings.TrimSpace(text[i+1 : len(text)-1])
if text == "" {
return nil, newErrUsage("empty block")
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "package %s\n", patternPkg.Name)
importOK := true
body := func() {
if importOK {
fmt.Fprintf(&buf, "func _() { type any interface{}\n")
for _, pragma := range []string{"avoid", "strict", "implicit"} {
fmt.Fprintf(&buf, "var __%s__ func(...interface{})\n_ = __%s__\n", pragma, pragma)
}
importOK = false
}
}
for text != "" {
stmt, rest, _ := cutAny(text, ";\n") // TODO
text = rest
stmt = strings.TrimSpace(stmt)
if stmt == "" {
continue
}
switch kw := strings.Fields(stmt)[0]; kw {
case "package", "func", "const":
return nil, newErrUsage("%s declaration not allowed", kw)
case "defer", "for", "go", "if", "return", "select", "switch":
return nil, newErrUsage("%s statement not allowed", kw)
case "import":
file, err := parser.ParseFile(fset, "ex.go", "package p;"+stmt, 0)
if err != nil {
return nil, newErrUsage("parsing %s: %v", stmt, err)
}
imp := file.Imports[0]
pkg := importPath(imp)
have := false
for _, p := range snap.Packages() {
if p.Types.Path() == pkg {
have = true
}
}
if !have {
return nil, newErrUsage("import %q not available", pkg)
}
if !importOK {
return nil, newErrUsage("parsing %s: import too late", stmt)
}
fmt.Fprintf(&buf, "%s\n", stmt)
case "type", "var":
if _, err := parser.ParseExpr("func() {" + stmt + "}"); err != nil {
return nil, newErrUsage("parsing %s: %v", stmt, err)
}
body()
fmt.Fprintf(&buf, "%s\n", stmt)
case "avoid", "strict", "implicit":
stmt = strings.TrimSpace(strings.TrimPrefix(stmt, kw))
if stmt == "" {
return nil, newErrUsage("missing arguments for %s", kw)
}
if _, err := parser.ParseExpr("f(" + stmt + ")"); err != nil {
return nil, newErrUsage("parsing %s: %v", stmt, err)
}
body()
fmt.Fprintf(&buf, "__%s__(%s)\n", kw, stmt)
default:
// Must be rewrite x -> y.
// No possible error from cutGo
// because we already processed it once.
before, after, ok, _ := cutGo(stmt, "->")
if !ok {
return nil, newErrUsage("parsing: %s: missing -> in rewrite", stmt)
}
before = strings.TrimSpace(before)
after = strings.TrimSpace(after)
if before == "" {
return nil, newErrUsage("missing pattern in example: %s", stmt)
}
if after == "" {
return nil, newErrUsage("missing substitution in example: %s", stmt)
}
body()
if _, err := parser.ParseExpr("func() {" + before + "}"); err != nil {
before = "type _ " + before
if _, err := parser.ParseExpr("func() { " + before + "}"); err != nil {
return nil, newErrUsage("parsing %s: %v", stmt, err)
}
}
fmt.Fprintf(&buf, "{\n")
fmt.Fprintf(&buf, "{\n%s /* -> %s */\n}\n", before, after)
if after != "!" {
fn, err := parser.ParseExpr("func() {" + after + "}")
if err != nil && !isTypeAssert {
after = "type _ " + after
if _, err := parser.ParseExpr("func() { " + after + "}"); err != nil {
return nil, newErrUsage("parsing %s: %v", stmt, err)
}
}
if isTypeAssert {
foundAssert := false
s := fn.(*ast.FuncLit).Body.List[0]
if s, ok := s.(*ast.ExprStmt); ok {
if ta, ok := s.X.(*ast.TypeAssertExpr); ok {
if _, ok := ta.X.(*ast.Ident); ok {
foundAssert = true
}
}
}
if !foundAssert {
return nil, newErrUsage("parsing %s: arrow must be followed by name.(T)", stmt)
}
}
fmt.Fprintf(&buf, "{\n/* %s -> */ %s\n}\n", before, after)
}
fmt.Fprintf(&buf, "}\n")
}
}
if importOK {
return nil, newErrUsage("no example rewrites")
}
fmt.Fprintf(&buf, "}\n")
ex := &exArgs{
snap: snap,
patternPkg: patternPkg,
targets: targets,
code: buf.String(),
typeAssert: isTypeAssert,
}
return ex, nil
}
func (ex *exArgs) check() error {
snap := ex.snap
codePos := token.Pos(snap.Fset().Base())
var codeLines []string
f, err := parser.ParseFile(snap.Fset(), "ex.go", ex.code, 0)
if err != nil {
return fmt.Errorf("internal error: %v\ncode:\n%s", err, ex.code)
}
var errs refactor.ErrorList
conf := &types.Config{
Error: func(err error) {
if strings.HasSuffix(err.Error(), " is not used") {
return
}
if strings.HasSuffix(err.Error(), " declared but not used") ||
strings.HasSuffix(err.Error(), " declared and not used") {
return
}
if strings.HasSuffix(err.Error(), " (type) is not an expression") {
return
}
if err, ok := err.(types.Error); ok {
if codeLines == nil {
codeLines = strings.Split(ex.code, "\n")
}
posn := snap.Fset().Position(err.Pos)
if posn.Filename == "ex.go" && posn.Line >= 1 && posn.Line < len(codeLines) {
errs.Add(fmt.Errorf("%s\n%s", err.Msg, codeLines[posn.Line-1]))
return
}
}
errs.Add(err)
},
Importer: importerFunc(func(pkg string) (*types.Package, error) {
for _, p := range snap.Packages() {
if p.Types.Path() == pkg {
return p.Types, nil
}
}
return nil, fmt.Errorf("unknown import %q", pkg)
}),
}
check := types.NewChecker(conf, snap.Fset(), ex.patternPkg.Types, ex.patternPkg.TypesInfo)
err = check.Files([]*ast.File{f})
_ = err // already handled in conf.Error
if err := errs.Err(); err != nil {
return newErrPrecondition("errors in example:\n%s", err.Error())
}
var avoids []types.Object
stricts := map[types.Object]bool{}
implicits := map[types.Object]bool{}
body := f.Decls[len(f.Decls)-1].(*ast.FuncDecl).Body.List
info := ex.patternPkg.TypesInfo
var rewrites []example
for _, stmt := range body {
if stmt, ok := stmt.(*ast.ExprStmt); ok {
if pragma, ok := stmt.X.(*ast.CallExpr); ok {
kw := strings.Trim(pragma.Fun.(*ast.Ident).Name, "_")
for _, n := range pragma.Args {
// New thing to avoid.
var obj types.Object
switch n := n.(type) {
default:
return newErrUsage("cannot %s %T", kw, n)
case *ast.Ident:
obj = info.Uses[n]
case *ast.SelectorExpr:
obj = info.Uses[n.Sel]
}
if obj == nil {
return newErrPrecondition("cannot find %s %v", kw, astString(snap.Fset(), n))
}
switch kw {
case "avoid":
avoids = append(avoids, obj)
case "strict":
if obj, ok := obj.(*types.Var); ok && obj.Pos() >= codePos {
stricts[obj] = true
break
}
return newErrPrecondition("%s: %v is not a pattern variable", kw, obj)
case "implicit":
// TODO(mdempsky): Support multi-valued expressions?
if obj, ok := obj.(*types.Var); ok && obj.Pos() >= codePos {
if typ, ok := obj.Type().(*types.Signature); ok && typ.Params().Len() == 1 && !typ.Variadic() {
implicits[obj] = true
break
}
}
return newErrPrecondition("%s: %v is not a single-parameter function-typed variable", kw, obj)
default:
panic("unreachable")
}
}
}
}
stmt, ok := stmt.(*ast.BlockStmt)
if !ok { // var decl
continue
}
var pattern, subst ast.Node
pattern = stmt.List[0].(*ast.BlockStmt).List[0]
switch x := pattern.(type) {
case *ast.ExprStmt:
pattern = x.X
case *ast.DeclStmt:
pattern = x.Decl.(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type
}
if len(stmt.List) >= 2 {
subst = stmt.List[1].(*ast.BlockStmt).List[0]
switch x := subst.(type) {
case *ast.ExprStmt:
subst = x.X
case *ast.DeclStmt:
subst = x.Decl.(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Type
}
}
if ex.typeAssert {
x, ok := pattern.(*ast.BinaryExpr)
if !ok || x.Op != token.EQL {
return newErrUsage("invalid typeassert condition (must be ==): %v", astString(snap.Fset(), pattern))
}
}
rewrites = append(rewrites, example{pattern, subst})
}
ex.avoids = avoids
ex.stricts = stricts
ex.implicits = implicits
ex.codePos = codePos
ex.rewrites = rewrites
return nil
}
func avoidOf(snap *refactor.Snapshot, avoids []types.Object, substInfo *types.Info, subst ast.Node) map[ast.Node]bool {
avoid := make(map[ast.Node]bool)
avoidObj := func(obj types.Object) {
stack := snap.SyntaxAt(obj.Pos())
for i := 0; i < len(stack); i++ {
switch n := stack[i].(type) {
case *ast.FuncDecl, *ast.GenDecl:
avoid[n] = true
}
}
}
for _, obj := range avoids {
avoidObj(obj)
}
if subst != nil {
refactor.Walk(subst, func(stack []ast.Node) {
id, ok := stack[0].(*ast.Ident)
if !ok {
return
}
// Definitions from the universe and built-ins don't have a
// position, but there's also no chance of walking into them so
// there's nothing to avoid.
if obj := substInfo.Uses[id]; obj != nil && obj.Parent() != types.Universe && !isBuiltin(obj) {
avoidObj(obj)
}
})
}
return avoid
}
func isBuiltin(obj types.Object) bool {
_, isBuiltin := obj.(*types.Builtin)
return isBuiltin
}
func (ex *exArgs) run() {
m := &matcher{
snap: ex.snap,
code: ex.code,
codePos: ex.codePos,
fset: ex.snap.Fset(),
wildOK: true, // TODO(rsc): remove
wildPos: ex.codePos,
pkgX: ex.patternPkg.Types,
infoX: ex.patternPkg.TypesInfo,
env: make(map[types.Object]envBind),
envT: make(map[string]types.Type),
stricts: ex.stricts,
}
var avoid map[ast.Node]bool
for _, target := range ex.targets {
m.target = target
m.pkgY = target.Types
m.infoY = target.TypesInfo
for _, file := range target.Files {
if file.Syntax == nil {
continue
}
// Post-order traversal lets us rewrite children before parents,
// which means that the parent rewrite is wrapping the child node,
// its appending edits apply *after* any appending edits in the child.
// For example consider:
// x -> fx()
// y = x -> sety(x)
// The first rewrite appends "()", and the second ")".
// We want to end up with sety(fx()).
// Postorder places the inner rewrites appends before the outer one.
// This is not quite correct in general, but it works well.
refactor.WalkPost(file.Syntax, func(stack []ast.Node) {
// Do not match against the bare selector within a qualified identifier.
if len(stack) >= 2 {
if sel, ok := stack[1].(*ast.SelectorExpr); ok && sel.Sel == stack[0] {
if x, ok := sel.X.(*ast.Ident); ok {
if _, ok := m.infoY.Uses[x].(*types.PkgName); ok {
return
}
}
}
}
if _, ok := stack[0].(*ast.ParenExpr); ok {
// Matcher is blind to parens.
// Let the inside match, and avoid a spurious match here too.
return
}
for _, example := range ex.rewrites {
pattern, subst := example.old, example.new
m.reset()
if call, ok := pattern.(*ast.CallExpr); ok {
if ident, ok := call.Fun.(*ast.Ident); ok {
if lval := ex.patternPkg.TypesInfo.Uses[ident]; ex.implicits[lval] {
typ := assigneeType(stack, target.TypesInfo)
if typ == nil || !m.identical(typ, lval.Type().(*types.Signature).Params().At(0).Type()) {
continue
}
pattern = call.Args[0]
}
}
}
if !m.match(pattern, stack[0]) {
continue
}
// Matched a "!" pattern.
// Return to avoid trying further patterns.
if subst == nil {
return
}
if !contextAppropriate(subst, ex.patternPkg.TypesInfo, stack, target.TypesInfo) {
continue
}
// Do not apply substitution in its own definition.
// TODO(rsc): This cache is wrong: it should build a different avoid map for
// each different subst, not cache the first for all rewrites.
// It's also probably wrong that an avoid applies to rewrites
// above it in the input. Restructing this would probably help
// but we'd run into the post-order traversal bug again too.
// More thought is needed.
if avoid == nil {
avoid = avoidOf(ex.snap, ex.avoids, ex.patternPkg.TypesInfo, subst)
}
for _, n := range stack {
if avoid[n] {
return
}
}
substText, target := m.applySubst(subst, stack)
if lit := m.compositeLitNeedsParen(subst, stack); lit != nil {
substText = "(" + substText
ex.snap.InsertAt(lit.End(), ")")
}
replaceMinimal(ex.snap, target.Pos(), target.End(), substText)
// We're done with this AST node.
// Don't try any further patterns.
return
}
})
}
}
}
func (m *matcher) applySubst(subst ast.Node, matchContext []ast.Node) (string, ast.Node) {
// Substitute pattern variable values from match into substitution text.
// Because these values are coming from the same source location
// as they will eventually be placed into, import references and the
// like are all OK and don't need updating.
matchPos := matchContext[0].Pos()
buf := refactor.NewBufferAt(m.snap, subst.Pos(), []byte(m.code[subst.Pos()-m.codePos:subst.End()-m.codePos]))
refactor.Walk(subst, func(stack []ast.Node) {
id, ok := stack[0].(*ast.Ident)
if !ok {
return
}
// Pattern variable -> captured subexpression.
if xobj, ok := m.wildcardObj(id); ok {
var repl string
switch xobj := xobj.(type) {
case *types.Var:
b := m.env[xobj]
replx := b.matchExpr
var outer ast.Node
if len(stack) >= 2 {
outer = stack[1]
} else if len(matchContext) >= 2 {
outer = matchContext[1]
}
// Apply implicit op except in selector expressions.
op := b.implicitOp
if op != 0 && outer != nil {
if sel, ok := outer.(*ast.SelectorExpr); ok && sel.X == id {
// Selector will apply the implicit op for us.
op = 0
}
if addr, ok := outer.(*ast.UnaryExpr); ok && op == '*' && addr.Op == token.AND {
// Delete the outer &.
buf.Delete(outer.Pos(), outer.Pos()+1)
op = 0
}
if _, ok := outer.(*ast.StarExpr); ok && op == '&' {
// Delete the outer *.
buf.Delete(outer.Pos(), outer.Pos()+1)
op = 0
}
}
if op == '*' {
if addr, ok := replx.(*ast.UnaryExpr); ok && addr.Op == token.AND {
// Delete the inner &.
replx = addr.X
op = 0
}
if px, ok := replx.(*ast.ParenExpr); ok {
if addr, ok := px.X.(*ast.UnaryExpr); ok && addr.Op == token.AND {
// Delete the inner &.
replx = addr.X
op = 0
}
}
}
if op == '&' {
if addr, ok := replx.(*ast.UnaryExpr); ok && addr.Op == token.AND {
// Delete the inner *.
replx = addr.X
op = 0
}
if px, ok := replx.(*ast.ParenExpr); ok {
if addr, ok := px.X.(*ast.UnaryExpr); ok && addr.Op == token.AND {
// Delete the inner *.
replx = addr.X
op = 0
}
}
}
// If substituting an explicit * or & into a selector, drop the * or & when possible.
if sel, ok := outer.(*ast.SelectorExpr); ok && sel.X == id && op == 0 {
if addr, ok := replx.(*ast.UnaryExpr); ok && addr.Op == token.AND && !isPointer(typeOf(m.infoY, addr.X)) {
// Selector will insert implicit & to convert non-pointer to pointer.
replx = addr.X
} else if star, ok := replx.(*ast.StarExpr); ok && !isPointer(typeOf(m.infoY, star)) {
// Selector will insert implicit * to convert pointer to non-pointer.
replx = star.X
}
}
// The captured subexpression does not need import fixes,
// because it is coming from the original source file (where it is staying).
// It can be substituted directly, possibly with parens and implicit * or &.
repl = string(m.snap.Text(replx.Pos(), replx.End()))
if op != 0 {
repl = string(b.implicitOp) + repl
replx = &ast.UnaryExpr{X: replx} // only for precedence for needParen
}
if needParen(replx, stack) || len(stack) == 1 && needParen(replx, matchContext) {
repl = "(" + repl + ")"
}
case *types.TypeName:
typ := m.envT[xobj.Name()]
repl = types.TypeString(typ, func(pkg *types.Package) string {
if pkg == m.target.Types {
return ""
}
// TODO(mdempsky): Handle missing and renamed imports.
return pkg.Name()
})
if needParenType(typ, stack) {
repl = "(" + repl + ")"
}
default:
panic("unreachable")
}
buf.Replace(id.Pos(), id.End(), repl)
return
}
// If this ID is p.ID where p is a package,
// make sure we have the import available,
// or if we are inserting into package p, remove the p.
if len(stack) >= 2 {
if sel, ok := stack[1].(*ast.SelectorExpr); ok && sel.X == stack[0] {
if xid, ok := sel.X.(*ast.Ident); ok {
if pid, ok := m.infoX.Uses[xid].(*types.PkgName); ok {
if pid.Imported() == m.target.Types {
sobj := m.infoX.Uses[sel.Sel]
xobj := m.snap.LookupAt(sel.Sel.Name, matchPos)
if xobj != sobj {
m.snap.ErrorAt(matchPos, "%s is shadowed in replacement - %v", sel.Sel.Name, xobj)
}
buf.Delete(sel.Pos(), sel.Sel.Pos())
} else {
name := m.snap.NeedImport(matchPos, "", pid.Imported())
buf.Replace(sel.Pos(), sel.Sel.Pos(), name+".")
}
}
}
return
}
}
// Is this ID referring to a global in the original package? If so:
// - Is the original package the target package?
// Then make sure the global isn't shadowed.
// - Otherwise, make sure the target has an import, and qualify the identifier.
obj := m.infoX.Uses[id]
if m.pkgX != nil && obj.Parent() == m.pkgX.Scope() {
if m.pkgX == m.target.Types {
if xobj := m.snap.LookupAt(id.Name, matchPos); xobj != obj {
m.snap.ErrorAt(matchPos, "%s is shadowed in replacement - %v", id.Name, xobj)
}
} else {
name := m.snap.NeedImport(matchPos, m.pkgX.Name(), m.pkgX)
buf.Insert(id.Pos(), name+".")
}
}
})
if needParen(subst, matchContext) {
return "(" + buf.String() + ")", matchContext[0]
}
return buf.String(), matchContext[0]
}
func isPointer(t types.Type) bool {
_, ok := t.(*types.Pointer)
return ok
}
// needParen reports whether replacing stack[0] with newX requires parens around newX.
func needParen(newX ast.Node, stack []ast.Node) bool {
if len(stack) == 1 {
return false
}
inner, outer := stack[0], stack[1]
if _, ok := outer.(ast.Expr); !ok {
// Context is not an expression; no chance of an expression breaking apart.
return false
}
var prec int
switch newX := newX.(type) {
default:
panic(fmt.Sprintf("needParen inner %T", newX))
case *ast.SelectorExpr,
*ast.TypeAssertExpr,
*ast.CallExpr,
*ast.IndexExpr,
*ast.SliceExpr,
*ast.ParenExpr,
*ast.Ident,
*ast.BasicLit,
*ast.CompositeLit,
*ast.ArrayType,
*ast.MapType:
return false // nothing can tear these apart
case *ast.ChanType:
if newX.Dir != ast.RECV {
return false
}
case *ast.BinaryExpr:
prec = newX.Op.Precedence()
case *ast.StarExpr, *ast.UnaryExpr:
prec = token.UnaryPrec
}
switch outer := outer.(type) {
default:
panic(fmt.Sprintf("needParen outer %T", outer))
case *ast.BinaryExpr:
return prec < outer.Op.Precedence()
case *ast.StarExpr, *ast.UnaryExpr:
return prec < token.UnaryPrec
case *ast.SelectorExpr:
return prec < token.HighestPrec
case *ast.TypeAssertExpr:
if inner == outer.X {
return prec < token.HighestPrec
}
return false
case *ast.KeyValueExpr, *ast.ParenExpr:
return false // arguments are safe
case *ast.CallExpr:
if inner == outer.Fun {
return prec < token.HighestPrec
}
return false
case *ast.IndexExpr:
if inner == outer.X {
return prec < token.HighestPrec
}
return false // arguments are safe
case *ast.SliceExpr:
if inner == outer.X {
return prec < token.HighestPrec
}
return false // arguments are safe
case *ast.CompositeLit:
return false
case *ast.ArrayType, *ast.MapType:
return false
case *ast.ChanType:
if outer.Dir != ast.SEND|ast.RECV {
return false
}
_, need := newX.(*ast.ChanType)
return need
}
}
func needParenType(newT types.Type, stack []ast.Node) bool {
// Substituting "<-chan T" into "chan _" needs to become "chan
// (<-chan T)", otherwise it will be parsed as "chan<- (chan T)".
if ch1, ok := newT.(*types.Chan); ok && ch1.Dir() == types.RecvOnly {
if ch2, ok := stack[1].(*ast.ChanType); ok && ch2.Dir == ast.SEND|ast.RECV {
return true
}
}
return false
}
// compositeLitNeedsParen reports whether we're substituting an
// identifier into the type of a composite literal expression, which
// appears in an ambiguous context (i.e., between an "if", "for", or
// "switch" keyword and the correspsonding open brace token).
func (m *matcher) compositeLitNeedsParen(subst ast.Node, stack []ast.Node) *ast.CompositeLit {
if _, ok := subst.(*ast.Ident); !ok {
return nil
}
lit, ok := stack[1].(*ast.CompositeLit)
if !ok || lit.Type != stack[0] {
return nil
}
for i := 2; i < len(stack); i++ {
inner := stack[i-1]
switch outer := stack[i].(type) {
case *ast.IfStmt, *ast.ForStmt, *ast.SwitchStmt, *ast.TypeSwitchStmt:
return lit
// enclosed in parentheses
case *ast.ParenExpr:
return nil
case *ast.CallExpr:
for _, arg := range outer.Args {
if arg == inner {
return nil
}
}
case *ast.TypeAssertExpr:
if outer.Type == inner {
return nil
}
// enclosed in square brackets
case *ast.IndexExpr:
if outer.Index == inner {
return nil
}
case *ast.SliceExpr:
if outer.Low == inner || outer.High == inner || outer.Max == inner {
return nil
}
case *ast.ArrayType:
if outer.Len == inner {
return nil
}
case *ast.MapType:
if outer.Key == inner {
return nil
}
// enclosed in curly braces
case *ast.BlockStmt, *ast.StructType, *ast.InterfaceType:
return nil
case *ast.CompositeLit:
for _, elt := range outer.Elts {
if elt == inner {
return nil
}
}
}
}
return nil
}
// importPath returns the unquoted import path of s,
// or "" if the path is not properly quoted.
func importPath(s *ast.ImportSpec) string {
t, err := strconv.Unquote(s.Path.Value)
if err != nil {
return ""
}
return t
}
type importerFunc func(string) (*types.Package, error)
func (f importerFunc) Import(s string) (*types.Package, error) { return f(s) }
func replaceMinimal(snap *refactor.Snapshot, pos, end token.Pos, repl string) {
text := snap.Text(pos, end)
posX := 0
posY := 0
for _, r := range commonRanges(string(text), repl) {
snap.ReplaceAt(pos+token.Pos(posX), pos+token.Pos(r.posX), repl[posY:r.posY])
posX = r.posX + r.n
posY = r.posY + r.n
}
snap.ReplaceAt(pos+token.Pos(posX), end, repl[posY:])
}
type rangePair struct{ posX, posY, n int }
func commonRanges(x, y string) []rangePair {
// t[i,j] = length of longest common substring of x[i:], y[j:]
// t[i,len(y)] = t[len(x),j] = 0
// t[i,j] = max {
// t[i+1,j]
// t[i,j+1]
// t[i+1,j+1] + 1 only if x[i] == y[j]
// }
t := make([][]int, len(x)+1)
data := make([]int, (len(x)+1)*(len(y)+1))
for i := range t {
t[i], data = data[:len(y)+1], data[len(y)+1:]
}
for i := len(x) - 1; i >= 0; i-- {
for j := len(y) - 1; j >= 0; j-- {
m := t[i+1][j]
if m < t[i][j+1] {
m = t[i][j+1]
}
if x[i] == y[j] {
if m < t[i+1][j+1]+1 {
m = t[i+1][j+1] + 1
}
}
t[i][j] = m
}
}
/*
fmt.Println(x)
fmt.Println(y)
for _, row := range t {
fmt.Println(row)
}
*/
i := 0
j := 0
var pairs []rangePair
for i < len(x) && j < len(y) {
switch m := t[i][j]; {
case m == t[i+1][j+1]+1 && x[i] == y[j]:
// Start a new range.
posX := i
posY := j
for i < len(x) && j < len(y) && t[i][j] == t[i+1][j+1]+1 && x[i] == y[j] {
i++
j++
}
pairs = append(pairs, rangePair{posX, posY, i - posX})
case m == t[i+1][j]:
i++
case m == t[i][j+1]:
j++
default:
panic("inconsistent")
}
}
return pairs
}
// assigneeType returns the type of the variable that stack[0] is
// being assigned to. Assignment here includes the assignment implied
// by passing arguments to a function call, return results,
// initializing composite literals, and map indexing.
//
// If the variable at the top of the stack is not being assigned, then
// assigneeType returns nil.
func assigneeType(stack []ast.Node, info *types.Info) types.Type {
if len(stack) < 2 {
return nil
}
val := stack[0]
switch parent := stack[1].(type) {
case *ast.AssignStmt:
if len(parent.Lhs) != len(parent.Rhs) {
break
}
for i, rhs := range parent.Rhs {
if rhs == val {
return info.TypeOf(parent.Lhs[i])
}
}
case *ast.ValueSpec:
if len(parent.Names) != len(parent.Values) {
break
}
for i, rhs := range parent.Values {
if rhs == val {
return info.TypeOf(parent.Names[i])
}
}
case *ast.CallExpr:
if parent.Fun == val {
break
}