Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement LOOP in a FORTH-like language interpreter written in C

I'm writing a simple stack-based language in C and was wondering how I should go about implementing a loop structure of some kind, and/or lookahead symbols. Since the code is a bit long for this page (over 200 lines) I've put it in a GitHub repository.

EDIT: The main program is in file stack.c.

EDIT: The code just takes in input in words, kind of like FORTH. It uses scanf and works left to right. Then it uses a series of ifs and strcmps to decide what to do. That's really it.

like image 352
tekknolagi Avatar asked Aug 04 '11 22:08

tekknolagi


1 Answers

The Forth approach is to add a separate loop stack alongside the data stack. You then define operations that work with this loop stack. For example:

5 0 DO I . LOOP

Will print

0 1 2 3 4

The way this works is:

  • DO moves the index (0) and the control (5) over to the loop stack.
  • I copies the top of the loop stack to the data stack.
  • LOOP increments the index (top of loop stack). If the index is less than the control (one below the top of loop stack), then it reruns the commands from DO back to LOOP. If the index is >=, then it pops the index and control from the loop stack, and control resumes as normal.
like image 170
Jeremy W. Sherman Avatar answered Sep 26 '22 15:09

Jeremy W. Sherman