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

Diff of /stack/stack.c

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

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

Legend:
Removed from v.1.24  
changed lines
  Added in v.1.83

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26