github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/starlib/starext/method.go (about) 1 package starext 2 3 import ( 4 "fmt" 5 6 "go.starlark.net/starlark" 7 ) 8 9 type BuiltinFn func(*starlark.Thread, string, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) 10 11 type Builtin struct { 12 name string 13 fn BuiltinFn 14 } 15 16 func MakeBuiltin(name string, fn BuiltinFn) Builtin { 17 return Builtin{ 18 name: name, 19 fn: fn, 20 } 21 } 22 23 func (b Builtin) Name() string { return b.name } 24 func (b Builtin) Freeze() {} // immutable 25 func (b Builtin) Hash() (uint32, error) { return starlark.String(b.name).Hash() } 26 func (b Builtin) String() string { 27 return fmt.Sprintf("<builtin_function %s>", b.Name()) 28 } 29 func (b Builtin) Type() string { return "builtin_function" } 30 func (b Builtin) Truth() starlark.Bool { return true } 31 func (b Builtin) CallInternal(thread *starlark.Thread, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { 32 return b.fn(thread, b.name, args, kwargs) 33 } 34 35 type Method struct { 36 Builtin 37 recv starlark.Value 38 } 39 40 func MakeMethod(recv starlark.Value, name string, fn BuiltinFn) Method { 41 return Method{ 42 Builtin: MakeBuiltin(name, fn), 43 recv: recv, 44 } 45 } 46 47 func (m Method) String() string { 48 return fmt.Sprintf("<builtin_method %s of %s value>", m.name, m.recv.Type()) 49 } 50 func (m Method) Type() string { return "builtin_method" } 51 func (m Method) CallInternal(thread *starlark.Thread, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { 52 return m.fn(thread, m.recv.Type()+"."+m.name, args, kwargs) 53 }