]> Cypherpunks.ru repositories - gostls13.git/commit
go/types, types2: reverse inference of function type arguments
authorRobert Griesemer <gri@golang.org>
Mon, 13 Mar 2023 23:38:14 +0000 (16:38 -0700)
committerGopher Robot <gobot@golang.org>
Wed, 29 Mar 2023 20:53:08 +0000 (20:53 +0000)
commitcc048b32f3de4168de6b0207fd01c65e51d37ac0
treea8dc26316b4550692afb9acb97c88485e5c85451
parent93b3035dbbcd21c1d0538142cba4e7f79631e7a2
go/types, types2: reverse inference of function type arguments

This CL implements type inference for generic functions used in
assignments: variable init expressions, regular assignments, and
return statements, but (not yet) function arguments passed to
functions. For instance, given a generic function

        func f[P any](x P)

and a variable of function type

        var v func(x int)

the assignment

        v = f

is valid w/o explicit instantiation of f, and the missing type
argument for f is inferred from the type of v. More generally,
the function f may have multiple type arguments, and it may be
partially instantiated.

This new form of inference is not enabled by default (it needs
to go through the proposal process first). It can be enabled
by setting Config.EnableReverseTypeInference.

The mechanism is implemented as follows:

- The various expression evaluation functions take an additional
  (first) argument T, which is the target type for the expression.
  If not nil, it is the type of the LHS in an assignment.

- The method Checker.funcInst is changed such that it uses both,
  provided type arguments (if any), and a target type (if any)
  to augment type inference.

Change-Id: Idfde61078e1ee4f22abcca894a4c84d681734ff6
Reviewed-on: https://go-review.googlesource.com/c/go/+/476075
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Run-TryBot: Robert Griesemer <gri@google.com>
23 files changed:
src/cmd/compile/internal/types2/api.go
src/cmd/compile/internal/types2/assignments.go
src/cmd/compile/internal/types2/builtins.go
src/cmd/compile/internal/types2/call.go
src/cmd/compile/internal/types2/check_test.go
src/cmd/compile/internal/types2/decl.go
src/cmd/compile/internal/types2/expr.go
src/cmd/compile/internal/types2/index.go
src/cmd/compile/internal/types2/stmt.go
src/cmd/compile/internal/types2/typexpr.go
src/go/types/api.go
src/go/types/assignments.go
src/go/types/builtins.go
src/go/types/call.go
src/go/types/check_test.go
src/go/types/decl.go
src/go/types/eval.go
src/go/types/expr.go
src/go/types/index.go
src/go/types/stmt.go
src/go/types/typexpr.go
src/internal/types/testdata/examples/inference.go
src/internal/types/testdata/examples/inference2.go [new file with mode: 0644]