github.com/mshitrit/go-mutesting@v0.0.0-20210528084812-ff81dcaedfea/mutator/branch/mutateelse.go (about)

     1  package branch
     2  
     3  import (
     4  	"go/ast"
     5  	"go/types"
     6  
     7  	"github.com/zimmski/go-mutesting/astutil"
     8  	"github.com/zimmski/go-mutesting/mutator"
     9  )
    10  
    11  func init() {
    12  	mutator.Register("branch/else", MutatorElse)
    13  }
    14  
    15  // MutatorElse implements a mutator for else branches.
    16  func MutatorElse(pkg *types.Package, info *types.Info, node ast.Node) []mutator.Mutation {
    17  	n, ok := node.(*ast.IfStmt)
    18  	if !ok {
    19  		return nil
    20  	}
    21  	// We ignore else ifs and nil blocks
    22  	_, ok = n.Else.(*ast.IfStmt)
    23  	if ok || n.Else == nil {
    24  		return nil
    25  	}
    26  
    27  	old := n.Else
    28  
    29  	return []mutator.Mutation{
    30  		{
    31  			Change: func() {
    32  				n.Else = astutil.CreateNoopOfStatement(pkg, info, old)
    33  			},
    34  			Reset: func() {
    35  				n.Else = old
    36  			},
    37  		},
    38  	}
    39  }