~mna/siberian

4d0db11e1050a91fb7ac25ad8ade83957d105ce0 — Martin Angers 4 years ago db08d81
add Matches API func, start thinking about visiting Matchers
3 files changed, 71 insertions(+), 1 deletions(-)

A parse.go
R grammar_test.go => parse_test.go
A visit.go
A parse.go => parse.go +10 -0
@@ 0,0 1,10 @@
package siberian

// 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).
// To check if m matches the full input b, make sure the matcher ends with
// an EOF matcher (e.g. a Seq{Ms: []Matcher{SomeMatcher, EOF}}).
func Matches(m Matcher, b []byte) bool {
	n := m.Match(b, 0)
	return n >= 0
}

R grammar_test.go => parse_test.go +54 -1
@@ 2,7 2,7 @@ package siberian

import "testing"

func TestGrammar_AB(t *testing.T) {
func TestMatches_AB(t *testing.T) {
	// Start = { As | B } .
	// As = A+ .
	// A = "a" .


@@ 38,6 38,59 @@ func TestGrammar_AB(t *testing.T) {
			if n != c.len {
				t.Errorf("want match of length %d, got %d", c.len, n)
			}
			matches := Matches(g, []byte(c.in))
			if want := n >= 0; want != matches {
				t.Errorf("want match? %t, got %t", want, matches)
			}
		})
	}
}

func TestMatches_AB_EOF(t *testing.T) {
	// Start = { As | B } .
	// As = A+ .
	// A = "a" .
	// B = "b" .
	g := &Seq{
		Ms: []Matcher{
			&Repeat{
				Min: 0,
				Max: -1,
				M: &Alt{
					Ms: []Matcher{
						&Repeat{
							Min: 1,
							Max: -1,
							M:   Equal("a"),
						},
						Equal("b"),
					},
				},
			},
			EOF,
		},
	}
	cases := []matcherTest{
		{"", 0},
		{"a", 1},
		{"b", 1},
		{"c", -1},
		{"aa", 2},
		{"aaab", 4},
		{"bb", 2},
		{"bbaa", 4},
		{"aaabc", -1},
	}
	for _, c := range cases {
		t.Run(c.in, func(t *testing.T) {
			n := g.Match([]byte(c.in), 0)
			if n != c.len {
				t.Errorf("want match of length %d, got %d", c.len, n)
			}
			matches := Matches(g, []byte(c.in))
			if want := n >= 0; want != matches {
				t.Errorf("want match? %t, got %t", want, matches)
			}
		})
	}
}

A visit.go => visit.go +7 -0
@@ 0,0 1,7 @@
package siberian

/*
func Visit(m Matcher, fn func(m Matcher) Matcher) {

}
*/