Skip to content

Commit

Permalink
internal/core/adt: add logging utilities for debugging
Browse files Browse the repository at this point in the history
Change-Id: I5983a0b0758785a08674aa5a42ec636ef16bd347
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/8044
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
  • Loading branch information
mpvl committed Jan 2, 2021
1 parent 1fa69d5 commit d5b4ca8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
43 changes: 43 additions & 0 deletions internal/core/adt/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package adt

import (
"fmt"
"log"
"os"
"reflect"
"regexp"
Expand All @@ -34,6 +35,11 @@ import (
// false otherwise.
var Debug bool = os.Getenv("CUE_DEBUG") != "0"

// Verbosity sets the log level. There are currently only two levels:
// 0: no logging
// 1: logging
var Verbosity int

// Assert panics if the condition is false. Assert can be used to check for
// conditions that are considers to break an internal variant or unexpected
// condition, but that nonetheless probably will be handled correctly down the
Expand All @@ -59,6 +65,43 @@ func (c *OpContext) Assertf(pos token.Pos, b bool, format string, args ...interf
}
}

func init() {
log.SetFlags(log.Lshortfile)
}

func Logf(format string, args ...interface{}) {
if Verbosity == 0 {
return
}
s := fmt.Sprintf(format, args...)
_ = log.Output(2, s)
}

var pMap = map[*Vertex]int{}

func (c *OpContext) Logf(v *Vertex, format string, args ...interface{}) {
if Verbosity == 0 {
return
}
p := pMap[v]
if p == 0 {
p = len(pMap) + 1
pMap[v] = p
}
a := append([]interface{}{
p,
v.Label.SelectorString(c),
v.Path(),
}, args...)
for i := 2; i < len(a); i++ {
if n, ok := a[i].(Node); ok {
a[i] = c.Str(n)
}
}
s := fmt.Sprintf(" [%d] %s/%v"+format, a...)
_ = log.Output(2, s)
}

// A Unifier implements a strategy for CUE's unification operation. It must
// handle the following aspects of CUE evaluation:
//
Expand Down
3 changes: 3 additions & 0 deletions internal/core/eval/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/rogpeppe/go-internal/txtar"

"cuelang.org/go/cue"
"cuelang.org/go/internal/core/adt"
"cuelang.org/go/internal/core/debug"
"cuelang.org/go/internal/core/eval"
"cuelang.org/go/internal/core/validate"
Expand Down Expand Up @@ -120,9 +121,11 @@ module: "example.com"
// t.Error(debug.NodeString(r, v, nil))
// eval.Debug = true

adt.Verbosity = 1
e := eval.New(r)
ctx := e.NewContext(v)
v.Finalize(ctx)
adt.Verbosity = 0

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

Expand Down

0 comments on commit d5b4ca8

Please sign in to comment.