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

Diff of /stack/stack.c

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

revision 1.43 by masse, Wed Feb 6 23:27:22 2002 UTC revision 1.60 by teddy, Fri Feb 8 05:12:37 2002 UTC
# Line 1  Line 1 
1  /* printf */  /* printf, sscanf, fgets, fprintf */
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    
12  #define HASHTBLSIZE 65536  #define HASHTBLSIZE 65536
13    
# Line 48  typedef symbol *hashtbl[HASHTBLSIZE]; /* Line 48  typedef symbol *hashtbl[HASHTBLSIZE]; /*
48  typedef struct stackitem_struct  typedef struct stackitem_struct
49  {  {
50    value *item;                  /* The value on the stack */    value *item;                  /* The value on the stack */
51                                    /* (This is never NULL) */
52    struct stackitem_struct *next; /* Next item */    struct stackitem_struct *next; /* Next item */
53  } stackitem;  } stackitem;
54    
# Line 57  typedef struct { Line 58  typedef struct {
58    stackitem *head;              /* Head of the stack */    stackitem *head;              /* Head of the stack */
59    hashtbl symbols;              /* Hash table of all variable bindings */    hashtbl symbols;              /* Hash table of all variable bindings */
60    int err;                      /* Error flag */    int err;                      /* Error flag */
61      int non_eval_flag;
62  } environment;  } environment;
63    
64  /* A type for pointers to external functions */  /* A type for pointers to external functions */
# Line 66  typedef void (*funcp)(environment *); /* Line 68  typedef void (*funcp)(environment *); /*
68  /* Initialize a newly created environment */  /* Initialize a newly created environment */
69  void init_env(environment *env)  void init_env(environment *env)
70  {  {
71    long i;    int i;
72    
73    env->err=0;    env->err= 0;
74      env->non_eval_flag= 0;
75    for(i= 0; i<HASHTBLSIZE; i++)    for(i= 0; i<HASHTBLSIZE; i++)
76      env->symbols[i]= NULL;      env->symbols[i]= NULL;
77  }  }
78    
79    void printerr(const char* in_string) {
80      fprintf(stderr, "Err: %s\n", in_string);
81    }
82    
83    /* Throw away a value */
84    void free_val(value *val){
85      stackitem *item, *temp;
86    
87      val->refcount--;              /* Decrease the reference count */
88      if(val->refcount == 0){
89        switch (val->type){         /* and free the contents if necessary */
90        case string:
91          free(val->content.ptr);
92          break;
93        case list:                  /* lists needs to be freed recursively */
94          item=val->content.ptr;
95          while(item != NULL) {     /* for all stack items */
96            free_val(item->item);   /* free the value */
97            temp=item->next;        /* save next ptr */
98            free(item);             /* free the stackitem */
99            item=temp;              /* go to next stackitem */
100          }
101          free(val);                /* Free the actual list value */
102          break;
103        case integer:
104        case func:
105        case symb:
106          break;
107        }
108      }
109    }
110    
111    /* Discard the top element of the stack. */
112    extern void toss(environment *env)
113    {
114      stackitem *temp= env->head;
115    
116      if((env->head)==NULL) {
117        printerr("Too Few Arguments");
118        env->err=1;
119        return;
120      }
121      
122      free_val(env->head->item);    /* Free the value */
123      env->head= env->head->next;   /* Remove the top stack item */
124      free(temp);                   /* Free the old top stack item */
125    }
126    
127  /* 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. */
128  symbol **hash(hashtbl in_hashtbl, const char *in_string)  symbol **hash(hashtbl in_hashtbl, const char *in_string)
129  {  {
130    long i= 0;    int i= 0;
131    unsigned long out_hash= 0;    unsigned int out_hash= 0;
132    char key= '\0';    char key= '\0';
133    symbol **position;    symbol **position;
134        
# Line 147  void push_cstring(stackitem **stack_head Line 198  void push_cstring(stackitem **stack_head
198    push(stack_head, new_item);    push(stack_head, new_item);
199  }  }
200    
201    /* Mangle a symbol name to a valid C identifier name */
202    char *mangle_str(const char *old_string){
203      char validchars[]
204        ="0123456789abcdef";
205      char *new_string, *current;
206    
207      new_string=malloc((strlen(old_string)*2)+4);
208      strcpy(new_string, "sx_");    /* Stack eXternal */
209      current=new_string+3;
210      while(old_string[0] != '\0'){
211        current[0]=validchars[(unsigned char)(old_string[0])/16];
212        current[1]=validchars[(unsigned char)(old_string[0])%16];
213        current+=2;
214        old_string++;
215      }
216      current[0]='\0';
217    
218      return new_string;            /* The caller must free() it */
219    }
220    
221    extern void mangle(environment *env){
222      value *new_value;
223      char *new_string;
224    
225      if((env->head)==NULL) {
226        printerr("Too Few Arguments");
227        env->err=1;
228        return;
229      }
230    
231      if(env->head->item->type!=string) {
232        printerr("Bad Argument Type");
233        env->err=2;
234        return;
235      }
236    
237      new_string= mangle_str((const char *)(env->head->item->content.ptr));
238    
239      toss(env);
240      if(env->err) return;
241    
242      new_value= malloc(sizeof(value));
243      new_value->content.ptr= new_string;
244      new_value->type= string;
245      new_value->refcount=1;
246    
247      push_val(&(env->head), new_value);
248    }
249    
250  /* Push a symbol onto the stack. */  /* Push a symbol onto the stack. */
251  void push_sym(environment *env, const char *in_string)  void push_sym(environment *env, const char *in_string)
252  {  {
# Line 161  void push_sym(environment *env, const ch Line 261  void push_sym(environment *env, const ch
261    void *funcptr;                /* A function pointer */    void *funcptr;                /* A function pointer */
262    
263    static void *handle= NULL;    /* Dynamic linker handle */    static void *handle= NULL;    /* Dynamic linker handle */
264      const char *dlerr;            /* Dynamic linker error */
265      char *mangled;                /* Mangled function name */
266    
267    /* Create a new stack item containing a new value */    /* Create a new stack item containing a new value */
268    new_item= malloc(sizeof(stackitem));    new_item= malloc(sizeof(stackitem));
# Line 193  void push_sym(environment *env, const ch Line 295  void push_sym(environment *env, const ch
295        handle= dlopen(NULL, RTLD_LAZY);        handle= dlopen(NULL, RTLD_LAZY);
296    
297      funcptr= dlsym(handle, in_string); /* Get function pointer */      funcptr= dlsym(handle, in_string); /* Get function pointer */
298      if(dlerror()==NULL) {       /* If a function was found */      dlerr=dlerror();
299        if(dlerr != NULL) {         /* If no function was found */
300          mangled=mangle_str(in_string);
301          funcptr= dlsym(handle, mangled); /* try mangling it */
302          free(mangled);
303          dlerr=dlerror();
304        }
305        if(dlerr==NULL) {           /* If a function was found */
306        new_fvalue= malloc(sizeof(value)); /* Create a new value */        new_fvalue= malloc(sizeof(value)); /* Create a new value */
307        new_fvalue->type=func;    /* The new value is a function pointer */        new_fvalue->type=func;    /* The new value is a function pointer */
308        new_fvalue->content.ptr=funcptr; /* Store function pointer */        new_fvalue->content.ptr=funcptr; /* Store function pointer */
# Line 205  void push_sym(environment *env, const ch Line 314  void push_sym(environment *env, const ch
314    push(&(env->head), new_item);    push(&(env->head), new_item);
315  }  }
316    
 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;  
     }  
   }  
 }  
   
 /* 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 */  
 }  
   
317  /* Print newline. */  /* Print newline. */
318  extern void nl()  extern void nl()
319  {  {
# Line 284  extern void type(environment *env){ Line 347  extern void type(environment *env){
347    case list:    case list:
348      push_sym(env, "list");      push_sym(env, "list");
349      break;      break;
   default:  
     push_sym(env, "unknown");  
     break;  
350    }    }
351  }      }    
352    
# Line 298  void print_h(stackitem *stack_head) Line 358  void print_h(stackitem *stack_head)
358      printf("%d", stack_head->item->content.val);      printf("%d", stack_head->item->content.val);
359      break;      break;
360    case string:    case string:
361      printf("\"%s\"", (char*)stack_head->item->content.ptr);      printf("%s", (char*)stack_head->item->content.ptr);
362      break;      break;
363    case symb:    case symb:
364      printf("'%s'", ((symbol *)(stack_head->item->content.ptr))->id);      printf("%s", ((symbol *)(stack_head->item->content.ptr))->id);
365      break;      break;
366    case func:    case func:
367      printf("#<function %p>", (funcp)(stack_head->item->content.ptr));      printf("#<function %p>", (funcp)(stack_head->item->content.ptr));
# Line 317  void print_h(stackitem *stack_head) Line 377  void print_h(stackitem *stack_head)
377      }      }
378      printf("]");      printf("]");
379      break;      break;
   default:  
     printf("#<unknown %p>", (stack_head->item->content.ptr));  
     break;  
380    }    }
381  }  }
382    
# Line 350  void print_st(stackitem *stack_head, lon Line 407  void print_st(stackitem *stack_head, lon
407    nl();    nl();
408  }  }
409    
   
   
410  /* Prints the stack. */  /* Prints the stack. */
411  extern void printstack(environment *env)  extern void printstack(environment *env)
412  {  {
# Line 367  extern void swap(environment *env) Line 422  extern void swap(environment *env)
422  {  {
423    stackitem *temp= env->head;    stackitem *temp= env->head;
424        
425    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) {  
426      printerr("Too Few Arguments");      printerr("Too Few Arguments");
427      env->err=1;      env->err=1;
428      return;      return;
# Line 384  extern void swap(environment *env) Line 433  extern void swap(environment *env)
433    env->head->next= temp;    env->head->next= temp;
434  }  }
435    
436  stackitem* copy(stackitem* in_item)  /* Rotate the first three elements on the stack. */
437    extern void rot(environment *env)
438  {  {
439    stackitem *out_item= malloc(sizeof(stackitem));    stackitem *temp= env->head;
440      
441    memcpy(out_item, in_item, sizeof(stackitem));    if(env->head==NULL || env->head->next==NULL
442    out_item->next= NULL;        || env->head->next->next==NULL) {
443        printerr("Too Few Arguments");
444        env->err=1;
445        return;
446      }
447    
448    return out_item;    env->head= env->head->next->next;
449      temp->next->next= env->head->next;
450      env->head->next= temp;
451  }  }
452    
453  /* Recall a value from a symbol, if bound */  /* Recall a value from a symbol, if bound */
# Line 422  extern void rcl(environment *env) Line 478  extern void rcl(environment *env)
478    push_val(&(env->head), val); /* Return its bound value */    push_val(&(env->head), val); /* Return its bound value */
479  }  }
480    
481    void stack_read(environment*, char*);
482    
483  /* 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
484     function value, and if it is, toss the symbol and execute the     function value, and if it is, toss the symbol and execute the
485     function. */     function. */
486  extern void eval(environment *env)  extern void eval(environment *env)
487  {  {
488    funcp in_func;    funcp in_func;
489      value* temp_val;
490      stackitem* iterator;
491      char* temp_string;
492    
493    if(env->head==NULL) {    if(env->head==NULL) {
494      printerr("Too Few Arguments");      printerr("Too Few Arguments");
495      env->err=1;      env->err=1;
496      return;      return;
497    }    }
498    
499    /* if it's a symbol */    switch(env->head->item->type) {
500    if(env->head->item->type==symb) {      /* if it's a symbol */
501      case symb:
502      rcl(env);                   /* get its contents */      rcl(env);                   /* get its contents */
503      if(env->err) return;      if(env->err) return;
504      if(env->head->item->type!=symb){ /* don't recurse symbols */      if(env->head->item->type!=symb){ /* don't recurse symbols */
505        eval(env);                        /* evaluate the value */        return eval(env);         /* evaluate the value */
       return;  
506      }      }
507    }      return;
508    
509    /* If it's a lone function value, run it */      /* If it's a lone function value, run it */
510    if(env->head->item->type==func) {    case func:
511      in_func= (funcp)(env->head->item->content.ptr);      in_func= (funcp)(env->head->item->content.ptr);
512      toss(env);      toss(env);
513      if(env->err) return;      if(env->err) return;
514      (*in_func)(env);      return (*in_func)(env);
515    
516        /* If it's a list */
517      case list:
518        temp_val= env->head->item;
519        env->head->item->refcount++;
520        toss(env);
521        if(env->err) return;
522        iterator= (stackitem*)temp_val->content.ptr;
523        while(iterator!=NULL) {
524          push_val(&(env->head), iterator->item);
525          if(env->head->item->type==symb
526            && strcmp(";", ((symbol*)(env->head->item->content.ptr))->id)==0) {
527            toss(env);
528            if(env->err) return;
529            if(iterator->next == NULL){
530              free_val(temp_val);
531              return eval(env);
532            }
533            eval(env);
534            if(env->err) return;
535          }
536          iterator= iterator->next;
537        }
538        free_val(temp_val);
539        return;
540    
541        /* If it's a string */
542      case string:
543        temp_val= env->head->item;
544        env->head->item->refcount++;
545        toss(env);
546        if(env->err) return;
547        temp_string= malloc(strlen((char*)temp_val->content.ptr)+5);
548        strcpy(temp_string, "[ ");
549        strcpy(temp_string+2, (char*)temp_val->content.ptr);
550        free_val(temp_val);
551        strcat(temp_string, " ]");
552        stack_read(env, temp_string);
553        free(temp_string);
554        return eval(env);
555    
556      case integer:
557        return;
558    }    }
559  }  }
560    
561  /* Reverse a list */  /* Reverse (flip) a list */
562  extern void rev(environment *env){  extern void rev(environment *env){
563    stackitem *old_head, *new_head, *item;    stackitem *old_head, *new_head, *item;
564    
# Line 531  void stack_read(environment *env, char * Line 635  void stack_read(environment *env, char *
635    int itemp;    int itemp;
636    size_t inlength= strlen(in_line)+1;    size_t inlength= strlen(in_line)+1;
637    int convert= 0;    int convert= 0;
   static int non_eval_flag= 0;  
638    
639    temp= malloc(inlength);    temp= malloc(inlength);
640    rest= malloc(inlength);    rest= malloc(inlength);
# Line 567  void stack_read(environment *env, char * Line 670  void stack_read(environment *env, char *
670      /* If single char */      /* If single char */
671      if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest))) {      if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest))) {
672        if(*temp==';') {        if(*temp==';') {
673          if(!non_eval_flag) {          if(!env->non_eval_flag) {
674            eval(env);            /* Evaluate top element */            eval(env);            /* Evaluate top element */
675            break;            break;
676          }          }
# Line 579  void stack_read(environment *env, char * Line 682  void stack_read(environment *env, char *
682        if(*temp==']') {        if(*temp==']') {
683          push_sym(env, "[");          push_sym(env, "[");
684          pack(env);          pack(env);
685          if(non_eval_flag!=0)          if(env->non_eval_flag)
686            non_eval_flag--;            env->non_eval_flag--;
687          break;          break;
688        }        }
689    
690        if(*temp=='[') {        if(*temp=='[') {
691          push_sym(env, "[");          push_sym(env, "[");
692          non_eval_flag++;          env->non_eval_flag++;
693          break;          break;
694        }        }
695      }      }
# Line 811  int main() Line 914  int main()
914    quit(&myenv);    quit(&myenv);
915    return EXIT_FAILURE;    return EXIT_FAILURE;
916  }  }
917    
918    /* + */
919    extern void sx_2b(environment *env) {
920      int a, b;
921      size_t len;
922      char* new_string;
923      value *a_val, *b_val;
924    
925      if((env->head)==NULL || env->head->next==NULL) {
926        printerr("Too Few Arguments");
927        env->err=1;
928        return;
929      }
930    
931      if(env->head->item->type==string
932         && env->head->next->item->type==string) {
933        a_val= env->head->item;
934        b_val= env->head->next->item;
935        a_val->refcount++;
936        b_val->refcount++;
937        toss(env); if(env->err) return;
938        toss(env); if(env->err) return;
939        len= strlen(a_val->content.ptr)+strlen(b_val->content.ptr)+1;
940        new_string= malloc(len);
941        strcpy(new_string, b_val->content.ptr);
942        strcat(new_string, a_val->content.ptr);
943        free_val(a_val); free_val(b_val);
944        push_cstring(&(env->head), new_string);
945        free(new_string);
946        return;
947      }
948      
949      if(env->head->item->type!=integer
950         || env->head->next->item->type!=integer) {
951        printerr("Bad Argument Type");
952        env->err=2;
953        return;
954      }
955      a=env->head->item->content.val;
956      toss(env);
957      if(env->err) return;
958      b=env->head->item->content.val;
959      toss(env);
960      if(env->err) return;
961      push_int(&(env->head), a+b);
962    }
963    
964    /* - */
965    extern void sx_2d(environment *env) {
966      int a;
967    
968      if((env->head)==NULL || env->head->next==NULL) {
969        printerr("Too Few Arguments");
970        env->err=1;
971        return;
972      }
973      
974      if(env->head->item->type!=integer
975         || env->head->next->item->type!=integer) {
976        printerr("Bad Argument Type");
977        env->err=2;
978        return;
979      }
980      a=env->head->item->content.val;
981      toss(env);
982      if(env->err) return;
983      env->head->item->content.val -= a;
984    }
985    
986    /* Return copy of a value */
987    value *copy_val(value *old_value){
988      stackitem *old_item, *new_item, *prev_item;
989    
990      value *new_value=malloc(sizeof(value));
991    
992      new_value->type=old_value->type;
993      new_value->refcount=0;        /* This is increased if/when this
994                                       value is referenced somewhere, like
995                                       in a stack item or a variable */
996      switch(old_value->type){
997      case integer:
998        new_value->content.val=old_value->content.val;
999        break;
1000      case string:
1001        (char *)(new_value->content.ptr)
1002          = strdup((char *)(old_value->content.ptr));
1003        break;
1004      case func:
1005      case symb:
1006        new_value->content.ptr=old_value->content.ptr;
1007        break;
1008      case list:
1009        new_value->content.ptr=NULL;
1010    
1011        prev_item=NULL;
1012        old_item=(stackitem *)(old_value->content.ptr);
1013    
1014        while(old_item != NULL) {   /* While list is not empty */
1015          new_item= malloc(sizeof(stackitem));
1016          new_item->item=copy_val(old_item->item); /* recurse */
1017          new_item->next=NULL;
1018          if(prev_item != NULL)     /* If this wasn't the first item */
1019            prev_item->next=new_item; /* point the previous item to the
1020                                         new item */
1021          else
1022            new_value->content.ptr=new_item;
1023          old_item=old_item->next;
1024          prev_item=new_item;
1025        }    
1026        break;
1027      }
1028      return new_value;
1029    }
1030    
1031    /* duplicates an item on the stack */
1032    extern void dup(environment *env) {
1033      if((env->head)==NULL) {
1034        printerr("Too Few Arguments");
1035        env->err=1;
1036        return;
1037      }
1038      push_val(&(env->head), copy_val(env->head->item));
1039    }
1040    
1041    /* "if", If-Then */
1042    extern void sx_6966(environment *env) {
1043    
1044      int truth;
1045    
1046      if((env->head)==NULL || env->head->next==NULL) {
1047        printerr("Too Few Arguments");
1048        env->err=1;
1049        return;
1050      }
1051    
1052      if(env->head->next->item->type != integer) {
1053        printerr("Bad Argument Type");
1054        env->err=2;
1055        return;
1056      }
1057      
1058      swap(env);
1059      if(env->err) return;
1060      
1061      truth=env->head->item->content.val;
1062    
1063      toss(env);
1064      if(env->err) return;
1065    
1066      if(truth)
1067        eval(env);
1068      else
1069        toss(env);
1070    }
1071    
1072    /* If-Then-Else */
1073    extern void ifelse(environment *env) {
1074    
1075      int truth;
1076    
1077      if((env->head)==NULL || env->head->next==NULL
1078         || env->head->next->next==NULL) {
1079        printerr("Too Few Arguments");
1080        env->err=1;
1081        return;
1082      }
1083    
1084      if(env->head->next->next->item->type != integer) {
1085        printerr("Bad Argument Type");
1086        env->err=2;
1087        return;
1088      }
1089      
1090      rot(env);
1091      if(env->err) return;
1092      
1093      truth=env->head->item->content.val;
1094    
1095      toss(env);
1096      if(env->err) return;
1097    
1098      if(!truth)
1099        swap(env);
1100      if(env->err) return;
1101    
1102      toss(env);
1103      if(env->err) return;
1104    
1105      eval(env);
1106    }
1107    
1108    /* while */
1109    extern void sx_7768696c65(environment *env) {
1110    
1111      int truth;
1112    
1113      if((env->head)==NULL || env->head->next==NULL) {
1114        printerr("Too Few Arguments");
1115        env->err=1;
1116        return;
1117      }
1118    
1119      do {
1120        swap(env); if(env->err) return;
1121        dup(env); if(env->err) return;
1122        eval(env); if(env->err) return;
1123        
1124        if(env->head->item->type != integer) {
1125          printerr("Bad Argument Type");
1126          env->err=2;
1127          return;
1128        }
1129        
1130        truth= env->head->item->content.val;
1131        
1132        toss(env); if(env->err) return;
1133        swap(env); if(env->err) return;
1134        
1135        if(truth) {
1136          dup(env);
1137          eval(env);
1138        } else {
1139          toss(env);
1140          toss(env);
1141        }
1142      
1143      } while(truth);
1144    }

Legend:
Removed from v.1.43  
changed lines
  Added in v.1.60

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26