Add is.Mn1 alias for is.Min{1,This}

This commit is contained in:
rwxrob 2022-03-02 21:10:13 -05:00
parent f2033baee8
commit e453035fdc
No known key found for this signature in database
GPG Key ID: 2B9111F33082AE77
3 changed files with 35 additions and 3 deletions

View File

@ -49,6 +49,9 @@ type Min struct {
This any
}
// Mn1 scannable struct is shorthand for Min{1,This}.
type Mn1 struct{ This any }
// N scannable struct represents exactly X number of the given scannable
// items (This).
type N struct {

View File

@ -340,6 +340,14 @@ func (s *Scanner) Expect(scannables ...any) (*Cur, error) {
}
end = last
case is.Mn1: // ----------------------------------------------------
m, err := s.Expect(is.Min{1, v.This})
if err != nil {
s.Jump(beg)
return nil, s.ErrorExpected(v)
}
end = m
case is.Min: // ----------------------------------------------------
c := 0
last := s.Mark()
@ -414,6 +422,9 @@ func (s *Scanner) ErrorExpected(this any, args ...any) error {
case is.Opt:
str := `expected an optional %v`
msg = fmt.Sprintf(str, v)
case is.Mn1:
str := `expected at least one of %q`
msg = fmt.Sprintf(str, v.This)
case is.Min:
str := `expected min %v of %q`
msg = fmt.Sprintf(str, v.Min, v.This)

View File

@ -253,6 +253,24 @@ func ExampleExpect_opt() {
// U+0020 ' ' 1,5-5 (5-5)
}
func ExampleExpect_mn1() {
s, _ := scan.New("sommme thing")
start := s.Mark()
s.ScanN(2)
c, _ := s.Expect(is.Mn1{'m'}) // goggles up all three
c.Print()
s.Print()
s.Jump(start)
c, _ = s.Expect(is.Mn1{'s'}) // yep, just one
c.Print()
s.Print()
// Output:
// U+006D 'm' 1,5-5 (5-5)
// U+0065 'e' 1,6-6 (6-6)
// U+0073 's' 1,1-1 (1-1)
// U+006F 'o' 1,2-2 (2-2)
}
func ExampleExpect_min() {
s, _ := scan.New("sommme thing")
start := s.Mark()
@ -295,12 +313,12 @@ func ExampleExpect_count() {
s.Snap()
s.ScanN(2)
s.Print()
s.Expect(is.X{3, 'm'}) // goggles up all three
s.Expect(is.N{3, 'm'}) // goggles up all three
s.Print()
s.Back()
s.Expect(is.X{1, 's'}) // yes, but silly since 's' is easier
s.Expect(is.N{1, 's'}) // yes, but silly since 's' is easier
s.Print()
_, err := s.Expect(is.X{3, 'X'}) // nope
_, err := s.Expect(is.N{3, 'X'}) // nope
fmt.Println(err)
// Output:
// U+006D 'm' 1,3-3 (3-3)