traefik / yaegi

Yaegi is Another Elegant Go Interpreter
https://pkg.go.dev/github.com/traefik/yaegi
Apache License 2.0
6.82k stars 342 forks source link

fix(interp): convert bin interface to src interface. #1562

Open laushunyu opened 1 year ago

laushunyu commented 1 year ago

fix: #1558

test case:

package main

import "fmt"

type A struct {
}

func (a A) String() string {
    return "String"
}

func (a A) GoString() string {
    return "GoString"
}

type Stringer interface {
    String() string
}

type GoStringer interface {
    GoString() string
}

func Fuck(in fmt.Stringer) {
    var a Stringer = A{}

    {
        t, ok := a.(GoStringer)
        fmt.Printf("src to src: %v\n", ok)
        if ok {
            fmt.Println(t.GoString())
        }
    }

    {
        t, ok := a.(fmt.GoStringer)
        fmt.Printf("src to src: %v\n", ok)
        if ok {
            fmt.Println(t.GoString())
        }
    }

    {
        t, ok := in.(GoStringer)
        fmt.Printf("bin to src: %v\n", ok)
        if ok {
            fmt.Println(t.GoString())
        }
    }

    {
        t, ok := in.(fmt.GoStringer)
        fmt.Printf("bin to bin: %v\n", ok)
        if ok {
            fmt.Println(t.GoString())
        }
    }
}

runner:

package main

import (
    "fmt"
    "github.com/traefik/yaegi/interp"
    "github.com/traefik/yaegi/stdlib"
    "os"
)

type B struct {
}

func (a B) String() string {
    return "String"
}

func (a B) GoString() string {
    return "GoString"
}

func main() {
    interpreter := interp.New(interp.Options{
        SourcecodeFilesystem: os.DirFS("_lib"),
    })
    interpreter.Use(stdlib.Symbols)

    _, err := interpreter.CompilePath("fuck")
    if err != nil {
        panic(err)
    }

    mainSymbols := interpreter.Symbols("fuck")["fuck"]
    fn := mainSymbols["Fuck"].Interface().(func(stringer fmt.Stringer))
    fn(B{})
}

output:

src to src: true
GoString
src to src: true
GoString
bin to src: true
GoString
bin to bin: true
GoString

it works, but i dont know whether the fix will cause more bugs....