-
Notifications
You must be signed in to change notification settings - Fork 283
/
inline.go
2686 lines (2490 loc) · 84.1 KB
/
inline.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 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 inline
import (
"bytes"
"fmt"
"go/ast"
"go/constant"
"go/format"
"go/parser"
"go/token"
"go/types"
pathpkg "path"
"reflect"
"strconv"
"strings"
internalastutil "cuelang.org/go/internal/golangorgx/tools/astutil"
"cuelang.org/go/internal/golangorgx/tools/typeparams"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/types/typeutil"
"golang.org/x/tools/imports"
)
// A Caller describes the function call and its enclosing context.
//
// The client is responsible for populating this struct and passing it to Inline.
type Caller struct {
Fset *token.FileSet
Types *types.Package
Info *types.Info
File *ast.File
Call *ast.CallExpr
Content []byte // source of file containing
path []ast.Node // path from call to root of file syntax tree
enclosingFunc *ast.FuncDecl // top-level function/method enclosing the call, if any
}
// Inline inlines the called function (callee) into the function call (caller)
// and returns the updated, formatted content of the caller source file.
//
// Inline does not mutate any public fields of Caller or Callee.
//
// The log records the decision-making process.
//
// TODO(adonovan): provide an API for clients that want structured
// output: a list of import additions and deletions plus one or more
// localized diffs (or even AST transformations, though ownership and
// mutation are tricky) near the call site.
func Inline(logf func(string, ...any), caller *Caller, callee *Callee) ([]byte, error) {
logf("inline %s @ %v",
debugFormatNode(caller.Fset, caller.Call),
caller.Fset.PositionFor(caller.Call.Lparen, false))
if !consistentOffsets(caller) {
return nil, fmt.Errorf("internal error: caller syntax positions are inconsistent with file content (did you forget to use FileSet.PositionFor when computing the file name?)")
}
// TODO(adonovan): use go1.21's ast.IsGenerated.
// Break the string literal so we can use inlining in this file. :)
if bytes.Contains(caller.Content, []byte("// Code generated by "+"cmd/cgo; DO NOT EDIT.")) {
return nil, fmt.Errorf("cannot inline calls from files that import \"C\"")
}
res, err := inline(logf, caller, &callee.impl)
if err != nil {
return nil, err
}
// Replace the call (or some node that encloses it) by new syntax.
assert(res.old != nil, "old is nil")
assert(res.new != nil, "new is nil")
// A single return operand inlined to a unary
// expression context may need parens. Otherwise:
// func two() int { return 1+1 }
// print(-two()) => print(-1+1) // oops!
//
// Usually it is not necessary to insert ParenExprs
// as the formatter is smart enough to insert them as
// needed by the context. But the res.{old,new}
// substitution is done by formatting res.new in isolation
// and then splicing its text over res.old, so the
// formatter doesn't see the parent node and cannot do
// the right thing. (One solution would be to always
// format the enclosing node of old, but that requires
// non-lossy comment handling, #20744.)
//
// So, we must analyze the call's context
// to see whether ambiguity is possible.
// For example, if the context is x[y:z], then
// the x subtree is subject to precedence ambiguity
// (replacing x by p+q would give p+q[y:z] which is wrong)
// but the y and z subtrees are safe.
if needsParens(caller.path, res.old, res.new) {
res.new = &ast.ParenExpr{X: res.new.(ast.Expr)}
}
// Some reduction strategies return a new block holding the
// callee's statements. The block's braces may be elided when
// there is no conflict between names declared in the block
// with those declared by the parent block, and no risk of
// a caller's goto jumping forward across a declaration.
//
// This elision is only safe when the ExprStmt is beneath a
// BlockStmt, CaseClause.Body, or CommClause.Body;
// (see "statement theory").
elideBraces := false
if newBlock, ok := res.new.(*ast.BlockStmt); ok {
i := nodeIndex(caller.path, res.old)
parent := caller.path[i+1]
var body []ast.Stmt
switch parent := parent.(type) {
case *ast.BlockStmt:
body = parent.List
case *ast.CommClause:
body = parent.Body
case *ast.CaseClause:
body = parent.Body
}
if body != nil {
callerNames := declares(body)
// If BlockStmt is a function body,
// include its receiver, params, and results.
addFieldNames := func(fields *ast.FieldList) {
if fields != nil {
for _, field := range fields.List {
for _, id := range field.Names {
callerNames[id.Name] = true
}
}
}
}
switch f := caller.path[i+2].(type) {
case *ast.FuncDecl:
addFieldNames(f.Recv)
addFieldNames(f.Type.Params)
addFieldNames(f.Type.Results)
case *ast.FuncLit:
addFieldNames(f.Type.Params)
addFieldNames(f.Type.Results)
}
if len(callerLabels(caller.path)) > 0 {
// TODO(adonovan): be more precise and reject
// only forward gotos across the inlined block.
logf("keeping block braces: caller uses control labels")
} else if intersects(declares(newBlock.List), callerNames) {
logf("keeping block braces: avoids name conflict")
} else {
elideBraces = true
}
}
}
// Don't call replaceNode(caller.File, res.old, res.new)
// as it mutates the caller's syntax tree.
// Instead, splice the file, replacing the extent of the "old"
// node by a formatting of the "new" node, and re-parse.
// We'll fix up the imports on this new tree, and format again.
var f *ast.File
{
start := offsetOf(caller.Fset, res.old.Pos())
end := offsetOf(caller.Fset, res.old.End())
var out bytes.Buffer
out.Write(caller.Content[:start])
// TODO(adonovan): might it make more sense to use
// callee.Fset when formatting res.new?
// The new tree is a mix of (cloned) caller nodes for
// the argument expressions and callee nodes for the
// function body. In essence the question is: which
// is more likely to have comments?
// Usually the callee body will be larger and more
// statement-heavy than the the arguments, but a
// strategy may widen the scope of the replacement
// (res.old) from CallExpr to, say, its enclosing
// block, so the caller nodes dominate.
// Precise comment handling would make this a
// non-issue. Formatting wouldn't really need a
// FileSet at all.
if elideBraces {
for i, stmt := range res.new.(*ast.BlockStmt).List {
if i > 0 {
out.WriteByte('\n')
}
if err := format.Node(&out, caller.Fset, stmt); err != nil {
return nil, err
}
}
} else {
if err := format.Node(&out, caller.Fset, res.new); err != nil {
return nil, err
}
}
out.Write(caller.Content[end:])
const mode = parser.ParseComments | parser.SkipObjectResolution | parser.AllErrors
f, err = parser.ParseFile(caller.Fset, "callee.go", &out, mode)
if err != nil {
// Something has gone very wrong.
logf("failed to parse <<%s>>", &out) // debugging
return nil, err
}
}
// Add new imports.
//
// Insert new imports after last existing import,
// to avoid migration of pre-import comments.
// The imports will be organized below.
if len(res.newImports) > 0 {
var importDecl *ast.GenDecl
if len(f.Imports) > 0 {
// Append specs to existing import decl
importDecl = f.Decls[0].(*ast.GenDecl)
} else {
// Insert new import decl.
importDecl = &ast.GenDecl{Tok: token.IMPORT}
f.Decls = prepend[ast.Decl](importDecl, f.Decls...)
}
for _, imp := range res.newImports {
// Check that the new imports are accessible.
path, _ := strconv.Unquote(imp.spec.Path.Value)
if !canImport(caller.Types.Path(), path) {
return nil, fmt.Errorf("can't inline function %v as its body refers to inaccessible package %q", callee, path)
}
importDecl.Specs = append(importDecl.Specs, imp.spec)
}
}
var out bytes.Buffer
if err := format.Node(&out, caller.Fset, f); err != nil {
return nil, err
}
newSrc := out.Bytes()
// Remove imports that are no longer referenced.
//
// It ought to be possible to compute the set of PkgNames used
// by the "old" code, compute the free identifiers of the
// "new" code using a syntax-only (no go/types) algorithm, and
// see if the reduction in the number of uses of any PkgName
// equals the number of times it appears in caller.Info.Uses,
// indicating that it is no longer referenced by res.new.
//
// However, the notorious ambiguity of resolving T{F: 0} makes this
// unreliable: without types, we can't tell whether F refers to
// a field of struct T, or a package-level const/var of a
// dot-imported (!) package.
//
// So, for now, we run imports.Process, which is
// unsatisfactory as it has to run the go command, and it
// looks at the user's module cache state--unnecessarily,
// since this step cannot add new imports.
//
// TODO(adonovan): replace with a simpler implementation since
// all the necessary imports are present but merely untidy.
// That will be faster, and also less prone to nondeterminism
// if there are bugs in our logic for import maintenance.
//
// However, cuelang.org/go/internal/golangorgx/tools/imports.ApplyFixes is
// too simple as it requires the caller to have figured out
// all the logical edits. In our case, we know all the new
// imports that are needed (see newImports), each of which can
// be specified as:
//
// &imports.ImportFix{
// StmtInfo: imports.ImportInfo{path, name,
// IdentName: name,
// FixType: imports.AddImport,
// }
//
// but we don't know which imports are made redundant by the
// inlining itself. For example, inlining a call to
// fmt.Println may make the "fmt" import redundant.
//
// Also, both imports.Process and internal/imports.ApplyFixes
// reformat the entire file, which is not ideal for clients
// such as gopls. (That said, the point of a canonical format
// is arguably that any tool can reformat as needed without
// this being inconvenient.)
//
// We could invoke imports.Process and parse its result,
// compare against the original AST, compute a list of import
// fixes, and return that too.
// Recompute imports only if there were existing ones.
if len(f.Imports) > 0 {
formatted, err := imports.Process("output", newSrc, nil)
if err != nil {
logf("cannot reformat: %v <<%s>>", err, &out)
return nil, err // cannot reformat (a bug?)
}
newSrc = formatted
}
return newSrc, nil
}
type newImport struct {
pkgName string
spec *ast.ImportSpec
}
type result struct {
newImports []newImport
old, new ast.Node // e.g. replace call expr by callee function body expression
}
// inline returns a pair of an old node (the call, or something
// enclosing it) and a new node (its replacement, which may be a
// combination of caller, callee, and new nodes), along with the set
// of new imports needed.
//
// TODO(adonovan): rethink the 'result' interface. The assumption of a
// one-to-one replacement seems fragile. One can easily imagine the
// transformation replacing the call and adding new variable
// declarations, for example, or replacing a call statement by zero or
// many statements.)
//
// TODO(adonovan): in earlier drafts, the transformation was expressed
// by splicing substrings of the two source files because syntax
// trees don't preserve comments faithfully (see #20744), but such
// transformations don't compose. The current implementation is
// tree-based but is very lossy wrt comments. It would make a good
// candidate for evaluating an alternative fully self-contained tree
// representation, such as any proposed solution to #20744, or even
// dst or some private fork of go/ast.)
func inline(logf func(string, ...any), caller *Caller, callee *gobCallee) (*result, error) {
checkInfoFields(caller.Info)
// Inlining of dynamic calls is not currently supported,
// even for local closure calls. (This would be a lot of work.)
calleeSymbol := typeutil.StaticCallee(caller.Info, caller.Call)
if calleeSymbol == nil {
// e.g. interface method
return nil, fmt.Errorf("cannot inline: not a static function call")
}
// Reject cross-package inlining if callee has
// free references to unexported symbols.
samePkg := caller.Types.Path() == callee.PkgPath
if !samePkg && len(callee.Unexported) > 0 {
return nil, fmt.Errorf("cannot inline call to %s because body refers to non-exported %s",
callee.Name, callee.Unexported[0])
}
// -- analyze callee's free references in caller context --
// Compute syntax path enclosing Call, innermost first (Path[0]=Call),
// and outermost enclosing function, if any.
caller.path, _ = astutil.PathEnclosingInterval(caller.File, caller.Call.Pos(), caller.Call.End())
for _, n := range caller.path {
if decl, ok := n.(*ast.FuncDecl); ok {
caller.enclosingFunc = decl
break
}
}
// If call is within a function, analyze all its
// local vars for the "single assignment" property.
// (Taking the address &v counts as a potential assignment.)
var assign1 func(v *types.Var) bool // reports whether v a single-assignment local var
{
updatedLocals := make(map[*types.Var]bool)
if caller.enclosingFunc != nil {
escape(caller.Info, caller.enclosingFunc, func(v *types.Var, _ bool) {
updatedLocals[v] = true
})
logf("multiple-assignment vars: %v", updatedLocals)
}
assign1 = func(v *types.Var) bool { return !updatedLocals[v] }
}
// import map, initially populated with caller imports.
//
// For simplicity we ignore existing dot imports, so that a
// qualified identifier (QI) in the callee is always
// represented by a QI in the caller, allowing us to treat a
// QI like a selection on a package name.
importMap := make(map[string][]string) // maps package path to local name(s)
for _, imp := range caller.File.Imports {
if pkgname, ok := importedPkgName(caller.Info, imp); ok &&
pkgname.Name() != "." &&
pkgname.Name() != "_" {
path := pkgname.Imported().Path()
importMap[path] = append(importMap[path], pkgname.Name())
}
}
// localImportName returns the local name for a given imported package path.
var newImports []newImport
localImportName := func(obj *object) string {
// Does an import exist?
for _, name := range importMap[obj.PkgPath] {
// Check that either the import preexisted,
// or that it was newly added (no PkgName) but is not shadowed,
// either in the callee (shadows) or caller (caller.lookup).
if !obj.Shadow[name] {
found := caller.lookup(name)
if is[*types.PkgName](found) || found == nil {
return name
}
}
}
newlyAdded := func(name string) bool {
for _, new := range newImports {
if new.pkgName == name {
return true
}
}
return false
}
// import added by callee
//
// Choose local PkgName based on last segment of
// package path plus, if needed, a numeric suffix to
// ensure uniqueness.
//
// "init" is not a legal PkgName.
//
// TODO(rfindley): is it worth preserving local package names for callee
// imports? Are they likely to be better or worse than the name we choose
// here?
base := obj.PkgName
name := base
for n := 0; obj.Shadow[name] || caller.lookup(name) != nil || newlyAdded(name) || name == "init"; n++ {
name = fmt.Sprintf("%s%d", base, n)
}
logf("adding import %s %q", name, obj.PkgPath)
spec := &ast.ImportSpec{
Path: &ast.BasicLit{
Kind: token.STRING,
Value: strconv.Quote(obj.PkgPath),
},
}
// Use explicit pkgname (out of necessity) when it differs from the declared name,
// or (for good style) when it differs from base(pkgpath).
if name != obj.PkgName || name != pathpkg.Base(obj.PkgPath) {
spec.Name = makeIdent(name)
}
newImports = append(newImports, newImport{
pkgName: name,
spec: spec,
})
importMap[obj.PkgPath] = append(importMap[obj.PkgPath], name)
return name
}
// Compute the renaming of the callee's free identifiers.
objRenames := make([]ast.Expr, len(callee.FreeObjs)) // nil => no change
for i, obj := range callee.FreeObjs {
// obj is a free object of the callee.
//
// Possible cases are:
// - builtin function, type, or value (e.g. nil, zero)
// => check not shadowed in caller.
// - package-level var/func/const/types
// => same package: check not shadowed in caller.
// => otherwise: import other package, form a qualified identifier.
// (Unexported cross-package references were rejected already.)
// - type parameter
// => not yet supported
// - pkgname
// => import other package and use its local name.
//
// There can be no free references to labels, fields, or methods.
// Note that we must consider potential shadowing both
// at the caller side (caller.lookup) and, when
// choosing new PkgNames, within the callee (obj.shadow).
var newName ast.Expr
if obj.Kind == "pkgname" {
// Use locally appropriate import, creating as needed.
newName = makeIdent(localImportName(&obj)) // imported package
} else if !obj.ValidPos {
// Built-in function, type, or value (e.g. nil, zero):
// check not shadowed at caller.
found := caller.lookup(obj.Name) // always finds something
if found.Pos().IsValid() {
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)",
obj.Name, objectKind(found),
caller.Fset.PositionFor(found.Pos(), false).Line)
}
} else {
// Must be reference to package-level var/func/const/type,
// since type parameters are not yet supported.
qualify := false
if obj.PkgPath == callee.PkgPath {
// reference within callee package
if samePkg {
// Caller and callee are in same package.
// Check caller has not shadowed the decl.
//
// This may fail if the callee is "fake", such as for signature
// refactoring where the callee is modified to be a trivial wrapper
// around the refactored signature.
found := caller.lookup(obj.Name)
if found != nil && !isPkgLevel(found) {
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)",
obj.Kind, obj.Name,
objectKind(found),
caller.Fset.PositionFor(found.Pos(), false).Line)
}
} else {
// Cross-package reference.
qualify = true
}
} else {
// Reference to a package-level declaration
// in another package, without a qualified identifier:
// it must be a dot import.
qualify = true
}
// Form a qualified identifier, pkg.Name.
if qualify {
pkgName := localImportName(&obj)
newName = &ast.SelectorExpr{
X: makeIdent(pkgName),
Sel: makeIdent(obj.Name),
}
}
}
objRenames[i] = newName
}
res := &result{
newImports: newImports,
}
// Parse callee function declaration.
calleeFset, calleeDecl, err := parseCompact(callee.Content)
if err != nil {
return nil, err // "can't happen"
}
// replaceCalleeID replaces an identifier in the callee.
// The replacement tree must not belong to the caller; use cloneNode as needed.
replaceCalleeID := func(offset int, repl ast.Expr) {
id := findIdent(calleeDecl, calleeDecl.Pos()+token.Pos(offset))
logf("- replace id %q @ #%d to %q", id.Name, offset, debugFormatNode(calleeFset, repl))
replaceNode(calleeDecl, id, repl)
}
// Generate replacements for each free identifier.
// (The same tree may be spliced in multiple times, resulting in a DAG.)
for _, ref := range callee.FreeRefs {
if repl := objRenames[ref.Object]; repl != nil {
replaceCalleeID(ref.Offset, repl)
}
}
// Gather the effective call arguments, including the receiver.
// Later, elements will be eliminated (=> nil) by parameter substitution.
args, err := arguments(caller, calleeDecl, assign1)
if err != nil {
return nil, err // e.g. implicit field selection cannot be made explicit
}
// Gather effective parameter tuple, including the receiver if any.
// Simplify variadic parameters to slices (in all cases but one).
var params []*parameter // including receiver; nil => parameter substituted
{
sig := calleeSymbol.Type().(*types.Signature)
if sig.Recv() != nil {
params = append(params, ¶meter{
obj: sig.Recv(),
fieldType: calleeDecl.Recv.List[0].Type,
info: callee.Params[0],
})
}
// Flatten the list of syntactic types.
var types []ast.Expr
for _, field := range calleeDecl.Type.Params.List {
if field.Names == nil {
types = append(types, field.Type)
} else {
for range field.Names {
types = append(types, field.Type)
}
}
}
for i := 0; i < sig.Params().Len(); i++ {
params = append(params, ¶meter{
obj: sig.Params().At(i),
fieldType: types[i],
info: callee.Params[len(params)],
})
}
// Variadic function?
//
// There are three possible types of call:
// - ordinary f(a1, ..., aN)
// - ellipsis f(a1, ..., slice...)
// - spread f(recv?, g()) where g() is a tuple.
// The first two are desugared to non-variadic calls
// with an ordinary slice parameter;
// the third is tricky and cannot be reduced, and (if
// a receiver is present) cannot even be literalized.
// Fortunately it is vanishingly rare.
//
// TODO(adonovan): extract this to a function.
if sig.Variadic() {
lastParam := last(params)
if len(args) > 0 && last(args).spread {
// spread call to variadic: tricky
lastParam.variadic = true
} else {
// ordinary/ellipsis call to variadic
// simplify decl: func(T...) -> func([]T)
lastParamField := last(calleeDecl.Type.Params.List)
lastParamField.Type = &ast.ArrayType{
Elt: lastParamField.Type.(*ast.Ellipsis).Elt,
}
if caller.Call.Ellipsis.IsValid() {
// ellipsis call: f(slice...) -> f(slice)
// nop
} else {
// ordinary call: f(a1, ... aN) -> f([]T{a1, ..., aN})
n := len(params) - 1
ordinary, extra := args[:n], args[n:]
var elts []ast.Expr
pure, effects := true, false
for _, arg := range extra {
elts = append(elts, arg.expr)
pure = pure && arg.pure
effects = effects || arg.effects
}
args = append(ordinary, &argument{
expr: &ast.CompositeLit{
Type: lastParamField.Type,
Elts: elts,
},
typ: lastParam.obj.Type(),
constant: nil,
pure: pure,
effects: effects,
duplicable: false,
freevars: nil, // not needed
})
}
}
}
}
// Log effective arguments.
for i, arg := range args {
logf("arg #%d: %s pure=%t effects=%t duplicable=%t free=%v type=%v",
i, debugFormatNode(caller.Fset, arg.expr),
arg.pure, arg.effects, arg.duplicable, arg.freevars, arg.typ)
}
// Note: computation below should be expressed in terms of
// the args and params slices, not the raw material.
// Perform parameter substitution.
// May eliminate some elements of params/args.
substitute(logf, caller, params, args, callee.Effects, callee.Falcon, replaceCalleeID)
// Update the callee's signature syntax.
updateCalleeParams(calleeDecl, params)
// Create a var (param = arg; ...) decl for use by some strategies.
bindingDeclStmt := createBindingDecl(logf, caller, args, calleeDecl, callee.Results)
var remainingArgs []ast.Expr
for _, arg := range args {
if arg != nil {
remainingArgs = append(remainingArgs, arg.expr)
}
}
// -- let the inlining strategies begin --
//
// When we commit to a strategy, we log a message of the form:
//
// "strategy: reduce expr-context call to { return expr }"
//
// This is a terse way of saying:
//
// we plan to reduce a call
// that appears in expression context
// to a function whose body is of the form { return expr }
// TODO(adonovan): split this huge function into a sequence of
// function calls with an error sentinel that means "try the
// next strategy", and make sure each strategy writes to the
// log the reason it didn't match.
// Special case: eliminate a call to a function whose body is empty.
// (=> callee has no results and caller is a statement.)
//
// func f(params) {}
// f(args)
// => _, _ = args
//
if len(calleeDecl.Body.List) == 0 {
logf("strategy: reduce call to empty body")
// Evaluate the arguments for effects and delete the call entirely.
stmt := callStmt(caller.path, false) // cannot fail
res.old = stmt
if nargs := len(remainingArgs); nargs > 0 {
// Emit "_, _ = args" to discard results.
// TODO(adonovan): if args is the []T{a1, ..., an}
// literal synthesized during variadic simplification,
// consider unwrapping it to its (pure) elements.
// Perhaps there's no harm doing this for any slice literal.
// Make correction for spread calls
// f(g()) or recv.f(g()) where g() is a tuple.
if last := last(args); last != nil && last.spread {
nspread := last.typ.(*types.Tuple).Len()
if len(args) > 1 { // [recv, g()]
// A single AssignStmt cannot discard both, so use a 2-spec var decl.
res.new = &ast.GenDecl{
Tok: token.VAR,
Specs: []ast.Spec{
&ast.ValueSpec{
Names: []*ast.Ident{makeIdent("_")},
Values: []ast.Expr{args[0].expr},
},
&ast.ValueSpec{
Names: blanks[*ast.Ident](nspread),
Values: []ast.Expr{args[1].expr},
},
},
}
return res, nil
}
// Sole argument is spread call.
nargs = nspread
}
res.new = &ast.AssignStmt{
Lhs: blanks[ast.Expr](nargs),
Tok: token.ASSIGN,
Rhs: remainingArgs,
}
} else {
// No remaining arguments: delete call statement entirely
res.new = &ast.EmptyStmt{}
}
return res, nil
}
// If all parameters have been substituted and no result
// variable is referenced, we don't need a binding decl.
// This may enable better reduction strategies.
allResultsUnreferenced := forall(callee.Results, func(i int, r *paramInfo) bool { return len(r.Refs) == 0 })
needBindingDecl := !allResultsUnreferenced ||
exists(params, func(i int, p *parameter) bool { return p != nil })
// The two strategies below overlap for a tail call of {return exprs}:
// The expr-context reduction is nice because it keeps the
// caller's return stmt and merely switches its operand,
// without introducing a new block, but it doesn't work with
// implicit return conversions.
//
// TODO(adonovan): unify these cases more cleanly, allowing return-
// operand replacement and implicit conversions, by adding
// conversions around each return operand (if not a spread return).
// Special case: call to { return exprs }.
//
// Reduces to:
// { var (bindings); _, _ = exprs }
// or _, _ = exprs
// or expr
//
// If:
// - the body is just "return expr" with trivial implicit conversions,
// or the caller's return type matches the callee's,
// - all parameters and result vars can be eliminated
// or replaced by a binding decl,
// then the call expression can be replaced by the
// callee's body expression, suitably substituted.
if len(calleeDecl.Body.List) == 1 &&
is[*ast.ReturnStmt](calleeDecl.Body.List[0]) &&
len(calleeDecl.Body.List[0].(*ast.ReturnStmt).Results) > 0 { // not a bare return
results := calleeDecl.Body.List[0].(*ast.ReturnStmt).Results
context := callContext(caller.path)
// statement context
if stmt, ok := context.(*ast.ExprStmt); ok &&
(!needBindingDecl || bindingDeclStmt != nil) {
logf("strategy: reduce stmt-context call to { return exprs }")
clearPositions(calleeDecl.Body)
if callee.ValidForCallStmt {
logf("callee body is valid as statement")
// Inv: len(results) == 1
if !needBindingDecl {
// Reduces to: expr
res.old = caller.Call
res.new = results[0]
} else {
// Reduces to: { var (bindings); expr }
res.old = stmt
res.new = &ast.BlockStmt{
List: []ast.Stmt{
bindingDeclStmt,
&ast.ExprStmt{X: results[0]},
},
}
}
} else {
logf("callee body is not valid as statement")
// The call is a standalone statement, but the
// callee body is not suitable as a standalone statement
// (f() or <-ch), explicitly discard the results:
// Reduces to: _, _ = exprs
discard := &ast.AssignStmt{
Lhs: blanks[ast.Expr](callee.NumResults),
Tok: token.ASSIGN,
Rhs: results,
}
res.old = stmt
if !needBindingDecl {
// Reduces to: _, _ = exprs
res.new = discard
} else {
// Reduces to: { var (bindings); _, _ = exprs }
res.new = &ast.BlockStmt{
List: []ast.Stmt{
bindingDeclStmt,
discard,
},
}
}
}
return res, nil
}
// expression context
if !needBindingDecl {
clearPositions(calleeDecl.Body)
if callee.NumResults == 1 {
logf("strategy: reduce expr-context call to { return expr }")
// (includes some simple tail-calls)
// Make implicit return conversion explicit.
if callee.TrivialReturns < callee.TotalReturns {
results[0] = convert(calleeDecl.Type.Results.List[0].Type, results[0])
}
res.old = caller.Call
res.new = results[0]
return res, nil
} else if callee.TrivialReturns == callee.TotalReturns {
logf("strategy: reduce spread-context call to { return expr }")
// There is no general way to reify conversions in a spread
// return, hence the requirement above.
//
// TODO(adonovan): allow this reduction when no
// conversion is required by the context.
// The call returns multiple results but is
// not a standalone call statement. It must
// be the RHS of a spread assignment:
// var x, y = f()
// x, y := f()
// x, y = f()
// or the sole argument to a spread call:
// printf(f())
// or spread return statement:
// return f()
res.old = context
switch context := context.(type) {
case *ast.AssignStmt:
// Inv: the call must be in Rhs[0], not Lhs.
assign := shallowCopy(context)
assign.Rhs = results
res.new = assign
case *ast.ValueSpec:
// Inv: the call must be in Values[0], not Names.
spec := shallowCopy(context)
spec.Values = results
res.new = spec
case *ast.CallExpr:
// Inv: the call must be in Args[0], not Fun.
call := shallowCopy(context)
call.Args = results
res.new = call
case *ast.ReturnStmt:
// Inv: the call must be Results[0].
ret := shallowCopy(context)
ret.Results = results
res.new = ret
default:
return nil, fmt.Errorf("internal error: unexpected context %T for spread call", context)
}
return res, nil
}
}
}
// Special case: tail-call.
//
// Inlining:
// return f(args)
// where:
// func f(params) (results) { body }
// reduces to:
// { var (bindings); body }
// { body }
// so long as:
// - all parameters can be eliminated or replaced by a binding decl,
// - call is a tail-call;
// - all returns in body have trivial result conversions,
// or the caller's return type matches the callee's,
// - there is no label conflict;
// - no result variable is referenced by name,
// or implicitly by a bare return.
//
// The body may use defer, arbitrary control flow, and
// multiple returns.
//
// TODO(adonovan): add a strategy for a 'void tail
// call', i.e. a call statement prior to an (explicit
// or implicit) return.
if ret, ok := callContext(caller.path).(*ast.ReturnStmt); ok &&
len(ret.Results) == 1 &&
tailCallSafeReturn(caller, calleeSymbol, callee) &&
!callee.HasBareReturn &&
(!needBindingDecl || bindingDeclStmt != nil) &&
!hasLabelConflict(caller.path, callee.Labels) &&
allResultsUnreferenced {
logf("strategy: reduce tail-call")
body := calleeDecl.Body
clearPositions(body)
if needBindingDecl {
body.List = prepend(bindingDeclStmt, body.List...)
}
res.old = ret
res.new = body
return res, nil
}
// Special case: call to void function
//
// Inlining:
// f(args)
// where:
// func f(params) { stmts }
// reduces to:
// { var (bindings); stmts }
// { stmts }
// so long as:
// - callee is a void function (no returns)
// - callee does not use defer
// - there is no label conflict between caller and callee
// - all parameters and result vars can be eliminated
// or replaced by a binding decl,
// - caller ExprStmt is in unrestricted statement context.
if stmt := callStmt(caller.path, true); stmt != nil &&
(!needBindingDecl || bindingDeclStmt != nil) &&
!callee.HasDefer &&
!hasLabelConflict(caller.path, callee.Labels) &&
callee.TotalReturns == 0 {
logf("strategy: reduce stmt-context call to { stmts }")
body := calleeDecl.Body
var repl ast.Stmt = body
clearPositions(repl)
if needBindingDecl {
body.List = prepend(bindingDeclStmt, body.List...)
}
res.old = stmt
res.new = repl
return res, nil
}
// TODO(adonovan): parameterless call to { stmts; return expr }
// from one of these contexts:
// x, y = f()
// x, y := f()
// var x, y = f()
// =>
// var (x T1, y T2); { stmts; x, y = expr }
//