github.com/haraldrudell/parl@v0.4.176/preflect/function-name.go (about)

     1  /*
     2  © 2024–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package preflect
     7  
     8  import (
     9  	"reflect"
    10  	"runtime"
    11  
    12  	"github.com/haraldrudell/parl"
    13  	"github.com/haraldrudell/parl/perrors"
    14  	"github.com/haraldrudell/parl/pruntime"
    15  )
    16  
    17  // FuncName returns information on a function value
    18  //   - funcOrMethod: non-nil function value such as:
    19  //   - — a top-level function: “func main() {”
    20  //   - — a method: “errors.New("").Error”
    21  //   - — an anonymous function: “var f = func() {}”
    22  //     returned like “SomeFunc.func1”
    23  //   - cL is a function-describing structure of basic types only
    24  //   - — [pruntime.CodeLocation.FuncIdentifier] returns the function name identifier,
    25  //     a single word
    26  //   - error is returned if:
    27  //   - — funcOrMethod is nil or not a function value
    28  //   - — function value retrieval failed in runtime
    29  func FuncName(funcOrMethod any) (cL *pruntime.CodeLocation, err error) {
    30  
    31  	// funcOrMethod cannot be nil
    32  	if funcOrMethod == nil {
    33  		err = parl.NilError("funcOrMethod")
    34  		return
    35  	}
    36  
    37  	// funcOrMethod must be underlying type func
    38  	var reflectValue = reflect.ValueOf(funcOrMethod)
    39  	if reflectValue.Kind() != reflect.Func {
    40  		err = perrors.ErrorfPF("funcOrMethod not func: %T", funcOrMethod)
    41  		return
    42  	}
    43  
    44  	// get func name, “func1” for anonymous
    45  	var runtimeFunc = runtime.FuncForPC(reflectValue.Pointer())
    46  	if runtimeFunc == nil {
    47  		err = perrors.NewPF("runtime.FuncForPC returned nil")
    48  		return
    49  	}
    50  	cL = pruntime.CodeLocationFromFunc(runtimeFunc)
    51  
    52  	return
    53  }