~mna/siberian

ded5adc5c6b77b39fed8184de74ea3c51f5e8256 — Martin Angers 2 years ago 2b5a82e
add Debug func, incomplete
2 files changed, 30 insertions(+), 1 deletions(-)

M parse.go
M parse_test.go
M parse.go => parse.go +22 -1
@@ 1,6 1,10 @@
package siberian

import "reflect"
import (
	"fmt"
	"io"
	"reflect"
)

// Matches returns true if m matches for input b. Note that if m allows a
// zero match, Matches still returns true (a 0-match is still a match).


@@ 11,6 15,23 @@ func Matches(m Matcher, b []byte) bool {
	return n >= 0
}

// Debug wraps m in a Matcher that will print to w the max previous successful
// matches before the farthest non-successful match. If max is -1, all previous
// matches are printed.
func Debug(m Matcher, w io.Writer, max int) Matcher {
	farthest := -1
	return VisitMatcher(m, func(m Matcher) Matcher {
		return MatcherFunc(func(b []byte, p int) int {
			n := m.Match(b, p)
			if n < 0 && p > farthest {
				farthest = p
				fmt.Fprintf(w, "!%d: %T\n", p, m)
			}
			return n
		})
	})
}

// VisitContext maintains context during a visit of Matchers. Because
// Matchers can refer to themselves and have cycles, it keeps track
// of Matchers that have already been visited.

M parse_test.go => parse_test.go +8 -0
@@ 1,6 1,7 @@
package siberian_test

import (
	"bytes"
	"testing"

	"git.sr.ht/~mna/siberian"


@@ 116,3 117,10 @@ func TestVisitMatcher(t *testing.T) {
		t.Fatalf("want %d matches, got %d", 2, countMatches)
	}
}

func TestDebug(t *testing.T) {
	var buf bytes.Buffer
	m := siberian.Debug(jsonmatcher.Doc, &buf, -1)
	siberian.Matches(m, []byte("1a"))
	t.Log(buf.String())
}