From c2b63444505a015c8213ccee4078c1d3f07d9503 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Sun, 23 Sep 2018 08:41:21 +0200 Subject: ... --- go/forth/forth.go | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/go/forth/forth.go b/go/forth/forth.go index 3215f77..389036e 100644 --- a/go/forth/forth.go +++ b/go/forth/forth.go @@ -136,10 +136,10 @@ func number(s string) (int, bool) { } func colon(dict dictionary, l *lexer) error { - name, err := l.Next() - if err != nil { - return err + if l.atEOL() { + return ErrEOL } + name := l.next() if _, ok := number(name); ok { return ErrWord } @@ -153,11 +153,8 @@ func colon(dict dictionary, l *lexer) error { func compile(dict dictionary, l *lexer) ([]word, error) { var words []word - for { - v, err := l.Next() - if err == ErrEOL { - return words, nil - } + for !l.atEOL() { + v := l.next() // colon operator if v == ":" { if err := colon(dict, l); err != nil { @@ -166,7 +163,7 @@ func compile(dict dictionary, l *lexer) ([]word, error) { continue } if v == ";" { - return words, nil + break } // lookup dictionary first if w, ok := dict.find(v); ok { @@ -180,21 +177,22 @@ func compile(dict dictionary, l *lexer) ([]word, error) { } return nil, ErrUnknown } + return words, nil } type lexer []string -func NewLexer(line string) lexer { +func newLexer(line string) lexer { return strings.Fields(line) } -func (l *lexer) Next() (string, error) { - if len(*l) == 0 { - return "", ErrEOL - } - s := (*l)[0] - *l = (*l)[1:] - return s, nil +func (l *lexer) atEOL() bool { + return len(*l) == 0 +} + +func (l *lexer) next() (s string) { + s, *l = (*l)[0], (*l)[1:] + return s } func Forth(v []string) ([]int, error) { @@ -210,7 +208,7 @@ func Forth(v []string) ([]int, error) { s := new(stack) for _, line := range v { // compile - l := NewLexer(line) + l := newLexer(line) words, err := compile(dict, &l) if err != nil { return nil, err -- cgit v1.2.3