modernc.org/knuth@v0.0.4/mft/etc.go (about) 1 // Copyright 2023 The Knuth 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 5 package mft // modernc.org/knuth/mft 6 7 import ( 8 "fmt" 9 "os" 10 "path/filepath" 11 "runtime" 12 "strings" 13 ) 14 15 // origin returns caller's short position, skipping skip frames. 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 41 // todo prints and returns caller's position and an optional message tagged with TODO. Output goes to stderr. 42 //lint:ignore U1000 whatever 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 56 // trc prints and returns caller's position and an optional message tagged with TRC. Output goes to stderr. 57 //lint:ignore U1000 whatever 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 %s", origin(2), s) 66 fmt.Fprintf(os.Stderr, "%s\n", r) 67 os.Stderr.Sync() 68 return r 69 }