/[cvs]/stack/stack.c
ViewVC logotype

Diff of /stack/stack.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.42 by teddy, Wed Feb 6 21:26:46 2002 UTC revision 1.89 by masse, Sun Feb 17 04:03:57 2002 UTC
# Line 1  Line 1 
1  /* printf */  /* printf, sscanf, fgets, fprintf, fopen, perror */
2  #include <stdio.h>  #include <stdio.h>
3  /* EXIT_SUCCESS */  /* exit, EXIT_SUCCESS, malloc, free */
4  #include <stdlib.h>  #include <stdlib.h>
5  /* NULL */  /* NULL */
6  #include <stddef.h>  #include <stddef.h>
7  /* dlopen, dlsym, dlerror */  /* dlopen, dlsym, dlerror */
8  #include <dlfcn.h>  #include <dlfcn.h>
9  /* assert */  /* strcmp, strcpy, strlen, strcat, strdup */
10  #include <assert.h>  #include <string.h>
11    /* getopt, STDIN_FILENO, STDOUT_FILENO */
12    #include <unistd.h>
13    /* EX_NOINPUT, EX_USAGE */
14    #include <sysexits.h>
15    /* mtrace, muntrace */
16    #include <mcheck.h>
17    
18  #define HASHTBLSIZE 65536  #include "stack.h"
   
 /* First, define some types. */  
   
 /* A value of some type */  
 typedef struct {  
   enum {  
     integer,  
     string,  
     func,                       /* Function pointer */  
     symb,  
     list  
   } type;                       /* Type of stack element */  
   
   union {  
     void *ptr;                  /* Pointer to the content */  
     int val;                    /* ...or an integer */  
   } content;                    /* Stores a pointer or an integer */  
   
   int refcount;                 /* Reference counter */  
   
 } value;  
   
 /* A symbol with a name and possible value */  
 /* (These do not need reference counters, they are kept unique by  
    hashing.) */  
 typedef struct symbol_struct {  
   char *id;                     /* Symbol name */  
   value *val;                   /* The value (if any) bound to it */  
   struct symbol_struct *next;   /* In case of hashing conflicts, a */  
 } symbol;                       /* symbol is a kind of stack item. */  
   
 /* A type for a hash table for symbols */  
 typedef symbol *hashtbl[HASHTBLSIZE]; /* Hash table declaration */  
   
 /* An item (value) on a stack */  
 typedef struct stackitem_struct  
 {  
   value *item;                  /* The value on the stack */  
   struct stackitem_struct *next; /* Next item */  
 } stackitem;  
   
 /* An environment; gives access to the stack and a hash table of  
    defined symbols */  
 typedef struct {  
   stackitem *head;              /* Head of the stack */  
   hashtbl symbols;              /* Hash table of all variable bindings */  
   int err;                      /* Error flag */  
 } environment;  
   
 /* A type for pointers to external functions */  
 typedef void (*funcp)(environment *); /* funcp is a pointer to a void  
                                          function (environment *) */  
19    
20  /* Initialize a newly created environment */  /* Initialize a newly created environment */
21  void init_env(environment *env)  void init_env(environment *env)
22  {  {
23    long i;    int i;
24    
25    env->err=0;    env->gc_limit= 20;
26      env->gc_count= 0;
27    
28      env->head= NULL;
29    for(i= 0; i<HASHTBLSIZE; i++)    for(i= 0; i<HASHTBLSIZE; i++)
30      env->symbols[i]= NULL;      env->symbols[i]= NULL;
31      env->err= 0;
32      env->in_string= NULL;
33      env->free_string= NULL;
34      env->inputstream= stdin;
35      env->interactive= 1;
36    }
37    
38    void printerr(const char* in_string) {
39      fprintf(stderr, "Err: %s\n", in_string);
40    }
41    
42    /* Discard the top element of the stack. */
43    extern void toss(environment *env)
44    {
45      stackitem *temp= env->head;
46    
47      if((env->head)==NULL) {
48        printerr("Too Few Arguments");
49        env->err=1;
50        return;
51      }
52      
53      env->head= env->head->next;   /* Remove the top stack item */
54      free(temp);                   /* Free the old top stack item */
55  }  }
56    
57  /* Returns a pointer to a pointer to an element in the hash table. */  /* Returns a pointer to a pointer to an element in the hash table. */
58  symbol **hash(hashtbl in_hashtbl, const char *in_string)  symbol **hash(hashtbl in_hashtbl, const char *in_string)
59  {  {
60    long i= 0;    int i= 0;
61    unsigned long out_hash= 0;    unsigned int out_hash= 0;
62    char key= '\0';    char key= '\0';
63    symbol **position;    symbol **position;
64        
# Line 102  symbol **hash(hashtbl in_hashtbl, const Line 83  symbol **hash(hashtbl in_hashtbl, const
83    }    }
84  }  }
85    
86  /* Generic push function. */  value* new_val(environment *env) {
87  void push(stackitem** stack_head, stackitem* in_item)    value *nval= malloc(sizeof(value));
88  {    stackitem *nitem= malloc(sizeof(stackitem));
89    in_item->next= *stack_head;  
90    *stack_head= in_item;    nval->content.ptr= NULL;
91    
92      nitem->item= nval;
93      nitem->next= env->gc_ref;
94      env->gc_ref= nitem;
95    
96      env->gc_count++;
97    
98      return nval;
99    }
100    
101    void gc_mark(value *val) {
102      stackitem *iterator;
103    
104      if(val==NULL || val->gc_garb==0)
105        return;
106    
107      val->gc_garb= 0;
108    
109      if(val->type==list) {
110        iterator= val->content.ptr;
111    
112        while(iterator!=NULL) {
113          gc_mark(iterator->item);
114          iterator= iterator->next;
115        }
116      }
117    }
118    
119    extern void gc_init(environment *env) {
120      stackitem *new_head= NULL, *titem, *iterator= env->gc_ref;
121      symbol *tsymb;
122      int i;
123    
124      if(env->gc_count < env->gc_limit)
125        return;
126    
127      while(iterator!=NULL) {
128        iterator->item->gc_garb= 1;
129        iterator= iterator->next;
130      }
131    
132      /* Mark */
133      iterator= env->head;
134      while(iterator!=NULL) {
135        gc_mark(iterator->item);
136        iterator= iterator->next;
137      }
138    
139      for(i= 0; i<HASHTBLSIZE; i++) {
140        tsymb= env->symbols[i];
141        while(tsymb!=NULL) {
142          gc_mark(tsymb->val);
143          tsymb= tsymb->next;
144        }
145      }
146    
147      env->gc_count= 0;
148    
149      /* Sweep */
150      while(env->gc_ref!=NULL) {
151        if(env->gc_ref->item->gc_garb) {
152          switch(env->gc_ref->item->type) {
153          case string:
154            free(env->gc_ref->item->content.ptr);
155            break;
156          case integer:
157            break;
158          case list:
159            while(env->gc_ref->item->content.ptr!=NULL) {
160              titem= env->gc_ref->item->content.ptr;
161              env->gc_ref->item->content.ptr= titem->next;
162              free(titem);
163            }
164            break;
165          default:
166            break;
167          }
168          free(env->gc_ref->item);
169          titem= env->gc_ref->next;
170          free(env->gc_ref);
171          env->gc_ref= titem;
172        } else {
173          titem= env->gc_ref->next;
174          env->gc_ref->next= new_head;
175          new_head= env->gc_ref;
176          env->gc_ref= titem;
177          env->gc_count++;
178        }
179      }
180    
181      env->gc_limit= env->gc_count*2;
182      env->gc_ref= new_head;
183  }  }
184    
185  /* Push a value onto the stack */  /* Push a value onto the stack */
186  void push_val(stackitem **stack_head, value *val)  void push_val(environment *env, value *val)
187  {  {
188    stackitem *new_item= malloc(sizeof(stackitem));    stackitem *new_item= malloc(sizeof(stackitem));
189    new_item->item= val;    new_item->item= val;
190    val->refcount++;    new_item->next= env->head;
191    push(stack_head, new_item);    env->head= new_item;
192  }  }
193    
194  /* Push an integer onto the stack. */  /* Push an integer onto the stack. */
195  void push_int(stackitem **stack_head, int in_val)  void push_int(environment *env, int in_val)
196  {  {
197    value *new_value= malloc(sizeof(value));    value *new_value= new_val(env);
   stackitem *new_item= malloc(sizeof(stackitem));  
   new_item->item= new_value;  
198        
199    new_value->content.val= in_val;    new_value->content.val= in_val;
200    new_value->type= integer;    new_value->type= integer;
   new_value->refcount=1;  
201    
202    push(stack_head, new_item);    push_val(env, new_value);
203  }  }
204    
205  /* Copy a string onto the stack. */  /* Copy a string onto the stack. */
206  void push_cstring(stackitem **stack_head, const char *in_string)  void push_cstring(environment *env, const char *in_string)
207  {  {
208    value *new_value= malloc(sizeof(value));    value *new_value= new_val(env);
   stackitem *new_item= malloc(sizeof(stackitem));  
   new_item->item=new_value;  
209    
210    new_value->content.ptr= malloc(strlen(in_string)+1);    new_value->content.ptr= malloc(strlen(in_string)+1);
211    strcpy(new_value->content.ptr, in_string);    strcpy(new_value->content.ptr, in_string);
212    new_value->type= string;    new_value->type= string;
   new_value->refcount=1;  
213    
214    push(stack_head, new_item);    push_val(env, new_value);
215    }
216    
217    /* Mangle a symbol name to a valid C identifier name */
218    char *mangle_str(const char *old_string){
219      char validchars[]
220        ="0123456789abcdef";
221      char *new_string, *current;
222    
223      new_string=malloc((strlen(old_string)*2)+4);
224      strcpy(new_string, "sx_");    /* Stack eXternal */
225      current=new_string+3;
226      while(old_string[0] != '\0'){
227        current[0]=validchars[(unsigned char)(old_string[0])/16];
228        current[1]=validchars[(unsigned char)(old_string[0])%16];
229        current+=2;
230        old_string++;
231      }
232      current[0]='\0';
233    
234      return new_string;            /* The caller must free() it */
235    }
236    
237    extern void mangle(environment *env){
238      char *new_string;
239    
240      if((env->head)==NULL) {
241        printerr("Too Few Arguments");
242        env->err=1;
243        return;
244      }
245    
246      if(env->head->item->type!=string) {
247        printerr("Bad Argument Type");
248        env->err=2;
249        return;
250      }
251    
252      new_string= mangle_str((const char *)(env->head->item->content.ptr));
253    
254      toss(env);
255      if(env->err) return;
256    
257      push_cstring(env, new_string);
258  }  }
259    
260  /* Push a symbol onto the stack. */  /* Push a symbol onto the stack. */
261  void push_sym(environment *env, const char *in_string)  void push_sym(environment *env, const char *in_string)
262  {  {
   stackitem *new_item;          /* The new stack item */  
   /* ...which will contain... */  
263    value *new_value;             /* A new symbol value */    value *new_value;             /* A new symbol value */
264    /* ...which might point to... */    /* ...which might point to... */
265    symbol **new_symbol;          /* (if needed) A new actual symbol */    symbol **new_symbol;          /* (if needed) A new actual symbol */
# Line 161  void push_sym(environment *env, const ch Line 269  void push_sym(environment *env, const ch
269    void *funcptr;                /* A function pointer */    void *funcptr;                /* A function pointer */
270    
271    static void *handle= NULL;    /* Dynamic linker handle */    static void *handle= NULL;    /* Dynamic linker handle */
272      const char *dlerr;            /* Dynamic linker error */
273      char *mangled;                /* Mangled function name */
274    
275    /* Create a new stack item containing a new value */    new_value= new_val(env);
   new_item= malloc(sizeof(stackitem));  
   new_value= malloc(sizeof(value));  
   new_item->item=new_value;  
276    
277    /* The new value is a symbol */    /* The new value is a symbol */
278    new_value->type= symb;    new_value->type= symb;
   new_value->refcount= 1;  
279    
280    /* Look up the symbol name in the hash table */    /* Look up the symbol name in the hash table */
281    new_symbol= hash(env->symbols, in_string);    new_symbol= hash(env->symbols, in_string);
# Line 192  void push_sym(environment *env, const ch Line 298  void push_sym(environment *env, const ch
298      if(handle==NULL)            /* If no handle */      if(handle==NULL)            /* If no handle */
299        handle= dlopen(NULL, RTLD_LAZY);        handle= dlopen(NULL, RTLD_LAZY);
300    
301      funcptr= dlsym(handle, in_string); /* Get function pointer */      mangled=mangle_str(in_string); /* mangle the name */
302      if(dlerror()==NULL) {       /* If a function was found */      funcptr= dlsym(handle, mangled); /* and try to find it */
303        new_fvalue= malloc(sizeof(value)); /* Create a new value */      free(mangled);
304        dlerr=dlerror();
305        if(dlerr != NULL) {         /* If no function was found */
306          funcptr= dlsym(handle, in_string); /* Get function pointer */
307          dlerr=dlerror();
308        }
309        if(dlerr==NULL) {           /* If a function was found */
310          new_fvalue= new_val(env); /* Create a new value */
311        new_fvalue->type=func;    /* The new value is a function pointer */        new_fvalue->type=func;    /* The new value is a function pointer */
312        new_fvalue->content.ptr=funcptr; /* Store function pointer */        new_fvalue->content.ptr=funcptr; /* Store function pointer */
313        (*new_symbol)->val= new_fvalue; /* Bind the symbol to the new        (*new_symbol)->val= new_fvalue; /* Bind the symbol to the new
314                                           function value */                                           function value */
       new_fvalue->refcount= 1;  
     }  
   }  
   push(&(env->head), new_item);  
 }  
   
 void printerr(const char* in_string) {  
   fprintf(stderr, "Err: %s\n", in_string);  
 }  
   
 /* Throw away a value */  
 void free_val(value *val){  
   stackitem *item, *temp;  
   
   val->refcount--;              /* Decrease the reference count */  
   if(val->refcount == 0){  
     switch (val->type){         /* and free the contents if necessary */  
     case string:  
       free(val->content.ptr);  
       break;  
     case list:                  /* lists needs to be freed recursively */  
       item=val->content.ptr;  
       while(item != NULL) {     /* for all stack items */  
         free_val(item->item);   /* free the value */  
         temp=item->next;        /* save next ptr */  
         free(item);             /* free the stackitem */  
         item=temp;              /* go to next stackitem */  
       }  
       free(val);                /* Free the actual list value */  
       break;  
     default:  
       break;  
315      }      }
316    }    }
317  }    push_val(env, new_value);
   
 /* Discard the top element of the stack. */  
 extern void toss(environment *env)  
 {  
   stackitem *temp= env->head;  
   
   if((env->head)==NULL) {  
     printerr("Too Few Arguments");  
     env->err=1;  
     return;  
   }  
     
   free_val(env->head->item);    /* Free the value */  
   env->head= env->head->next;   /* Remove the top stack item */  
   free(temp);                   /* Free the old top stack item */  
318  }  }
319    
320  /* Print newline. */  /* Print newline. */
# Line 284  extern void type(environment *env){ Line 350  extern void type(environment *env){
350    case list:    case list:
351      push_sym(env, "list");      push_sym(env, "list");
352      break;      break;
   default:  
     push_sym(env, "unknown");  
     break;  
353    }    }
354  }      }    
355    
356  /* Prints the top element of the stack. */  /* Prints the top element of the stack. */
357  void print_h(stackitem *stack_head)  void print_h(stackitem *stack_head, int noquote)
358  {  {
359    switch(stack_head->item->type) {    switch(stack_head->item->type) {
360    case integer:    case integer:
361      printf("%d", stack_head->item->content.val);      printf("%d", stack_head->item->content.val);
362      break;      break;
363    case string:    case string:
364      printf("\"%s\"", (char*)stack_head->item->content.ptr);      if(noquote)
365          printf("%s", (char*)stack_head->item->content.ptr);
366        else
367          printf("\"%s\"", (char*)stack_head->item->content.ptr);
368      break;      break;
369    case symb:    case symb:
370      printf("'%s'", ((symbol *)(stack_head->item->content.ptr))->id);      printf("%s", ((symbol *)(stack_head->item->content.ptr))->id);
371      break;      break;
372    case func:    case func:
373      printf("#<function %p>", (funcp)(stack_head->item->content.ptr));      printf("#<function %p>", (funcp)(stack_head->item->content.ptr));
# Line 311  void print_h(stackitem *stack_head) Line 377  void print_h(stackitem *stack_head)
377      stack_head=(stackitem *)(stack_head->item->content.ptr);      stack_head=(stackitem *)(stack_head->item->content.ptr);
378      printf("[ ");      printf("[ ");
379      while(stack_head != NULL) {      while(stack_head != NULL) {
380        print_h(stack_head);        print_h(stack_head, noquote);
381        printf(" ");        printf(" ");
382        stack_head=stack_head->next;        stack_head=stack_head->next;
383      }      }
384      printf("]");      printf("]");
385      break;      break;
   default:  
     printf("#<unknown %p>", (stack_head->item->content.ptr));  
     break;  
386    }    }
387  }  }
388    
# Line 329  extern void print_(environment *env) { Line 392  extern void print_(environment *env) {
392      env->err=1;      env->err=1;
393      return;      return;
394    }    }
395    print_h(env->head);    print_h(env->head, 0);
396      nl();
397  }  }
398    
399  /* Prints the top element of the stack and then discards it. */  /* Prints the top element of the stack and then discards it. */
# Line 340  extern void print(environment *env) Line 404  extern void print(environment *env)
404    toss(env);    toss(env);
405  }  }
406    
407    extern void princ_(environment *env) {
408      if(env->head==NULL) {
409        printerr("Too Few Arguments");
410        env->err=1;
411        return;
412      }
413      print_h(env->head, 1);
414    }
415    
416    /* Prints the top element of the stack and then discards it. */
417    extern void princ(environment *env)
418    {
419      princ_(env);
420      if(env->err) return;
421      toss(env);
422    }
423    
424  /* Only to be called by function printstack. */  /* Only to be called by function printstack. */
425  void print_st(stackitem *stack_head, long counter)  void print_st(stackitem *stack_head, long counter)
426  {  {
427    if(stack_head->next != NULL)    if(stack_head->next != NULL)
428      print_st(stack_head->next, counter+1);      print_st(stack_head->next, counter+1);
429    printf("%ld: ", counter);    printf("%ld: ", counter);
430    print_h(stack_head);    print_h(stack_head, 0);
431    nl();    nl();
432  }  }
433    
   
   
434  /* Prints the stack. */  /* Prints the stack. */
435  extern void printstack(environment *env)  extern void printstack(environment *env)
436  {  {
437    if(env->head == NULL) {    if(env->head == NULL) {
438        printf("Stack Empty\n");
439      return;      return;
440    }    }
441    print_st(env->head, 1);    print_st(env->head, 1);
   nl();  
442  }  }
443    
444  /* Swap the two top elements on the stack. */  /* Swap the two top elements on the stack. */
# Line 367  extern void swap(environment *env) Line 446  extern void swap(environment *env)
446  {  {
447    stackitem *temp= env->head;    stackitem *temp= env->head;
448        
449    if((env->head)==NULL) {    if(env->head==NULL || env->head->next==NULL) {
     printerr("Too Few Arguments");  
     env->err=1;  
     return;  
   }  
   
   if(env->head->next==NULL) {  
450      printerr("Too Few Arguments");      printerr("Too Few Arguments");
451      env->err=1;      env->err=1;
452      return;      return;
# Line 384  extern void swap(environment *env) Line 457  extern void swap(environment *env)
457    env->head->next= temp;    env->head->next= temp;
458  }  }
459    
460  stackitem* copy(stackitem* in_item)  /* Rotate the first three elements on the stack. */
461    extern void rot(environment *env)
462  {  {
463    stackitem *out_item= malloc(sizeof(stackitem));    stackitem *temp= env->head;
464      
465    memcpy(out_item, in_item, sizeof(stackitem));    if(env->head==NULL || env->head->next==NULL
466    out_item->next= NULL;        || env->head->next->next==NULL) {
467        printerr("Too Few Arguments");
468        env->err=1;
469        return;
470      }
471    
472    return out_item;    env->head= env->head->next->next;
473      temp->next->next= env->head->next;
474      env->head->next= temp;
475  }  }
476    
477  /* Recall a value from a symbol, if bound */  /* Recall a value from a symbol, if bound */
# Line 419  extern void rcl(environment *env) Line 499  extern void rcl(environment *env)
499    }    }
500    toss(env);            /* toss the symbol */    toss(env);            /* toss the symbol */
501    if(env->err) return;    if(env->err) return;
502    push_val(&(env->head), val); /* Return its bound value */    push_val(env, val); /* Return its bound value */
503  }  }
504    
505  /* If the top element is a symbol, determine if it's bound to a  /* If the top element is a symbol, determine if it's bound to a
# Line 428  extern void rcl(environment *env) Line 508  extern void rcl(environment *env)
508  extern void eval(environment *env)  extern void eval(environment *env)
509  {  {
510    funcp in_func;    funcp in_func;
511      value* temp_val;
512      stackitem* iterator;
513    
514     eval_start:
515    
516    if(env->head==NULL) {    if(env->head==NULL) {
517      printerr("Too Few Arguments");      printerr("Too Few Arguments");
518      env->err=1;      env->err=1;
519      return;      return;
520    }    }
521    
522    /* if it's a symbol */    switch(env->head->item->type) {
523    if(env->head->item->type==symb) {      /* if it's a symbol */
524      case symb:
525      rcl(env);                   /* get its contents */      rcl(env);                   /* get its contents */
526      if(env->err) return;      if(env->err) return;
527      if(env->head->item->type!=symb){ /* don't recurse symbols */      if(env->head->item->type!=symb){ /* don't recurse symbols */
528        eval(env);                        /* evaluate the value */        goto eval_start;
       return;  
529      }      }
530    }      return;
531    
532    /* If it's a lone function value, run it */      /* If it's a lone function value, run it */
533    if(env->head->item->type==func) {    case func:
534      in_func= (funcp)(env->head->item->content.ptr);      in_func= (funcp)(env->head->item->content.ptr);
535      toss(env);      toss(env);
536      if(env->err) return;      if(env->err) return;
537      (*in_func)(env);      return in_func(env);
538    
539        /* If it's a list */
540      case list:
541        temp_val= env->head->item;
542        toss(env);
543        if(env->err) return;
544        iterator= (stackitem*)temp_val->content.ptr;
545        while(iterator!=NULL) {
546          push_val(env, iterator->item);
547          if(env->head->item->type==symb
548            && strcmp(";", ((symbol*)(env->head->item->content.ptr))->id)==0) {
549            toss(env);
550            if(env->err) return;
551            if(iterator->next == NULL){
552              goto eval_start;
553            }
554            eval(env);
555            if(env->err) return;
556          }
557          iterator= iterator->next;
558        }
559        return;
560    
561      default:
562        return;
563    }    }
564  }  }
565    
566  /* Reverse a list */  /* Reverse (flip) a list */
567  extern void rev(environment *env){  extern void rev(environment *env){
568    stackitem *old_head, *new_head, *item;    stackitem *old_head, *new_head, *item;
569    
# Line 484  extern void rev(environment *env){ Line 593  extern void rev(environment *env){
593  /* Make a list. */  /* Make a list. */
594  extern void pack(environment *env)  extern void pack(environment *env)
595  {  {
   void* delimiter;  
596    stackitem *iterator, *temp;    stackitem *iterator, *temp;
597    value *pack;    value *pack;
598    
   delimiter= env->head->item->content.ptr; /* Get delimiter */  
   toss(env);  
   
599    iterator= env->head;    iterator= env->head;
600    
601    if(iterator==NULL || iterator->item->content.ptr==delimiter) {    if(iterator==NULL
602         || (iterator->item->type==symb
603         && ((symbol*)(iterator->item->content.ptr))->id[0]=='[')) {
604      temp= NULL;      temp= NULL;
605      toss(env);      toss(env);
606    } else {    } else {
607      /* Search for first delimiter */      /* Search for first delimiter */
608      while(iterator->next!=NULL      while(iterator->next!=NULL
609            && iterator->next->item->content.ptr!=delimiter)            && (iterator->next->item->type!=symb
610              || ((symbol*)(iterator->next->item->content.ptr))->id[0]!='['))
611        iterator= iterator->next;        iterator= iterator->next;
612            
613      /* Extract list */      /* Extract list */
# Line 512  extern void pack(environment *env) Line 620  extern void pack(environment *env)
620    }    }
621    
622    /* Push list */    /* Push list */
623    pack= malloc(sizeof(value));    pack= new_val(env);
624    pack->type= list;    pack->type= list;
625    pack->content.ptr= temp;    pack->content.ptr= temp;
   pack->refcount= 1;  
   
   temp= malloc(sizeof(stackitem));  
   temp->item= pack;  
626    
627    push(&(env->head), temp);    push_val(env, pack);
628    rev(env);    rev(env);
629  }  }
630    
 /* Parse input. */  
 void stack_read(environment *env, char *in_line)  
 {  
   char *temp, *rest;  
   int itemp;  
   size_t inlength= strlen(in_line)+1;  
   int convert= 0;  
   static int non_eval_flag= 0;  
   
   temp= malloc(inlength);  
   rest= malloc(inlength);  
   
   do {  
     /* If string */  
     if((convert= sscanf(in_line, "\"%[^\"\n\r]\" %[^\n\r]", temp, rest))) {  
       push_cstring(&(env->head), temp);  
       break;  
     }  
     /* If integer */  
     if((convert= sscanf(in_line, "%d %[^\n\r]", &itemp, rest))) {  
       push_int(&(env->head), itemp);  
       break;  
     }  
     /* Escape ';' with '\' */  
     if((convert= sscanf(in_line, "\\%c%[^\n\r]", temp, rest))) {  
       temp[1]= '\0';  
       push_sym(env, temp);  
       break;  
     }  
     /* If symbol */  
     if((convert= sscanf(in_line, "%[^][ ;\n\r]%[^\n\r]", temp, rest))) {  
         push_sym(env, temp);  
         break;  
     }  
     /* If single char */  
     if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest))) {  
       if(*temp==';') {  
         if(!non_eval_flag) {  
           eval(env);            /* Evaluate top element */  
           break;  
         }  
           
         push_sym(env, ";");  
         break;  
       }  
   
       if(*temp==']') {  
         push_sym(env, "[");  
         pack(env);  
         if(non_eval_flag!=0)  
           non_eval_flag--;  
         break;  
       }  
   
       if(*temp=='[') {  
         push_sym(env, "[");  
         non_eval_flag++;  
         break;  
       }  
     }  
   } while(0);  
   
   free(temp);  
   
   if(convert<2) {  
     free(rest);  
     return;  
   }  
     
   stack_read(env, rest);  
     
   free(rest);  
 }  
   
631  /* Relocate elements of the list on the stack. */  /* Relocate elements of the list on the stack. */
632  extern void expand(environment *env)  extern void expand(environment *env)
633  {  {
# Line 615  extern void expand(environment *env) Line 645  extern void expand(environment *env)
645      return;      return;
646    }    }
647    
648      rev(env);
649    
650      if(env->err)
651        return;
652    
653    /* The first list element is the new stack head */    /* The first list element is the new stack head */
654    new_head= temp= env->head->item->content.ptr;    new_head= temp= env->head->item->content.ptr;
655    
   env->head->item->refcount++;  
656    toss(env);    toss(env);
657    
658    /* Find the end of the list */    /* Find the end of the list */
# Line 649  extern void eq(environment *env) Line 683  extern void eq(environment *env)
683    result= (left==right);    result= (left==right);
684        
685    toss(env); toss(env);    toss(env); toss(env);
686    push_int(&(env->head), result);    push_int(env, result);
687  }  }
688    
689  /* Negates the top element on the stack. */  /* Negates the top element on the stack. */
# Line 671  extern void not(environment *env) Line 705  extern void not(environment *env)
705    
706    val= env->head->item->content.val;    val= env->head->item->content.val;
707    toss(env);    toss(env);
708    push_int(&(env->head), !val);    push_int(env, !val);
709  }  }
710    
711  /* Compares the two top elements on the stack and return 0 if they're the  /* Compares the two top elements on the stack and return 0 if they're the
# Line 704  extern void def(environment *env) Line 738  extern void def(environment *env)
738    sym=env->head->item->content.ptr;    sym=env->head->item->content.ptr;
739    
740    /* if the symbol was bound to something else, throw it away */    /* if the symbol was bound to something else, throw it away */
   if(sym->val != NULL)  
     free_val(sym->val);  
741    
742    /* Bind the symbol to the value */    /* Bind the symbol to the value */
743    sym->val= env->head->next->item;    sym->val= env->head->next->item;
   sym->val->refcount++;         /* Increase the reference counter */  
744    
745    toss(env); toss(env);    toss(env); toss(env);
746  }  }
# Line 717  extern void def(environment *env) Line 748  extern void def(environment *env)
748  /* Quit stack. */  /* Quit stack. */
749  extern void quit(environment *env)  extern void quit(environment *env)
750  {  {
751      long i;
752    
753      clear(env);
754    
755      if (env->err) return;
756      for(i= 0; i<HASHTBLSIZE; i++) {
757        while(env->symbols[i]!= NULL) {
758          forget_sym(&(env->symbols[i]));
759        }
760        env->symbols[i]= NULL;
761      }
762    
763      gc_init(env);
764    
765      if(env->free_string!=NULL)
766        free(env->free_string);
767      
768      muntrace();
769    
770    exit(EXIT_SUCCESS);    exit(EXIT_SUCCESS);
771  }  }
772    
# Line 742  extern void words(environment *env) Line 792  extern void words(environment *env)
792    }    }
793  }  }
794    
795    /* Internal forget function */
796    void forget_sym(symbol **hash_entry) {
797      symbol *temp;
798    
799      temp= *hash_entry;
800      *hash_entry= (*hash_entry)->next;
801      
802      free(temp->id);
803      free(temp);
804    }
805    
806  /* Forgets a symbol (remove it from the hash table) */  /* Forgets a symbol (remove it from the hash table) */
807  extern void forget(environment *env)  extern void forget(environment *env)
808  {  {
809    char* sym_id;    char* sym_id;
810    stackitem *stack_head= env->head;    stackitem *stack_head= env->head;
   symbol **hash_entry, *temp;  
811    
812    if(stack_head==NULL) {    if(stack_head==NULL) {
813      printerr("Too Few Arguments");      printerr("Too Few Arguments");
# Line 764  extern void forget(environment *env) Line 824  extern void forget(environment *env)
824    sym_id= ((symbol*)(stack_head->item->content.ptr))->id;    sym_id= ((symbol*)(stack_head->item->content.ptr))->id;
825    toss(env);    toss(env);
826    
827    hash_entry= hash(env->symbols, sym_id);    return forget_sym(hash(env->symbols, sym_id));
   temp= *hash_entry;  
   *hash_entry= (*hash_entry)->next;  
     
   if(temp->val!=NULL) {  
     free_val(temp->val);  
   }  
   free(temp->id);  
   free(temp);  
828  }  }
829    
830  /* Returns the current error number to the stack */  /* Returns the current error number to the stack */
831  extern void errn(environment *env){  extern void errn(environment *env){
832    push_int(&(env->head), env->err);    push_int(env, env->err);
833  }  }
834    
835  int main()  int main(int argc, char **argv)
836  {  {
837    environment myenv;    environment myenv;
838    char in_string[100];  
839      int c;                        /* getopt option character */
840    
841      mtrace();
842    
843    init_env(&myenv);    init_env(&myenv);
844    
845    printf("okidok\n ");    myenv.interactive = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO);
846    
847    while(fgets(in_string, 100, stdin) != NULL) {    while ((c = getopt (argc, argv, "i")) != -1)
848      stack_read(&myenv, in_string);      switch (c)
849      if(myenv.err) {        {
850        printf("(error %d) ", myenv.err);        case 'i':
851            myenv.interactive = 1;
852            break;
853          case '?':
854            fprintf (stderr,
855                     "Unknown option character `\\x%x'.\n",
856                     optopt);
857            return EX_USAGE;
858          default:
859            abort ();
860          }
861      
862      if (optind < argc) {
863        myenv.interactive = 0;
864        myenv.inputstream= fopen(argv[optind], "r");
865        if(myenv.inputstream== NULL) {
866          perror(argv[0]);
867          exit (EX_NOINPUT);
868        }
869      }
870    
871      while(1) {
872        if(myenv.in_string==NULL) {
873          if (myenv.interactive) {
874            if(myenv.err) {
875              printf("(error %d)\n", myenv.err);
876            }
877            nl();
878            printstack(&myenv);
879            printf("> ");
880          }
881        myenv.err=0;        myenv.err=0;
882      }      }
883      printf("okidok\n ");      sx_72656164(&myenv);
884        if (myenv.err==4) {
885          return EX_NOINPUT;
886        } else if(myenv.head!=NULL
887                  && myenv.head->item->type==symb
888                  && ((symbol*)(myenv.head->item->content.ptr))->id[0]==';') {
889          toss(&myenv);             /* No error check in main */
890          eval(&myenv);
891        }
892        gc_init(&myenv);
893    }    }
894    quit(&myenv);    quit(&myenv);
895    return EXIT_FAILURE;    return EXIT_FAILURE;
896  }  }
897    
898    /* "+" */
899    extern void sx_2b(environment *env) {
900      int a, b;
901      size_t len;
902      char* new_string;
903      value *a_val, *b_val;
904    
905      if((env->head)==NULL || env->head->next==NULL) {
906        printerr("Too Few Arguments");
907        env->err=1;
908        return;
909      }
910    
911      if(env->head->item->type==string
912         && env->head->next->item->type==string) {
913        a_val= env->head->item;
914        b_val= env->head->next->item;
915        toss(env); if(env->err) return;
916        toss(env); if(env->err) return;
917        len= strlen(a_val->content.ptr)+strlen(b_val->content.ptr)+1;
918        new_string= malloc(len);
919        strcpy(new_string, b_val->content.ptr);
920        strcat(new_string, a_val->content.ptr);
921        push_cstring(env, new_string);
922        free(new_string);
923        return;
924      }
925      
926      if(env->head->item->type!=integer
927         || env->head->next->item->type!=integer) {
928        printerr("Bad Argument Type");
929        env->err=2;
930        return;
931      }
932      a=env->head->item->content.val;
933      toss(env); if(env->err) return;
934      
935      b=env->head->item->content.val;
936      toss(env); if(env->err) return;
937      push_int(env, a+b);
938    }
939    
940    /* "-" */
941    extern void sx_2d(environment *env) {
942      int a, b;
943    
944      if((env->head)==NULL || env->head->next==NULL) {
945        printerr("Too Few Arguments");
946        env->err=1;
947        return;
948      }
949      
950      if(env->head->item->type!=integer
951         || env->head->next->item->type!=integer) {
952        printerr("Bad Argument Type");
953        env->err=2;
954        return;
955      }
956      a=env->head->item->content.val;
957      toss(env); if(env->err) return;
958      b=env->head->item->content.val;
959      toss(env); if(env->err) return;
960      push_int(env, b-a);
961    }
962    
963    /* ">" */
964    extern void sx_3e(environment *env) {
965      int a, b;
966    
967      if((env->head)==NULL || env->head->next==NULL) {
968        printerr("Too Few Arguments");
969        env->err=1;
970        return;
971      }
972      
973      if(env->head->item->type!=integer
974         || env->head->next->item->type!=integer) {
975        printerr("Bad Argument Type");
976        env->err=2;
977        return;
978      }
979      a=env->head->item->content.val;
980      toss(env); if(env->err) return;
981      b=env->head->item->content.val;
982      toss(env); if(env->err) return;
983      push_int(env, b>a);
984    }
985    
986    /* Return copy of a value */
987    value *copy_val(environment *env, value *old_value){
988      stackitem *old_item, *new_item, *prev_item;
989    
990      value *new_value=new_val(env);
991    
992      new_value->type=old_value->type;
993    
994      switch(old_value->type){
995      case integer:
996        new_value->content.val=old_value->content.val;
997        break;
998      case string:
999        (char *)(new_value->content.ptr)
1000          = strdup((char *)(old_value->content.ptr));
1001        break;
1002      case func:
1003      case symb:
1004        new_value->content.ptr=old_value->content.ptr;
1005        break;
1006      case list:
1007        new_value->content.ptr=NULL;
1008    
1009        prev_item=NULL;
1010        old_item=(stackitem *)(old_value->content.ptr);
1011    
1012        while(old_item != NULL) {   /* While list is not empty */
1013          new_item= malloc(sizeof(stackitem));
1014          new_item->item=copy_val(env, old_item->item); /* recurse */
1015          new_item->next=NULL;
1016          if(prev_item != NULL)     /* If this wasn't the first item */
1017            prev_item->next=new_item; /* point the previous item to the
1018                                         new item */
1019          else
1020            new_value->content.ptr=new_item;
1021          old_item=old_item->next;
1022          prev_item=new_item;
1023        }    
1024        break;
1025      }
1026      return new_value;
1027    }
1028    
1029    /* "dup"; duplicates an item on the stack */
1030    extern void sx_647570(environment *env) {
1031      if((env->head)==NULL) {
1032        printerr("Too Few Arguments");
1033        env->err=1;
1034        return;
1035      }
1036      push_val(env, copy_val(env, env->head->item));
1037    }
1038    
1039    /* "if", If-Then */
1040    extern void sx_6966(environment *env) {
1041    
1042      int truth;
1043    
1044      if((env->head)==NULL || env->head->next==NULL) {
1045        printerr("Too Few Arguments");
1046        env->err=1;
1047        return;
1048      }
1049    
1050      if(env->head->next->item->type != integer) {
1051        printerr("Bad Argument Type");
1052        env->err=2;
1053        return;
1054      }
1055      
1056      swap(env);
1057      if(env->err) return;
1058      
1059      truth=env->head->item->content.val;
1060    
1061      toss(env);
1062      if(env->err) return;
1063    
1064      if(truth)
1065        eval(env);
1066      else
1067        toss(env);
1068    }
1069    
1070    /* If-Then-Else */
1071    extern void ifelse(environment *env) {
1072    
1073      int truth;
1074    
1075      if((env->head)==NULL || env->head->next==NULL
1076         || env->head->next->next==NULL) {
1077        printerr("Too Few Arguments");
1078        env->err=1;
1079        return;
1080      }
1081    
1082      if(env->head->next->next->item->type != integer) {
1083        printerr("Bad Argument Type");
1084        env->err=2;
1085        return;
1086      }
1087      
1088      rot(env);
1089      if(env->err) return;
1090      
1091      truth=env->head->item->content.val;
1092    
1093      toss(env);
1094      if(env->err) return;
1095    
1096      if(!truth)
1097        swap(env);
1098      if(env->err) return;
1099    
1100      toss(env);
1101      if(env->err) return;
1102    
1103      eval(env);
1104    }
1105    
1106    /* "while" */
1107    extern void sx_7768696c65(environment *env) {
1108    
1109      int truth;
1110      value *loop, *test;
1111    
1112      if((env->head)==NULL || env->head->next==NULL) {
1113        printerr("Too Few Arguments");
1114        env->err=1;
1115        return;
1116      }
1117    
1118      loop= env->head->item;
1119      toss(env); if(env->err) return;
1120    
1121      test= env->head->item;
1122      toss(env); if(env->err) return;
1123    
1124      do {
1125        push_val(env, test);
1126        eval(env);
1127        
1128        if(env->head->item->type != integer) {
1129          printerr("Bad Argument Type");
1130          env->err=2;
1131          return;
1132        }
1133        
1134        truth= env->head->item->content.val;
1135        toss(env); if(env->err) return;
1136        
1137        if(truth) {
1138          push_val(env, loop);
1139          eval(env);
1140        } else {
1141          toss(env);
1142        }
1143      
1144      } while(truth);
1145    }
1146    
1147    
1148    /* "for"; for-loop */
1149    extern void sx_666f72(environment *env) {
1150      value *loop;
1151      int foo1, foo2;
1152    
1153      if(env->head==NULL || env->head->next==NULL
1154         || env->head->next->next==NULL) {
1155        printerr("Too Few Arguments");
1156        env->err= 1;
1157        return;
1158      }
1159    
1160      if(env->head->next->item->type!=integer
1161         || env->head->next->next->item->type!=integer) {
1162        printerr("Bad Argument Type");
1163        env->err= 2;
1164        return;
1165      }
1166    
1167      loop= env->head->item;
1168      toss(env); if(env->err) return;
1169    
1170      foo2= env->head->item->content.val;
1171      toss(env); if(env->err) return;
1172    
1173      foo1= env->head->item->content.val;
1174      toss(env); if(env->err) return;
1175    
1176      if(foo1<=foo2) {
1177        while(foo1<=foo2) {
1178          push_int(env, foo1);
1179          push_val(env, loop);
1180          eval(env); if(env->err) return;
1181          foo1++;
1182        }
1183      } else {
1184        while(foo1>=foo2) {
1185          push_int(env, foo1);
1186          push_val(env, loop);
1187          eval(env); if(env->err) return;
1188          foo1--;
1189        }
1190      }
1191    }
1192    
1193    /* Variant of for-loop */
1194    extern void foreach(environment *env) {
1195      
1196      value *loop, *foo;
1197      stackitem *iterator;
1198      
1199      if((env->head)==NULL || env->head->next==NULL) {
1200        printerr("Too Few Arguments");
1201        env->err=1;
1202        return;
1203      }
1204    
1205      if(env->head->next->item->type != list) {
1206        printerr("Bad Argument Type");
1207        env->err=2;
1208        return;
1209      }
1210    
1211      loop= env->head->item;
1212      toss(env); if(env->err) return;
1213    
1214      foo= env->head->item;
1215      toss(env); if(env->err) return;
1216    
1217      iterator= foo->content.ptr;
1218    
1219      while(iterator!=NULL) {
1220        push_val(env, iterator->item);
1221        push_val(env, loop);
1222        eval(env); if(env->err) return;
1223        iterator= iterator->next;
1224      }
1225    }
1226    
1227    /* "to" */
1228    extern void to(environment *env) {
1229      int i, start, ending;
1230      stackitem *temp_head;
1231      value *temp_val;
1232      
1233      if((env->head)==NULL || env->head->next==NULL) {
1234        printerr("Too Few Arguments");
1235        env->err=1;
1236        return;
1237      }
1238    
1239      if(env->head->item->type!=integer
1240         || env->head->next->item->type!=integer) {
1241        printerr("Bad Argument Type");
1242        env->err=2;
1243        return;
1244      }
1245    
1246      ending= env->head->item->content.val;
1247      toss(env); if(env->err) return;
1248      start= env->head->item->content.val;
1249      toss(env); if(env->err) return;
1250    
1251      temp_head= env->head;
1252      env->head= NULL;
1253    
1254      if(ending>=start) {
1255        for(i= ending; i>=start; i--)
1256          push_int(env, i);
1257      } else {
1258        for(i= ending; i<=start; i++)
1259          push_int(env, i);
1260      }
1261    
1262      temp_val= new_val(env);
1263      temp_val->content.ptr= env->head;
1264      temp_val->type= list;
1265      env->head= temp_head;
1266      push_val(env, temp_val);
1267    }
1268    
1269    /* Read a string */
1270    extern void readline(environment *env) {
1271      char in_string[101];
1272    
1273      if(fgets(in_string, 100, env->inputstream)==NULL)
1274        push_cstring(env, "");
1275      else
1276        push_cstring(env, in_string);
1277    }
1278    
1279    /* "read"; Read a value and place on stack */
1280    extern void sx_72656164(environment *env) {
1281      const char symbform[]= "%[a-zA-Z0-9!$%*+./:<=>?@^_~-]%n";
1282      const char strform[]= "\"%[^\"]\"%n";
1283      const char intform[]= "%i%n";
1284      const char blankform[]= "%*[ \t]%n";
1285      const char ebrackform[]= "%*1[]]%n";
1286      const char semicform[]= "%*1[;]%n";
1287      const char bbrackform[]= "%*1[[]%n";
1288    
1289      int itemp, readlength= -1;
1290      static int depth= 0;
1291      char *match;
1292      size_t inlength;
1293    
1294      if(env->in_string==NULL) {
1295        if(depth > 0 && env->interactive) {
1296          printf("]> ");
1297        }
1298        readline(env); if(env->err) return;
1299    
1300        if(((char *)(env->head->item->content.ptr))[0]=='\0'){
1301          env->err= 4;              /* "" means EOF */
1302          return;
1303        }
1304        
1305        env->in_string= malloc(strlen(env->head->item->content.ptr)+1);
1306        env->free_string= env->in_string; /* Save the original pointer */
1307        strcpy(env->in_string, env->head->item->content.ptr);
1308        toss(env); if(env->err) return;
1309      }
1310      
1311      inlength= strlen(env->in_string)+1;
1312      match= malloc(inlength);
1313    
1314      if(sscanf(env->in_string, blankform, &readlength)!=EOF
1315         && readlength != -1) {
1316        ;
1317      } else if(sscanf(env->in_string, intform, &itemp, &readlength) != EOF
1318                && readlength != -1) {
1319        push_int(env, itemp);
1320      } else if(sscanf(env->in_string, strform, match, &readlength) != EOF
1321                && readlength != -1) {
1322        push_cstring(env, match);
1323      } else if(sscanf(env->in_string, symbform, match, &readlength) != EOF
1324                && readlength != -1) {
1325        push_sym(env, match);
1326      } else if(sscanf(env->in_string, ebrackform, &readlength) != EOF
1327                && readlength != -1) {
1328        pack(env); if(env->err) return;
1329        if(depth != 0) depth--;
1330      } else if(sscanf(env->in_string, semicform, &readlength) != EOF
1331                && readlength != -1) {
1332        push_sym(env, ";");
1333      } else if(sscanf(env->in_string, bbrackform, &readlength) != EOF
1334                && readlength != -1) {
1335        push_sym(env, "[");
1336        depth++;
1337      } else {
1338        free(env->free_string);
1339        env->in_string = env->free_string = NULL;
1340      }
1341      if ( env->in_string != NULL) {
1342        env->in_string += readlength;
1343      }
1344    
1345      free(match);
1346    
1347      if(depth)
1348        return sx_72656164(env);
1349    }

Legend:
Removed from v.1.42  
changed lines
  Added in v.1.89

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26