Skip to content

Commit 59d5230

Browse files
adonovangopherbot
authored andcommitted
gopls/internal/golang: fix panic in inlineOneVariable
I excluded selectors expr.field and expr.method, but forgot about field references {field: ...} in composite literals, which are of course also non-lexical references. + regression test For golang/go#74347 Change-Id: I3edb148c1be88314a29dc004e5b07c48a2be58b8 Reviewed-on: https://go-review.googlesource.com/c/tools/+/711860 LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Auto-Submit: Alan Donovan <adonovan@google.com> Reviewed-by: Madeline Kalil <mkalil@google.com>
1 parent 9bc1825 commit 59d5230

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

gopls/internal/golang/inline.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,10 +240,14 @@ func inlineVariableOne(pkg *cache.Package, pgf *parsego.File, start, end token.P
240240
if obj1 == nil {
241241
continue // undefined; or a def, not a use
242242
}
243+
if v, ok := obj1.(*types.Var); ok && v.IsField() {
244+
continue // a field reference T{F: 0} is non-lexical
245+
}
243246
if internalastutil.NodeContains(curRHS.Node(), obj1.Pos()) {
244247
continue // not free (id is defined within RHS)
245248
}
246249
_, obj2 := scope.LookupParent(id.Name, pos)
250+
// Inv: obj2 is non-nil.
247251
if obj1 != obj2 {
248252
return nil, nil, fmt.Errorf("cannot inline variable: its initializer expression refers to %q, which is shadowed by the declaration at line %d", id.Name, safetoken.Position(pgf.Tok, obj2.Pos()).Line)
249253
}

gopls/internal/test/marker/testdata/codeaction/inline-var-74347.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
This is a regressoon test of a crash in refactor.inline.variable.
1+
This is a regression test of a crash in refactor.inline.variable.
22

33
-- go.mod --
44
module example.com/a
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
This is regression test of a second crash in
2+
refactor.inline.variable covered by #74347.
3+
4+
-- go.mod --
5+
module example.com/a
6+
go 1.18
7+
8+
-- a/a.go --
9+
package a
10+
11+
func _() {
12+
type S struct{ F int }
13+
x := S{F: 0}
14+
_ = x //@codeaction("x", "refactor.inline.variable", result=out)
15+
}
16+
17+
-- @out/a/a.go --
18+
package a
19+
20+
func _() {
21+
type S struct{ F int }
22+
x := S{F: 0}
23+
_ = S{F: 0} //@codeaction("x", "refactor.inline.variable", result=out)
24+
}
25+

0 commit comments

Comments
 (0)