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

Diff of /stack/stack.c

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

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

Legend:
Removed from v.1.19  
changed lines
  Added in v.1.69

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26