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

Diff of /stack/stack.c

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

revision 1.17 by masse, Thu Jan 31 23:09:07 2002 UTC revision 1.82 by masse, Thu Feb 14 19:49:48 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    /* strcmp, strcpy, strlen, strcat, strdup */
10    #include <string.h>
11    
12  #define HASHTBLSIZE 65536  #define HASHTBLSIZE 2048
13    
14  typedef struct stack_item  /* First, define some types. */
15  {  
16    /* A value of some type */
17    typedef struct {
18    enum {    enum {
19      value,                      /* Integer */      integer,
20      string,      string,
     ref,            /* Reference (to an element in the hash table) */  
21      func,                       /* Function pointer */      func,                       /* Function pointer */
22      symbol,      symb,
23      list      list
24    } type;                       /* Tells what kind of stack element */    } type;                       /* Type of stack element */
25      
26    union {    union {
27      void* ptr;                  /* Pointer to the content */      void *ptr;                  /* Pointer to the content */
28      int val;                    /* ...or an integer */      int val;                    /* ...or an integer */
29    } content;                    /* Stores a pointer or an integer */    } content;                    /* Stores a pointer or an integer */
30    
31    char* id;                     /* Symbol name */    int refcount;                 /* Reference counter */
   struct stack_item* next;      /* Next element */  
 } stackitem;  
32    
33    } value;
34    
35  typedef stackitem* hashtbl[HASHTBLSIZE]; /* Hash table declaration */  /* A symbol with a name and possible value */
36  typedef void (*funcp)(stackitem**); /* Function pointer declaration */  /* (These do not need reference counters, they are kept unique by
37       hashing.) */
38    typedef struct symbol_struct {
39      char *id;                     /* Symbol name */
40      value *val;                   /* The value (if any) bound to it */
41      struct symbol_struct *next;   /* In case of hashing conflicts, a */
42    } symbol;                       /* symbol is a kind of stack item. */
43    
44    /* A type for a hash table for symbols */
45    typedef symbol *hashtbl[HASHTBLSIZE]; /* Hash table declaration */
46    
47    /* An item (value) on a stack */
48    typedef struct stackitem_struct
49    {
50      value *item;                  /* The value on the stack */
51                                    /* (This is never NULL) */
52      struct stackitem_struct *next; /* Next item */
53    } stackitem;
54    
55    /* An environment; gives access to the stack and a hash table of
56       defined symbols */
57    typedef struct {
58      stackitem *head;              /* Head of the stack */
59      hashtbl symbols;              /* Hash table of all variable bindings */
60      int err;                      /* Error flag */
61      char *in_string;              /* Input pending to be read */
62      char *free_string;            /* Free this string when all input is
63                                       read from in_string */
64    } environment;
65    
66    /* A type for pointers to external functions */
67    typedef void (*funcp)(environment *); /* funcp is a pointer to a void
68                                             function (environment *) */
69    
70  /* Initiates a newly created hash table. */  /* Initialize a newly created environment */
71  void init_hashtbl(hashtbl out_hash)  void init_env(environment *env)
72  {  {
73    long i;    int i;
74    
75      env->in_string= NULL;
76      env->err= 0;
77    for(i= 0; i<HASHTBLSIZE; i++)    for(i= 0; i<HASHTBLSIZE; i++)
78      out_hash[i]= NULL;      env->symbols[i]= NULL;
79    }
80    
81    void printerr(const char* in_string) {
82      fprintf(stderr, "Err: %s\n", in_string);
83    }
84    
85    /* Throw away a value */
86    void free_val(value *val){
87      stackitem *item, *temp;
88    
89      val->refcount--;              /* Decrease the reference count */
90      if(val->refcount == 0){
91        switch (val->type){         /* and free the contents if necessary */
92        case string:
93          free(val->content.ptr);
94          break;
95        case list:                  /* lists needs to be freed recursively */
96          item=val->content.ptr;
97          while(item != NULL) {     /* for all stack items */
98            free_val(item->item);   /* free the value */
99            temp=item->next;        /* save next ptr */
100            free(item);             /* free the stackitem */
101            item=temp;              /* go to next stackitem */
102          }
103          break;
104        case integer:
105        case func:
106          break;
107        case symb:
108          free(((symbol*)(val->content.ptr))->id);
109          if(((symbol*)(val->content.ptr))->val!=NULL)
110            free_val(((symbol*)(val->content.ptr))->val);
111          free(val->content.ptr);
112          break;
113        }
114        free(val);          /* Free the actual list value */
115      }
116  }  }
117    
118  /* Returns a pointer to an element in the hash table. */  /* Discard the top element of the stack. */
119  stackitem** hash(hashtbl in_hashtbl, const char* in_string)  extern void toss(environment *env)
120  {  {
121    long i= 0;    stackitem *temp= env->head;
122    unsigned long out_hash= 0;  
123    char key= 0;    if((env->head)==NULL) {
124    stackitem** position;      printerr("Too Few Arguments");
125        env->err=1;
126        return;
127      }
128      
129      free_val(env->head->item);    /* Free the value */
130      env->head= env->head->next;   /* Remove the top stack item */
131      free(temp);                   /* Free the old top stack item */
132    }
133    
134    /* Returns a pointer to a pointer to an element in the hash table. */
135    symbol **hash(hashtbl in_hashtbl, const char *in_string)
136    {
137      int i= 0;
138      unsigned int out_hash= 0;
139      char key= '\0';
140      symbol **position;
141        
142    while(1){                     /* Hash in_string */    while(1){                     /* Hash in_string */
143      key= in_string[i++];      key= in_string[i++];
# Line 61  stackitem** hash(hashtbl in_hashtbl, con Line 149  stackitem** hash(hashtbl in_hashtbl, con
149    out_hash= out_hash%HASHTBLSIZE;    out_hash= out_hash%HASHTBLSIZE;
150    position= &(in_hashtbl[out_hash]);    position= &(in_hashtbl[out_hash]);
151    
152    while(1){                     /* Return position if empty */    while(1){
153      if(*position==NULL)      if(*position==NULL)         /* If empty */
154        return position;        return position;
155            
156      if(strcmp(in_string, (*position)->id)==0) /* Return position if match */      if(strcmp(in_string, (*position)->id)==0) /* If match */
157        return position;        return position;
158    
159      position= &((*position)->next); /* Try next */      position= &((*position)->next); /* Try next */
160    }    }
161  }  }
162    
163  /* Generic push function. */  /* Push a value onto the stack */
164  int push(stackitem** stack_head, stackitem* in_item)  void push_val(environment *env, value *val)
165  {  {
166    in_item->next= *stack_head;    stackitem *new_item= malloc(sizeof(stackitem));
167    *stack_head= in_item;    new_item->item= val;
168    return 1;    val->refcount++;
169      new_item->next= env->head;
170      env->head= new_item;
171  }  }
172    
173  /* Push a value on the stack. */  /* Push an integer onto the stack. */
174  int push_val(stackitem** stack_head, int in_val)  void push_int(environment *env, int in_val)
175  {  {
176    stackitem* new_item= malloc(sizeof(stackitem));    value *new_value= malloc(sizeof(value));
177    new_item->content.val= in_val;    
178    new_item->type= value;    new_value->content.val= in_val;
179      new_value->type= integer;
180      new_value->refcount= 1;
181    
182    push(stack_head, new_item);    push_val(env, new_value);
   return 1;  
183  }  }
184    
185  /* Copy a string onto the stack. */  /* Copy a string onto the stack. */
186  int push_cstring(stackitem** stack_head, const char* in_string)  void push_cstring(environment *env, const char *in_string)
187  {  {
188    stackitem* new_item= malloc(sizeof(stackitem));    value *new_value= malloc(sizeof(value));
   new_item->content.ptr= malloc(strlen(in_string)+1);  
   strcpy(new_item->content.ptr, in_string);  
   new_item->type= string;  
189    
190    push(stack_head, new_item);    new_value->content.ptr= malloc(strlen(in_string)+1);
191    return 1;    strcpy(new_value->content.ptr, in_string);
192      new_value->type= string;
193      new_value->refcount= 1;
194    
195      push_val(env, new_value);
196    }
197    
198    /* Mangle a symbol name to a valid C identifier name */
199    char *mangle_str(const char *old_string){
200      char validchars[]
201        ="0123456789abcdef";
202      char *new_string, *current;
203    
204      new_string=malloc((strlen(old_string)*2)+4);
205      strcpy(new_string, "sx_");    /* Stack eXternal */
206      current=new_string+3;
207      while(old_string[0] != '\0'){
208        current[0]=validchars[(unsigned char)(old_string[0])/16];
209        current[1]=validchars[(unsigned char)(old_string[0])%16];
210        current+=2;
211        old_string++;
212      }
213      current[0]='\0';
214    
215      return new_string;            /* The caller must free() it */
216  }  }
217    
218  /* Create a new hash entry. */  extern void mangle(environment *env){
219  int mk_hashentry(hashtbl in_hashtbl, stackitem* in_item, const char* id)    char *new_string;
 {  
   in_item->id= malloc(strlen(id)+1);  
220    
221    strcpy(in_item->id, id);    if((env->head)==NULL) {
222    push(hash(in_hashtbl, id), in_item);      printerr("Too Few Arguments");
223        env->err=1;
224        return;
225      }
226    
227    return 1;    if(env->head->item->type!=string) {
228  }      printerr("Bad Argument Type");
229        env->err=2;
230        return;
231      }
232    
233  /* Define a function a new function in the hash table. */    new_string= mangle_str((const char *)(env->head->item->content.ptr));
 void def_func(hashtbl in_hashtbl, funcp in_func, const char* id)  
 {  
   stackitem* temp= malloc(sizeof(stackitem));  
234    
235    temp->type= func;    toss(env);
236    temp->content.ptr= in_func;    if(env->err) return;
237    
238    mk_hashentry(in_hashtbl, temp, id);    push_cstring(env, new_string);
239  }  }
240    
241  /* Define a new symbol in the hash table. */  /* Push a symbol onto the stack. */
242  void def_sym(hashtbl in_hashtbl, const char* id)  void push_sym(environment *env, const char *in_string)
243  {  {
244    stackitem* temp= malloc(sizeof(stackitem));    value *new_value;             /* A new symbol value */
245        /* ...which might point to... */
246    temp->type= symbol;    symbol **new_symbol;          /* (if needed) A new actual symbol */
247    mk_hashentry(in_hashtbl, temp, id);    /* ...which, if possible, will be bound to... */
248  }    value *new_fvalue;            /* (if needed) A new function value */
249      /* ...which will point to... */
250      void *funcptr;                /* A function pointer */
251    
252  /* Push a reference to an entry in the hash table onto the stack. */    static void *handle= NULL;    /* Dynamic linker handle */
253  int push_ref(stackitem** stack_head, hashtbl in_hash, const char* in_string)    const char *dlerr;            /* Dynamic linker error */
254  {    char *mangled;                /* Mangled function name */
   static void* handle= NULL;  
   void* symbol;  
255    
256    stackitem* new_item= malloc(sizeof(stackitem));    new_value= malloc(sizeof(value));
   new_item->content.ptr= *hash(in_hash, in_string);  
   new_item->type= ref;  
257    
258    if(new_item->content.ptr==NULL) { /* If hash entry empty */    /* The new value is a symbol */
259      if(handle==NULL)            /* If no handle */    new_value->type= symb;
260        handle= dlopen(NULL, RTLD_LAZY);        new_value->refcount= 1;
261    
262      symbol= dlsym(handle, in_string); /* Get function pointer */    /* Look up the symbol name in the hash table */
263      if(dlerror()==NULL)         /* If existing function pointer */    new_symbol= hash(env->symbols, in_string);
264        def_func(in_hash, symbol, in_string); /* Store function pointer */    new_value->content.ptr= *new_symbol;
     else  
       def_sym(in_hash, in_string); /* Make symbol */  
         
     new_item->content.ptr= *hash(in_hash, in_string); /* XXX */  
     new_item->type= ref;  
   }  
265    
266    push(stack_head, new_item);    if(*new_symbol==NULL) { /* If symbol was undefined */
   return 1;  
 }  
267    
268  void printerr(const char* in_string) {      /* Create a new symbol */
269    fprintf(stderr, "Err: %s\n", in_string);      (*new_symbol)= malloc(sizeof(symbol));
270  }      (*new_symbol)->val= NULL;   /* undefined value */
271        (*new_symbol)->next= NULL;
272        (*new_symbol)->id= malloc(strlen(in_string)+1);
273        strcpy((*new_symbol)->id, in_string);
274    
275  /* Discard the top element of the stack. */      /* Intern the new symbol in the hash table */
276  extern void toss(stackitem** stack_head)      new_value->content.ptr= *new_symbol;
 {  
   stackitem* temp= *stack_head;  
277    
278    if((*stack_head)==NULL) {      /* Try to load the symbol name as an external function, to see if
279      printerr("Stack empty");         we should bind the symbol to a new function pointer value */
280      return;      if(handle==NULL)            /* If no handle */
281    }        handle= dlopen(NULL, RTLD_LAZY);
     
   if((*stack_head)->type==string)  
     free((*stack_head)->content.ptr);  
282    
283    *stack_head= (*stack_head)->next;      funcptr= dlsym(handle, in_string); /* Get function pointer */
284    free(temp);      dlerr=dlerror();
285        if(dlerr != NULL) {         /* If no function was found */
286          mangled=mangle_str(in_string);
287          funcptr= dlsym(handle, mangled); /* try mangling it */
288          free(mangled);
289          dlerr=dlerror();
290        }
291        if(dlerr==NULL) {           /* If a function was found */
292          new_fvalue= malloc(sizeof(value)); /* Create a new value */
293          new_fvalue->type=func;    /* The new value is a function pointer */
294          new_fvalue->content.ptr=funcptr; /* Store function pointer */
295          (*new_symbol)->val= new_fvalue; /* Bind the symbol to the new
296                                             function value */
297          new_fvalue->refcount= 1;
298        }
299      }
300      push_val(env, new_value);
301  }  }
302    
303  /* Print newline. */  /* Print newline. */
# Line 189  extern void nl() Line 306  extern void nl()
306    printf("\n");    printf("\n");
307  }  }
308    
309  /* Prints the top element of the stack. */  /* Gets the type of a value */
310  void print_(stackitem** stack_head)  extern void type(environment *env){
311  {    int typenum;
312    if((*stack_head)==NULL) {  
313      printerr("Stack empty");    if((env->head)==NULL) {
314        printerr("Too Few Arguments");
315        env->err=1;
316      return;      return;
317    }    }
318      typenum=env->head->item->type;
319      toss(env);
320      switch(typenum){
321      case integer:
322        push_sym(env, "integer");
323        break;
324      case string:
325        push_sym(env, "string");
326        break;
327      case symb:
328        push_sym(env, "symbol");
329        break;
330      case func:
331        push_sym(env, "function");
332        break;
333      case list:
334        push_sym(env, "list");
335        break;
336      }
337    }    
338    
339    switch((*stack_head)->type) {  /* Prints the top element of the stack. */
340    case value:  void print_h(stackitem *stack_head, int noquote)
341      printf("%d", (*stack_head)->content.val);  {
342      switch(stack_head->item->type) {
343      case integer:
344        printf("%d", stack_head->item->content.val);
345      break;      break;
346    case string:    case string:
347      printf("%s", (char*)(*stack_head)->content.ptr);      if(noquote)
348          printf("%s", (char*)stack_head->item->content.ptr);
349        else
350          printf("\"%s\"", (char*)stack_head->item->content.ptr);
351      break;      break;
352    case ref:    case symb:
353      printf("%s", ((stackitem*)(*stack_head)->content.ptr)->id);      printf("%s", ((symbol *)(stack_head->item->content.ptr))->id);
354      break;      break;
355    case symbol:    case func:
356    default:      printf("#<function %p>", (funcp)(stack_head->item->content.ptr));
357      printf("%p", (*stack_head)->content.ptr);      break;
358      case list:
359        /* A list is just a stack, so make stack_head point to it */
360        stack_head=(stackitem *)(stack_head->item->content.ptr);
361        printf("[ ");
362        while(stack_head != NULL) {
363          print_h(stack_head, noquote);
364          printf(" ");
365          stack_head=stack_head->next;
366        }
367        printf("]");
368      break;      break;
369    }    }
370  }  }
371    
372    extern void print_(environment *env) {
373      if(env->head==NULL) {
374        printerr("Too Few Arguments");
375        env->err=1;
376        return;
377      }
378      print_h(env->head, 0);
379      nl();
380    }
381    
382    /* Prints the top element of the stack and then discards it. */
383    extern void print(environment *env)
384    {
385      print_(env);
386      if(env->err) return;
387      toss(env);
388    }
389    
390    extern void princ_(environment *env) {
391      if(env->head==NULL) {
392        printerr("Too Few Arguments");
393        env->err=1;
394        return;
395      }
396      print_h(env->head, 1);
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. */
400  extern void print(stackitem** stack_head)  extern void princ(environment *env)
401  {  {
402    print_(stack_head);    princ_(env);
403    toss(stack_head);    if(env->err) return;
404      toss(env);
405  }  }
406    
407  /* Only to be called by function printstack. */  /* Only to be called by function printstack. */
408  void print_st(stackitem* stack_head, long counter)  void print_st(stackitem *stack_head, long counter)
409  {  {
410    if(stack_head->next != NULL)    if(stack_head->next != NULL)
411      print_st(stack_head->next, counter+1);      print_st(stack_head->next, counter+1);
   
412    printf("%ld: ", counter);    printf("%ld: ", counter);
413    print_(&stack_head);    print_h(stack_head, 0);
414    nl();    nl();
415  }  }
416    
417  /* Prints the stack. */  /* Prints the stack. */
418  extern void printstack(stackitem** stack_head)  extern void printstack(environment *env)
419  {  {
420    if(*stack_head != NULL) {    if(env->head == NULL) {
421      print_st(*stack_head, 1);      printf("Stack Empty\n");
422      printf("\n");      return;
   } else {  
     printerr("Stack empty");  
423    }    }
424      print_st(env->head, 1);
425  }  }
426    
427  /* If the top element is a reference, determine if it's a reference to a  /* Swap the two top elements on the stack. */
428     function, and if it is, toss the reference and execute the function. */  extern void swap(environment *env)
 extern void eval(stackitem** stack_head)  
429  {  {
430    funcp in_func;    stackitem *temp= env->head;
431      
432      if(env->head==NULL || env->head->next==NULL) {
433        printerr("Too Few Arguments");
434        env->err=1;
435        return;
436      }
437    
438      env->head= env->head->next;
439      temp->next= env->head->next;
440      env->head->next= temp;
441    }
442    
443    /* Rotate the first three elements on the stack. */
444    extern void rot(environment *env)
445    {
446      stackitem *temp= env->head;
447      
448      if(env->head==NULL || env->head->next==NULL
449          || env->head->next->next==NULL) {
450        printerr("Too Few Arguments");
451        env->err=1;
452        return;
453      }
454    
455      env->head= env->head->next->next;
456      temp->next->next= env->head->next;
457      env->head->next= temp;
458    }
459    
460    /* Recall a value from a symbol, if bound */
461    extern void rcl(environment *env)
462    {
463      value *val;
464    
465      if(env->head == NULL) {
466        printerr("Too Few Arguments");
467        env->err=1;
468        return;
469      }
470    
471    if((*stack_head)==NULL || (*stack_head)->type!=ref) {    if(env->head->item->type!=symb) {
472      printerr("Stack empty or not a reference");      printerr("Bad Argument Type");
473        env->err=2;
474      return;      return;
475    }    }
476    
477    if(((stackitem*)(*stack_head)->content.ptr)->type==func) {    val=((symbol *)(env->head->item->content.ptr))->val;
478      in_func= (funcp)((stackitem*)(*stack_head)->content.ptr)->content.ptr;    if(val == NULL){
479      toss(stack_head);      printerr("Unbound Variable");
480      (*in_func)(stack_head);      env->err=3;
481      return;      return;
482    } else    }
483      printerr("Not a function");    toss(env);            /* toss the symbol */
484      if(env->err) return;
485      push_val(env, val); /* Return its bound value */
486  }  }
487    
488  /* Parse input. */  /* If the top element is a symbol, determine if it's bound to a
489  int stack_read(stackitem** stack_head, hashtbl in_hash, char* in_line)     function value, and if it is, toss the symbol and execute the
490       function. */
491    extern void eval(environment *env)
492  {  {
493    char *temp, *rest;    funcp in_func;
494    int itemp;    value* temp_val;
495    size_t inlength= strlen(in_line)+1;    stackitem* iterator;
   int convert= 0;  
496    
497    temp= malloc(inlength);   eval_start:
   rest= malloc(inlength);  
498    
499    do {    if(env->head==NULL) {
500      /* If string */      printerr("Too Few Arguments");
501      if((convert= sscanf(in_line, "\"%[^\"\n\r]\" %[^\n\r]", temp, rest))) {      env->err=1;
502        push_cstring(stack_head, temp);      return;
503        break;    }
     }  
     /* If value */  
     if((convert= sscanf(in_line, "%d %[^\n\r]", &itemp, rest))) {  
       push_val(stack_head, itemp);  
       break;  
     }  
     /* Escape ';' with '\' */  
     if((convert= sscanf(in_line, "\\%c%[^\n\r]", temp, rest))) {  
       temp[1]= '\0';  
       push_ref(stack_head, in_hash, temp);  
       break;  
     }  
     /* If symbol */  
     if((convert= sscanf(in_line, "%[^ ;\n\r]%[^\n\r]", temp, rest))) {  
         push_ref(stack_head, in_hash, temp);  
         break;  
     }  
     /* If ';' */  
     if((convert= sscanf(in_line, "%c%[^\n\r]", temp, rest)) && *temp==';') {  
       eval(stack_head);         /* Evaluate top element */  
       break;  
     }  
   } while(0);  
504    
505      switch(env->head->item->type) {
506        /* if it's a symbol */
507      case symb:
508        rcl(env);                   /* get its contents */
509        if(env->err) return;
510        if(env->head->item->type!=symb){ /* don't recurse symbols */
511          goto eval_start;
512        }
513        return;
514    
515    free(temp);      /* If it's a lone function value, run it */
516      case func:
517        in_func= (funcp)(env->head->item->content.ptr);
518        toss(env);
519        if(env->err) return;
520        return (*in_func)(env);
521    
522        /* If it's a list */
523      case list:
524        temp_val= env->head->item;
525        env->head->item->refcount++;
526        toss(env);
527        if(env->err) return;
528        iterator= (stackitem*)temp_val->content.ptr;
529        while(iterator!=NULL) {
530          push_val(env, iterator->item);
531          if(env->head->item->type==symb
532            && strcmp(";", ((symbol*)(env->head->item->content.ptr))->id)==0) {
533            toss(env);
534            if(env->err) return;
535            if(iterator->next == NULL){
536              free_val(temp_val);
537              goto eval_start;
538            }
539            eval(env);
540            if(env->err) return;
541          }
542          iterator= iterator->next;
543        }
544        free_val(temp_val);
545        return;
546    
547    if(convert<2) {    default:
548      free(rest);      return;
     return 0;  
549    }    }
     
   stack_read(stack_head, in_hash, rest);  
     
   free(rest);  
   return 1;  
550  }  }
551    
552  /* Make a list. */  /* Reverse (flip) a list */
553  extern void pack(stackitem** stack_head)  extern void rev(environment *env){
554  {    stackitem *old_head, *new_head, *item;
555    void* delimiter;  
556    stackitem *iterator, *temp, *pack;    if((env->head)==NULL) {
557        printerr("Too Few Arguments");
558        env->err=1;
559        return;
560      }
561    
562    if((*stack_head)==NULL) {    if(env->head->item->type!=list) {
563      printerr("Stack empty");      printerr("Bad Argument Type");
564        env->err=2;
565      return;      return;
566    }    }
567    
568    delimiter= (*stack_head)->content.ptr; /* Get delimiter */    old_head=(stackitem *)(env->head->item->content.ptr);
569    toss(stack_head);    new_head=NULL;
570      while(old_head != NULL){
571        item=old_head;
572        old_head=old_head->next;
573        item->next=new_head;
574        new_head=item;
575      }
576      env->head->item->content.ptr=new_head;
577    }
578    
579    iterator= *stack_head;  /* Make a list. */
580    extern void pack(environment *env)
581    {
582      stackitem *iterator, *temp;
583      value *pack;
584    
585    /* Search for first delimiter */    iterator= env->head;
   while(iterator->next!=NULL && iterator->next->content.ptr!=delimiter)  
     iterator= iterator->next;  
586    
587    /* Extract list */    if(iterator==NULL
588    temp= *stack_head;       || (iterator->item->type==symb
589    *stack_head= iterator->next;       && ((symbol*)(iterator->item->content.ptr))->id[0]=='[')) {
590    iterator->next= NULL;      temp= NULL;
591          toss(env);
592    if(*stack_head!=NULL && (*stack_head)->content.ptr==delimiter)    } else {
593      toss(stack_head);      /* Search for first delimiter */
594        while(iterator->next!=NULL
595              && (iterator->next->item->type!=symb
596              || ((symbol*)(iterator->next->item->content.ptr))->id[0]!='['))
597          iterator= iterator->next;
598        
599        /* Extract list */
600        temp= env->head;
601        env->head= iterator->next;
602        iterator->next= NULL;
603        
604        if(env->head!=NULL)
605          toss(env);
606      }
607    
608    /* Push list */    /* Push list */
609    pack= malloc(sizeof(stackitem));    pack= malloc(sizeof(value));
610    pack->type= list;    pack->type= list;
611    pack->content.ptr= temp;    pack->content.ptr= temp;
612      pack->refcount= 1;
613    
614    push(stack_head, pack);    push_val(env, pack);
615      rev(env);
616  }  }
617    
618  /* Relocate elements of the list on the stack. */  /* Relocate elements of the list on the stack. */
619  extern void expand(stackitem** stack_head)  extern void expand(environment *env)
620  {  {
621    stackitem *temp, *new_head;    stackitem *temp, *new_head;
622    
623    /* Is top element a list? */    /* Is top element a list? */
624    if((*stack_head)==NULL || (*stack_head)->type!=list) {    if(env->head==NULL) {
625      printerr("Stack empty or not a list");      printerr("Too Few Arguments");
626        env->err=1;
627        return;
628      }
629      if(env->head->item->type!=list) {
630        printerr("Bad Argument Type");
631        env->err=2;
632      return;      return;
633    }    }
634    
635      rev(env);
636    
637      if(env->err)
638        return;
639    
640    /* The first list element is the new stack head */    /* The first list element is the new stack head */
641    new_head= temp= (*stack_head)->content.ptr;    new_head= temp= env->head->item->content.ptr;
642    toss(stack_head);  
643      env->head->item->refcount++;
644      toss(env);
645    
646    /* Search the end of the list */    /* Find the end of the list */
647    while(temp->next!=NULL)    while(temp->next!=NULL)
648      temp= temp->next;      temp= temp->next;
649    
650    /* Connect the the tail of the list with the old stack head */    /* Connect the tail of the list with the old stack head */
651    temp->next= *stack_head;    temp->next= env->head;
652    *stack_head= new_head;        /* ...and voila! */    env->head= new_head;          /* ...and voila! */
 }  
   
 /* Swap the two top elements on the stack. */  
 extern void swap(stackitem** stack_head)  
 {  
   stackitem* temp= (*stack_head);  
     
   if((*stack_head)==NULL) {  
     printerr("Stack empty");  
     return;  
   }  
   
   if((*stack_head)->next==NULL)  
     return;  
653    
654    *stack_head= (*stack_head)->next;  }
   temp->next= (*stack_head)->next;  
   (*stack_head)->next= temp;  
 }  
655    
656  /* Compares two elements by reference. */  /* Compares two elements by reference. */
657  extern void eq(stackitem** stack_head)  extern void eq(environment *env)
658  {  {
659    void *left, *right;    void *left, *right;
660    int result;    int result;
661    
662    if((*stack_head)==NULL || (*stack_head)->next==NULL) {    if((env->head)==NULL || env->head->next==NULL) {
663      printerr("Not enough elements to compare");      printerr("Too Few Arguments");
664        env->err=1;
665      return;      return;
666    }    }
667    
668    left= (*stack_head)->content.ptr;    left= env->head->item->content.ptr;
669    swap(stack_head);    swap(env);
670    right= (*stack_head)->content.ptr;    right= env->head->item->content.ptr;
671    result= (left==right);    result= (left==right);
672        
673    toss(stack_head); toss(stack_head);    toss(env); toss(env);
674    push_val(stack_head, (left==right));    push_int(env, result);
675  }  }
676    
677  /* Negates the top element on the stack. */  /* Negates the top element on the stack. */
678  extern void not(stackitem** stack_head)  extern void not(environment *env)
679  {  {
680    int value;    int val;
681    
682    if((*stack_head)==NULL || (*stack_head)->type!=value) {    if((env->head)==NULL) {
683      printerr("Stack empty or element is not a value");      printerr("Too Few Arguments");
684        env->err=1;
685      return;      return;
686    }    }
687    
688    value= (*stack_head)->content.val;    if(env->head->item->type!=integer) {
689    toss(stack_head);      printerr("Bad Argument Type");
690    push_val(stack_head, !value);      env->err=2;
691        return;
692      }
693    
694      val= env->head->item->content.val;
695      toss(env);
696      push_int(env, !val);
697  }  }
698    
699  /* 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
700     same. */     same. */
701  extern void neq(stackitem** stack_head)  extern void neq(environment *env)
702  {  {
703    eq(stack_head);    eq(env);
704    not(stack_head);    not(env);
705  }  }
706    
707  /* Give a symbol some content. */  /* Give a symbol some content. */
708  extern void def(stackitem** stack_head)  extern void def(environment *env)
709  {  {
710    stackitem *temp, *value;    symbol *sym;
711    
712    if(*stack_head==NULL || (*stack_head)->next==NULL    /* Needs two values on the stack, the top one must be a symbol */
713       || (*stack_head)->type!=ref) {    if(env->head==NULL || env->head->next==NULL) {
714      printerr("Define what?");      printerr("Too Few Arguments");
715        env->err=1;
716      return;      return;
717    }    }
718    
719    temp= (*stack_head)->content.ptr;    if(env->head->item->type!=symb) {
720    value= (*stack_head)->next;      printerr("Bad Argument Type");
721    temp->content= value->content;      env->err=2;
722    value->content.ptr=NULL;      return;
723    temp->type= value->type;    }
724    
725      /* long names are a pain */
726      sym=env->head->item->content.ptr;
727    
728      /* if the symbol was bound to something else, throw it away */
729      if(sym->val != NULL)
730        free_val(sym->val);
731    
732      /* Bind the symbol to the value */
733      sym->val= env->head->next->item;
734      sym->val->refcount++;         /* Increase the reference counter */
735    
736    toss(stack_head); toss(stack_head);    toss(env); toss(env);
737  }  }
738    
739    extern void clear(environment *);
740    void forget_sym(symbol **);
741    
742  /* Quit stack. */  /* Quit stack. */
743  extern void quit()  extern void quit(environment *env)
744  {  {
745      long i;
746    
747      clear(env);
748      if (env->err) return;
749      for(i= 0; i<HASHTBLSIZE; i++) {
750        while(env->symbols[i]!= NULL) {
751          forget_sym(&(env->symbols[i]));
752        }
753        env->symbols[i]= NULL;
754      }
755    exit(EXIT_SUCCESS);    exit(EXIT_SUCCESS);
756  }  }
757    
758    /* Clear stack */
759    extern void clear(environment *env)
760    {
761      while(env->head!=NULL)
762        toss(env);
763    }
764    
765    /* List all defined words */
766    extern void words(environment *env)
767    {
768      symbol *temp;
769      int i;
770      
771      for(i= 0; i<HASHTBLSIZE; i++) {
772        temp= env->symbols[i];
773        while(temp!=NULL) {
774          printf("%s\n", temp->id);
775          temp= temp->next;
776        }
777      }
778    }
779    
780    /* Internal forget function */
781    void forget_sym(symbol **hash_entry) {
782      symbol *temp;
783    
784      temp= *hash_entry;
785      *hash_entry= (*hash_entry)->next;
786      
787      if(temp->val!=NULL) {
788        free_val(temp->val);
789      }
790      free(temp->id);
791      free(temp);
792    }
793    
794    /* Forgets a symbol (remove it from the hash table) */
795    extern void forget(environment *env)
796    {
797      char* sym_id;
798      stackitem *stack_head= env->head;
799    
800      if(stack_head==NULL) {
801        printerr("Too Few Arguments");
802        env->err=1;
803        return;
804      }
805      
806      if(stack_head->item->type!=symb) {
807        printerr("Bad Argument Type");
808        env->err=2;
809        return;
810      }
811    
812      sym_id= ((symbol*)(stack_head->item->content.ptr))->id;
813      toss(env);
814    
815      return forget_sym(hash(env->symbols, sym_id));
816    }
817    
818    /* Returns the current error number to the stack */
819    extern void errn(environment *env){
820      push_int(env, env->err);
821    }
822    
823    extern void read(environment*);
824    
825  int main()  int main()
826  {  {
827    stackitem* s= NULL;    environment myenv;
828    hashtbl myhash;  
829    char in_string[100];    init_env(&myenv);
830    
831    init_hashtbl(myhash);    while(1) {
832        if(myenv.in_string==NULL) {
833          nl();
834          printstack(&myenv);
835          printf("> ");
836        }
837        read(&myenv);
838        if(myenv.err) {
839          printf("(error %d) ", myenv.err);
840          myenv.err=0;
841        } else if(myenv.head!=NULL
842                  && myenv.head->item->type==symb
843                  && ((symbol*)(myenv.head->item->content.ptr))->id[0]==';') {
844          toss(&myenv);             /* No error check in main */
845          eval(&myenv);
846        }
847      }
848      quit(&myenv);
849      return EXIT_FAILURE;
850    }
851    
852    printf("okidok\n ");  /* + */
853    extern void sx_2b(environment *env) {
854      int a, b;
855      size_t len;
856      char* new_string;
857      value *a_val, *b_val;
858    
859      if((env->head)==NULL || env->head->next==NULL) {
860        printerr("Too Few Arguments");
861        env->err=1;
862        return;
863      }
864    
865    while(fgets(in_string, 100, stdin) != NULL) {    if(env->head->item->type==string
866      stack_read(&s, myhash, in_string);       && env->head->next->item->type==string) {
867      printf("okidok\n ");      a_val= env->head->item;
868        b_val= env->head->next->item;
869        a_val->refcount++;
870        b_val->refcount++;
871        toss(env); if(env->err) return;
872        toss(env); if(env->err) return;
873        len= strlen(a_val->content.ptr)+strlen(b_val->content.ptr)+1;
874        new_string= malloc(len);
875        strcpy(new_string, b_val->content.ptr);
876        strcat(new_string, a_val->content.ptr);
877        free_val(a_val); free_val(b_val);
878        push_cstring(env, new_string);
879        free(new_string);
880        return;
881      }
882      
883      if(env->head->item->type!=integer
884         || env->head->next->item->type!=integer) {
885        printerr("Bad Argument Type");
886        env->err=2;
887        return;
888    }    }
889      a=env->head->item->content.val;
890      toss(env);
891      if(env->err) return;
892      if(env->head->item->refcount == 1)
893        env->head->item->content.val += a;
894      else {
895        b=env->head->item->content.val;
896        toss(env);
897        if(env->err) return;
898        push_int(env, a+b);
899      }
900    }
901    
902    exit(EXIT_SUCCESS);  /* - */
903    extern void sx_2d(environment *env) {
904      int a, b;
905    
906      if((env->head)==NULL || env->head->next==NULL) {
907        printerr("Too Few Arguments");
908        env->err=1;
909        return;
910      }
911      
912      if(env->head->item->type!=integer
913         || env->head->next->item->type!=integer) {
914        printerr("Bad Argument Type");
915        env->err=2;
916        return;
917      }
918      a=env->head->item->content.val;
919      toss(env);
920      if(env->err) return;
921      if(env->head->item->refcount == 1)
922        env->head->item->content.val -= a;
923      else {
924        b=env->head->item->content.val;
925        toss(env);
926        if(env->err) return;
927        push_int(env, b-a);
928      }
929    }
930    
931    /* > */
932    extern void sx_3e(environment *env) {
933      int a, b;
934    
935      if((env->head)==NULL || env->head->next==NULL) {
936        printerr("Too Few Arguments");
937        env->err=1;
938        return;
939      }
940      
941      if(env->head->item->type!=integer
942         || env->head->next->item->type!=integer) {
943        printerr("Bad Argument Type");
944        env->err=2;
945        return;
946      }
947      a=env->head->item->content.val;
948      toss(env);
949      if(env->err) return;
950      if(env->head->item->refcount == 1)
951        env->head->item->content.val = (env->head->item->content.val > a);
952      else {
953        b=env->head->item->content.val;
954        toss(env);
955        if(env->err) return;
956        push_int(env, b>a);
957      }
958    }
959    
960    /* Return copy of a value */
961    value *copy_val(value *old_value){
962      stackitem *old_item, *new_item, *prev_item;
963    
964      value *new_value=malloc(sizeof(value));
965    
966      new_value->type=old_value->type;
967      new_value->refcount=0;        /* This is increased if/when this
968                                       value is referenced somewhere, like
969                                       in a stack item or a variable */
970      switch(old_value->type){
971      case integer:
972        new_value->content.val=old_value->content.val;
973        break;
974      case string:
975        (char *)(new_value->content.ptr)
976          = strdup((char *)(old_value->content.ptr));
977        break;
978      case func:
979      case symb:
980        new_value->content.ptr=old_value->content.ptr;
981        break;
982      case list:
983        new_value->content.ptr=NULL;
984    
985        prev_item=NULL;
986        old_item=(stackitem *)(old_value->content.ptr);
987    
988        while(old_item != NULL) {   /* While list is not empty */
989          new_item= malloc(sizeof(stackitem));
990          new_item->item=copy_val(old_item->item); /* recurse */
991          new_item->next=NULL;
992          if(prev_item != NULL)     /* If this wasn't the first item */
993            prev_item->next=new_item; /* point the previous item to the
994                                         new item */
995          else
996            new_value->content.ptr=new_item;
997          old_item=old_item->next;
998          prev_item=new_item;
999        }    
1000        break;
1001      }
1002      return new_value;
1003  }  }
1004    
1005  /* Local Variables: */  /* duplicates an item on the stack */
1006  /* compile-command:"make CFLAGS=\"-Wall -g -rdynamic -ldl\" stack" */  extern void dup(environment *env) {
1007  /* End: */    if((env->head)==NULL) {
1008        printerr("Too Few Arguments");
1009        env->err=1;
1010        return;
1011      }
1012      push_val(env, copy_val(env->head->item));
1013    }
1014    
1015    /* "if", If-Then */
1016    extern void sx_6966(environment *env) {
1017    
1018      int truth;
1019    
1020      if((env->head)==NULL || env->head->next==NULL) {
1021        printerr("Too Few Arguments");
1022        env->err=1;
1023        return;
1024      }
1025    
1026      if(env->head->next->item->type != integer) {
1027        printerr("Bad Argument Type");
1028        env->err=2;
1029        return;
1030      }
1031      
1032      swap(env);
1033      if(env->err) return;
1034      
1035      truth=env->head->item->content.val;
1036    
1037      toss(env);
1038      if(env->err) return;
1039    
1040      if(truth)
1041        eval(env);
1042      else
1043        toss(env);
1044    }
1045    
1046    /* If-Then-Else */
1047    extern void ifelse(environment *env) {
1048    
1049      int truth;
1050    
1051      if((env->head)==NULL || env->head->next==NULL
1052         || env->head->next->next==NULL) {
1053        printerr("Too Few Arguments");
1054        env->err=1;
1055        return;
1056      }
1057    
1058      if(env->head->next->next->item->type != integer) {
1059        printerr("Bad Argument Type");
1060        env->err=2;
1061        return;
1062      }
1063      
1064      rot(env);
1065      if(env->err) return;
1066      
1067      truth=env->head->item->content.val;
1068    
1069      toss(env);
1070      if(env->err) return;
1071    
1072      if(!truth)
1073        swap(env);
1074      if(env->err) return;
1075    
1076      toss(env);
1077      if(env->err) return;
1078    
1079      eval(env);
1080    }
1081    
1082    /* while */
1083    extern void sx_7768696c65(environment *env) {
1084    
1085      int truth;
1086      value *loop, *test;
1087    
1088      if((env->head)==NULL || env->head->next==NULL) {
1089        printerr("Too Few Arguments");
1090        env->err=1;
1091        return;
1092      }
1093    
1094      loop= env->head->item;
1095      loop->refcount++;
1096      toss(env); if(env->err) return;
1097    
1098      test= env->head->item;
1099      test->refcount++;
1100      toss(env); if(env->err) return;
1101    
1102      do {
1103        push_val(env, test);
1104        eval(env);
1105        
1106        if(env->head->item->type != integer) {
1107          printerr("Bad Argument Type");
1108          env->err=2;
1109          return;
1110        }
1111        
1112        truth= env->head->item->content.val;
1113        toss(env); if(env->err) return;
1114        
1115        if(truth) {
1116          push_val(env, loop);
1117          eval(env);
1118        } else {
1119          toss(env);
1120        }
1121      
1122      } while(truth);
1123    
1124      free_val(test);
1125      free_val(loop);
1126    }
1127    
1128    /* For-loop */
1129    extern void sx_666f72(environment *env) {
1130      
1131      value *loop, *foo;
1132      stackitem *iterator;
1133      
1134      if((env->head)==NULL || env->head->next==NULL) {
1135        printerr("Too Few Arguments");
1136        env->err=1;
1137        return;
1138      }
1139    
1140      if(env->head->next->item->type != list) {
1141        printerr("Bad Argument Type");
1142        env->err=2;
1143        return;
1144      }
1145    
1146      loop= env->head->item;
1147      loop->refcount++;
1148      toss(env); if(env->err) return;
1149    
1150      foo= env->head->item;
1151      foo->refcount++;
1152      toss(env); if(env->err) return;
1153    
1154      iterator= foo->content.ptr;
1155    
1156      while(iterator!=NULL) {
1157        push_val(env, iterator->item);
1158        push_val(env, loop);
1159        eval(env); if(env->err) return;
1160        iterator= iterator->next;
1161      }
1162    
1163      free_val(loop);
1164      free_val(foo);
1165    }
1166    
1167    /* 'to' */
1168    extern void to(environment *env) {
1169      int i, start, ending;
1170      stackitem *temp_head;
1171      value *temp_val;
1172      
1173      if((env->head)==NULL || env->head->next==NULL) {
1174        printerr("Too Few Arguments");
1175        env->err=1;
1176        return;
1177      }
1178    
1179      if(env->head->item->type!=integer
1180         || env->head->next->item->type!=integer) {
1181        printerr("Bad Argument Type");
1182        env->err=2;
1183        return;
1184      }
1185    
1186      ending= env->head->item->content.val;
1187      toss(env); if(env->err) return;
1188      start= env->head->item->content.val;
1189      toss(env); if(env->err) return;
1190    
1191      temp_head= env->head;
1192      env->head= NULL;
1193    
1194      if(ending>=start) {
1195        for(i= ending; i>=start; i--)
1196          push_int(env, i);
1197      } else {
1198        for(i= ending; i<=start; i++)
1199          push_int(env, i);
1200      }
1201    
1202      temp_val= malloc(sizeof(value));
1203      temp_val->content.ptr= env->head;
1204      temp_val->refcount= 1;
1205      temp_val->type= list;
1206      env->head= temp_head;
1207      push_val(env, temp_val);
1208    }
1209    
1210    /* Read a string */
1211    extern void readline(environment *env) {
1212      char in_string[101];
1213    
1214      fgets(in_string, 100, stdin);
1215      push_cstring(env, in_string);
1216    }
1217    
1218    /* Read a value and place on stack */
1219    extern void read(environment *env) {
1220      const char symbform[]= "%[a-zA-Z0-9!$%*+./:<=>?@^_~-]%n";
1221      const char strform[]= "\"%[^\"]\"%n";
1222      const char intform[]= "%i%n";
1223      const char blankform[]= "%*[ \t]%n";
1224      const char ebrackform[]= "%*1[]]%n";
1225      const char semicform[]= "%*1[;]%n";
1226      const char bbrackform[]= "%*1[[]%n";
1227    
1228      int itemp, readlength= -1;
1229      static int depth= 0;
1230      char *rest, *match;
1231      size_t inlength;
1232    
1233      if(env->in_string==NULL) {
1234        if(depth > 0) {
1235          printf("]> ");
1236        }
1237        readline(env); if(env->err) return;
1238        
1239        env->in_string= malloc(strlen(env->head->item->content.ptr)+1);
1240        env->free_string= env->in_string; /* Save the original pointer */
1241        strcpy(env->in_string, env->head->item->content.ptr);
1242        toss(env); if(env->err) return;
1243      }
1244      
1245      inlength= strlen(env->in_string)+1;
1246      match= malloc(inlength);
1247      rest= malloc(inlength);
1248    
1249      if(sscanf(env->in_string, blankform, &readlength)!=EOF
1250         && readlength != -1) {
1251        ;
1252      } else if(sscanf(env->in_string, intform, &itemp, &readlength) != EOF
1253                && readlength != -1) {
1254        push_int(env, itemp);
1255      } else if(sscanf(env->in_string, strform, match, &readlength) != EOF
1256                && readlength != -1) {
1257        push_cstring(env, match);
1258      } else if(sscanf(env->in_string, symbform, match, &readlength) != EOF
1259                && readlength != -1) {
1260        push_sym(env, match);
1261      } else if(sscanf(env->in_string, ebrackform, &readlength) != EOF
1262                && readlength != -1) {
1263        pack(env); if(env->err) return;
1264        if(depth != 0) depth--;
1265      } else if(sscanf(env->in_string, semicform, &readlength) != EOF
1266                && readlength != -1) {
1267        push_sym(env, ";");
1268      } else if(sscanf(env->in_string, bbrackform, &readlength) != EOF
1269                && readlength != -1) {
1270        push_sym(env, "[");
1271        depth++;
1272      } else {
1273        free(env->free_string);
1274        env->in_string = env->free_string = NULL;
1275        free(match);
1276      }
1277      if ( env->in_string != NULL) {
1278        env->in_string += readlength;
1279      }
1280    
1281      if(depth)
1282        return read(env);
1283    }

Legend:
Removed from v.1.17  
changed lines
  Added in v.1.82

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26