etc.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2024 The tk9.0-go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tk9_0 // import "modernc.org/tk9.0"
  5. import (
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. )
  13. // origin returns caller's short position, skipping skip frames.
  14. //
  15. //lint:ignore U1000 debug helper
  16. func origin(skip int) string {
  17. pc, fn, fl, _ := runtime.Caller(skip)
  18. f := runtime.FuncForPC(pc)
  19. var fns string
  20. if f != nil {
  21. fns = f.Name()
  22. if x := strings.LastIndex(fns, "."); x > 0 {
  23. fns = fns[x+1:]
  24. }
  25. if strings.HasPrefix(fns, "func") {
  26. num := true
  27. for _, c := range fns[len("func"):] {
  28. if c < '0' || c > '9' {
  29. num = false
  30. break
  31. }
  32. }
  33. if num {
  34. return origin(skip + 2)
  35. }
  36. }
  37. }
  38. return fmt.Sprintf("%s:%d:%s", filepath.Base(fn), fl, fns)
  39. }
  40. // todo prints and return caller's position and an optional message tagged with TODO. Output goes to stderr.
  41. //
  42. //lint:ignore U1000 debug helper
  43. func todo(s string, args ...interface{}) string {
  44. switch {
  45. case s == "":
  46. s = fmt.Sprintf(strings.Repeat("%v ", len(args)), args...)
  47. default:
  48. s = fmt.Sprintf(s, args...)
  49. }
  50. r := fmt.Sprintf("%s\n\tTODO %s", origin(2), s)
  51. // fmt.Fprintf(os.Stderr, "%s\n", r)
  52. // os.Stdout.Sync()
  53. return r
  54. }
  55. // trc prints and return caller's position and an optional message tagged with TRC. Output goes to stderr.
  56. //
  57. //lint:ignore U1000 debug helper
  58. func trc(s string, args ...interface{}) string {
  59. switch {
  60. case s == "":
  61. s = fmt.Sprintf(strings.Repeat("%v ", len(args)), args...)
  62. default:
  63. s = fmt.Sprintf(s, args...)
  64. }
  65. r := fmt.Sprintf("%s: TRC(id=%v) %s", origin(2), goroutineID(), s)
  66. fmt.Fprintf(os.Stderr, "%s\n", r)
  67. os.Stderr.Sync()
  68. return r
  69. }
  70. func goroutineID() int {
  71. var (
  72. buf [64]byte
  73. n = runtime.Stack(buf[:], false)
  74. stk = strings.TrimPrefix(string(buf[:n]), "goroutine")
  75. )
  76. idField := strings.Fields(stk)[0]
  77. id, err := strconv.Atoi(idField)
  78. if err != nil {
  79. panic(fmt.Errorf("can not get goroutine id: %v", err))
  80. }
  81. return id
  82. }