SetFunc sets the function associated with the FuncButton to the given function or method value. For documentation information for the function to be obtained, it must be added to [types].
(fun any)
| 175 | // given function or method value. For documentation information for |
| 176 | // the function to be obtained, it must be added to [types]. |
| 177 | func (fb *FuncButton) SetFunc(fun any) *FuncButton { |
| 178 | fnm := types.FuncName(fun) |
| 179 | if fnm == "" { |
| 180 | return fb.SetText("None") |
| 181 | } |
| 182 | fnm = strings.ReplaceAll(fnm, "[...]", "") // remove any labeling for generics |
| 183 | // the "-fm" suffix indicates that it is a method |
| 184 | if strings.HasSuffix(fnm, "-fm") { |
| 185 | fnm = strings.TrimSuffix(fnm, "-fm") |
| 186 | // the last dot separates the function name |
| 187 | li := strings.LastIndex(fnm, ".") |
| 188 | metnm := fnm[li+1:] |
| 189 | typnm := fnm[:li] |
| 190 | // get rid of any parentheses and pointer receivers |
| 191 | // that may surround the type name |
| 192 | typnm = strings.ReplaceAll(typnm, "(*", "") |
| 193 | typnm = strings.TrimSuffix(typnm, ")") |
| 194 | gtyp := types.TypeByName(typnm) |
| 195 | var met *types.Method |
| 196 | if gtyp == nil { |
| 197 | if fb.WarnUnadded { |
| 198 | slog.Warn("core.FuncButton.SetFunc called with a method whose receiver type has not been added to types", "function", fnm) |
| 199 | } |
| 200 | met = &types.Method{Name: metnm} |
| 201 | } else { |
| 202 | for _, m := range gtyp.Methods { |
| 203 | if m.Name == metnm { |
| 204 | met = &m |
| 205 | break |
| 206 | } |
| 207 | } |
| 208 | if met == nil { |
| 209 | if fb.WarnUnadded { |
| 210 | slog.Warn("core.FuncButton.SetFunc called with a method that has not been added to types (even though the receiver type was, you still need to add the method itself)", "function", fnm) |
| 211 | } |
| 212 | met = &types.Method{Name: metnm} |
| 213 | } |
| 214 | } |
| 215 | return fb.setMethodImpl(met, reflect.ValueOf(fun)) |
| 216 | } |
| 217 | |
| 218 | if isAnonymousFunction(fnm) { |
| 219 | f := &types.Func{Name: fnm, Doc: "Anonymous function " + fnm} |
| 220 | return fb.setFuncImpl(f, reflect.ValueOf(fun)) |
| 221 | } |
| 222 | |
| 223 | f := types.FuncByName(fnm) |
| 224 | if f == nil { |
| 225 | if fb.WarnUnadded { |
| 226 | slog.Warn("core.FuncButton.SetFunc called with a function that has not been added to types", "function", fnm) |
| 227 | } |
| 228 | f = &types.Func{Name: fnm} |
| 229 | } |
| 230 | return fb.setFuncImpl(f, reflect.ValueOf(fun)) |
| 231 | } |
| 232 | |
| 233 | func isAnonymousFunction(fnm string) bool { |
| 234 | // FuncName.funcN indicates that a function was defined anonymously |
no test coverage detected