fix(go): type receivers from package-qualified parameters and call results; no guess for outside types

Closed
DA
1mo ago
+540-28

Rebased onto main at 8a5ba3d0 and reduced once more. #2489 now resolves a call through a parameter or local named like a standard-library package (isGoProjectLocalCall), by the variable's declaration. This PR carried its own rule for the same thing — skip pkg.X as a standard-library call only when the file imports a package under that name — and that rule is dropped in favour of #2489's: src/resolution/index.ts is untouched now, and the two "no guess for a standard-library-named local" lines in the matcher are gone. What remains is qualified parameters, call results and conversions, and "a receiver typed outside the project gets no edge".

Two things below predate this rebase and are not re-measured: the harbor figures (from ed199e60; 28 of the 478 added sites were standard-library-named variables, which are #2489's now), and the "Standard-library names" bullets in Problem and Fix, kept for the record. The test file has 20 cases, 13 of which fail on main at 8a5ba3d0; the case dropped is a standard-library-named local bound from a function-typed parameter's result (token := get(); token.LocalAddr()), which #2489 links to the project's only method of that name.


Rebased onto main at ed199e60 and reduced again to what main still lacks. #2417 gave type aliases nodes and resolves a method through them, so the alias reader this PR carried is gone with its tests. #2410 registers the name goimports assumes for an import, so the standard-library check no longer matches on path segments. What is left is one commit.

Problem

Three receiver shapes still get no type on main, and a receiver typed outside the project still gets a guess by method name:

  • A variable named like a standard-library package. ring, token, parser, user and url are on the standard-library package list, so every ring.X() is skipped as a call into that package, whether or not the file imports it. func flush(ring *ringLog) { ring.Write(b) } never resolves.
  • A package-qualified parameter or receiver type: s *store.Store.
  • A receiver bound to a call: r := newRing(), e, err := NewEngine(), s := store.NewStore(), if r := find(id); r != nil, and a conversion such as list := model.BotList(bots).
  • A receiver typed outside the project. ctx.Done() on a context.Context goes to the one project type that declares a Done, and req.WithContext(…) on an *http.Request to a project WithContext.

Fix

Resolver only, with no extraction change. The receiver scan keeps its per-line memo.

  • Standard-library names. A pkg.X reference is skipped as a standard-library call only when the file imports a package under that name. Otherwise the receiver is typed like any other. When its type can't be read it still gets no edge, as before.
  • Qualified parameters. The parameter pattern #2361 added for unexported types also reads name *pkg.Type. The package is found through the file's imports.
  • Call results. x[, err] := f(…) is typed from the first result in the callee's signature, read in the callee's file. The callee must be a function of the same package or of an imported project package, or a conversion to a project type. Two guards:
    • the call must be the whole right-hand side, so r := newRing().Reader() is not typed by newRing;
    • a call that takes the receiver itself (e := wrap(e.Run())) is skipped, because on that line e is still the outer variable.
  • Scope. The scan reads the receiver's declaration in scope and no other line (the scope index that gives a := the innermost block it is written in, which the branch already consulted for a written type). A := in a block or a function literal that closed before the call (if true { r := other.New() }, go func() { r := other.New() }()) is another variable, not the receiver's binding. (From review.)
  • A variable named like a package. x := store.New() with store a parameter, receiver or local of the function is a call on that variable, not on the imported store package: x is typed by what the method of the variable's declared type returns, and stays untyped when the declaration writes no type. (From review.)
  • Outside types. A receiver gets no edge when its declared type comes from a package outside the project's modules: conn net.Conn, ctx context.Context, req *http.Request, an alias of one, or the result of an outside function such as net.Dial(…). "Outside" is the same test main already applies to a type reference written through an import.
    • An alias of an outside type (type Ctx = context.Context) is read from the alias node #2417 added. #2417 leaves that case to a lookup by name; on main ctx.Done() on a Ctx then goes to Ctx::Done of another package when one declares a struct Ctx. The right-hand side of the declaration is read by a small helper split out of goAliasTarget, which is otherwise unchanged.
    • One exception: a project function whose result is an outside type by value (func NewRateLimitedTransport(…) http.RoundTripper) is left as it is on main. That is usually an interface a project type implements. A pointer result (*os.File) is that outside type.

Measured

goharbor/harbor at f25e9da, src/ only (1,595 Go files), indexed from scratch with builds of main ed199e60 and of this branch, native kernel. Counts are Go calls edges. A call site is a file, line, column and callee name. Both builds index it identically run to run.

mainthis branch
edges25,53825,861
call sites with an edge20,58620,909
nodes38,26438,264

Index time was 22–54 s for either build on a shared machine, with no difference I could separate from the noise.

changecall siteschecked
added47812 read, all correct
retargeted23721 read (15 spread over the target pairs, 6 from the less common ones), all correct
dropped155all classified by a script, 47 read in the source
  • Added. Typed through a call result (mgr := config.GetCfgManager(ctx), cx, exist := security.FromContext(d.Ctx), st := job.Status(ack.Status)), a qualified parameter (ctx job.Context, userMgr pkguser.Manager, resources types.ResourceList) or a variable named like a standard-library package (parser := &license{…}, context := NewSecurityContext(…); 28 of the 478).

  • Retargeted. A guess by name moved to the method of the declared type. Examples: logger := log.GetLogger(ctx) from a replication Logger::Warningf to lib/log's; ctx := NewSecurityContext(nil) from the v2token context to the local one; err := New(cause) from an allowlist error to lib/errors; client := registryclient.NewClient(…) from the unexported client::BlobExist to the Client interface the constructor returns.

  • Dropped. Every one of the 155 has a receiver declared with a type of a package outside the module, or bound to a call into one. The script reads the receiver's declaration and the file's imports independently of the resolver; it files 146 that way, and the other 9 were read by hand (an io.ReadCloser, a distribution.Manifest ×4, an http.Handler ×2, and two project functions returning *redis.Pool and *sdktrace.TracerProvider). By what main linked them to:

    receivermain's targetsites
    req.WithContext(…) on an *http.Requesta jobservice Worker::WithContext84
    w.WriteHeader(…) / w.Header() on an http.ResponseWriter, an httptest recorder, a tar.Writera project response recorder or log writer13
    man.Payload() / man.References() on a distribution.Manifesta mock under testing/11
    handler.ServeHTTP(…) on an http.Handlera registryctl blob handler8
    file.Close() on an *os.File / io.ReadClosera job logger's Close6
    client.Do / Get / Post / Head on an *http.Client and similarcommon/http's Client6
    ctx.Done() on a context.Context, wg.Done() on a sync.WaitGroupan ORM context wrapper5
    other (server.Client() on an httptest.Server, err.Error(), rootRouter.Path(…) on a gorilla router, …)22

    114 of them are concrete outside types. The other 41 are outside interfaces (http.ResponseWriter, http.Handler, distribution.Manifest, context.Context, health.Checker, io.ReadCloser, error) that main linked by name to one project type declaring the method. Two of those are arguable: checker.Check() on a health.Checker parameter (an interface of docker/distribution) went to the project's updater::Check, which is what a registered checker can be at run time. The declared type is an outside interface, so the call gets no edge, the same as ctx.Done().

Outside calls, 13 references edges are gone and nothing else changed. All 13 were read: each is a field read through a receiver that is now typed (opts.IgnoreLimitation, params.WithTag, model.AuthMode, u.ReferenceID), which main linked to a package-level function of the same name.

With #2368 merged in as well (the two touch the same condition; only CHANGELOG.md conflicts), harbor gets exactly the sum of the two changes: 25,538 → 28,537 calls edges, with the same 155 dropped and 237 retargeted sites.

Known limits

  • A method's result (x := v.Method()) and a range variable are not typed.
  • A := binding whose type can't be read leaves the receiver untyped: the scan does not fall through to an outer declaration of the same name (that would be another variable).
  • A binding from a call through a variable named like one of the file's imports (req := suite.NewRequest(…) in a method with receiver suite, beside import "github.com/stretchr/testify/suite") is typed by the method's result when the variable's declaration writes its type, and gets no edge otherwise. #2410 lists the same shadowing for qualified references.
  • Whether an import is "outside the project" follows the project's go.mod files. A project indexed below its go.mod, or with none, treats every non-relative import as outside, as main already does for type references.

Tests

__tests__/go-receiver-type.test.ts, 23 cases. On current main the three standard-library-named receivers and the package-qualified parameter already pass (they are regression guards, as review noted); the call-result, conversion, outside-type and scoping cases fail there:

  • three receivers named like a standard-library package;
  • five call bindings: unexported and exported constructors, a multi-line call, an if header, a constructor of another package;
  • a package-qualified parameter;
  • four receivers typed outside the project: a qualified pointer, a qualified interface, an outside function's result, a project function returning *os.File;
  • a conversion;
  • ctx.Done() on a context.Context;
  • ctx.Done() on an alias of context.Context, with a struct of the alias's name in another package;
  • two shadowing := bindings in a closed block and in a function literal, and a parameter named like an imported package (from review).

The five controls pass on main and here:

  • a binding is not typed by the head of a call chain, nor on its own line;
  • a variable named like a standard-library package with an unreadable type gets no edge;
  • an outside interface returned by a project function still reaches its implementation;
  • a defined type is not followed;
  • an alias of a project type still resolves on that type, as #2417 made it.

The three alias cases the previous version had (type Context = web.Context, a grouped pointer alias, an alias embedded in a struct) pass on main since #2417 and were removed.

The file passes with the native kernel and with CODEGRAPH_KERNEL=0, together with the Go suites (go-*, goframe, rust-go-call-shape, gin-middleware-chain), resolution, function-ref, member-function-ref-owner, frameworks-integration, dead-code and the receiver suites around them (27 files, 557 tests native; 18 files, 386 tests WASM).

🤖 Generated with Claude Code