2017-08-07 12:07:29 +02:00
|
|
|
package goparsify
|
2017-08-06 15:32:10 +02:00
|
|
|
|
2017-08-07 13:20:30 +02:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
)
|
2017-08-06 15:32:10 +02:00
|
|
|
|
|
|
|
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) }
|
|
|
|
|
2017-08-08 12:59:48 +02:00
|
|
|
type WSFunc func(c byte) bool
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
type State struct {
|
2017-08-07 13:20:30 +02:00
|
|
|
Input string
|
|
|
|
Pos int
|
|
|
|
Error Error
|
2017-08-08 12:59:48 +02:00
|
|
|
WSFunc WSFunc
|
2017-08-07 13:20:30 +02:00
|
|
|
NoAutoWS bool
|
2017-08-06 15:32:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *State) Advance(i int) {
|
|
|
|
s.Pos += i
|
|
|
|
}
|
|
|
|
|
2017-08-07 13:20:30 +02:00
|
|
|
// AutoWS consumes all whitespace
|
|
|
|
func (s *State) AutoWS() {
|
|
|
|
if s.NoAutoWS {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
s.WS()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *State) WS() {
|
2017-08-08 12:59:48 +02:00
|
|
|
for s.Pos < len(s.Input) && s.WSFunc(s.Input[s.Pos]) {
|
|
|
|
s.Pos++
|
2017-08-07 13:20:30 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
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 {
|
2017-08-08 12:59:48 +02:00
|
|
|
return &State{
|
|
|
|
Input: input,
|
|
|
|
WSFunc: func(b byte) bool {
|
|
|
|
switch b {
|
|
|
|
case '\t', '\n', '\v', '\f', '\r', ' ':
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
},
|
|
|
|
}
|
2017-08-06 15:32:10 +02:00
|
|
|
}
|