yaegi icon indicating copy to clipboard operation
yaegi copied to clipboard

using reflection, cannot get name of type declared inside Eval'uated code

Open en-vee opened this issue 5 years ago • 6 comments

Hi, My aim is to provide a plugin interface for my application where the plugin source code looks like below :

plugin.go

package my

type M1 struct {
    X int
}

func (m *M1) Key() int {
    return 100
}

func F1() (interface{}, error) {
   m1 := &M1{}
   m1.X = 20
   return m1,nil
}

In my application code which reads the above plugin code, I do the following :

package main

type Keyer interface {
     Key() int
}

func main() {
     ip := interp.New(interp.Options{})
     ip.Use(stdlib.Symbols)
     _, err := ip.Eval(src) // Note : src is the contents of the above plugin.go file
     v, err := ip.Eval("my.F1")
     F1 := v.Interface().(func() (interface{}, error))
     m1, err = F1()
     keyer, ok := m1.(Keyer)     
    fmt.Println(ok)     // At this point ok = false
}

Expected result: Expected ok = true as m1 implements the Key() method as shown in plugin.go

Got: ok=false

Also, when I do fmt.Println(reflect.TypeOf(m1)), I just get *struct { X int }

Why do I not get the name *my.M printed using the reflection API ?

I guess if I am able to type-assert on the Keyer interface successfully, even that should solve my problems.

I see great potential in using yaegi as an embedded plugin framework.

Please help me achieve my goal of being able to invoke methods on the type defined in my interpreted/plugin Go source code above.

Or alternatively, any way of determining the plugin/interperted code defined type name using reflection.

en-vee avatar Nov 05 '20 23:11 en-vee

Basically, it appears that any reflect.Value which is returned by the interpreter.Eval method does not retain the type information for custom types. It only does so for the ones which are part of stdlib.

en-vee avatar Nov 06 '20 02:11 en-vee

Any comments friends ?

en-vee avatar Nov 06 '20 22:11 en-vee

Similar as #939.

mvertes avatar Nov 09 '20 16:11 mvertes

thank you very much @mvertes any estimate by when this will be fixed ? or how complex this is ?

en-vee avatar Nov 10 '20 01:11 en-vee

@en-vee btw, aside from the problems of making the interfaces cross boundaries between the evaled code, and the caller, there were some unsupported cases regarding type assertions so far (which have just been fixed). So what you're trying to do is still hard/not possible for now, but at least it won't fail because of these cases.

mpl avatar Dec 03 '20 11:12 mpl

@mpl thanks for that. I'll give this a go.

en-vee avatar Dec 06 '20 02:12 en-vee