summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2018-09-23 08:41:21 +0200
committerDimitri Sokolyuk <demon@dim13.org>2018-09-23 08:41:21 +0200
commitc2b63444505a015c8213ccee4078c1d3f07d9503 (patch)
tree0d1f208d773dca891703bf2e3b0ada0aafbbf5b9
parent18c80a0b8613b4d5bb15068512ae1aa764bd12c2 (diff)
...
-rw-r--r--go/forth/forth.go34
1 files 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