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

Diff of /stack/stack.c

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

revision 1.1 by masse, Mon Jan 7 23:09:01 2002 UTC revision 1.29 by teddy, Tue Feb 5 12:14:42 2002 UTC
# Line 4  Line 4 
4  #include <stdlib.h>  #include <stdlib.h>
5  /* NULL */  /* NULL */
6  #include <stddef.h>  #include <stddef.h>
7    /* dlopen, dlsym, dlerror */
8  #include <dlfcn.h>  #include <dlfcn.h>
9    /* assert */
10    #include <assert.h>
11    
12  #define HASHTBLSIZE 65536  #define HASHTBLSIZE 65536
13    
14  typedef struct stack_item  /* First, define some types. */
15  {  
16    enum {value, string, ref, func} type;  /* A value of some type */
17    typedef struct {
18      enum {
19        integer,
20        string,
21        ref,                        /* Reference (to an element in the
22                                       hash table) */
23        func,                       /* Function pointer */
24        symb,
25        list
26      } type;                       /* Type of stack element */
27    
28    union {    union {
29      void* ptr;      void *ptr;                  /* Pointer to the content */
30      int val;      int val;                    /* ...or an integer */
31    } content;    } content;                    /* Stores a pointer or an integer */
32    
33      int refcount;                 /* Reference counter */
34    
35    } value;
36    
37    /* A symbol with a name and possible value */
38    /* (These do not need reference counters, they are kept unique by
39       hashing.) */
40    typedef struct symbol_struct {
41      char *id;                     /* Symbol name */
42      value *val;                   /* The value (if any) bound to it */
43      struct symbol_struct *next;   /* In case of hashing conflicts, a */
44    } symbol;                       /* symbol is a kind of stack item. */
45    
46    char* id;  /* A type for a hash table for symbols */
47    struct stack_item* next;  typedef symbol *hashtbl[HASHTBLSIZE]; /* Hash table declaration */
 } stackitem;  
48    
49    /* An item (value) on a stack */
50    typedef struct stackitem_struct
51    {
52      value *item;                  /* The value on the stack */
53      struct stackitem_struct *next; /* Next item */
54    } stackitem;
55    
56  typedef stackitem* hashtbl[HASHTBLSIZE];  /* An environment; gives access to the stack and a hash table of
57  typedef void (*funcp)(stackitem**);     defined symbols */
58    typedef struct {
59      stackitem *head;              /* Head of the stack */
60      hashtbl symbols;              /* Hash table of all variable bindings */
61    } environment;
62    
63    /* A type for pointers to external functions */
64    typedef void (*funcp)(environment *); /* funcp is a pointer to a void
65                                             function (environment *) */
66    
67  void init_hashtbl(hashtbl out_hash)  /* Initialize a newly created environment */
68    void init_env(environment *env)
69  {  {
70    long i;    long i;
71    
72    for(i= 0; i<HASHTBLSIZE; i++)    for(i= 0; i<HASHTBLSIZE; i++)
73      out_hash[i]= NULL;      env->symbols[i]= NULL;
74  }  }
75    
76  stackitem** hash(hashtbl in_hashtbl, const char* in_string)  /* Returns a pointer to a pointer to an element in the hash table. */
77    symbol **hash(hashtbl in_hashtbl, const char *in_string)
78  {  {
79    long i= 0;    long i= 0;
80    unsigned long out_hash= 0;    unsigned long out_hash= 0;
81    char key= 0;    char key= '\0';
82    stackitem** position;    symbol **position;
83        
84    while(1){    while(1){                     /* Hash in_string */
85      key= in_string[i++];      key= in_string[i++];
86      if(key=='\0')      if(key=='\0')
87        break;        break;
# Line 50  stackitem** hash(hashtbl in_hashtbl, con Line 92  stackitem** hash(hashtbl in_hashtbl, con
92    position= &(in_hashtbl[out_hash]);    position= &(in_hashtbl[out_hash]);
93    
94    while(1){    while(1){
95      if(*position==NULL)      if(*position==NULL)         /* If empty */
96        return position;        return position;
97            
98      if(strcmp(in_string, (*position)->id)==0)      if(strcmp(in_string, (*position)->id)==0) /* If match */
99        return position;        return position;
100    
101      position= &((*position)->next);      position= &((*position)->next); /* Try next */
102    }    }
103  }  }
104    
105    /* Generic push function. */
106  int push(stackitem** stack_head, stackitem* in_item)  int push(stackitem** stack_head, stackitem* in_item)
107  {  {
108    in_item->next= *stack_head;    in_item->next= *stack_head;
# Line 68  int push(stackitem** stack_head, stackit Line 110  int push(stackitem** stack_head, stackit
110    return 1;    return 1;
111  }  }
112    
113  int push_val(stackitem** stack_head, int in_val)  /* Push a value onto the stack */
114    void push_val(stackitem **stack_head, value *val)
115  {  {
116    stackitem* new_item= malloc(sizeof(stackitem));    stackitem *new_item= malloc(sizeof(stackitem));
117    new_item->content.val= in_val;    new_item->item= val;
118    new_item->type= value;    val->refcount++;
   
119    push(stack_head, new_item);    push(stack_head, new_item);
   return 1;  
120  }  }
121    
122  int push_cstring(stackitem** stack_head, const char* in_string)  /* Push an integer onto the stack. */
123    int push_int(stackitem **stack_head, int in_val)
124  {  {
125    stackitem* new_item= malloc(sizeof(stackitem));    value *new_value= malloc(sizeof(value));
126    new_item->content.ptr= malloc(strlen(in_string)+1);    stackitem *new_item= malloc(sizeof(stackitem));
127    strcpy(new_item->content.ptr, in_string);    new_item->item= new_value;
128    new_item->type= string;    
129      new_value->content.val= in_val;
130      new_value->type= integer;
131      new_value->refcount=1;
132    
133    push(stack_head, new_item);    push(stack_head, new_item);
134    return 1;    return 1;
135  }  }
136    
137  int mk_hashentry(hashtbl in_hashtbl, stackitem* in_item, const char* id)  /* Copy a string onto the stack. */
138    int push_cstring(stackitem **stack_head, const char *in_string)
139  {  {
140    in_item->id= malloc(strlen(id)+1);    value *new_value= malloc(sizeof(value));
141      stackitem *new_item= malloc(sizeof(stackitem));
142    strcpy(in_item->id, id);    new_item->item=new_value;
143    push(hash(in_hashtbl, id), in_item);  
144      new_value->content.ptr= malloc(strlen(in_string)+1);
145      strcpy(new_value->content.ptr, in_string);
146      new_value->type= string;
147      new_value->refcount=1;
148    
149      push(stack_head, new_item);
150    return 1;    return 1;
151  }  }
152    
153  void def_func(hashtbl in_hashtbl, funcp in_func, const char* id)  /* Push a symbol onto the stack. */
154    int push_sym(environment *env, const char *in_string)
155  {  {
156    stackitem* temp= malloc(sizeof(stackitem));    stackitem *new_item;          /* The new stack item */
157      /* ...which will contain... */
158      value *new_value;             /* A new symbol value */
159      /* ...which might point to... */
160      symbol **new_symbol;          /* (if needed) A new actual symbol */
161      /* ...which, if possible, will be bound to... */
162      value *new_fvalue;            /* (if needed) A new function value */
163      /* ...which will point to... */
164      void *funcptr;                /* A function pointer */
165    
166      static void *handle= NULL;    /* Dynamic linker handle */
167    
168      /* Create a new stack item containing a new value */
169      new_item= malloc(sizeof(stackitem));
170      new_value= malloc(sizeof(value));
171      new_item->item=new_value;
172    
173      /* The new value is a symbol */
174      new_value->type= symb;
175      new_value->refcount= 1;
176    
177      /* Look up the symbol name in the hash table */
178      new_symbol= hash(env->symbols, in_string);
179      new_value->content.ptr= *new_symbol;
180    
181      if(new_value->content.ptr==NULL) { /* If symbol was undefined */
182    
183        /* Create a new symbol */
184        *new_symbol= malloc(sizeof(symbol));
185        (*new_symbol)->val= NULL;   /* undefined value */
186        (*new_symbol)->next= NULL;
187        (*new_symbol)->id= malloc(strlen(in_string)+1);
188        strcpy((*new_symbol)->id, in_string);
189    
190        /* Intern the new symbol in the hash table */
191        new_value->content.ptr= *new_symbol;
192    
193        /* Try to load the symbol name as an external function, to see if
194           we should bind the symbol to a new function pointer value */
195        if(handle==NULL)            /* If no handle */
196          handle= dlopen(NULL, RTLD_LAZY);
197    
198        funcptr= dlsym(handle, in_string); /* Get function pointer */
199        if(dlerror()==NULL) {       /* If a function was found */
200          new_fvalue= malloc(sizeof(value)); /* Create a new value */
201          new_fvalue->type=func;    /* The new value is a function pointer */
202          new_fvalue->content.ptr=funcptr; /* Store function pointer */
203          (*new_symbol)->val= new_fvalue; /* Bind the symbol to the new
204                                             function value */
205          new_fvalue->refcount= 1;
206        }
207      }
208      push(&(env->head), new_item);
209      return 1;
210    }
211    
212    temp->type= func;  void printerr(const char* in_string) {
213    temp->content.ptr= in_func;    fprintf(stderr, "Err: %s\n", in_string);
214    }
215    
216    mk_hashentry(in_hashtbl, temp, id);  /* Throw away a value */
217    void free_val(value *val){
218      stackitem *item, *temp;
219    
220      val->refcount--;              /* Decrease the reference count */
221      if(val->refcount == 0){
222        switch (val->type){         /* and free the contents if necessary */
223        case string:
224          free(val->content.ptr);
225        case list:                  /* lists needs to be freed recursively */
226          item=val->content.ptr;
227          while(item != NULL) {     /* for all stack items */
228            free_val(item->item);   /* free the value */
229            temp=item->next;        /* save next ptr */
230            free(item);             /* free the stackitem */
231            item=temp;              /* go to next stackitem */
232          }
233          free(val);                /* Free the actual list value */
234          break;
235        default:
236          break;
237        }
238      }
239  }  }
240    
241  int push_ref(stackitem** stack_head, hashtbl in_hash, const char* in_string)  /* Discard the top element of the stack. */
242    extern void toss(environment *env)
243  {  {
244    void* handle;    stackitem *temp= env->head;
   void* symbol;  
     
   stackitem* new_item= malloc(sizeof(stackitem));  
   new_item->content.ptr= *hash(in_hash, in_string);  
   new_item->type= ref;  
245    
246    if(new_item->content.ptr==NULL) {    if((env->head)==NULL) {
247      handle= dlopen(NULL, RTLD_LAZY);      printerr("Stack empty");
248      symbol= dlsym(handle, in_string);      return;
     if(dlerror()==NULL) {  
       def_func(in_hash, symbol, in_string);  
       new_item->content.ptr= *hash(in_hash, in_string);  
       new_item->type= ref;  
     }  
249    }    }
250      
251      free_val(env->head->item);    /* Free the value */
252      env->head= env->head->next;   /* Remove the top stack item */
253      free(temp);                   /* Free the old top stack item */
254    }
255    
256    push(stack_head, new_item);  /* Print newline. */
257    return 1;  extern void nl()
258    {
259      printf("\n");
260  }  }
261    
262  extern void toss(stackitem** stack_head)  /* Prints the top element of the stack. */
263    void print_h(stackitem *stack_head)
264  {  {
   stackitem* temp= *stack_head;  
265    
266    *stack_head= (*stack_head)->next;    if(stack_head==NULL) {
267    free(temp);      printerr("Stack empty");
268        return;
269      }
270    
271      switch(stack_head->item->type) {
272      case integer:
273        printf("%d", stack_head->item->content.val);
274        break;
275      case string:
276        printf("\"%s\"", (char*)stack_head->item->content.ptr);
277        break;
278      case symb:
279        printf("'%s'", ((symbol *)(stack_head->item->content.ptr))->id);
280        break;
281      default:
282        printf("%p", (funcp)(stack_head->item->content.ptr));
283        break;
284      }
285  }  }
286    
287    extern void print_(environment *env) {
288      print_h(env->head);
289    }
290    
291  /* print_stack(stack); */  /* Prints the top element of the stack and then discards it. */
292  void print_st(stackitem* stack_head, long counter)  extern void print(environment *env)
293    {
294      print_(env);
295      toss(env);
296    }
297    
298    /* Only to be called by function printstack. */
299    void print_st(stackitem *stack_head, long counter)
300  {  {
301    if(stack_head->next != NULL)    if(stack_head->next != NULL)
302      print_st(stack_head->next, counter+1);      print_st(stack_head->next, counter+1);
303      printf("%ld: ", counter);
304      print_h(stack_head);
305      nl();
306    }
307    
308    if(stack_head->type==value)  
309      printf("%ld: %d\n", counter, (int)stack_head->content.val);  
310    else if(stack_head->type==string)  /* Prints the stack. */
311      printf("%ld: \"%s\"\n", counter, (char*)stack_head->content.ptr);  extern void printstack(environment *env)
312    else  {
313      printf("%ld: %p\n", counter, stack_head->content.ptr);    if(env->head != NULL) {
314        print_st(env->head, 1);
315        nl();
316      } else {
317        printerr("Stack empty");
318      }
319  }  }
320    
321  extern void printstack(stackitem** stack_head)  /* Swap the two top elements on the stack. */
322    extern void swap(environment *env)
323  {  {
324    if(*stack_head != NULL) {    stackitem *temp= env->head;
325      print_st(*stack_head, 1);    
326      printf("\n");    if((env->head)==NULL) {
327        printerr("Stack empty");
328        return;
329    }    }
330    
331      if(env->head->next==NULL) {
332        printerr("Not enough arguments");
333        return;
334      }
335    
336      env->head= env->head->next;
337      temp->next= env->head->next;
338      env->head->next= temp;
339    }
340    
341    stackitem* copy(stackitem* in_item)
342    {
343      stackitem *out_item= malloc(sizeof(stackitem));
344    
345      memcpy(out_item, in_item, sizeof(stackitem));
346      out_item->next= NULL;
347    
348      return out_item;
349  }  }
350    
351    
352  extern void eval(stackitem** stack_head)  /* If the top element is a symbol, determine if it's bound to a
353       function value, and if it is, toss the symbol and execute the
354       function. */
355    extern void eval(environment *env)
356  {  {
357    funcp in_func;    funcp in_func;
358      value* val;
359    if((*stack_head)==NULL || (*stack_head)->type!=ref)    if(env->head==NULL) {
360        printerr("Stack empty");
361      return;      return;
362      }
363    
364      /* if it's a symbol */
365      if(env->head->item->type==symb) {
366    
367    if(((stackitem*)(*stack_head)->content.ptr)->type==func) {      /* If it's not bound to anything */
368      in_func= (funcp)((stackitem*)(*stack_head)->content.ptr)->content.ptr;      if (((symbol *)(env->head->item->content.ptr))->val == NULL) {
369      toss(stack_head);        printerr("Unbound variable");
370      (*in_func)(stack_head);        return;
371        }
372        
373        /* If it contains a function */
374        if (((symbol *)(env->head->item->content.ptr))->val->type == func) {
375          in_func=
376            (funcp)(((symbol *)(env->head->item->content.ptr))->val->content.ptr);
377          toss(env);
378          (*in_func)(env);          /* Run the function */
379          return;
380        } else {                    /* If it's not a function */
381          val=((symbol *)(env->head->item->content.ptr))->val;
382          toss(env);                /* toss the symbol */
383          push_val(&(env->head), val); /* Return its bound value */
384        }
385      }
386    
387      /* If it's a lone function value, run it */
388      if(env->head->item->type==func) {
389        in_func= (funcp)(env->head->item->content.ptr);
390        toss(env);
391        (*in_func)(env);
392      return;      return;
393    }    }
394    
395    /*    push(&(env->head), copy(env->head)); */
396    /*    swap(env); */
397    /*    toss(env); */
398    }
399    
400    /* Make a list. */
401    extern void pack(environment *env)
402    {
403      void* delimiter;
404      stackitem *iterator, *temp;
405      value *pack;
406    
407      delimiter= env->head->item->content.ptr; /* Get delimiter */
408      toss(env);
409    
410      iterator= env->head;
411    
412      if(iterator==NULL || iterator->item->content.ptr==delimiter) {
413        temp= NULL;
414        toss(env);
415      } else {
416        /* Search for first delimiter */
417        while(iterator->next!=NULL
418              && iterator->next->item->content.ptr!=delimiter)
419          iterator= iterator->next;
420        
421        /* Extract list */
422        temp= env->head;
423        env->head= iterator->next;
424        iterator->next= NULL;
425        
426        if(env->head!=NULL)
427          toss(env);
428      }
429    
430      /* Push list */
431      pack= malloc(sizeof(value));
432      pack->type= list;
433      pack->content.ptr= temp;
434      pack->refcount= 1;
435    
436      temp= malloc(sizeof(stackitem));
437      temp->item= pack;
438    
439      push(&(env->head), temp);
440  }  }
441    
442  int stack_read(stackitem** stack_head, hashtbl in_hash, char* in_line)  /* Parse input. */
443    int stack_read(environment *env, char *in_line)
444  {  {
445    char *temp, *rest;    char *temp, *rest;
446    int itemp;    int itemp;
447    size_t inlength= strlen(in_line)+1;    size_t inlength= strlen(in_line)+1;
448    int convert= 0;    int convert= 0;
449      static int non_eval_flag= 0;
450    
451    temp= malloc(inlength);    temp= malloc(inlength);
452    rest= malloc(inlength);    rest= malloc(inlength);
453    
454    if((convert= sscanf(in_line, "\"%[^\"\n\r]\" %[^\n\r]", temp, rest)) >= 1)    do {
455      push_cstring(stack_head, temp);      /* If string */
456    else if((convert= sscanf(in_line, "%d %[^\n\r]", &itemp, rest)) >= 1)      if((convert= sscanf(in_line, "\"%[^\"\n\r]\" %[^\n\r]", temp, rest))) {
457      push_val(stack_head, itemp);        push_cstring(&(env->head), temp);
458    else if((convert= sscanf(in_line, "%[^ ;\n\r]%[^\n\r]", temp, rest)) >= 1)        break;
459      push_ref(stack_head, in_hash, temp);      }
460    else if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest)) >= 1)      /* If integer */
461      if(*temp==';')      if((convert= sscanf(in_line, "%d %[^\n\r]", &itemp, rest))) {
462        eval(stack_head);        push_int(&(env->head), itemp);
463          break;
464        }
465        /* Escape ';' with '\' */
466        if((convert= sscanf(in_line, "\\%c%[^\n\r]", temp, rest))) {
467          temp[1]= '\0';
468          push_sym(env, temp);
469          break;
470        }
471        /* If symbol */
472        if((convert= sscanf(in_line, "%[^][ ;\n\r_]%[^\n\r]", temp, rest))) {
473            push_sym(env, temp);
474            break;
475        }
476        /* If single char */
477        if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest))) {
478          if(*temp==';') {
479            if(!non_eval_flag) {
480              eval(env);            /* Evaluate top element */
481              break;
482            }
483            
484            push_sym(env, ";");
485            break;
486          }
487    
488          if(*temp==']') {
489            push_sym(env, "[");
490            pack(env);
491            if(non_eval_flag!=0)
492              non_eval_flag--;
493            break;
494          }
495    
496          if(*temp=='[') {
497            push_sym(env, "[");
498            non_eval_flag++;
499            break;
500          }
501        }
502      } while(0);
503    
504    
505    free(temp);    free(temp);
506    
# Line 206  int stack_read(stackitem** stack_head, h Line 509  int stack_read(stackitem** stack_head, h
509      return 0;      return 0;
510    }    }
511        
512    stack_read(stack_head, in_hash, rest);    stack_read(env, rest);
513        
514    free(rest);    free(rest);
515    return 1;    return 1;
516  }  }
517    
518  extern void print(stackitem** stack_head)  /* Relocate elements of the list on the stack. */
519    extern void expand(environment *env)
520  {  {
521    if((*stack_head)==NULL)    stackitem *temp, *new_head;
522    
523      /* Is top element a list? */
524      if(env->head==NULL || env->head->item->type!=list) {
525        printerr("Stack empty or not a list");
526      return;      return;
527      }
528    
529    if((*stack_head)->type==value)    /* The first list element is the new stack head */
530      printf("%d", (*stack_head)->content.val);    new_head= temp= env->head->item->content.ptr;
531    else if((*stack_head)->type==string)  
532      printf("%s", (char*)(*stack_head)->content.ptr);    env->head->item->refcount++;
533    else    toss(env);
534      printf("%p", (*stack_head)->content.ptr);  
535      /* Find the end of the list */
536      while(temp->next!=NULL)
537        temp= temp->next;
538    
539      /* Connect the tail of the list with the old stack head */
540      temp->next= env->head;
541      env->head= new_head;          /* ...and voila! */
542    
   toss(stack_head);  
543  }  }
544    
545  extern void nl()  /* Compares two elements by reference. */
546    extern void eq(environment *env)
547  {  {
548    printf("\n");    void *left, *right;
549      int result;
550    
551      if((env->head)==NULL || env->head->next==NULL) {
552        printerr("Not enough elements to compare");
553        return;
554      }
555    
556      left= env->head->item->content.ptr;
557      swap(env);
558      right= env->head->item->content.ptr;
559      result= (left==right);
560      
561      toss(env); toss(env);
562      push_int(&(env->head), result);
563    }
564    
565    /* Negates the top element on the stack. */
566    extern void not(environment *env)
567    {
568      int val;
569    
570      if((env->head)==NULL || env->head->item->type!=integer) {
571        printerr("Stack empty or element is not a integer");
572        return;
573      }
574    
575      val= env->head->item->content.val;
576      toss(env);
577      push_int(&(env->head), !val);
578    }
579    
580    /* Compares the two top elements on the stack and return 0 if they're the
581       same. */
582    extern void neq(environment *env)
583    {
584      eq(env);
585      not(env);
586    }
587    
588    /* Give a symbol some content. */
589    extern void def(environment *env)
590    {
591      symbol *sym;
592    
593      /* Needs two values on the stack, the top one must be a symbol */
594      if(env->head==NULL || env->head->next==NULL
595         || env->head->item->type!=symb) {
596        printerr("Define what?");
597        return;
598      }
599    
600      /* long names are a pain */
601      sym=env->head->item->content.ptr;
602    
603      /* if the symbol was bound to something else, throw it away */
604      if(sym->val != NULL)
605        free_val(sym->val);
606    
607      /* Bind the symbol to the value */
608      sym->val= env->head->next->item;
609      sym->val->refcount++;         /* Increase the reference counter */
610    
611      toss(env); toss(env);
612    }
613    
614    /* Quit stack. */
615    extern void quit(environment *env)
616    {
617      exit(EXIT_SUCCESS);
618    }
619    
620    /* Clear stack */
621    extern void clear(environment *env)
622    {
623      while(env->head!=NULL)
624        toss(env);
625  }  }
626    
627  int main()  int main()
628  {  {
629    stackitem* s= NULL;    environment myenv;
   hashtbl myhash;  
630    char in_string[100];    char in_string[100];
631    
632    init_hashtbl(myhash);    init_env(&myenv);
633    
634    printf("okidok\n ");    printf("okidok\n ");
635    
636    while(fgets(in_string, 100, stdin) != NULL) {    while(fgets(in_string, 100, stdin) != NULL) {
637      stack_read(&s, myhash, in_string);      stack_read(&myenv, in_string);
638      printf("okidok\n ");      printf("okidok\n ");
639    }    }
640    
641      exit(EXIT_SUCCESS);
   return EXIT_SUCCESS;  
642  }  }

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.29

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26