Skip to content

Commit d5b4ca8

Browse files
committed
internal/core/adt: add logging utilities for debugging
Change-Id: I5983a0b0758785a08674aa5a42ec636ef16bd347 Reviewed-on: https://cue-review.googlesource.com/c/cue/+/8044 Reviewed-by: Marcel van Lohuizen <[email protected]>
1 parent 1fa69d5 commit d5b4ca8

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

internal/core/adt/context.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package adt
1616

1717
import (
1818
"fmt"
19+
"log"
1920
"os"
2021
"reflect"
2122
"regexp"
@@ -34,6 +35,11 @@ import (
3435
// false otherwise.
3536
var Debug bool = os.Getenv("CUE_DEBUG") != "0"
3637

38+
// Verbosity sets the log level. There are currently only two levels:
39+
// 0: no logging
40+
// 1: logging
41+
var Verbosity int
42+
3743
// Assert panics if the condition is false. Assert can be used to check for
3844
// conditions that are considers to break an internal variant or unexpected
3945
// condition, but that nonetheless probably will be handled correctly down the
@@ -59,6 +65,43 @@ func (c *OpContext) Assertf(pos token.Pos, b bool, format string, args ...interf
5965
}
6066
}
6167

68+
func init() {
69+
log.SetFlags(log.Lshortfile)
70+
}
71+
72+
func Logf(format string, args ...interface{}) {
73+
if Verbosity == 0 {
74+
return
75+
}
76+
s := fmt.Sprintf(format, args...)
77+
_ = log.Output(2, s)
78+
}
79+
80+
var pMap = map[*Vertex]int{}
81+
82+
func (c *OpContext) Logf(v *Vertex, format string, args ...interface{}) {
83+
if Verbosity == 0 {
84+
return
85+
}
86+
p := pMap[v]
87+
if p == 0 {
88+
p = len(pMap) + 1
89+
pMap[v] = p
90+
}
91+
a := append([]interface{}{
92+
p,
93+
v.Label.SelectorString(c),
94+
v.Path(),
95+
}, args...)
96+
for i := 2; i < len(a); i++ {
97+
if n, ok := a[i].(Node); ok {
98+
a[i] = c.Str(n)
99+
}
100+
}
101+
s := fmt.Sprintf(" [%d] %s/%v"+format, a...)
102+
_ = log.Output(2, s)
103+
}
104+
62105
// A Unifier implements a strategy for CUE's unification operation. It must
63106
// handle the following aspects of CUE evaluation:
64107
//

internal/core/eval/eval_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"github.com/rogpeppe/go-internal/txtar"
2424

2525
"cuelang.org/go/cue"
26+
"cuelang.org/go/internal/core/adt"
2627
"cuelang.org/go/internal/core/debug"
2728
"cuelang.org/go/internal/core/eval"
2829
"cuelang.org/go/internal/core/validate"
@@ -120,9 +121,11 @@ module: "example.com"
120121
// t.Error(debug.NodeString(r, v, nil))
121122
// eval.Debug = true
122123

124+
adt.Verbosity = 1
123125
e := eval.New(r)
124126
ctx := e.NewContext(v)
125127
v.Finalize(ctx)
128+
adt.Verbosity = 0
126129

127130
t.Error(debug.NodeString(r, v, nil))
128131

0 commit comments

Comments
 (0)