Wednesday, November 11, 2015

Day 1: A fresh restart, A forth interpreter in C.



I do not know why I stop some projects until they are dead or nearly dead. I have forgotten the components of the last Forth interpreter I wrote, and I'd rather rewrite from scratch. So without further ado, here is my latest attempt for a Forth interpreter. As a start, we simply read from the standard input and prints out the tokens. Forth is simple in that tokens are separated by spaces. Here we allow tabs and new lines.


/
#include 
#include 
#define MAXBUFFSIZE 128

char    BUFF[MAXBUFFSIZE];   // input string buffer.

char delims[] = " \t\n";

int main() {
  int i =0;
  int exitnow = 0;
  while (1) {
    fputs(">>", stdout);
    fgets(BUFF, MAXBUFFSIZE-1, stdin);
    char *tok = strtok(BUFF, delims);
    while (tok)  {
      printf("%d %s\n", ++i, tok);
      if (tok == NULL) break;
      if (strcmp(tok, "quit")==0) {
 printf("quitting...\n");
 exitnow = 1;
 break;
      }
      tok = strtok(NULL, delims);
    } 
    if (exitnow) {
       puts("Thanks for using easyforth!\n");
       break;
    }
  };
  return 0;
}

Here is a run of our preliminary interpreter (without token execution).

toto@toto-VirtualBox:~/Projects/forth$ gcc easyforth.c
toto@toto-VirtualBox:~/Projects/forth$ ./a.out
>>123 456 789 10 + + + .
1 123
2 456
3 789
4 10
5 +
6 +
7 +
8 .
>>

next we shall revise the code above to execute simple arithmetic.


No comments:

Post a Comment