Skip to content

Commit

Permalink
Fix method-name collisions (#17)
Browse files Browse the repository at this point in the history
* Fix a bug that caused method names to collide with other top-level identifiers.

* A little more bulletproofing.
  • Loading branch information
bobg authored Jul 1, 2023
1 parent bf5b672 commit 5eeabfa
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 3 deletions.
13 changes: 11 additions & 2 deletions compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (c *comparer) compareMajor(older, newer map[string]*packages.Package) Resul
)

for id, obj := range topObjs {
if !ast.IsExported(id) {
if !isExported(id) {
continue
}
if newPkg == nil {
Expand Down Expand Up @@ -162,7 +162,7 @@ func (c *comparer) compareMinor(older, newer map[string]*packages.Package) Resul
)

for id, obj := range topObjs {
if !ast.IsExported(id) {
if !isExported(id) {
continue
}
if oldPkg == nil {
Expand Down Expand Up @@ -352,3 +352,12 @@ func (cb cloneBugErr) Error() string {
func (cb cloneBugErr) Unwrap() error {
return cb.err
}

// Calls ast.IsExported on the final element of name
// (which may be package/type-qualified).
func isExported(name string) bool {
if i := strings.LastIndex(name, "."); i > 0 {
name = name[i+1:]
}
return ast.IsExported(name)
}
28 changes: 28 additions & 0 deletions testdata/minor/familiarmethodname.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//// -*- mode: go -*-

//// {{ define "older" }}

package familiarmethodname

type Val int

const String Val = 1

//// {{ end }}

//// {{ define "newer" }}

package familiarmethodname

type Val int

const String Val = 1

func (v *Val) String() string {
switch *v {
case String: return "string"
}
return "<unknown>"
}

//// {{ end }}
11 changes: 10 additions & 1 deletion types.go
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,16 @@ func makeTopObjs(pkg *packages.Package) map[string]types.Object {
}

case *ast.FuncDecl:
res[decl.Name.Name] = pkg.TypesInfo.Defs[decl.Name]
// If decl is a method, qualify the name with the receiver type.
name := decl.Name.Name
if decl.Recv != nil && len(decl.Recv.List) > 0 {
recv := decl.Recv.List[0].Type
if info := pkg.TypesInfo.Types[recv]; info.Type != nil {
name = types.TypeString(info.Type, types.RelativeTo(pkg.Types)) + "." + name
}
}

res[name] = pkg.TypesInfo.Defs[decl.Name]
}
}
}
Expand Down

0 comments on commit 5eeabfa

Please sign in to comment.