Debian Codegraph @

internal/location/location.go

raw
1 // Copyright (c) 2018-2021, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package location
8
9 import (
10 "fmt"
11 "runtime"
12 "strings"
13 )
14
15 // Location records a place in a source file.
16 type Location struct {
17 File string // File name
18 Func string // Function name
19 Line int // Line number inside file
20 Inside string // Inside is used when Location is inside something else
21 BehindCmp bool // BehindCmp is true when operator is behind a Cmp* function
22 }
23
24 // GetLocationer is the interface that wraps the basic GetLocation method.
25 type GetLocationer interface {
26 GetLocation() Location
27 }
28
29 // New returns a new [Location]. callDepth is the number of
30 // stack frames to ascend to get the calling function (Func field),
31 // added to 1 to get the File & Line fields.
32 //
33 // If the location can not be determined, ok is false and location is
34 // not valid.
35 func New(callDepth int) (loc Location, ok bool) {
36 _, loc.File, loc.Line, ok = runtime.Caller(callDepth + 1)
37 if !ok {
38 return
39 }
40
41 if index := strings.LastIndexAny(loc.File, `/\`); index >= 0 {
42 loc.File = loc.File[index+1:]
43 }
44
45 pc, _, _, _ := runtime.Caller(callDepth)
46 loc.Func = runtime.FuncForPC(pc).Name()
47 return
48 }
49
50 // IsInitialized returns true if l is initialized
51 // (e.g. [NewLocation] called without an error), false otherwise.
52 func (l Location) IsInitialized() bool {
53 return l.File != ""
54 }
55
56 // Implements [fmt.Stringer].
57 func (l Location) String() string {
58 return fmt.Sprintf("%s %sat %s:%d", l.Func, l.Inside, l.File, l.Line)
59 }