1
2
3
4
5 package inline
6
7 import (
8 "bytes"
9 "fmt"
10 "go/ast"
11 "go/constant"
12 "go/format"
13 "go/parser"
14 "go/token"
15 "go/types"
16 "maps"
17 pathpkg "path"
18 "reflect"
19 "slices"
20 "strings"
21
22 "golang.org/x/tools/go/ast/astutil"
23 "golang.org/x/tools/go/types/typeutil"
24 internalastutil "golang.org/x/tools/internal/astutil"
25 "golang.org/x/tools/internal/astutil/free"
26 "golang.org/x/tools/internal/packagepath"
27 "golang.org/x/tools/internal/refactor"
28 "golang.org/x/tools/internal/typeparams"
29 "golang.org/x/tools/internal/typesinternal"
30 "golang.org/x/tools/internal/versions"
31 )
32
33
34
35
36 type Caller struct {
37 Fset *token.FileSet
38 Types *types.Package
39 Info *types.Info
40 File *ast.File
41 Call *ast.CallExpr
42
43
44
45 CountUses func(pkgname *types.PkgName) int
46
47 path []ast.Node
48 enclosingFunc *ast.FuncDecl
49 }
50
51 type logger = func(string, ...any)
52
53
54
55 type Options struct {
56 Logf logger
57 IgnoreEffects bool
58 }
59
60
61 type Result struct {
62 Edits []refactor.Edit
63 Literalized bool
64 BindingDecl bool
65 }
66
67
68
69
70
71 func Inline(caller *Caller, callee *Callee, opts *Options) (*Result, error) {
72 copy := *opts
73 opts = ©
74
75 if opts.Logf == nil {
76 opts.Logf = func(string, ...any) {}
77 }
78
79 st := &state{
80 caller: caller,
81 callee: callee,
82 opts: opts,
83 }
84 return st.inline()
85 }
86
87
88 type state struct {
89 caller *Caller
90 callee *Callee
91 opts *Options
92 }
93
94 func (st *state) inline() (*Result, error) {
95 logf, caller, callee := st.opts.Logf, st.caller, st.callee
96
97 logf("inline %s @ %v",
98 debugFormatNode(caller.Fset, caller.Call),
99 caller.Fset.PositionFor(caller.Call.Lparen, false))
100
101 if ast.IsGenerated(caller.File) {
102 return nil, fmt.Errorf("cannot inline calls from generated files")
103 }
104
105 res, err := st.inlineCall()
106 if err != nil {
107 return nil, err
108 }
109
110
111 assert(res.old != nil, "old is nil")
112 assert(res.new != nil, "new is nil")
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135 if needsParens(caller.path, res.old, res.new) {
136 res.new = &ast.ParenExpr{X: res.new.(ast.Expr)}
137 }
138
139
140
141
142
143
144
145
146
147
148
149
150
151 elideBraces := res.elideBraces
152 if !elideBraces {
153 if newBlock, ok := res.new.(*ast.BlockStmt); ok {
154 i := slices.Index(caller.path, res.old)
155 parent := caller.path[i+1]
156 var body []ast.Stmt
157 switch parent := parent.(type) {
158 case *ast.BlockStmt:
159 body = parent.List
160 case *ast.CommClause:
161 body = parent.Body
162 case *ast.CaseClause:
163 body = parent.Body
164 }
165 if body != nil {
166 callerNames := declares(body)
167
168
169
170 addFieldNames := func(fields *ast.FieldList) {
171 if fields != nil {
172 for _, field := range fields.List {
173 for _, id := range field.Names {
174 callerNames[id.Name] = true
175 }
176 }
177 }
178 }
179 switch f := caller.path[i+2].(type) {
180 case *ast.FuncDecl:
181 addFieldNames(f.Recv)
182 addFieldNames(f.Type.Params)
183 addFieldNames(f.Type.Results)
184 case *ast.FuncLit:
185 addFieldNames(f.Type.Params)
186 addFieldNames(f.Type.Results)
187 }
188
189 if len(callerLabels(caller.path)) > 0 {
190
191
192 logf("keeping block braces: caller uses control labels")
193 } else if intersects(declares(newBlock.List), callerNames) {
194 logf("keeping block braces: avoids name conflict")
195 } else {
196 elideBraces = true
197 }
198 }
199 }
200 }
201
202 var edits []refactor.Edit
203
204
205 {
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221 var out bytes.Buffer
222 if elideBraces {
223 for i, stmt := range res.new.(*ast.BlockStmt).List {
224 if i > 0 {
225 out.WriteByte('\n')
226 }
227 if err := format.Node(&out, caller.Fset, stmt); err != nil {
228 return nil, err
229 }
230 }
231 } else {
232 if err := format.Node(&out, caller.Fset, res.new); err != nil {
233 return nil, err
234 }
235 }
236
237 edits = append(edits, refactor.Edit{
238 Pos: res.old.Pos(),
239 End: res.old.End(),
240 NewText: out.Bytes(),
241 })
242 }
243
244
245
246
247
248
249
250 for _, imp := range res.newImports {
251
252 if !packagepath.CanImport(caller.Types.Path(), imp.path) {
253 return nil, fmt.Errorf("can't inline function %v as its body refers to inaccessible package %q", callee, imp.path)
254 }
255
256
257
258 name := ""
259 if imp.explicit {
260 name = imp.name
261 }
262 edits = append(edits, refactor.AddImportEdits(caller.File, name, imp.path)...)
263 }
264
265 literalized := false
266 if call, ok := res.new.(*ast.CallExpr); ok && is[*ast.FuncLit](call.Fun) {
267 literalized = true
268 }
269
270
271
272
273
274
275
276
277
278
279
280
281 for _, oldImport := range res.oldImports {
282 spec := oldImport.spec
283
284
285 pos := spec.Pos()
286 if doc := spec.Doc; doc != nil {
287 pos = doc.Pos()
288 }
289 end := spec.End()
290 if doc := spec.Comment; doc != nil {
291 end = doc.End()
292 }
293
294
295
296 for _, decl := range caller.File.Decls {
297 decl, ok := decl.(*ast.GenDecl)
298 if !(ok && decl.Tok == token.IMPORT) {
299 break
300 }
301 if internalastutil.NodeContainsPos(decl, spec.Pos()) && !decl.Rparen.IsValid() {
302
303 pos = decl.Pos()
304 if doc := decl.Doc; doc != nil {
305 pos = doc.Pos()
306 }
307 end = decl.End()
308 break
309 }
310 }
311
312 edits = append(edits, refactor.Edit{
313 Pos: pos,
314 End: end,
315 })
316 }
317
318 return &Result{
319 Edits: edits,
320 Literalized: literalized,
321 BindingDecl: res.bindingDecl,
322 }, nil
323 }
324
325
326 type oldImport struct {
327 pkgName *types.PkgName
328 spec *ast.ImportSpec
329 }
330
331
332 type newImport struct {
333 name string
334 path string
335 explicit bool
336 }
337
338
339 type importState struct {
340 logf func(string, ...any)
341 caller *Caller
342 importMap map[string][]string
343 newImports []newImport
344 oldImports []oldImport
345 }
346
347
348 func newImportState(logf func(string, ...any), caller *Caller, callee *gobCallee) *importState {
349
350
351
352 ist := &importState{
353 logf: logf,
354 caller: caller,
355 importMap: make(map[string][]string),
356 }
357
358
359
360 countUses := caller.CountUses
361 if countUses == nil {
362 uses := make(map[*types.PkgName]int)
363 for _, obj := range caller.Info.Uses {
364 if pkgname, ok := obj.(*types.PkgName); ok {
365 uses[pkgname]++
366 }
367 }
368 countUses = func(pkgname *types.PkgName) int {
369 return uses[pkgname]
370 }
371 }
372
373 for _, imp := range caller.File.Imports {
374 if pkgName, ok := importedPkgName(caller.Info, imp); ok &&
375 pkgName.Name() != "." &&
376 pkgName.Name() != "_" {
377
378
379
380
381
382
383
384
385
386
387
388
389 needed := true
390 if sel, ok := ast.Unparen(caller.Call.Fun).(*ast.SelectorExpr); ok &&
391 is[*ast.Ident](sel.X) &&
392 caller.Info.Uses[sel.X.(*ast.Ident)] == pkgName &&
393 countUses(pkgName) == 1 {
394 needed = false
395
396 for _, obj := range callee.FreeObjs {
397 if obj.PkgPath == pkgName.Imported().Path() && obj.Shadow[pkgName.Name()] == 0 {
398 needed = true
399 break
400 }
401 }
402 }
403
404
405
406 if needed {
407 path := pkgName.Imported().Path()
408 ist.importMap[path] = append(ist.importMap[path], pkgName.Name())
409 } else {
410 ist.oldImports = append(ist.oldImports, oldImport{pkgName: pkgName, spec: imp})
411 }
412 }
413 }
414 return ist
415 }
416
417
418
419
420
421 func (i *importState) importName(pkgPath string, shadow shadowMap) string {
422 for _, name := range i.importMap[pkgPath] {
423
424
425
426 if shadow[name] == 0 {
427 found := i.caller.lookup(name)
428 if is[*types.PkgName](found) || found == nil {
429 return name
430 }
431 }
432 }
433 return ""
434 }
435
436
437
438
439 func (i *importState) findNewLocalName(pkgName, calleePkgName string, shadow shadowMap) string {
440 newlyAdded := func(name string) bool {
441 return slices.ContainsFunc(i.newImports, func(n newImport) bool { return n.name == name })
442 }
443
444
445
446 shadowedInCaller := func(name string) bool {
447 obj := i.caller.lookup(name)
448 if obj == nil {
449 return false
450 }
451
452 return !slices.ContainsFunc(i.oldImports, func(o oldImport) bool { return o.pkgName == obj })
453 }
454
455
456
457
458
459
460
461
462
463 if shadow[calleePkgName] == 0 && !shadowedInCaller(calleePkgName) && !newlyAdded(calleePkgName) && calleePkgName != "init" {
464 return calleePkgName
465 }
466
467 base := pkgName
468 name := base
469 for n := 0; shadow[name] != 0 || shadowedInCaller(name) || newlyAdded(name) || name == "init"; n++ {
470 name = fmt.Sprintf("%s%d", base, n)
471 }
472
473 return name
474 }
475
476
477
478 func (i *importState) localName(pkgPath, pkgName, calleePkgName string, shadow shadowMap) string {
479
480 if name := i.importName(pkgPath, shadow); name != "" {
481 return name
482 }
483
484 name := i.findNewLocalName(pkgName, calleePkgName, shadow)
485 i.logf("adding import %s %q", name, pkgPath)
486
487
488 i.newImports = append(i.newImports, newImport{
489 name: name,
490 path: pkgPath,
491 explicit: name != pkgName || name != pathpkg.Base(pkgPath),
492 })
493 i.importMap[pkgPath] = append(i.importMap[pkgPath], name)
494 return name
495 }
496
497 type inlineCallResult struct {
498 newImports []newImport
499 oldImports []oldImport
500
501
502
503
504
505
506
507
508
509
510
511
512 elideBraces bool
513 bindingDecl bool
514 old, new ast.Node
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 func (st *state) inlineCall() (*inlineCallResult, error) {
559 logf, caller, callee := st.opts.Logf, st.caller, &st.callee.impl
560
561 checkInfoFields(caller.Info)
562
563
564
565 calleeSymbol := typeutil.StaticCallee(caller.Info, caller.Call)
566 if calleeSymbol == nil {
567
568 return nil, fmt.Errorf("cannot inline: not a static function call")
569 }
570
571
572
573 samePkg := caller.Types.Path() == callee.PkgPath
574 if !samePkg && len(callee.Unexported) > 0 {
575 return nil, fmt.Errorf("cannot inline call to %s because body refers to non-exported %s",
576 callee.Name, callee.Unexported[0])
577 }
578
579
580
581
582 callerGoVersion := caller.Info.FileVersions[caller.File]
583 if callerGoVersion != "" && callee.GoVersion != "" && versions.Before(callerGoVersion, callee.GoVersion) {
584 return nil, fmt.Errorf("cannot inline call to %s (declared using %s) into a file using %s",
585 callee.Name, callee.GoVersion, callerGoVersion)
586 }
587
588
589
590
591
592 caller.path, _ = astutil.PathEnclosingInterval(caller.File, caller.Call.Pos(), caller.Call.End())
593 for _, n := range caller.path {
594 if decl, ok := n.(*ast.FuncDecl); ok {
595 caller.enclosingFunc = decl
596 break
597 }
598 }
599
600
601
602
603 var assign1 func(v *types.Var) bool
604 {
605 updatedLocals := make(map[*types.Var]bool)
606 if caller.enclosingFunc != nil {
607 escape(caller.Info, caller.enclosingFunc, func(v *types.Var, _ bool) {
608 updatedLocals[v] = true
609 })
610 logf("multiple-assignment vars: %v", updatedLocals)
611 }
612 assign1 = func(v *types.Var) bool { return !updatedLocals[v] }
613 }
614
615
616 istate := newImportState(logf, caller, callee)
617
618
619 objRenames, err := st.renameFreeObjs(istate)
620 if err != nil {
621 return nil, err
622 }
623
624 res := &inlineCallResult{
625 newImports: istate.newImports,
626 oldImports: istate.oldImports,
627 }
628
629
630 calleeFset, calleeDecl, err := parseCompact(callee.Content)
631 if err != nil {
632 return nil, err
633 }
634
635
636
637 replaceCalleeID := func(offset int, repl ast.Expr, unpackVariadic bool) {
638 path, id := findIdent(calleeDecl, calleeDecl.Pos()+token.Pos(offset))
639 logf("- replace id %q @ #%d to %q", id.Name, offset, debugFormatNode(calleeFset, repl))
640
641 if lit, ok := repl.(*ast.CompositeLit); ok && unpackVariadic && len(path) > 0 {
642 if call, ok := last(path).(*ast.CallExpr); ok &&
643 call.Ellipsis.IsValid() &&
644 id == last(call.Args) {
645
646 call.Args = append(call.Args[:len(call.Args)-1], lit.Elts...)
647 call.Ellipsis = token.NoPos
648 return
649 }
650 }
651 replaceNode(calleeDecl, id, repl)
652 }
653
654
655
656 for _, ref := range callee.FreeRefs {
657 if repl := objRenames[ref.Object]; repl != nil {
658 replaceCalleeID(ref.Offset, repl, false)
659 }
660 }
661
662
663
664 args, err := st.arguments(caller, calleeDecl, assign1)
665 if err != nil {
666 return nil, err
667 }
668
669
670
671 var params []*parameter
672 {
673 sig := calleeSymbol.Type().(*types.Signature)
674 if sig.Recv() != nil {
675 params = append(params, ¶meter{
676 obj: sig.Recv(),
677 fieldType: calleeDecl.Recv.List[0].Type,
678 info: callee.Params[0],
679 })
680 }
681
682
683 var types []ast.Expr
684 for _, field := range calleeDecl.Type.Params.List {
685 if field.Names == nil {
686 types = append(types, field.Type)
687 } else {
688 for range field.Names {
689 types = append(types, field.Type)
690 }
691 }
692 }
693
694 for i := 0; i < sig.Params().Len(); i++ {
695 params = append(params, ¶meter{
696 obj: sig.Params().At(i),
697 fieldType: types[i],
698 info: callee.Params[len(params)],
699 })
700 }
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715 if sig.Variadic() {
716 lastParam := last(params)
717 if len(args) > 0 && last(args).spread {
718
719 lastParam.variadic = true
720 } else {
721
722
723
724 lastParamField := last(calleeDecl.Type.Params.List)
725 lastParamField.Type = &ast.ArrayType{
726 Elt: lastParamField.Type.(*ast.Ellipsis).Elt,
727 }
728
729 if caller.Call.Ellipsis.IsValid() {
730
731
732 } else {
733
734
735
736
737
738 n := len(params) - 1
739 ordinary, extra := args[:n], args[n:]
740 var elts []ast.Expr
741 freevars := make(map[string]bool)
742 pure, effects := true, false
743 for _, arg := range extra {
744 elts = append(elts, arg.expr)
745 pure = pure && arg.pure
746 effects = effects || arg.effects
747 maps.Copy(freevars, arg.freevars)
748 }
749 args = append(ordinary, &argument{
750 expr: &ast.CompositeLit{
751 Type: lastParamField.Type,
752 Elts: elts,
753 },
754 typ: lastParam.obj.Type(),
755 constant: nil,
756 pure: pure,
757 effects: effects,
758 duplicable: false,
759 freevars: freevars,
760 variadic: true,
761 })
762 }
763 }
764 }
765 }
766
767 typeArgs := st.typeArguments(caller.Call)
768 if len(typeArgs) != len(callee.TypeParams) {
769 return nil, fmt.Errorf("cannot inline: type parameter inference is not yet supported")
770 }
771 if err := substituteTypeParams(logf, callee.TypeParams, typeArgs, params, replaceCalleeID); err != nil {
772 return nil, err
773 }
774
775
776 for i, arg := range args {
777 logf("arg #%d: %s pure=%t effects=%t duplicable=%t free=%v type=%v",
778 i, debugFormatNode(caller.Fset, arg.expr),
779 arg.pure, arg.effects, arg.duplicable, arg.freevars, arg.typ)
780 }
781
782
783
784
785
786
787 substitute(logf, caller, params, args, callee.Effects, callee.Falcon, replaceCalleeID)
788
789
790 updateCalleeParams(calleeDecl, params)
791
792
793 bindingDecl := createBindingDecl(logf, caller, args, calleeDecl, callee.Results)
794
795 var remainingArgs []ast.Expr
796 for _, arg := range args {
797 if arg != nil {
798 remainingArgs = append(remainingArgs, arg.expr)
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 if len(calleeDecl.Body.List) == 0 {
827 logf("strategy: reduce call to empty body")
828
829
830
831
832
833 if stmt := callStmt(caller.path, false); stmt != nil {
834 res.old = stmt
835 if nargs := len(remainingArgs); nargs > 0 {
836
837
838
839
840
841
842
843
844
845 if last := last(args); last != nil && last.spread {
846 nspread := last.typ.(*types.Tuple).Len()
847 if len(args) > 1 {
848
849 res.new = &ast.GenDecl{
850 Tok: token.VAR,
851 Specs: []ast.Spec{
852 &ast.ValueSpec{
853 Names: []*ast.Ident{makeIdent("_")},
854 Values: []ast.Expr{args[0].expr},
855 },
856 &ast.ValueSpec{
857 Names: blanks[*ast.Ident](nspread),
858 Values: []ast.Expr{args[1].expr},
859 },
860 },
861 }
862 return res, nil
863 }
864
865
866 nargs = nspread
867 }
868
869 res.new = &ast.AssignStmt{
870 Lhs: blanks[ast.Expr](nargs),
871 Tok: token.ASSIGN,
872 Rhs: remainingArgs,
873 }
874
875 } else {
876
877 res.new = &ast.EmptyStmt{}
878 }
879 return res, nil
880 }
881 }
882
883
884
885
886 allResultsUnreferenced := forall(callee.Results, func(i int, r *paramInfo) bool { return len(r.Refs) == 0 })
887 needBindingDecl := !allResultsUnreferenced ||
888 exists(params, func(i int, p *parameter) bool { return p != nil })
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 if len(calleeDecl.Body.List) == 1 &&
915 is[*ast.ReturnStmt](calleeDecl.Body.List[0]) &&
916 len(calleeDecl.Body.List[0].(*ast.ReturnStmt).Results) > 0 {
917 results := calleeDecl.Body.List[0].(*ast.ReturnStmt).Results
918
919 parent, grandparent := callContext(caller.path)
920
921
922 if stmt, ok := parent.(*ast.ExprStmt); ok &&
923 (!needBindingDecl || bindingDecl != nil) {
924 logf("strategy: reduce stmt-context call to { return exprs }")
925 clearPositions(calleeDecl.Body)
926
927 if callee.ValidForCallStmt {
928 logf("callee body is valid as statement")
929
930 if !needBindingDecl {
931
932 res.old = caller.Call
933 res.new = results[0]
934 } else {
935
936 res.bindingDecl = true
937 res.old = stmt
938 res.new = &ast.BlockStmt{
939 List: []ast.Stmt{
940 bindingDecl.stmt,
941 &ast.ExprStmt{X: results[0]},
942 },
943 }
944 }
945 } else {
946 logf("callee body is not valid as statement")
947
948
949
950
951 discard := &ast.AssignStmt{
952 Lhs: blanks[ast.Expr](callee.NumResults),
953 Tok: token.ASSIGN,
954 Rhs: results,
955 }
956 res.old = stmt
957 if !needBindingDecl {
958
959 res.new = discard
960 } else {
961
962 res.bindingDecl = true
963 res.new = &ast.BlockStmt{
964 List: []ast.Stmt{
965 bindingDecl.stmt,
966 discard,
967 },
968 }
969 }
970 }
971 return res, nil
972 }
973
974
975
976
977
978 if stmt, ok := parent.(*ast.AssignStmt); ok &&
979 is[*ast.BlockStmt](grandparent) &&
980 (!needBindingDecl || (bindingDecl != nil && len(bindingDecl.names) == 0)) {
981
982
983 if newStmts, ok := st.assignStmts(stmt, results, istate.importName); ok {
984 logf("strategy: reduce assign-context call to { return exprs }")
985
986 clearPositions(calleeDecl.Body)
987
988 block := &ast.BlockStmt{
989 List: newStmts,
990 }
991 if needBindingDecl {
992 res.bindingDecl = true
993 block.List = prepend(bindingDecl.stmt, block.List...)
994 }
995
996
997
998
999 res.elideBraces = true
1000 res.old = stmt
1001 res.new = block
1002 return res, nil
1003 }
1004 }
1005
1006
1007 if !needBindingDecl {
1008 clearPositions(calleeDecl.Body)
1009
1010 anyNonTrivialReturns := hasNonTrivialReturn(callee.Returns)
1011
1012 if callee.NumResults == 1 {
1013 logf("strategy: reduce expr-context call to { return expr }")
1014
1015
1016
1017 if anyNonTrivialReturns {
1018 results[0] = convert(calleeDecl.Type.Results.List[0].Type, results[0])
1019 }
1020
1021 res.old = caller.Call
1022 res.new = results[0]
1023 return res, nil
1024
1025 } else if !anyNonTrivialReturns {
1026 logf("strategy: reduce spread-context call to { return expr }")
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043 res.old = parent
1044 switch context := parent.(type) {
1045 case *ast.AssignStmt:
1046
1047 assign := shallowCopy(context)
1048 assign.Rhs = results
1049 res.new = assign
1050 case *ast.ValueSpec:
1051
1052 spec := shallowCopy(context)
1053 spec.Values = results
1054 res.new = spec
1055 case *ast.CallExpr:
1056
1057 call := shallowCopy(context)
1058 call.Args = results
1059 res.new = call
1060 case *ast.ReturnStmt:
1061
1062 ret := shallowCopy(context)
1063 ret.Results = results
1064 res.new = ret
1065 default:
1066 return nil, fmt.Errorf("internal error: unexpected context %T for spread call", context)
1067 }
1068 return res, nil
1069 }
1070 }
1071 }
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097 parent, _ := callContext(caller.path)
1098 if ret, ok := parent.(*ast.ReturnStmt); ok &&
1099 len(ret.Results) == 1 &&
1100 tailCallSafeReturn(caller, calleeSymbol, callee) &&
1101 !callee.HasBareReturn &&
1102 (!needBindingDecl || bindingDecl != nil) &&
1103 !hasLabelConflict(caller.path, callee.Labels) &&
1104 allResultsUnreferenced {
1105 logf("strategy: reduce tail-call")
1106 body := calleeDecl.Body
1107 clearPositions(body)
1108 if needBindingDecl {
1109 res.bindingDecl = true
1110 body.List = prepend(bindingDecl.stmt, body.List...)
1111 }
1112 res.old = ret
1113 res.new = body
1114 return res, nil
1115 }
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133 if stmt := callStmt(caller.path, true); stmt != nil &&
1134 (!needBindingDecl || bindingDecl != nil) &&
1135 !callee.HasDefer &&
1136 !hasLabelConflict(caller.path, callee.Labels) &&
1137 len(callee.Returns) == 0 {
1138 logf("strategy: reduce stmt-context call to { stmts }")
1139 body := calleeDecl.Body
1140 var repl ast.Stmt = body
1141 clearPositions(repl)
1142 if needBindingDecl {
1143 body.List = prepend(bindingDecl.stmt, body.List...)
1144 }
1145 res.old = stmt
1146 res.new = repl
1147 return res, nil
1148 }
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175 if len(args) == 2 && args[0] != nil && args[1] != nil && is[*types.Tuple](args[1].typ) {
1176 return nil, fmt.Errorf("can't yet inline spread call to method")
1177 }
1178
1179
1180
1181
1182
1183 logf("strategy: literalization")
1184 funcLit := &ast.FuncLit{
1185 Type: calleeDecl.Type,
1186 Body: calleeDecl.Body,
1187 }
1188
1189
1190
1191 clearPositions(funcLit)
1192
1193
1194
1195
1196
1197
1198
1199
1200 if bindingDecl != nil && allResultsUnreferenced {
1201 funcLit.Type.Params.List = nil
1202 remainingArgs = nil
1203 res.bindingDecl = true
1204 funcLit.Body.List = prepend(bindingDecl.stmt, funcLit.Body.List...)
1205 }
1206
1207
1208
1209 newCall := &ast.CallExpr{
1210 Fun: funcLit,
1211 Ellipsis: token.NoPos,
1212 Args: remainingArgs,
1213 }
1214 res.old = caller.Call
1215 res.new = newCall
1216 return res, nil
1217 }
1218
1219
1220
1221
1222 func (st *state) renameFreeObjs(istate *importState) ([]ast.Expr, error) {
1223 caller, callee := st.caller, &st.callee.impl
1224 objRenames := make([]ast.Expr, len(callee.FreeObjs))
1225 for i, obj := range callee.FreeObjs {
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246 var newName ast.Expr
1247 if obj.Kind == "pkgname" {
1248
1249 n := istate.localName(obj.PkgPath, obj.PkgName, obj.Name, obj.Shadow)
1250 newName = makeIdent(n)
1251 } else if !obj.ValidPos {
1252
1253
1254 found := caller.lookup(obj.Name)
1255 if found.Pos().IsValid() {
1256 return nil, fmt.Errorf("cannot inline, because the callee refers to built-in %q, which in the caller is shadowed by a %s (declared at line %d)",
1257 obj.Name, objectKind(found),
1258 caller.Fset.PositionFor(found.Pos(), false).Line)
1259 }
1260
1261 } else {
1262
1263
1264 qualify := false
1265 if obj.PkgPath == callee.PkgPath {
1266
1267 if caller.Types.Path() == callee.PkgPath {
1268
1269
1270
1271
1272
1273
1274 found := caller.lookup(obj.Name)
1275 if found != nil && !isPkgLevel(found) {
1276 return nil, fmt.Errorf("cannot inline, because the callee refers to %s %q, which in the caller is shadowed by a %s (declared at line %d)",
1277 obj.Kind, obj.Name,
1278 objectKind(found),
1279 caller.Fset.PositionFor(found.Pos(), false).Line)
1280 }
1281 } else {
1282
1283 qualify = true
1284 }
1285 } else {
1286
1287
1288
1289 qualify = true
1290 }
1291
1292
1293 if qualify {
1294 pkgName := istate.localName(obj.PkgPath, obj.PkgName, obj.PkgName, obj.Shadow)
1295 newName = &ast.SelectorExpr{
1296 X: makeIdent(pkgName),
1297 Sel: makeIdent(obj.Name),
1298 }
1299 }
1300 }
1301 objRenames[i] = newName
1302 }
1303 return objRenames, nil
1304 }
1305
1306 type argument struct {
1307 expr ast.Expr
1308 typ types.Type
1309 constant constant.Value
1310 spread bool
1311 pure bool
1312 effects bool
1313 duplicable bool
1314 freevars map[string]bool
1315 variadic bool
1316 desugaredRecv bool
1317 }
1318
1319
1320
1321
1322 func (st *state) typeArguments(call *ast.CallExpr) []*argument {
1323 var exprs []ast.Expr
1324 switch d := ast.Unparen(call.Fun).(type) {
1325 case *ast.IndexExpr:
1326 exprs = []ast.Expr{d.Index}
1327 case *ast.IndexListExpr:
1328 exprs = d.Indices
1329 default:
1330
1331 return nil
1332 }
1333 var args []*argument
1334 for _, e := range exprs {
1335 arg := &argument{expr: e, freevars: freeVars(st.caller.Info, e)}
1336
1337
1338
1339
1340
1341
1342 if _, ok := arg.expr.(*ast.Ident); !ok {
1343 arg.expr = &ast.ParenExpr{X: arg.expr}
1344 }
1345 args = append(args, arg)
1346 }
1347 return args
1348 }
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380 func (st *state) arguments(caller *Caller, calleeDecl *ast.FuncDecl, assign1 func(*types.Var) bool) ([]*argument, error) {
1381 var args []*argument
1382
1383 callArgs := caller.Call.Args
1384 if calleeDecl.Recv != nil {
1385 if len(st.callee.impl.TypeParams) > 0 {
1386 return nil, fmt.Errorf("cannot inline: generic methods not yet supported")
1387 }
1388 sel := ast.Unparen(caller.Call.Fun).(*ast.SelectorExpr)
1389 seln := caller.Info.Selections[sel]
1390 var recvArg ast.Expr
1391 switch seln.Kind() {
1392 case types.MethodVal:
1393 recvArg = sel.X
1394 case types.MethodExpr:
1395 recvArg = callArgs[0]
1396 callArgs = callArgs[1:]
1397 }
1398 if recvArg != nil {
1399
1400
1401
1402 arg := &argument{
1403 expr: recvArg,
1404 typ: caller.Info.TypeOf(recvArg),
1405 constant: caller.Info.Types[recvArg].Value,
1406 pure: pure(caller.Info, assign1, recvArg),
1407 effects: st.effects(caller.Info, recvArg),
1408 duplicable: duplicable(caller.Info, recvArg),
1409 freevars: freeVars(caller.Info, recvArg),
1410 }
1411 recvArg = nil
1412
1413
1414 args = append(args, arg)
1415
1416
1417
1418 indices := seln.Index()
1419 for _, index := range indices[:len(indices)-1] {
1420 fld := typeparams.CoreType(typeparams.Deref(arg.typ)).(*types.Struct).Field(index)
1421 if fld.Pkg() != caller.Types && !fld.Exported() {
1422 return nil, fmt.Errorf("in %s, implicit reference to unexported field .%s cannot be made explicit",
1423 debugFormatNode(caller.Fset, caller.Call.Fun),
1424 fld.Name())
1425 }
1426 if isPointer(arg.typ) {
1427 arg.pure = false
1428 }
1429 arg.expr = &ast.SelectorExpr{
1430 X: arg.expr,
1431 Sel: makeIdent(fld.Name()),
1432 }
1433 arg.typ = fld.Type()
1434 arg.duplicable = false
1435 }
1436
1437
1438 argIsPtr := isPointer(arg.typ)
1439 paramIsPtr := isPointer(seln.Obj().Type().Underlying().(*types.Signature).Recv().Type())
1440 if !argIsPtr && paramIsPtr {
1441
1442 arg.expr = &ast.UnaryExpr{Op: token.AND, X: arg.expr}
1443 arg.typ = types.NewPointer(arg.typ)
1444 arg.desugaredRecv = true
1445 } else if argIsPtr && !paramIsPtr {
1446
1447 arg.expr = &ast.StarExpr{X: arg.expr}
1448 arg.typ = typeparams.Deref(arg.typ)
1449 arg.duplicable = false
1450 arg.pure = false
1451 arg.desugaredRecv = true
1452 }
1453 }
1454 }
1455 for _, expr := range callArgs {
1456 tv := caller.Info.Types[expr]
1457 args = append(args, &argument{
1458 expr: expr,
1459 typ: tv.Type,
1460 constant: tv.Value,
1461 spread: is[*types.Tuple](tv.Type),
1462 pure: pure(caller.Info, assign1, expr),
1463 effects: st.effects(caller.Info, expr),
1464 duplicable: duplicable(caller.Info, expr),
1465 freevars: freeVars(caller.Info, expr),
1466 })
1467 }
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487 for _, arg := range args {
1488 if arg.constant == nil {
1489 continue
1490 }
1491 info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}
1492 if err := types.CheckExpr(caller.Fset, caller.Types, caller.Call.Pos(), arg.expr, info); err != nil {
1493 return nil, err
1494 }
1495 arg.typ = info.TypeOf(arg.expr)
1496 }
1497
1498 return args, nil
1499 }
1500
1501 type parameter struct {
1502 obj *types.Var
1503 fieldType ast.Expr
1504 info *paramInfo
1505 variadic bool
1506 }
1507
1508
1509
1510
1511
1512 type replacer = func(offset int, repl ast.Expr, unpackVariadic bool)
1513
1514
1515
1516 func substituteTypeParams(logf logger, typeParams []*paramInfo, typeArgs []*argument, params []*parameter, replace replacer) error {
1517 assert(len(typeParams) == len(typeArgs), "mismatched number of type params/args")
1518 for i, paramInfo := range typeParams {
1519 arg := typeArgs[i]
1520
1521 for free := range arg.freevars {
1522 if paramInfo.Shadow[free] != 0 {
1523 return fmt.Errorf("cannot inline: type argument #%d (type parameter %s) is shadowed", i, paramInfo.Name)
1524 }
1525 }
1526 logf("replacing type param %s with %s", paramInfo.Name, debugFormatNode(token.NewFileSet(), arg.expr))
1527 for _, ref := range paramInfo.Refs {
1528 replace(ref.Offset, internalastutil.CloneNode(arg.expr), false)
1529 }
1530
1531
1532
1533 for _, p := range params {
1534 if id, ok := p.fieldType.(*ast.Ident); ok && id.Name == paramInfo.Name {
1535 p.fieldType = arg.expr
1536 } else {
1537 for _, id := range identsNamed(p.fieldType, paramInfo.Name) {
1538 replaceNode(p.fieldType, id, arg.expr)
1539 }
1540 }
1541 }
1542 }
1543 return nil
1544 }
1545
1546 func identsNamed(n ast.Node, name string) []*ast.Ident {
1547 var ids []*ast.Ident
1548 ast.Inspect(n, func(n ast.Node) bool {
1549 if id, ok := n.(*ast.Ident); ok && id.Name == name {
1550 ids = append(ids, id)
1551 }
1552 return true
1553 })
1554 return ids
1555 }
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576 func substitute(logf logger, caller *Caller, params []*parameter, args []*argument, effects []int, falcon falconResult, replace replacer) {
1577
1578
1579
1580
1581
1582
1583
1584 assert(len(args) <= len(params), "too many arguments")
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597 sg := make(substGraph)
1598 next:
1599 for i, param := range params {
1600 arg := args[i]
1601
1602
1603
1604
1605
1606
1607
1608
1609 if arg.spread {
1610
1611 logf("keeping param %q and following ones: argument %s is spread",
1612 param.info.Name, debugFormatNode(caller.Fset, arg.expr))
1613 return
1614 }
1615 assert(!param.variadic, "unsimplified variadic parameter")
1616 if param.info.Escapes {
1617 logf("keeping param %q: escapes from callee", param.info.Name)
1618 continue
1619 }
1620 if param.info.Assigned {
1621 logf("keeping param %q: assigned by callee", param.info.Name)
1622 continue
1623 }
1624 if len(param.info.Refs) > 1 && !arg.duplicable {
1625 logf("keeping param %q: argument is not duplicable", param.info.Name)
1626 continue
1627 }
1628 if len(param.info.Refs) == 0 {
1629 if arg.effects {
1630 logf("keeping param %q: though unreferenced, it has effects", param.info.Name)
1631 continue
1632 }
1633
1634
1635
1636
1637 if caller.enclosingFunc != nil {
1638 for free := range arg.freevars {
1639
1640
1641
1642 if v, ok := caller.lookup(free).(*types.Var); ok && within(v.Pos(), caller.enclosingFunc.Body) && !isUsedOutsideCall(caller, v) {
1643
1644
1645
1646 usedElsewhere := func() bool {
1647 for i, param := range params {
1648 if i < len(args) && len(param.info.Refs) > 0 {
1649 for name := range args[i].freevars {
1650 if caller.lookup(name) == v {
1651 return true
1652 }
1653 }
1654 }
1655 }
1656 return false
1657 }
1658 if !usedElsewhere() {
1659 logf("keeping param %q: arg contains perhaps the last reference to caller local %v @ %v",
1660 param.info.Name, v, caller.Fset.PositionFor(v.Pos(), false))
1661 continue next
1662 }
1663 }
1664 }
1665 }
1666 }
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681 sg[arg] = nil
1682 for free := range arg.freevars {
1683 switch s := param.info.Shadow[free]; {
1684 case s < 0:
1685
1686 delete(sg, arg)
1687 case s > 0:
1688
1689
1690 if s > len(args) {
1691
1692
1693 delete(sg, arg)
1694 }
1695 if edges, ok := sg[arg]; ok {
1696 sg[arg] = append(edges, args[s-1])
1697 }
1698 }
1699 }
1700 }
1701
1702
1703 sg.prune()
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762 for checkFalconConstraints(logf, params, args, falcon, sg) {
1763 sg.prune()
1764 }
1765
1766
1767
1768
1769
1770
1771
1772 for resolveEffects(logf, args, effects, sg) {
1773 sg.prune()
1774 }
1775
1776
1777 for i, param := range params {
1778 if arg := args[i]; sg.has(arg) {
1779
1780
1781
1782
1783
1784
1785 logf("replacing parameter %q by argument %q",
1786 param.info.Name, debugFormatNode(caller.Fset, arg.expr))
1787 for _, ref := range param.info.Refs {
1788
1789 argExpr := arg.expr
1790
1791
1792
1793
1794
1795
1796 if ref.IsSelectionOperand && arg.desugaredRecv {
1797 switch e := argExpr.(type) {
1798 case *ast.UnaryExpr:
1799 argExpr = e.X
1800 case *ast.StarExpr:
1801 argExpr = e.X
1802 }
1803 }
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839 needType := ref.AffectsInference ||
1840 (ref.Assignable && ref.IfaceAssignment && !param.info.IsInterface) ||
1841 (!ref.Assignable && !trivialConversion(arg.constant, arg.typ, param.obj.Type()))
1842
1843 if needType &&
1844 !types.Identical(types.Default(arg.typ), param.obj.Type()) {
1845
1846
1847 if call, ok := argExpr.(*ast.CallExpr); ok && len(call.Args) == 1 {
1848 if typ, ok := isConversion(caller.Info, call); ok && isNonTypeParamInterface(typ) {
1849 argExpr = call.Args[0]
1850 }
1851 }
1852
1853 argExpr = convert(param.fieldType, argExpr)
1854 logf("param %q (offset %d): adding explicit %s -> %s conversion around argument",
1855 param.info.Name, ref.Offset, arg.typ, param.obj.Type())
1856 }
1857 replace(ref.Offset, internalastutil.CloneNode(argExpr).(ast.Expr), arg.variadic)
1858 }
1859 params[i] = nil
1860 args[i] = nil
1861 }
1862 }
1863 }
1864
1865
1866
1867
1868
1869 func isConversion(info *types.Info, call *ast.CallExpr) (types.Type, bool) {
1870 if tv, ok := info.Types[call.Fun]; ok && tv.IsType() {
1871 return tv.Type, true
1872 }
1873 return nil, false
1874 }
1875
1876
1877
1878 func isNonTypeParamInterface(t types.Type) bool {
1879 return !typeparams.IsTypeParam(t) && types.IsInterface(t)
1880 }
1881
1882
1883
1884 func isUsedOutsideCall(caller *Caller, v *types.Var) bool {
1885 used := false
1886 ast.Inspect(caller.enclosingFunc.Body, func(n ast.Node) bool {
1887 if n == caller.Call {
1888 return false
1889 }
1890 switch n := n.(type) {
1891 case *ast.Ident:
1892 if use := caller.Info.Uses[n]; use == v {
1893 used = true
1894 }
1895 case *ast.FuncType:
1896
1897 for _, fld := range n.Params.List {
1898 for _, n := range fld.Names {
1899 if def := caller.Info.Defs[n]; def == v {
1900 used = true
1901 }
1902 }
1903 }
1904 }
1905 return !used
1906 })
1907 return used
1908 }
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919 func checkFalconConstraints(logf logger, params []*parameter, args []*argument, falcon falconResult, sg substGraph) bool {
1920
1921
1922 pkg := types.NewPackage("falcon", "falcon")
1923
1924
1925 for _, typ := range falcon.Types {
1926 logf("falcon env: type %s %s", typ.Name, types.Typ[typ.Kind])
1927 pkg.Scope().Insert(types.NewTypeName(token.NoPos, pkg, typ.Name, types.Typ[typ.Kind]))
1928 }
1929
1930
1931 nconst := 0
1932 for i, param := range params {
1933 name := param.info.Name
1934 if name == "" {
1935 continue
1936 }
1937 arg := args[i]
1938 if arg.constant != nil && sg.has(arg) && param.info.FalconType != "" {
1939 t := pkg.Scope().Lookup(param.info.FalconType).Type()
1940 pkg.Scope().Insert(types.NewConst(token.NoPos, pkg, name, t, arg.constant))
1941 logf("falcon env: const %s %s = %v", name, param.info.FalconType, arg.constant)
1942 nconst++
1943 } else {
1944 v := types.NewVar(token.NoPos, pkg, name, arg.typ)
1945 typesinternal.SetVarKind(v, typesinternal.PackageVar)
1946 pkg.Scope().Insert(v)
1947 logf("falcon env: var %s %s", name, arg.typ)
1948 }
1949 }
1950 if nconst == 0 {
1951 return false
1952 }
1953
1954
1955 fset := token.NewFileSet()
1956 removed := false
1957 for _, falcon := range falcon.Constraints {
1958 expr, err := parser.ParseExprFrom(fset, "falcon", falcon, 0)
1959 if err != nil {
1960 panic(fmt.Sprintf("failed to parse falcon constraint %s: %v", falcon, err))
1961 }
1962 if err := types.CheckExpr(fset, pkg, token.NoPos, expr, nil); err != nil {
1963 logf("falcon: constraint %s violated: %v", falcon, err)
1964 for j, arg := range args {
1965 if arg.constant != nil && sg.has(arg) {
1966 logf("keeping param %q due falcon violation", params[j].info.Name)
1967 removed = sg.remove(arg) || removed
1968 }
1969 }
1970 break
1971 }
1972 logf("falcon: constraint %s satisfied", falcon)
1973 }
1974 return removed
1975 }
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021 func resolveEffects(logf logger, args []*argument, effects []int, sg substGraph) bool {
2022 effectStr := func(effects bool, idx int) string {
2023 i := fmt.Sprint(idx)
2024 if idx == len(args) {
2025 i = "∞"
2026 }
2027 return string("RW"[btoi(effects)]) + i
2028 }
2029 removed := false
2030 for i := len(args) - 1; i >= 0; i-- {
2031 argi := args[i]
2032 if sg.has(argi) && !argi.pure {
2033
2034 idx := slices.Index(effects, i)
2035 if idx >= 0 {
2036 for _, j := range effects[:idx] {
2037 var (
2038 ji int
2039 jw bool
2040 )
2041 if j == winf || j == rinf {
2042 jw = j == winf
2043 ji = len(args)
2044 } else {
2045 jw = args[j].effects
2046 ji = j
2047 }
2048 if ji > i && (jw || argi.effects) {
2049 logf("binding argument %s: preceded by %s",
2050 effectStr(argi.effects, i), effectStr(jw, ji))
2051
2052 removed = sg.remove(argi) || removed
2053 break
2054 }
2055 }
2056 }
2057 }
2058 if !sg.has(argi) {
2059 for j := 0; j < i; j++ {
2060 argj := args[j]
2061 if argj.pure {
2062 continue
2063 }
2064 if (argi.effects || argj.effects) && sg.has(argj) {
2065 logf("binding argument %s: %s is bound",
2066 effectStr(argj.effects, j), effectStr(argi.effects, i))
2067
2068 removed = sg.remove(argj) || removed
2069 }
2070 }
2071 }
2072 }
2073 return removed
2074 }
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093 type substGraph map[*argument][]*argument
2094
2095
2096 func (g substGraph) has(arg *argument) bool {
2097 _, ok := g[arg]
2098 return ok
2099 }
2100
2101
2102
2103
2104
2105
2106
2107
2108 func (g substGraph) remove(arg *argument) bool {
2109 pre := len(g)
2110 delete(g, arg)
2111 return len(g) < pre
2112 }
2113
2114
2115
2116 func (g substGraph) prune() {
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133 var visit func(*argument, map[*argument]unit) bool
2134 visit = func(arg *argument, seen map[*argument]unit) bool {
2135 deps, ok := g[arg]
2136 if !ok {
2137 return false
2138 }
2139 if _, ok := seen[arg]; !ok {
2140 seen[arg] = unit{}
2141 for _, dep := range deps {
2142 if !visit(dep, seen) {
2143 delete(g, arg)
2144 return false
2145 }
2146 }
2147 }
2148 return true
2149 }
2150 for arg := range g {
2151
2152
2153
2154
2155 visit(arg, make(map[*argument]unit))
2156 }
2157 }
2158
2159
2160
2161
2162 func updateCalleeParams(calleeDecl *ast.FuncDecl, params []*parameter) {
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173 paramIdx := 0
2174 var newParams []*ast.Field
2175 filterParams := func(field *ast.Field) {
2176 var names []*ast.Ident
2177 if field.Names == nil {
2178
2179 if params[paramIdx] != nil {
2180
2181
2182
2183 names = append(names, makeIdent("_"))
2184 }
2185 paramIdx++
2186 } else {
2187
2188
2189
2190 for _, id := range field.Names {
2191 if pinfo := params[paramIdx]; pinfo != nil {
2192
2193
2194
2195
2196 if len(pinfo.info.Refs) == 0 {
2197 id = makeIdent("_")
2198 }
2199 names = append(names, id)
2200 }
2201 paramIdx++
2202 }
2203 }
2204 if names != nil {
2205 newParams = append(newParams, &ast.Field{
2206 Names: names,
2207 Type: field.Type,
2208 })
2209 }
2210 }
2211 if calleeDecl.Recv != nil {
2212 filterParams(calleeDecl.Recv.List[0])
2213 calleeDecl.Recv = nil
2214 }
2215 for _, field := range calleeDecl.Type.Params.List {
2216 filterParams(field)
2217 }
2218 calleeDecl.Type.Params.List = newParams
2219 }
2220
2221
2222
2223 type bindingDeclInfo struct {
2224 names map[string]bool
2225 stmt ast.Stmt
2226 }
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267 func createBindingDecl(logf logger, caller *Caller, args []*argument, calleeDecl *ast.FuncDecl, results []*paramInfo) *bindingDeclInfo {
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280 if lastArg := last(args); lastArg != nil && lastArg.spread {
2281 logf("binding decls not yet supported for spread calls")
2282 return nil
2283 }
2284
2285 var (
2286 specs []ast.Spec
2287 names = make(map[string]bool)
2288 )
2289
2290
2291
2292
2293 shadow := func(spec *ast.ValueSpec) bool {
2294
2295
2296
2297
2298
2299 const includeComplitIdents = true
2300 free := free.Names(spec.Type, includeComplitIdents)
2301 for _, value := range spec.Values {
2302 for name := range freeVars(caller.Info, value) {
2303 free[name] = true
2304 }
2305 }
2306 for name := range free {
2307 if names[name] {
2308 logf("binding decl would shadow free name %q", name)
2309 return true
2310 }
2311 }
2312 for _, id := range spec.Names {
2313 if id.Name != "_" {
2314 names[id.Name] = true
2315 }
2316 }
2317 return false
2318 }
2319
2320
2321
2322
2323
2324
2325 var values []ast.Expr
2326 for _, arg := range args {
2327 if arg != nil {
2328 values = append(values, arg.expr)
2329 }
2330 }
2331 for _, field := range calleeDecl.Type.Params.List {
2332
2333 spec := &ast.ValueSpec{
2334 Names: cleanNodes(field.Names),
2335 Type: cleanNode(field.Type),
2336 Values: values[:len(field.Names)],
2337 }
2338 values = values[len(field.Names):]
2339 if shadow(spec) {
2340 return nil
2341 }
2342 specs = append(specs, spec)
2343 }
2344 assert(len(values) == 0, "args/params mismatch")
2345
2346
2347
2348
2349
2350 if calleeDecl.Type.Results != nil {
2351 resultIdx := 0
2352 for _, field := range calleeDecl.Type.Results.List {
2353 if field.Names == nil {
2354 resultIdx++
2355 continue
2356 }
2357 var names []*ast.Ident
2358 for _, id := range field.Names {
2359 if len(results[resultIdx].Refs) > 0 {
2360 names = append(names, id)
2361 }
2362 resultIdx++
2363 }
2364 if len(names) > 0 {
2365 spec := &ast.ValueSpec{
2366 Names: cleanNodes(names),
2367 Type: cleanNode(field.Type),
2368 }
2369 if shadow(spec) {
2370 return nil
2371 }
2372 specs = append(specs, spec)
2373 }
2374 }
2375 }
2376
2377 if len(specs) == 0 {
2378 logf("binding decl not needed: all parameters substituted")
2379 return nil
2380 }
2381
2382 stmt := &ast.DeclStmt{
2383 Decl: &ast.GenDecl{
2384 Tok: token.VAR,
2385 Specs: specs,
2386 },
2387 }
2388 logf("binding decl: %s", debugFormatNode(caller.Fset, stmt))
2389 return &bindingDeclInfo{names: names, stmt: stmt}
2390 }
2391
2392
2393 func (caller *Caller) lookup(name string) types.Object {
2394 pos := caller.Call.Pos()
2395 for _, n := range caller.path {
2396 if scope := scopeFor(caller.Info, n); scope != nil {
2397 if _, obj := scope.LookupParent(name, pos); obj != nil {
2398 return obj
2399 }
2400 }
2401 }
2402 return nil
2403 }
2404
2405 func scopeFor(info *types.Info, n ast.Node) *types.Scope {
2406
2407
2408 switch fn := n.(type) {
2409 case *ast.FuncDecl:
2410 n = fn.Type
2411 case *ast.FuncLit:
2412 n = fn.Type
2413 }
2414 return info.Scopes[n]
2415 }
2416
2417
2418
2419
2420
2421
2422 func freeVars(info *types.Info, e ast.Expr) map[string]bool {
2423 free := make(map[string]bool)
2424 ast.Inspect(e, func(n ast.Node) bool {
2425 if id, ok := n.(*ast.Ident); ok {
2426
2427 if obj, ok := info.Uses[id]; ok && !within(obj.Pos(), e) && !isField(obj) {
2428 free[obj.Name()] = true
2429 }
2430 }
2431 return true
2432 })
2433 return free
2434 }
2435
2436
2437
2438
2439 func (st *state) effects(info *types.Info, expr ast.Expr) bool {
2440 effects := false
2441 ast.Inspect(expr, func(n ast.Node) bool {
2442 switch n := n.(type) {
2443 case *ast.FuncLit:
2444 return false
2445
2446 case *ast.CallExpr:
2447 if info.Types[n.Fun].IsType() {
2448
2449 } else if !typesinternal.CallsPureBuiltin(info, n) {
2450
2451
2452
2453
2454
2455
2456
2457 effects = true
2458 }
2459
2460 case *ast.UnaryExpr:
2461 if n.Op == token.ARROW {
2462 effects = true
2463 }
2464 }
2465 return true
2466 })
2467
2468
2469
2470 if st.opts.IgnoreEffects && effects {
2471 effects = false
2472 st.opts.Logf("ignoring potential effects of argument %s",
2473 debugFormatNode(st.caller.Fset, expr))
2474 }
2475
2476 return effects
2477 }
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498 func pure(info *types.Info, assign1 func(*types.Var) bool, e ast.Expr) bool {
2499 var pure func(e ast.Expr) bool
2500 pure = func(e ast.Expr) bool {
2501 switch e := e.(type) {
2502 case *ast.ParenExpr:
2503 return pure(e.X)
2504
2505 case *ast.Ident:
2506 if v, ok := info.Uses[e].(*types.Var); ok {
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516 return !isPkgLevel(v) && assign1(v)
2517 }
2518
2519
2520 return true
2521
2522 case *ast.FuncLit:
2523
2524
2525
2526
2527 return true
2528
2529 case *ast.BasicLit:
2530 return true
2531
2532 case *ast.UnaryExpr:
2533 return e.Op != token.ARROW && pure(e.X)
2534
2535 case *ast.BinaryExpr:
2536 return pure(e.X) && pure(e.Y)
2537
2538 case *ast.CallExpr:
2539
2540 if info.Types[e.Fun].IsType() {
2541 return pure(e.Args[0])
2542 }
2543
2544
2545 if typesinternal.CallsPureBuiltin(info, e) {
2546 for _, arg := range e.Args {
2547 if !pure(arg) {
2548 return false
2549 }
2550 }
2551 return true
2552 }
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563 return false
2564
2565 case *ast.CompositeLit:
2566
2567 for _, elt := range e.Elts {
2568 if kv, ok := elt.(*ast.KeyValueExpr); ok {
2569 if !pure(kv.Value) {
2570 return false
2571 }
2572 if id, ok := kv.Key.(*ast.Ident); ok {
2573 if v, ok := info.Uses[id].(*types.Var); ok && v.IsField() {
2574 continue
2575 }
2576 }
2577
2578 if !pure(kv.Key) {
2579 return false
2580 }
2581
2582 } else if !pure(elt) {
2583 return false
2584 }
2585 }
2586 return true
2587
2588 case *ast.SelectorExpr:
2589 if seln, ok := info.Selections[e]; ok {
2590
2591 switch seln.Kind() {
2592 case types.MethodExpr:
2593
2594
2595 return true
2596
2597 case types.MethodVal, types.FieldVal:
2598
2599
2600
2601 return !indirectSelection(seln) && pure(e.X)
2602
2603 default:
2604 panic(seln)
2605 }
2606 } else {
2607
2608
2609 return pure(e.Sel)
2610 }
2611
2612 case *ast.StarExpr:
2613 return false
2614
2615 default:
2616 return false
2617 }
2618 }
2619 return pure(e)
2620 }
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636 func duplicable(info *types.Info, e ast.Expr) bool {
2637 switch e := e.(type) {
2638 case *ast.ParenExpr:
2639 return duplicable(info, e.X)
2640
2641 case *ast.Ident:
2642 return true
2643
2644 case *ast.BasicLit:
2645 v := info.Types[e].Value
2646 switch e.Kind {
2647 case token.INT:
2648 return true
2649 case token.STRING:
2650 return consteq(v, kZeroString)
2651 case token.FLOAT:
2652 return consteq(v, kZeroFloat) || consteq(v, kOneFloat)
2653 }
2654
2655 case *ast.UnaryExpr:
2656 return (e.Op == token.ADD || e.Op == token.SUB) && duplicable(info, e.X)
2657
2658 case *ast.CompositeLit:
2659
2660
2661
2662 if len(e.Elts) == 0 {
2663 switch info.TypeOf(e).Underlying().(type) {
2664 case *types.Struct, *types.Array:
2665 return true
2666 }
2667 }
2668 return false
2669
2670 case *ast.CallExpr:
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680 if !info.Types[e.Fun].IsType() {
2681 return false
2682 }
2683
2684 fun := info.TypeOf(e.Fun)
2685 arg := info.TypeOf(e.Args[0])
2686
2687 switch fun := fun.Underlying().(type) {
2688 case *types.Slice:
2689
2690 elem, ok := fun.Elem().Underlying().(*types.Basic)
2691 if ok && (elem.Kind() == types.Rune || elem.Kind() == types.Byte) {
2692 from, ok := arg.Underlying().(*types.Basic)
2693 isString := ok && from.Info()&types.IsString != 0
2694 return !isString
2695 }
2696 case *types.TypeParam:
2697 return false
2698 }
2699 return true
2700
2701 case *ast.SelectorExpr:
2702 if seln, ok := info.Selections[e]; ok {
2703
2704
2705 return !indirectSelection(seln)
2706 }
2707
2708 return true
2709 }
2710 return false
2711 }
2712
2713 func consteq(x, y constant.Value) bool {
2714 return constant.Compare(x, token.EQL, y)
2715 }
2716
2717 var (
2718 kZeroInt = constant.MakeInt64(0)
2719 kZeroString = constant.MakeString("")
2720 kZeroFloat = constant.MakeFloat64(0.0)
2721 kOneFloat = constant.MakeFloat64(1.0)
2722 )
2723
2724
2725
2726 func assert(cond bool, msg string) {
2727 if !cond {
2728 panic(msg)
2729 }
2730 }
2731
2732
2733 func blanks[E ast.Expr](n int) []E {
2734 if n == 0 {
2735 panic("blanks(0)")
2736 }
2737 res := make([]E, n)
2738 for i := range res {
2739 res[i] = ast.Expr(makeIdent("_")).(E)
2740 }
2741 return res
2742 }
2743
2744 func makeIdent(name string) *ast.Ident {
2745 return &ast.Ident{Name: name}
2746 }
2747
2748
2749
2750 func importedPkgName(info *types.Info, imp *ast.ImportSpec) (*types.PkgName, bool) {
2751 var obj types.Object
2752 if imp.Name != nil {
2753 obj = info.Defs[imp.Name]
2754 } else {
2755 obj = info.Implicits[imp]
2756 }
2757 pkgname, ok := obj.(*types.PkgName)
2758 return pkgname, ok
2759 }
2760
2761 func isPkgLevel(obj types.Object) bool {
2762
2763
2764
2765 return obj.Pkg().Scope().Lookup(obj.Name()) == obj
2766 }
2767
2768
2769
2770 func callContext(callPath []ast.Node) (parent, grandparent ast.Node) {
2771 _ = callPath[0].(*ast.CallExpr)
2772 for _, n := range callPath[1:] {
2773 if !is[*ast.ParenExpr](n) {
2774 if parent == nil {
2775 parent = n
2776 } else {
2777 return parent, n
2778 }
2779 }
2780 }
2781 return parent, nil
2782 }
2783
2784
2785
2786
2787 func hasLabelConflict(callPath []ast.Node, calleeLabels []string) bool {
2788 labels := callerLabels(callPath)
2789 for _, label := range calleeLabels {
2790 if labels[label] {
2791 return true
2792 }
2793 }
2794 return false
2795 }
2796
2797
2798
2799 func callerLabels(callPath []ast.Node) map[string]bool {
2800 var callerBody *ast.BlockStmt
2801 switch f := callerFunc(callPath).(type) {
2802 case *ast.FuncDecl:
2803 callerBody = f.Body
2804 case *ast.FuncLit:
2805 callerBody = f.Body
2806 }
2807 var labels map[string]bool
2808 if callerBody != nil {
2809 ast.Inspect(callerBody, func(n ast.Node) bool {
2810 switch n := n.(type) {
2811 case *ast.FuncLit:
2812 return false
2813 case *ast.LabeledStmt:
2814 if labels == nil {
2815 labels = make(map[string]bool)
2816 }
2817 labels[n.Label.Name] = true
2818 }
2819 return true
2820 })
2821 }
2822 return labels
2823 }
2824
2825
2826
2827 func callerFunc(callPath []ast.Node) ast.Node {
2828 _ = callPath[0].(*ast.CallExpr)
2829 for _, n := range callPath[1:] {
2830 if is[*ast.FuncDecl](n) || is[*ast.FuncLit](n) {
2831 return n
2832 }
2833 }
2834 return nil
2835 }
2836
2837
2838
2839
2840
2841
2842
2843
2844 func callStmt(callPath []ast.Node, unrestricted bool) *ast.ExprStmt {
2845 parent, _ := callContext(callPath)
2846 stmt, ok := parent.(*ast.ExprStmt)
2847 if ok && unrestricted {
2848 switch callPath[slices.Index(callPath, ast.Node(stmt))+1].(type) {
2849 case *ast.LabeledStmt,
2850 *ast.BlockStmt,
2851 *ast.CaseClause,
2852 *ast.CommClause:
2853
2854 default:
2855
2856
2857
2858
2859
2860 return nil
2861 }
2862 }
2863 return stmt
2864 }
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909 func replaceNode(root ast.Node, from, to ast.Node) {
2910 if from == nil {
2911 panic("from == nil")
2912 }
2913 if reflect.ValueOf(from).IsNil() {
2914 panic(fmt.Sprintf("from == (%T)(nil)", from))
2915 }
2916 if from == root {
2917 panic("from == root")
2918 }
2919 found := false
2920 var parent reflect.Value
2921 var visit func(reflect.Value)
2922 visit = func(v reflect.Value) {
2923 switch v.Kind() {
2924 case reflect.Pointer:
2925 if v.Interface() == from {
2926 found = true
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936 if !v.CanAddr() {
2937 v = parent
2938 }
2939
2940
2941 var toV reflect.Value
2942 if to != nil {
2943 toV = reflect.ValueOf(to)
2944 } else {
2945 toV = reflect.Zero(v.Type())
2946 }
2947 v.Set(toV)
2948
2949 } else if !v.IsNil() {
2950 switch v.Interface().(type) {
2951 case *ast.Object, *ast.Scope:
2952
2953 default:
2954 visit(v.Elem())
2955 }
2956 }
2957
2958 case reflect.Struct:
2959 for i := range v.Type().NumField() {
2960 visit(v.Field(i))
2961 }
2962
2963 case reflect.Slice:
2964 compact := false
2965 for i := range v.Len() {
2966 visit(v.Index(i))
2967 if v.Index(i).IsNil() {
2968 compact = true
2969 }
2970 }
2971 if compact {
2972
2973
2974
2975 j := 0
2976 for i := range v.Len() {
2977 if !v.Index(i).IsNil() {
2978 v.Index(j).Set(v.Index(i))
2979 j++
2980 }
2981 }
2982 v.SetLen(j)
2983 }
2984 case reflect.Interface:
2985 parent = v
2986 visit(v.Elem())
2987
2988 case reflect.Array, reflect.Chan, reflect.Func, reflect.Map, reflect.UnsafePointer:
2989 panic(v)
2990 default:
2991
2992 }
2993 parent = reflect.Value{}
2994 }
2995 visit(reflect.ValueOf(root))
2996 if !found {
2997 panic(fmt.Sprintf("%T not found", from))
2998 }
2999 }
3000
3001
3002
3003
3004
3005 func cleanNode[T ast.Node](node T) T {
3006 clone := internalastutil.CloneNode(node)
3007 clearPositions(clone)
3008 return clone
3009 }
3010
3011 func cleanNodes[T ast.Node](nodes []T) []T {
3012 var clean []T
3013 for _, node := range nodes {
3014 clean = append(clean, cleanNode(node))
3015 }
3016 return clean
3017 }
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030 func clearPositions(root ast.Node) {
3031 posType := reflect.TypeFor[token.Pos]()
3032 ast.Inspect(root, func(n ast.Node) bool {
3033 if n != nil {
3034 v := reflect.ValueOf(n).Elem()
3035 fields := v.Type().NumField()
3036 for i := range fields {
3037 f := v.Field(i)
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047 if f.Type() == posType {
3048 if f.Interface() != token.NoPos {
3049 f.Set(reflect.ValueOf(token.Pos(1)))
3050 }
3051 }
3052 }
3053 }
3054 return true
3055 })
3056 }
3057
3058
3059
3060
3061
3062 func findIdent(root ast.Node, pos token.Pos) ([]ast.Node, *ast.Ident) {
3063
3064 var (
3065 path []ast.Node
3066 found *ast.Ident
3067 )
3068 ast.Inspect(root, func(n ast.Node) bool {
3069 if found != nil {
3070 return false
3071 }
3072 if n == nil {
3073 path = path[:len(path)-1]
3074 return false
3075 }
3076 if id, ok := n.(*ast.Ident); ok {
3077 if id.Pos() == pos {
3078 found = id
3079 return true
3080 }
3081 }
3082 path = append(path, n)
3083 return true
3084 })
3085 if found == nil {
3086 panic(fmt.Sprintf("findIdent %d not found in %s",
3087 pos, debugFormatNode(token.NewFileSet(), root)))
3088 }
3089 return path, found
3090 }
3091
3092 func prepend[T any](elem T, slice ...T) []T {
3093 return append([]T{elem}, slice...)
3094 }
3095
3096
3097
3098 func debugFormatNode(fset *token.FileSet, n ast.Node) string {
3099 var out strings.Builder
3100 if err := format.Node(&out, fset, n); err != nil {
3101 out.WriteString(err.Error())
3102 }
3103 return out.String()
3104 }
3105
3106 func shallowCopy[T any](ptr *T) *T {
3107 copy := *ptr
3108 return ©
3109 }
3110
3111
3112 func forall[T any](list []T, f func(i int, x T) bool) bool {
3113 for i, x := range list {
3114 if !f(i, x) {
3115 return false
3116 }
3117 }
3118 return true
3119 }
3120
3121
3122 func exists[T any](list []T, f func(i int, x T) bool) bool {
3123 for i, x := range list {
3124 if f(i, x) {
3125 return true
3126 }
3127 }
3128 return false
3129 }
3130
3131
3132 func last[T any](slice []T) T {
3133 n := len(slice)
3134 if n > 0 {
3135 return slice[n-1]
3136 }
3137 return *new(T)
3138 }
3139
3140
3141
3142
3143 func needsParens(callPath []ast.Node, old, new ast.Node) bool {
3144
3145 i := slices.Index(callPath, old)
3146 if i == -1 {
3147 panic("not found")
3148 }
3149
3150
3151
3152 if !is[ast.Expr](old) {
3153 return false
3154 }
3155
3156
3157
3158 parent, ok := callPath[i+1].(ast.Expr)
3159 if !ok {
3160 return false
3161 }
3162
3163 precedence := func(n ast.Node) int {
3164 switch n := n.(type) {
3165 case *ast.UnaryExpr, *ast.StarExpr:
3166 return token.UnaryPrec
3167 case *ast.BinaryExpr:
3168 return n.Op.Precedence()
3169 }
3170 return -1
3171 }
3172
3173
3174
3175 newprec := precedence(new)
3176 if newprec < 0 {
3177 return false
3178 }
3179
3180
3181
3182 if precedence(parent) > newprec {
3183 return true
3184 }
3185
3186
3187
3188
3189
3190
3191
3192 switch parent := parent.(type) {
3193 case *ast.SelectorExpr:
3194 return parent.X == old
3195 case *ast.IndexExpr:
3196 return parent.X == old
3197 case *ast.SliceExpr:
3198 return parent.X == old
3199 case *ast.TypeAssertExpr:
3200 return parent.X == old
3201 case *ast.CallExpr:
3202 return parent.Fun == old
3203 }
3204 return false
3205 }
3206
3207
3208
3209
3210 func declares(stmts []ast.Stmt) map[string]bool {
3211 names := make(map[string]bool)
3212 for _, stmt := range stmts {
3213 switch stmt := stmt.(type) {
3214 case *ast.DeclStmt:
3215 for _, spec := range stmt.Decl.(*ast.GenDecl).Specs {
3216 switch spec := spec.(type) {
3217 case *ast.ValueSpec:
3218 for _, id := range spec.Names {
3219 names[id.Name] = true
3220 }
3221 case *ast.TypeSpec:
3222 names[spec.Name.Name] = true
3223 }
3224 }
3225
3226 case *ast.AssignStmt:
3227 if stmt.Tok == token.DEFINE {
3228 for _, lhs := range stmt.Lhs {
3229 names[lhs.(*ast.Ident).Name] = true
3230 }
3231 }
3232 }
3233 }
3234 delete(names, "_")
3235 return names
3236 }
3237
3238
3239
3240
3241
3242
3243
3244
3245 type importNameFunc = func(pkgPath string, shadow shadowMap) string
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289 func (st *state) assignStmts(callerStmt *ast.AssignStmt, returnOperands []ast.Expr, importName importNameFunc) ([]ast.Stmt, bool) {
3290 logf, caller, callee := st.opts.Logf, st.caller, &st.callee.impl
3291
3292 assert(len(callee.Returns) == 1, "unexpected multiple returns")
3293 resultInfo := callee.Returns[0]
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305 var (
3306 lhs []ast.Expr
3307 defs = make([]*ast.Ident, len(callerStmt.Lhs))
3308 blanks = make([]bool, len(callerStmt.Lhs))
3309 byType typeutil.Map
3310 )
3311 for i, expr := range callerStmt.Lhs {
3312 lhs = append(lhs, expr)
3313 if name, ok := expr.(*ast.Ident); ok {
3314 if name.Name == "_" {
3315 blanks[i] = true
3316 continue
3317 }
3318
3319 if obj, isDef := caller.Info.Defs[name]; isDef {
3320 defs[i] = name
3321 typ := obj.Type()
3322 idxs, _ := byType.At(typ).([]int)
3323 idxs = append(idxs, i)
3324 byType.Set(typ, idxs)
3325 }
3326 }
3327 }
3328
3329
3330
3331
3332
3333 var (
3334 rhs []ast.Expr
3335 callIdx = -1
3336 nilBlankAssigns = make(map[int]unit)
3337 freeNames = make(map[string]bool)
3338 nonTrivial = make(map[int]bool)
3339 )
3340 const includeComplitIdents = true
3341
3342 for i, expr := range callerStmt.Rhs {
3343 if expr == caller.Call {
3344 assert(callIdx == -1, "malformed (duplicative) AST")
3345 callIdx = i
3346 for j, returnOperand := range returnOperands {
3347 maps.Copy(freeNames, free.Names(returnOperand, includeComplitIdents))
3348 rhs = append(rhs, returnOperand)
3349 if resultInfo[j]&nonTrivialResult != 0 {
3350 nonTrivial[i+j] = true
3351 }
3352 if blanks[i+j] && resultInfo[j]&untypedNilResult != 0 {
3353 nilBlankAssigns[i+j] = unit{}
3354 }
3355 }
3356 } else {
3357
3358 expr = internalastutil.CloneNode(expr)
3359 clearPositions(expr)
3360 maps.Copy(freeNames, free.Names(expr, includeComplitIdents))
3361 rhs = append(rhs, expr)
3362 }
3363 }
3364 assert(callIdx >= 0, "failed to find call in RHS")
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379 if len(nonTrivial) == 0 {
3380
3381 logf("substrategy: splice assignment")
3382 return []ast.Stmt{&ast.AssignStmt{
3383 Lhs: lhs,
3384 Tok: callerStmt.Tok,
3385 TokPos: callerStmt.TokPos,
3386 Rhs: rhs,
3387 }}, true
3388 }
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399 universeAny := types.Universe.Lookup("any")
3400 typeExpr := func(typ types.Type, shadow shadowMap) ast.Expr {
3401 var (
3402 typeName string
3403 obj *types.TypeName
3404 )
3405 if tname := typesinternal.TypeNameFor(typ); tname != nil {
3406 obj = tname
3407 typeName = tname.Name()
3408 }
3409
3410
3411
3412 if typ == universeAny.Type() {
3413 typeName = "any"
3414 }
3415
3416 if typeName == "" {
3417 return nil
3418 }
3419
3420 if obj == nil || obj.Pkg() == nil || obj.Pkg() == caller.Types {
3421 if shadow[typeName] != 0 {
3422 logf("cannot write shadowed type name %q", typeName)
3423 return nil
3424 }
3425 obj, _ := caller.lookup(typeName).(*types.TypeName)
3426 if obj != nil && types.Identical(obj.Type(), typ) {
3427 return ast.NewIdent(typeName)
3428 }
3429 } else if pkgName := importName(obj.Pkg().Path(), shadow); pkgName != "" {
3430 return &ast.SelectorExpr{
3431 X: ast.NewIdent(pkgName),
3432 Sel: ast.NewIdent(typeName),
3433 }
3434 }
3435 return nil
3436 }
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452 if len(rhs) != len(lhs) {
3453 assert(len(rhs) == 1 && len(returnOperands) == 1, "expected spread call")
3454
3455 for _, id := range defs {
3456 if id != nil && freeNames[id.Name] {
3457
3458
3459 return nil, false
3460 }
3461 }
3462
3463
3464
3465 var (
3466 specs []ast.Spec
3467 specIdxs []int
3468 shadow = make(shadowMap)
3469 )
3470 failed := false
3471 byType.Iterate(func(typ types.Type, v any) {
3472 if failed {
3473 return
3474 }
3475 idxs := v.([]int)
3476 specIdxs = append(specIdxs, idxs[0])
3477 texpr := typeExpr(typ, shadow)
3478 if texpr == nil {
3479 failed = true
3480 return
3481 }
3482 spec := &ast.ValueSpec{
3483 Type: texpr,
3484 }
3485 for _, idx := range idxs {
3486 spec.Names = append(spec.Names, ast.NewIdent(defs[idx].Name))
3487 }
3488 specs = append(specs, spec)
3489 })
3490 if failed {
3491 return nil, false
3492 }
3493 logf("substrategy: spread assignment")
3494 return []ast.Stmt{
3495 &ast.DeclStmt{
3496 Decl: &ast.GenDecl{
3497 Tok: token.VAR,
3498 Specs: specs,
3499 },
3500 },
3501 &ast.AssignStmt{
3502 Lhs: callerStmt.Lhs,
3503 Tok: token.ASSIGN,
3504 Rhs: returnOperands,
3505 },
3506 }, true
3507 }
3508
3509 assert(len(lhs) == len(rhs), "mismatching LHS and RHS")
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524 var origIdxs []int
3525 i := 0
3526 for j := range lhs {
3527 if _, ok := nilBlankAssigns[j]; !ok {
3528 lhs[i] = lhs[j]
3529 rhs[i] = rhs[j]
3530 origIdxs = append(origIdxs, j)
3531 i++
3532 }
3533 }
3534 lhs = lhs[:i]
3535 rhs = rhs[:i]
3536
3537 if len(lhs) == 0 {
3538 logf("trivial assignment after pruning nil blanks assigns")
3539
3540
3541 return nil, true
3542 }
3543
3544
3545
3546
3547
3548 for i, expr := range rhs {
3549 idx := origIdxs[i]
3550 if nonTrivial[idx] && defs[idx] != nil {
3551 typ := caller.Info.TypeOf(lhs[i])
3552 texpr := typeExpr(typ, nil)
3553 if texpr == nil {
3554 return nil, false
3555 }
3556 if _, ok := texpr.(*ast.StarExpr); ok {
3557
3558 texpr = &ast.ParenExpr{X: texpr}
3559 }
3560 rhs[i] = &ast.CallExpr{
3561 Fun: texpr,
3562 Args: []ast.Expr{expr},
3563 }
3564 }
3565 }
3566 logf("substrategy: convert assignment")
3567 return []ast.Stmt{&ast.AssignStmt{
3568 Lhs: lhs,
3569 Tok: callerStmt.Tok,
3570 Rhs: rhs,
3571 }}, true
3572 }
3573
3574
3575
3576 func tailCallSafeReturn(caller *Caller, calleeSymbol *types.Func, callee *gobCallee) bool {
3577
3578 if !hasNonTrivialReturn(callee.Returns) {
3579 return true
3580 }
3581
3582 var callerType types.Type
3583
3584
3585 loop:
3586 for _, n := range caller.path {
3587 switch f := n.(type) {
3588 case *ast.FuncDecl:
3589 callerType = caller.Info.ObjectOf(f.Name).Type()
3590 break loop
3591 case *ast.FuncLit:
3592 callerType = caller.Info.TypeOf(f)
3593 break loop
3594 }
3595 }
3596
3597
3598
3599
3600 callerResults := callerType.(*types.Signature).Results()
3601 calleeResults := calleeSymbol.Type().(*types.Signature).Results()
3602 return types.Identical(callerResults, calleeResults)
3603 }
3604
3605
3606
3607 func hasNonTrivialReturn(returnInfo [][]returnOperandFlags) bool {
3608 for _, resultInfo := range returnInfo {
3609 for _, r := range resultInfo {
3610 if r&nonTrivialResult != 0 {
3611 return true
3612 }
3613 }
3614 }
3615 return false
3616 }
3617
3618 type unit struct{}
3619
View as plain text