History

Catch bad integer errors too

rminnich committed 15 years ago

Commit ceeb8611 parent f12626e2 files · +26 −13Browse files

Unified · Split

2 files
  1. file_test.go +5 −0
  2. forth.go +21 −13
file_test.go+5−0
@@ -35,6 +35,7 @@ var forthTests = []forthTest{ · 34 unmodified lines
3535 {"1 dup +", "2", ""},
3636 {"4095 4096 roundup", "4096", ""},
3737 {"4097 8192 roundup", "8192", ""},
38+ {"2 x +", "", "parsing \"x\": invalid syntax"},
3839 }
3940
4041 func TestForth(t *testing.T) {
@@ -65,6 +66,10 @@ func TestForth(t *testing.T) { · 24 unmodified lines
6566 var err error
6667 res, err := Eval(f, tt.val)
6768 if res == tt.res || (err != nil && err.Error() == tt.err) {
69+ if err != nil {
70+ /* stack is not going to be right; reset it. */
71+ f.Reset()
72+ }
6873 fmt.Printf("Test: '%v' '%v' '%v': Pass\n", tt.val, res, err)
6974 } else {
7075 t.Errorf("Test: '%v' '%v' '%v': Fail\n", tt.val, res, err)
forth.go+21−13
@@ -145,44 +145,52 @@ func Eval(f Forth, s string) (ret string, err error) { · 144 unmodified lines
145145
146146 }
147147
148+func toInt(f Forth) int {
149+ i, err := strconv.Atoi(f.Pop())
150+ if err != nil {
151+ panic(err)
152+ }
153+ return i
154+}
155+
148156 func plus(f Forth) {
149− x, _ := strconv.Atoi(f.Pop())
150− y, _ := strconv.Atoi(f.Pop())
157+ x := toInt(f)
158+ y := toInt(f)
151159 z := x + y
152160 f.Push(strconv.Itoa(z))
153161 }
154162
155163 func times(f Forth) {
156− x, _ := strconv.Atoi(f.Pop())
157− y, _ := strconv.Atoi(f.Pop())
164+ x := toInt(f)
165+ y := toInt(f)
158166 z := x * y
159167 f.Push(strconv.Itoa(z))
160168 }
161169
162170 func sub(f Forth) {
163− x, _ := strconv.Atoi(f.Pop())
164− y, _ := strconv.Atoi(f.Pop())
171+ x := toInt(f)
172+ y := toInt(f)
165173 z := y - x
166174 f.Push(strconv.Itoa(z))
167175 }
168176
169177 func div(f Forth) {
170− x, _ := strconv.Atoi(f.Pop())
171− y, _ := strconv.Atoi(f.Pop())
178+ x := toInt(f)
179+ y := toInt(f)
172180 z := y / x
173181 f.Push(strconv.Itoa(z))
174182 }
175183
176184 func mod(f Forth) {
177− x, _ := strconv.Atoi(f.Pop())
178− y, _ := strconv.Atoi(f.Pop())
185+ x := toInt(f)
186+ y := toInt(f)
179187 z := y % x
180188 f.Push(strconv.Itoa(z))
181189 }
182190
183191 func roundup(f Forth) {
184− rnd, _ := strconv.Atoi(f.Pop())
185− v, _ := strconv.Atoi(f.Pop())
192+ rnd := toInt(f)
193+ v := toInt(f)
186194 v = ((v + rnd - 1) / rnd) * rnd
187195 f.Push(strconv.Itoa(v))
188196 }
@@ -207,7 +215,7 @@ func dup(f Forth) { · 18 unmodified lines
207215 }
208216
209217 func ifelse(f Forth) {
210− x, _ := strconv.Atoi(f.Pop())
218+ x := toInt(f)
211219 y := f.Pop()
212220 z := f.Pop()
213221 if x != 0 {