Skip to content

Commit

Permalink
coroc: better handle chained function calls (#100)
Browse files Browse the repository at this point in the history
This fixes some odd expression decomposition I noticed. In the worst
case (all functions in the chain may yield), a chain like
`time.Now().UTC()` is decomposed to:

```go
{
    _v2 := time.Now
    _v1 := _v2()
    _v0 := _v1.UTC
    _v0()
}
```

Although this is technically correct, it can cause issues with
serialization because the function types aren't necessarily registered.

This PR improves the handling of `ast.CallExpr` + `ast.SelectorExpr` so
that we instead get the following (in the worst case):

```go
{
    _v0 := time.Now()
    _v0.UTC()
}
```
  • Loading branch information
chriso authored Oct 13, 2023
2 parents fe62e2e + c9fed4e commit bca5511
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
12 changes: 10 additions & 2 deletions compiler/desugar.go
Original file line number Diff line number Diff line change
Expand Up @@ -767,11 +767,15 @@ const (
)

func (d *desugarer) mayYield(n ast.Node) bool {
switch n.(type) {
switch x := n.(type) {
case nil:
return false
case *ast.BasicLit, *ast.FuncLit, *ast.Ident:
return false
case *ast.SelectorExpr:
if _, ok := x.X.(*ast.Ident); ok {
return false
}
case *ast.ArrayType, *ast.ChanType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.StructType:
return false
}
Expand Down Expand Up @@ -820,7 +824,11 @@ func (d *desugarer) decomposeExpression(expr ast.Expr, flags exprFlags) (ast.Exp
continue
}
}
e.Fun = decompose(e.Fun)
if se, ok := e.Fun.(*ast.SelectorExpr); ok && d.mayYield(se.X) {
se.X = decompose(se.X)
} else {
e.Fun = decompose(e.Fun)
}
for i, arg := range e.Args {
e.Args[i] = decompose(arg)
}
Expand Down
10 changes: 10 additions & 0 deletions compiler/desugar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1134,6 +1134,16 @@ defer func() {
foo(_v0, _v1)
}()
}
`,
},
{
name: "repeated function calls",
body: "time.Now().UTC()",
expect: `
{
_v0 := time.Now()
_v0.UTC()
}
`,
},
} {
Expand Down

0 comments on commit bca5511

Please sign in to comment.