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

Diff of /stack/stack.c

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

revision 1.8 by masse, Tue Jan 8 14:17:33 2002 UTC revision 1.28 by teddy, Mon Feb 4 21:47:26 2002 UTC
# Line 6  Line 6 
6  #include <stddef.h>  #include <stddef.h>
7  /* dlopen, dlsym, dlerror */  /* 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, symbol, list} 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 51  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 69  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 an integer onto the stack. */
114    int push_val(stackitem **stack_head, int in_val)
115  {  {
116    stackitem* new_item= malloc(sizeof(stackitem));    value *new_value= malloc(sizeof(value));
117    new_item->content.val= in_val;    stackitem *new_item= malloc(sizeof(stackitem));
118    new_item->type= value;    new_item->item= new_value;
119      
120      new_value->content.val= in_val;
121      new_value->type= integer;
122      new_value->refcount=1;
123    
124    push(stack_head, new_item);    push(stack_head, new_item);
125    return 1;    return 1;
126  }  }
127    
128  int push_cstring(stackitem** stack_head, const char* in_string)  /* Copy a string onto the stack. */
129    int push_cstring(stackitem **stack_head, const char *in_string)
130  {  {
131    stackitem* new_item= malloc(sizeof(stackitem));    value *new_value= malloc(sizeof(value));
132    new_item->content.ptr= malloc(strlen(in_string)+1);    stackitem *new_item= malloc(sizeof(stackitem));
133    strcpy(new_item->content.ptr, in_string);    new_item->item=new_value;
134    new_item->type= string;  
135      new_value->content.ptr= malloc(strlen(in_string)+1);
136      strcpy(new_value->content.ptr, in_string);
137      new_value->type= string;
138      new_value->refcount=1;
139    
140    push(stack_head, new_item);    push(stack_head, new_item);
141    return 1;    return 1;
142  }  }
143    
144  int mk_hashentry(hashtbl in_hashtbl, stackitem* in_item, const char* id)  /* Push a symbol onto the stack. */
145    int push_sym(environment *env, const char *in_string)
146  {  {
147    in_item->id= malloc(strlen(id)+1);    stackitem *new_item;          /* The new stack item */
148      /* ...which will contain... */
149    strcpy(in_item->id, id);    value *new_value;             /* A new symbol value */
150    push(hash(in_hashtbl, id), in_item);    /* ...which might point to... */
151      symbol *new_symbol;           /* (if needed) A new actual symbol */
152      /* ...which, if possible, will be bound to... */
153      value *new_fvalue;            /* (if needed) A new function value */
154      /* ...which will point to... */
155      void *funcptr;                /* A function pointer */
156    
157      static void *handle= NULL;    /* Dynamic linker handle */
158    
159      /* Create a new stack item containing a new value */
160      new_item= malloc(sizeof(stackitem));
161      new_value= malloc(sizeof(value));
162      new_item->item=new_value;
163    
164      /* The new value is a symbol */
165      new_value->type= symb;
166      new_value->refcount= 1;
167    
168      /* Look up the symbol name in the hash table */
169      new_value->content.ptr= *hash(env->symbols, in_string);
170    
171      if(new_value->content.ptr==NULL) { /* If symbol was undefined */
172    
173        /* Create a new symbol */
174        new_symbol= malloc(sizeof(symbol));
175        new_symbol->val= NULL;      /* undefined value */
176        new_symbol->next= NULL;
177        new_symbol->id= malloc(strlen(in_string)+1);
178        strcpy(new_symbol->id, in_string);
179    
180        /* Intern the new symbol in the hash table */
181        new_value->content.ptr= new_symbol;
182    
183        /* Try to load the symbol name as an external function, to see if
184           we should bind the symbol to a new function pointer value */
185        if(handle==NULL)            /* If no handle */
186          handle= dlopen(NULL, RTLD_LAZY);
187    
188        funcptr= dlsym(handle, in_string); /* Get function pointer */
189        if(dlerror()==NULL) {       /* If a function was found */
190          new_fvalue= malloc(sizeof(value)); /* Create a new value */
191          new_fvalue->type=func;    /* The new value is a function pointer */
192          new_fvalue->content.ptr=funcptr; /* Store function pointer */
193          new_symbol->val= new_fvalue;      /* Bind the symbol to the new
194                                               function value */
195          new_fvalue->refcount= 1;
196        }
197      }
198      push(&(env->head), new_item);
199    return 1;    return 1;
200  }  }
201    
202  void def_func(hashtbl in_hashtbl, funcp in_func, const char* id)  void printerr(const char* in_string) {
203  {    fprintf(stderr, "Err: %s\n", in_string);
   stackitem* temp= malloc(sizeof(stackitem));  
   
   temp->type= func;  
   temp->content.ptr= in_func;  
   
   mk_hashentry(in_hashtbl, temp, id);  
 }  
   
 void def_sym(hashtbl in_hashtbl, const char* id)  
 {  
   stackitem* temp= malloc(sizeof(stackitem));  
     
   temp->type= symbol;  
   
   mk_hashentry(in_hashtbl, temp, id);  
204  }  }
205    
206  int push_ref(stackitem** stack_head, hashtbl in_hash, const char* in_string)  /* Throw away a value */
207  {  void free_val(value *val){
208    static void* handle= NULL;    stackitem *item, *temp;
209    void* symbol;  
210      val->refcount--;              /* Decrease the reference count */
211    stackitem* new_item= malloc(sizeof(stackitem));    if(val->refcount == 0){
212    new_item->content.ptr= *hash(in_hash, in_string);      switch (val->type){         /* and free the contents if necessary */
213    new_item->type= ref;      case string:
214          free(val->content.ptr);
215    if(handle==NULL)      case list:                  /* lists needs to be freed recursively */
216      handle= dlopen(NULL, RTLD_LAZY);        item=val->content.ptr;
217          while(item != NULL) {     /* for all stack items */
218    if(new_item->content.ptr==NULL) {          free_val(item->item);   /* free the value */
219      symbol= dlsym(handle, in_string);          temp=item->next;        /* save next ptr */
220      if(dlerror()==NULL)          free(item);             /* free the stackitem */
221        def_func(in_hash, symbol, in_string);          item=temp;              /* go to next stackitem */
222      else        }
223        def_sym(in_hash, in_string);        free(val);                /* Free the actual list value */
224                break;
225      new_item->content.ptr= *hash(in_hash, in_string);      default:
226      new_item->type= ref;        break;
227        }
228    }    }
   
   push(stack_head, new_item);  
   return 1;  
229  }  }
230    
231  extern void toss(stackitem** stack_head)  /* Discard the top element of the stack. */
232    extern void toss(environment *env)
233  {  {
234    stackitem* temp= *stack_head;    stackitem *temp= env->head;
235    
236    if((*stack_head)==NULL)    if((env->head)==NULL) {
237        printerr("Stack empty");
238      return;      return;
239      }
240        
241    if((*stack_head)->type==string)    free_val(env->head->item);    /* Free the value */
242      free((*stack_head)->content.ptr);    env->head= env->head->next;   /* Remove the top stack item */
243      free(temp);                   /* Free the old top stack item */
   *stack_head= (*stack_head)->next;  
   free(temp);  
244  }  }
245    
246    /* Print newline. */
247  extern void nl()  extern void nl()
248  {  {
249    printf("\n");    printf("\n");
250  }  }
251    
252  void prin(stackitem** stack_head)  /* Prints the top element of the stack. */
253    void print_h(stackitem *stack_head)
254  {  {
255    if((*stack_head)==NULL)  
256      if(stack_head==NULL) {
257        printerr("Stack empty");
258      return;      return;
259      }
260    
261    switch((*stack_head)->type) {    switch(stack_head->item->type) {
262    case value:    case integer:
263      printf("%d", (*stack_head)->content.val);      printf("%d", stack_head->item->content.val);
264      break;      break;
265    case string:    case string:
266      printf("%s", (char*)(*stack_head)->content.ptr);      printf("\"%s\"", (char*)stack_head->item->content.ptr);
267      break;      break;
268    case ref:    case symb:
269      printf("%s", ((stackitem*)(*stack_head)->content.ptr)->id);      printf("'%s'", ((symbol *)(stack_head->item->content.ptr))->id);
270      break;      break;
   case symbol:  
271    default:    default:
272      printf("%p", (*stack_head)->content.ptr);      printf("%p", (funcp)(stack_head->item->content.ptr));
273      break;      break;
274    }    }
275  }  }
276    
277  extern void print(stackitem** stack_head)  extern void print_(environment *env) {
278      print_h(env->head);
279    }
280    
281    /* Prints the top element of the stack and then discards it. */
282    extern void print(environment *env)
283  {  {
284    prin(stack_head);    print_(env);
285    toss(stack_head);    toss(env);
286  }  }
287    
288  /* print_stack(stack); */  /* Only to be called by function printstack. */
289  void print_st(stackitem* stack_head, long counter)  void print_st(stackitem *stack_head, long counter)
290  {  {
291    if(stack_head->next != NULL)    if(stack_head->next != NULL)
292      print_st(stack_head->next, counter+1);      print_st(stack_head->next, counter+1);
   
293    printf("%ld: ", counter);    printf("%ld: ", counter);
294    prin(&stack_head);    print_h(stack_head);
295    nl();    nl();
296  }  }
297    
298  extern void printstack(stackitem** stack_head)  
299    
300    /* Prints the stack. */
301    extern void printstack(environment *env)
302    {
303      if(env->head != NULL) {
304        print_st(env->head, 1);
305        nl();
306      } else {
307        printerr("Stack empty");
308      }
309    }
310    
311    /* Swap the two top elements on the stack. */
312    extern void swap(environment *env)
313  {  {
314    if(*stack_head != NULL) {    stackitem *temp= env->head;
315      print_st(*stack_head, 1);    
316      printf("\n");    if((env->head)==NULL) {
317        printerr("Stack empty");
318        return;
319    }    }
320    
321      if(env->head->next==NULL) {
322        printerr("Not enough arguments");
323        return;
324      }
325    
326      env->head= env->head->next;
327      temp->next= env->head->next;
328      env->head->next= temp;
329    }
330    
331    stackitem* copy(stackitem* in_item)
332    {
333      stackitem *out_item= malloc(sizeof(stackitem));
334    
335      memcpy(out_item, in_item, sizeof(stackitem));
336      out_item->next= NULL;
337    
338      return out_item;
339  }  }
340    
341    
342  extern void eval(stackitem** stack_head)  /* If the top element is a reference, determine if it's a reference to a
343       function, and if it is, toss the reference and execute the function. */
344    extern void eval(environment *env)
345  {  {
346    funcp in_func;    funcp in_func;
347      stackitem* temp= env->head;
348    
349      if(temp==NULL) {
350        printerr("Stack empty");
351        return;
352      }
353    
354    if((*stack_head)==NULL || (*stack_head)->type!=ref)    if(temp->item->type==symb
355         && ((symbol *)(temp->item->content.ptr))->val != NULL
356         && ((symbol *)(temp->item->content.ptr))->val->type == func) {
357        in_func= (funcp)(((symbol *)(temp->item->content.ptr))->val->content.ptr);
358        toss(env);
359        (*in_func)(env);
360      return;      return;
361      }
362        
363    
364    if(((stackitem*)(*stack_head)->content.ptr)->type==func) {    if(temp->item->type==func) {
365      in_func= (funcp)((stackitem*)(*stack_head)->content.ptr)->content.ptr;      in_func= (funcp)(temp->item->content.ptr);
366      toss(stack_head);      toss(env);
367      (*in_func)(stack_head);      (*in_func)(env);
368      return;      return;
369    }    }
370    
371      push(&(env->head), copy(temp));
372      swap(env);
373      toss(env);
374    }
375    
376    /* Make a list. */
377    extern void pack(environment *env)
378    {
379      void* delimiter;
380      stackitem *iterator, *temp;
381      value *pack;
382    
383      delimiter= env->head->item->content.ptr; /* Get delimiter */
384      toss(env);
385    
386      iterator= env->head;
387    
388      if(iterator==NULL || iterator->item->content.ptr==delimiter) {
389        temp= NULL;
390        toss(env);
391      } else {
392        /* Search for first delimiter */
393        while(iterator->next!=NULL
394              && iterator->next->item->content.ptr!=delimiter)
395          iterator= iterator->next;
396        
397        /* Extract list */
398        temp= env->head;
399        env->head= iterator->next;
400        iterator->next= NULL;
401        
402        if(env->head!=NULL)
403          toss(env);
404      }
405    
406      /* Push list */
407      pack= malloc(sizeof(value));
408      pack->type= list;
409      pack->content.ptr= temp;
410      pack->refcount= 1;
411    
412      temp= malloc(sizeof(stackitem));
413      temp->item= pack;
414    
415      push(&(env->head), temp);
416  }  }
417    
418  int stack_read(stackitem** stack_head, hashtbl in_hash, char* in_line)  /* Parse input. */
419    int stack_read(environment *env, char *in_line)
420  {  {
421    char *temp, *rest;    char *temp, *rest;
422    int itemp;    int itemp;
423    size_t inlength= strlen(in_line)+1;    size_t inlength= strlen(in_line)+1;
424    int convert= 0;    int convert= 0;
425      static int non_eval_flag= 0;
426    
427    temp= malloc(inlength);    temp= malloc(inlength);
428    rest= malloc(inlength);    rest= malloc(inlength);
429    
430    if((convert= sscanf(in_line, "\"%[^\"\n\r]\" %[^\n\r]", temp, rest)) >= 1)    do {
431      push_cstring(stack_head, temp);      /* If string */
432    else if((convert= sscanf(in_line, "%d %[^\n\r]", &itemp, rest)) >= 1)      if((convert= sscanf(in_line, "\"%[^\"\n\r]\" %[^\n\r]", temp, rest))) {
433      push_val(stack_head, itemp);        push_cstring(&(env->head), temp);
434    else if((convert= sscanf(in_line, "%[^ ;\n\r]%[^\n\r]", temp, rest)) >= 1)        break;
435      push_ref(stack_head, in_hash, temp);      }
436    else if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest)) >= 1)      /* If integer */
437      if(*temp==';')      if((convert= sscanf(in_line, "%d %[^\n\r]", &itemp, rest))) {
438        eval(stack_head);        push_val(&(env->head), itemp);
439          break;
440        }
441        /* Escape ';' with '\' */
442        if((convert= sscanf(in_line, "\\%c%[^\n\r]", temp, rest))) {
443          temp[1]= '\0';
444          push_sym(env, temp);
445          break;
446        }
447        /* If symbol */
448        if((convert= sscanf(in_line, "%[^][ ;\n\r_]%[^\n\r]", temp, rest))) {
449            push_sym(env, temp);
450            break;
451        }
452        /* If single char */
453        if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest))) {
454          if(*temp==';') {
455            if(!non_eval_flag) {
456              eval(env);            /* Evaluate top element */
457              break;
458            }
459            
460            push_sym(env, ";");
461            break;
462          }
463    
464          if(*temp==']') {
465            push_sym(env, "[");
466            pack(env);
467            if(non_eval_flag!=0)
468              non_eval_flag--;
469            break;
470          }
471    
472          if(*temp=='[') {
473            push_sym(env, "[");
474            non_eval_flag++;
475            break;
476          }
477        }
478      } while(0);
479    
480    
481    free(temp);    free(temp);
482    
# Line 255  int stack_read(stackitem** stack_head, h Line 485  int stack_read(stackitem** stack_head, h
485      return 0;      return 0;
486    }    }
487        
488    stack_read(stack_head, in_hash, rest);    stack_read(env, rest);
489        
490    free(rest);    free(rest);
491    return 1;    return 1;
492  }  }
493    
494  extern void pack(stackitem** stack_head)  /* Relocate elements of the list on the stack. */
495    extern void expand(environment *env)
496  {  {
497    void* delimiter;    stackitem *temp, *new_head;
   stackitem *iterator, *temp, *pack;  
498    
499    if((*stack_head)==NULL)    /* Is top element a list? */
500      if(env->head==NULL || env->head->item->type!=list) {
501        printerr("Stack empty or not a list");
502      return;      return;
503      }
504    
505      /* The first list element is the new stack head */
506      new_head= temp= env->head->item->content.ptr;
507    
508      env->head->item->refcount++;
509      toss(env);
510    
511      /* Find the end of the list */
512      while(temp->next!=NULL)
513        temp= temp->next;
514    
515    delimiter= (*stack_head)->content.ptr;    /* Connect the tail of the list with the old stack head */
516    toss(stack_head);    temp->next= env->head;
517      env->head= new_head;          /* ...and voila! */
518    
519    iterator= *stack_head;  }
520    
521    while(iterator->next!=NULL && iterator->next->content.ptr!=delimiter)  /* Compares two elements by reference. */
522      iterator= iterator->next;  extern void eq(environment *env)
523    {
524      void *left, *right;
525      int result;
526    
527      if((env->head)==NULL || env->head->next==NULL) {
528        printerr("Not enough elements to compare");
529        return;
530      }
531    
532    temp= *stack_head;    left= env->head->item->content.ptr;
533    *stack_head= iterator->next;    swap(env);
534    iterator->next= NULL;    right= env->head->item->content.ptr;
535      result= (left==right);
536        
537    if(*stack_head!=NULL && (*stack_head)->content.ptr==delimiter)    toss(env); toss(env);
538      toss(stack_head);    push_val(&(env->head), result);
539    }
540    
541    pack= malloc(sizeof(stackitem));  /* Negates the top element on the stack. */
542    pack->type= list;  extern void not(environment *env)
543    pack->content.ptr= temp;  {
544      int val;
545    
546      if((env->head)==NULL || env->head->item->type!=integer) {
547        printerr("Stack empty or element is not a integer");
548        return;
549      }
550    
551    push(stack_head, pack);    val= env->head->item->content.val;
552      toss(env);
553      push_val(&(env->head), !val);
554  }  }
555    
556  extern void expand(stackitem** stack_head)  /* Compares the two top elements on the stack and return 0 if they're the
557       same. */
558    extern void neq(environment *env)
559  {  {
560    stackitem *temp, *new_head;    eq(env);
561      not(env);
562    }
563    
564    /* Give a symbol some content. */
565    extern void def(environment *env)
566    {
567      symbol *sym;
568    
569    if((*stack_head)==NULL || (*stack_head)->type!=list)    /* Needs two values on the stack, the top one must be a symbol */
570      if(env->head==NULL || env->head->next==NULL
571         || env->head->item->type!=symb) {
572        printerr("Define what?");
573      return;      return;
574      }
575    
576    new_head= temp= (*stack_head)->content.ptr;    /* long names are a pain */
577    toss(stack_head);    sym=env->head->item->content.ptr;
578    
579    while(temp->next!=NULL)    /* if the symbol was bound to something else, throw it away */
580      temp= temp->next;    if(sym->val != NULL)
581        free_val(sym->val);
582    
583      /* Bind the symbol to the value */
584      sym->val= env->head->next->item;
585      sym->val->refcount++;         /* Increase the reference counter */
586    
587    temp->next= *stack_head;    toss(env); toss(env);
588    *stack_head= new_head;  }
 }  
589    
590  extern void quit()  /* Quit stack. */
591    extern void quit(environment *env)
592  {  {
593    exit(EXIT_SUCCESS);    exit(EXIT_SUCCESS);
594  }  }
595    
596    /* Clear stack */
597    extern void clear(environment *env)
598    {
599      while(env->head!=NULL)
600        toss(env);
601    }
602    
603  int main()  int main()
604  {  {
605    stackitem* s= NULL;    environment myenv;
   hashtbl myhash;  
606    char in_string[100];    char in_string[100];
607    
608    init_hashtbl(myhash);    init_env(&myenv);
609    
610    printf("okidok\n ");    printf("okidok\n ");
611    
612    while(fgets(in_string, 100, stdin) != NULL) {    while(fgets(in_string, 100, stdin) != NULL) {
613      stack_read(&s, myhash, in_string);      stack_read(&myenv, in_string);
614      printf("okidok\n ");      printf("okidok\n ");
615    }    }
616    
617      exit(EXIT_SUCCESS);
   return EXIT_SUCCESS;  
618  }  }
   
 /* Local Variables: */  
 /* compile-command:"make CFLAGS=\"-Wall -g -rdynamic -ldl\" stack" */  
 /* End: */  

Legend:
Removed from v.1.8  
changed lines
  Added in v.1.28

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26