Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- On Windows, the `codegraph` command in Git Bash now works in a terminal that turns off path conversion with `MSYS_NO_PATHCONV=1` or `MSYS2_ARG_CONV_EXCL=*`, as some agent harnesses do, instead of failing with "Cannot find module". Thanks @BlueberryDuck for the report. (#3464)
- On projects with fewer than 500 files, every tool named in `CODEGRAPH_MCP_TOOLS` is now listed to the agent, instead of only the small-repo defaults. Thanks @nchrisr for the report and the fix. (#3462)
- `codegraph callers` and `codegraph_callers` list callers outside tests before tests, so a symbol called mostly from tests no longer shows only tests under the default limit while its real callers are cut. Thanks @blairjordan for the report and the fix. (#3456)
- In Go, a variable given a one-line chain that starts with `new(T)`, `make(T)` or a struct literal, like `sub := new(Route).Host("x").Subrouter()`, now has the type the chain returns, so a method called on it links to that type's method, not to a same-named method of the type the chain starts from. Thanks @inth3shadows for the report and the analysis. (#3447)

## [1.6.4] - 2026-11-20

Expand Down
261 changes: 261 additions & 0 deletions __tests__/go-chain-head-locals.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
/**
* A Go local given a chain that starts with `new(T)` or a composite literal
* has the type the chain's last call returns, not T (#3447). `sub :=
* new(Route).Host("x").Subrouter()` is a `*Router`, but the local was typed
* by the start of its value alone, `new(Route)`, so `sub.Path("/a")` reached
* `Route`'s `Path`: gorilla/mux's subrouter tests are written this way. Only
* a value that is the `new(T)` or the literal and nothing more types the
* local by what it writes; a chain is read like any other call's result. A
* chain broken after the `.` is left as it was, typed by its first line.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import CodeGraph from '../src/index';

const FILES: Record<string, string> = {
'go.mod': 'module example.com/p\n\ngo 1.22\n',
'a_router.go': `package p

type Router struct{}

func (r *Router) Path(p string) *Route { return &Route{} }
`,
'b_route.go': `package p

type Route struct{}

func (r *Route) Path(p string) *Route { return r }

func (r *Route) Host(h string) *Route { return r }

func (r *Route) Subrouter() *Router { return &Router{} }

func NewRoute() *Route { return &Route{} }

type Plain struct{ Name string }

func (p Plain) Path(s string) Plain { return p }

func (p Plain) Router() *Router { return &Router{} }

type Set map[string]struct{}

func (s Set) Path(k string) Set { return s }

func (s Set) Router() *Router { return &Router{} }
`,
'use.go': `package p

func fromNew() {
sub := new(Route).Host("x").Subrouter()
sub.Path("/a")
}

func fromNewShort() {
sub := new(Route).Subrouter()
sub.Path("/a")
}

func fromNewBroken() {
sub := new(Route).
Host("x").
Subrouter()
sub.Path("/a")
}

func builderBroken() {
b := new(Route).
Host("x")
b.Path("/a")
}

func builderBrokenCommented() {
b := new(Route). // then
Host("x")
b.Path("/a")
}

func fromLiteralBroken() {
sub := Plain{}.
Router()
sub.Path("/a")
}

func fromFilledLiteralBroken() {
sub := Plain{
Name: "x",
}.
Router()
sub.Path("/a")
}

func fromHeader() {
if sub := new(Route).Subrouter(); sub != nil {
sub.Path("/a")
}
}

func fromVar() {
var sub = new(Route).Subrouter()
sub.Path("/a")
}

func fromFuncBroken() {
sub := NewRoute().
Host("x").
Subrouter()
sub.Path("/a")
}

func fromNewSpaced() {
sub := new(Route) .Subrouter()
sub.Path("/a")
}

func fromMake() {
sub := make(Set).Router()
sub.Path("/a")
}

func fromValueLiteral() {
sub := Plain{}.Router()
sub.Path("/a")
}

func fromFilledLiteral() {
sub := Plain{
Name: "x",
}.Router()
sub.Path("/a")
}

func fromLiteral() {
sub := (&Route{}).Host("x").Subrouter()
sub.Path("/a")
}

func fromFunc() {
sub := NewRoute().Host("x").Subrouter()
sub.Path("/a")
}

func fromLocal() {
rt := new(Route)
sub := rt.Subrouter()
sub.Path("/a")
}

func plainNew() {
x := new(Route)
x.Path("/a")
}

func plainPointerLiteral() {
x := &Route{}
x.Path("/a")
}

func plainValueLiteral() {
x := Plain{}
x.Path("/a")
}

func plainFilledLiteral() {
x := Plain{
Name: "x",
}
x.Path("/a")
}
`,
};

describe.each(['default', 'wasm'])('a Go local given a chain is typed by what the chain returns (%s)', (backend) => {
let root = '';
let cg: CodeGraph | undefined;
let kernel: string | undefined;

beforeAll(async () => {
kernel = process.env.CODEGRAPH_KERNEL;
if (backend === 'wasm') process.env.CODEGRAPH_KERNEL = '0';
else delete process.env.CODEGRAPH_KERNEL;
root = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-chain-head-'));
for (const [rel, content] of Object.entries(FILES)) {
fs.writeFileSync(path.join(root, rel), content);
}
cg = await CodeGraph.init(root, { index: true });
}, 60_000);

afterAll(() => {
cg?.close();
if (root) fs.rmSync(root, { recursive: true, force: true });
if (kernel === undefined) delete process.env.CODEGRAPH_KERNEL;
else process.env.CODEGRAPH_KERNEL = kernel;
});

/** The `Path` methods the function `name` in use.go calls, as `<file>::<qualified name>`. */
function pathCalls(name: string): string[] {
const fn = cg!.getNodesInFile('use.go').find((n) => n.name === name && n.kind === 'function');
expect(fn, name).toBeDefined();
return cg!
.getOutgoingEdges(fn!.id)
.filter((e) => e.kind === 'calls')
.map((e) => cg!.getNode(e.target)!)
.filter((n) => n.name === 'Path')
.map((n) => `${n.filePath}::${n.qualifiedName}`)
.sort();
}

const ROUTER = ['a_router.go::Router::Path'];

it("types the issue's `new(Route)…Subrouter()` locals as the Router the chain returns", () => {
expect(pathCalls('fromNew')).toEqual(ROUTER);
expect(pathCalls('fromNewShort')).toEqual(ROUTER);
});

it('reads a chain written with a space before its `.`', () => {
expect(pathCalls('fromNewSpaced')).toEqual(ROUTER);
});

it('reads a chain in an `if` header and in a `var` declaration', () => {
expect(pathCalls('fromHeader')).toEqual(ROUTER);
expect(pathCalls('fromVar')).toEqual(ROUTER);
});

it('types a chain broken after the `.` by its start, as before: right when the chain returns that type', () => {
expect(pathCalls('builderBroken')).toEqual(['b_route.go::Route::Path']);
expect(pathCalls('builderBrokenCommented')).toEqual(['b_route.go::Route::Path']);
});

// Not fixed here: a `:=` value is read to its line's end, so these keep the
// type their first line writes, and a function's broken chain has none.
it('leaves a broken chain that returns another type as it was', () => {
expect(pathCalls('fromNewBroken')).toEqual(['b_route.go::Route::Path']);
expect(pathCalls('fromLiteralBroken')).toEqual(['b_route.go::Plain::Path']);
expect(pathCalls('fromFilledLiteralBroken')).toEqual(['b_route.go::Plain::Path']);
expect(pathCalls('fromFuncBroken')).toEqual([]);
});

it('reads a chain that starts with `make(T)` the same way', () => {
expect(pathCalls('fromMake')).toEqual(ROUTER);
});

it('reads a chain that starts with a composite literal, on one line or several', () => {
expect(pathCalls('fromValueLiteral')).toEqual(ROUTER);
expect(pathCalls('fromFilledLiteral')).toEqual(ROUTER);
});

it('leaves the chains that already resolved as they were', () => {
expect(pathCalls('fromLiteral')).toEqual(ROUTER);
expect(pathCalls('fromFunc')).toEqual(ROUTER);
expect(pathCalls('fromLocal')).toEqual(ROUTER);
});

it('still types a local by the `new(T)` or the literal that is its whole value', () => {
expect(pathCalls('plainNew')).toEqual(['b_route.go::Route::Path']);
expect(pathCalls('plainPointerLiteral')).toEqual(['b_route.go::Route::Path']);
expect(pathCalls('plainValueLiteral')).toEqual(['b_route.go::Plain::Path']);
expect(pathCalls('plainFilledLiteral')).toEqual(['b_route.go::Plain::Path']);
});
});
31 changes: 23 additions & 8 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3723,8 +3723,19 @@ function readGoScopes(code: string): GoScopeIndex {
// declare; `x := pkg.New(…)` the package its value comes from, `x :=
// newStore(…)` the function of its own package.
const rhs = code.slice(i + 2, i + 160);
const literal = /^[ \t]*&?[ \t]*((?:[A-Za-z_]\w*\.)?[A-Za-z_]\w*)[ \t]*\{/.exec(rhs)?.[1] ??
/^[ \t]*new\([ \t]*((?:[A-Za-z_]\w*\.)?[A-Za-z_]\w*)[ \t]*\)/.exec(rhs)?.[1];
const written = /^[ \t]*&?[ \t]*((?:[A-Za-z_]\w*\.)?[A-Za-z_]\w*)[ \t]*\{/.exec(rhs) ??
/^[ \t]*new\([ \t]*((?:[A-Za-z_]\w*\.)?[A-Za-z_]\w*)[ \t]*\)/.exec(rhs);
// A selector after the literal or the `new(T)` makes it the start of a
// chain, `new(Route).Host("x").Subrouter()`: the local has the type the
// chain gives, read with its value like any call's result (#3447). Not
// when the line ends at the `.`: a value is read to its line's end, so a
// chain broken there keeps the type its first line writes.
let after = i + 1 + (written?.[0].length ?? 0);
if (written && code[after] === '{') after = close.get(after) ?? code.length;
do after++; while (code[after] === ' ' || code[after] === '\t');
const onward = /\.[ \t]*\S/y;
onward.lastIndex = after;
const literal = onward.test(code) ? undefined : written?.[1];
const type = names.length === 1 && literal && !GO_TYPE_KEYWORDS.has(literal) ? literal : undefined;
const from = /^[ \t]*&?[ \t]*([A-Za-z_]\w*)\.[A-Za-z_]\w*[ \t]*[({]/.exec(rhs)?.[1];
const call = from ? undefined : /^[ \t]*([A-Za-z_]\w*)[ \t]*(?:\[(?:[^[\]\n]|\[[^[\]\n]*\])*\][ \t]*)?\(/.exec(rhs)?.[1];
Expand Down Expand Up @@ -30644,8 +30655,9 @@ function goMethodOnElement(t: GoTypeText, ref: UnresolvedRef, context: Resolutio
/**
* Whether the value a Go declaration gives its name is a call or a
* conversion: `f(…)`, `pkg.F(…)`, `x.M(…)`, `T(x)`, `a.b().C(…)`, alone or
* as this name's place among several values (`a, b := f(), g()`). Not a
* `range` clause, a builtin's `make`/`new`/`append`, an assertion
* as this name's place among several values (`a, b := f(), g()`), a chain
* from a builtin's call too (`new(T).M()`). Not a `range` clause, a
* builtin's `make`/`new`/`append` that is the whole value, an assertion
* (goAssertedLocalType reads those) or a type switch's guard.
*/
function goValueIsCall(local: GoDecl, index: GoScopeIndex): boolean {
Expand All @@ -30658,7 +30670,10 @@ function goValueIsCall(local: GoDecl, index: GoScopeIndex): boolean {
// A type switch's guard (`switch v := x.(type)`) has each case's type, and
// an assertion (`v := x.(T)`) is goAssertedLocalType's to read.
if (/\.\s*\([^()]*(?:\([^()]*\)[^()]*)*\)\s*$/.test(value)) return false;
return /^\s*[A-Za-z_(][\s\S]*\)\s*$/.test(value) && !/^\s*(?:new|make|append)\s*\(/.test(value);
// A builtin's call that is the whole value; a chain from one is a call (#3447).
const builtin = /^\s*(?:new|make|append)\s*\(/.exec(value);
if (builtin && goClosingBracket(value, builtin[0].length - 1) === value.trimEnd().length - 1) return false;
return /^\s*[A-Za-z_(][\s\S]*\)\s*$/.test(value);
}

/**
Expand Down Expand Up @@ -31049,11 +31064,11 @@ function goExprType(
if (!t) return t;
return t.text.startsWith('*') ? { ...t, text: t.text.slice(1) } : undefined;
}
// `make(T, …)`, `new(T)`, `append(xs, …)`.
// `make(T, …)`, `new(T)`, `append(xs, …)`; a chain from one (`new(T).M()`)
// is read with the chains below.
const builtin = /^(make|new|append)\s*\(/.exec(s);
if (builtin) {
if (builtin && goClosingBracket(s, builtin[0].length - 1) === s.length - 1) {
const open = builtin[0].length - 1;
if (goClosingBracket(s, open) !== s.length - 1) return undefined;
const first = goSplitTopLevel(s.slice(open + 1, -1), ',')[0]?.trim();
if (!first) return undefined;
if (builtin[1] === 'make') return goTypeTextAt(first, filePath, at, index, context);
Expand Down