summaryrefslogtreecommitdiff
path: root/state.go
blob: e624082097e76080bbc4c54aef8c0e5b3ac116a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package goparsify

import (
	"fmt"
)

type Error struct {
	pos      int
	Expected string
}

func (e Error) Pos() int      { return e.pos }
func (e Error) Error() string { return fmt.Sprintf("offset %d: Expected %s", e.pos, e.Expected) }

type State struct {
	Input    string
	Pos      int
	Error    Error
	WSChars  []byte
	NoAutoWS bool
}

func (s *State) Advance(i int) {
	s.Pos += i
}

// AutoWS consumes all whitespace
func (s *State) AutoWS() {
	if s.NoAutoWS {
		return
	}
	s.WS()
}

func (s *State) WS() {
loop:
	for s.Pos < len(s.Input) {
		// Pretty sure this is unicode safe as long as WSChars is only in the ascii range...
		for _, ws := range s.WSChars {
			if s.Input[s.Pos] == ws {
				s.Pos++
				continue loop
			}
		}

		return
	}
}

func (s *State) Get() string {
	if s.Pos > len(s.Input) {
		return ""
	}
	return s.Input[s.Pos:]
}

func (s *State) ErrorHere(expected string) {
	s.Error.pos = s.Pos
	s.Error.Expected = expected
}

func (s *State) ClearError() {
	s.Error.Expected = ""
}

func (s *State) Errored() bool {
	return s.Error.Expected != ""
}

func InputString(input string) *State {
	return &State{Input: input, WSChars: []byte("\t\n\v\f\r ")}
}