lexer: Reader.Accept(), AcceptAll(), and StateFn #5
Merged
amery
merged 3 commits from pr-amery-lexer
into main
1 year ago
2 changed files with 64 additions and 0 deletions
@ -1,2 +1,31 @@ |
|||||||
// Package lexer provides basic helpers to implement parsers
|
// Package lexer provides basic helpers to implement parsers
|
||||||
package lexer |
package lexer |
||||||
|
|
||||||
|
import ( |
||||||
|
"errors" |
||||||
|
"io" |
||||||
|
) |
||||||
|
|
||||||
|
// StateFn is a State Function of the parser
|
||||||
|
type StateFn func() (StateFn, error) |
||||||
|
|
||||||
|
// Run runs a state machine until the state function either
|
||||||
|
// returns nil or an error
|
||||||
|
func Run(fn StateFn) error { |
||||||
|
for fn != nil { |
||||||
|
var err error |
||||||
|
|
||||||
|
fn, err = fn() |
||||||
|
switch { |
||||||
|
case errors.Is(err, io.EOF): |
||||||
|
// EOF
|
||||||
|
return nil |
||||||
|
case err != nil: |
||||||
|
// failed
|
||||||
|
return err |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
// ended
|
||||||
|
return nil |
||||||
|
} |
||||||
|
Loading…
Reference in new issue