Skip to content

Commit

Permalink
Fix uber-go#82 Match 1 or more returned values, Stricter
Browse files Browse the repository at this point in the history
  • Loading branch information
lverma14 committed Aug 21, 2023
1 parent 94feab3 commit 4770605
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
37 changes: 37 additions & 0 deletions internal/engine/reflect_match.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ package engine

import (
"go/ast"
"go/token"
"reflect"

"github.com/uber-go/gopatch/internal/data"
Expand Down Expand Up @@ -146,13 +147,49 @@ func (c *matcherCompiler) compileStruct(v reflect.Value) Matcher {
}
}

// Checks for special case of matching 1 return value w/o () against (...)
// the matcher expects a bracket but got i.e. the target node has none
func checkElision(got reflect.Value, m StructMatcher, i int) bool {
var ok bool
f := got.Field(i).Interface().(token.Pos)
// if current f is PositionMatcher and next Matcher is a SliceDotsMatcher
// then we should return true without modifying the data
// i.e. (...
if i+1 < len(m.Fields) {
if i+1 < len(m.Fields) {
if _, ok := m.Fields[i+1].(SliceDotsMatcher); ok && !f.IsValid() {
return true
}
}
}
// if current f is PosMatcher and previos Matcher is a SliceDotsMatcher
// then we should return true without modifying the data
// i.e. ...)
if i > 1 {
if _, ok = m.Fields[i-1].(SliceDotsMatcher); ok && !f.IsValid() {
return true
}
}
return false
}

// Match matches a struct.
func (m StructMatcher) Match(got reflect.Value, d data.Data, r Region) (data.Data, bool) {
if m.Type != got.Type() {
return d, false
}

for i, f := range m.Fields {
var ok bool
// checks for special case of matching elision against 1
// return value without paranthesis
if _, check := f.(PosMatcher); check && checkElision(got, m, i) {
// Return truw without modifying data d and move to
// next matcher
ok = true
continue
}

d, ok = f.Match(got.Field(i), d, r)
if !ok {
return d, false
Expand Down
8 changes: 8 additions & 0 deletions testdata/patch/return_elision.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Elision on function return argument
@@
@@
func f() (...) {
- fmt.Println("")
+ fmt.Println("hello")
...
}
13 changes: 13 additions & 0 deletions testdata/test_files/test_return_elision.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package test_files

import "fmt"

func f() string {
fmt.Println("")
return ""
}

func main() {
str := f()
fmt.Println(str)
}

0 comments on commit 4770605

Please sign in to comment.