Skip to content

go/types: add Info.ImplicitConversions mapping #70638

@adonovan

Description

@adonovan

Background: One of the many tricky subtasks of the type checker is to compute the conversions implicitly applied to an expression that is used on the right-hand side of an assignment (or passed as an argument, etc), arithmetic, and shifts. This information is hard to compute and useful to clients. Our refactoring tools have needed this information on several occasions.

For example:

  • The golang.org/x/tools/refactor/satisfy package tries to find all conversions to an interface type by reimplementing the logic from the type checker. This is necessary so that the renaming tool can detect when a method renaming would cause a type to no longer implement an interface that is necessary for compilation to succeed.
  • The inliner needs to know about implicit conversions in several places. For instance, it needs to know, in a call f(x) to func f(y Y) { g(y) }, whether it is safe to elide the implicit conversion Y(x), and this depends on both the implicit conversion from x to Y and on the implicit conversion from y to g's parameter type. Ascertaining that x and y are both subject to implicit conversions in general requires logic of many cases (duplicating the type checker), and is further complicated by the loss of untyped type information when x is a constant.

Proposal: We add a new field to types.Info to record all implicit conversions.

package types

type Info struct {
    // ImplicitConversions records, for an expression appearing in (say) an assignment
    // context, any implicit conversion applied to it.
    ImplicitConversions map[ast.Expr]ImplicitConversion
}

type ImplicitConversion struct {
    // From records the original type of the expression, and To records the type of the "hole".
    // (For historical reasons [1], 'from' is not necessarily the same as the type recorded
    // Info.Types for the expression: the latter includes untyped-to-typed conversions.)
    From, To types.Type
}

[1] historical reasons

Related:

@findleyr @timothy-king @griesemer

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Accepted

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions