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

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

root@recompile.se
ViewVC Help
Powered by ViewVC 1.1.26